mirror of
https://github.com/Alvin-Zilverstand/return-youtube-dislike.git
synced 2026-11-24 23:33:02 +01:00
Fix Shorts support and add userscript voting
Harden Shorts controls, reaction state, and navigation; share voting logic with the extension; improve ratio-bar rendering; and add comprehensive Jest, Playwright, artifact, and live-browser regression coverage.
This commit is contained in:
1 parent
4e6dfd1977
commit
3657de9b2c
74 files changed
+23328
-588
No files matched your search
@@ -0,0 +1,168 @@
|
||||
# Live YouTube smoke
|
||||
|
||||
This suite attaches over CDP to an already-running Brave profile. It is deliberately separate from `test:all` and CI.
|
||||
The same page-level checks run in either userscript or extension mode; installation, storage, and protocol failure
|
||||
coverage remain in the hermetic suites.
|
||||
|
||||
## Browser preparation
|
||||
|
||||
1. Open `brave://inspect/#remote-debugging` in the target Brave profile and enable **Allow remote debugging for this
|
||||
browser instance**. Set `RYD_CDP_ENDPOINT` to the explicit HTTP or WebSocket endpoint exposed by that Brave instance;
|
||||
`http://127.0.0.1:9222` is a common HTTP example, but use the actual port shown by Brave.
|
||||
2. Use a dedicated two-item playlist containing two allowlisted public or unlisted test videos. Both must be accessible
|
||||
to the signed-in profile and must have different rendered dislike counts.
|
||||
3. Enable exactly one runtime:
|
||||
- `userscript`: disable the browser extension and every other Return YouTube Dislike userscript, run
|
||||
`npm run build:live:userscript`, import
|
||||
`test-results/live-build/userscript/Return Youtube Dislike.user.js` into Tampermonkey, and enable it.
|
||||
- `extension`: disable every Return YouTube Dislike userscript and any store-installed copy of the extension, run
|
||||
`npm run build:live:extension`, then enable or reload only the unpacked extension at
|
||||
`Extensions/combined/dist/chrome`.
|
||||
Every live build receives a fresh random build ID even when its semantic version is unchanged. Import or reload the
|
||||
runtime **after the final live build command**; rebuilding again invalidates the installed copy for this smoke.
|
||||
4. Keep the Brave window open and do not interact with the tab created by the suite. The suite creates, uses, and closes
|
||||
only its own tab.
|
||||
|
||||
Only the explicit live-test builds expose page markers containing their runtime, version, and exact build ID. Normal
|
||||
production builds do not expose them. The suite reads the expected ID from the generated `live-build.json`, verifies
|
||||
that the installed runtime exposes that exact ID and expected version, and verifies that the other runtime marker is
|
||||
absent before every scenario. A stale installed script or extension therefore fails even when it has the same version.
|
||||
There is no environment override for the build ID.
|
||||
|
||||
The read-only smoke still loads real YouTube and allows the installed runtime to read from the production RYD API,
|
||||
including eager registration when the selected runtime has no confirmed identity. It does not mock API responses, but
|
||||
it blocks production `POST /interact/*` requests before transmission as described below.
|
||||
|
||||
## Non-voting smoke
|
||||
|
||||
Set the following in PowerShell. Video IDs are the 11-character values from YouTube URLs, and the playlist URL must
|
||||
start on `RYD_LIVE_WATCH_A`.
|
||||
|
||||
```powershell
|
||||
$env:RYD_LIVE_YOUTUBE="1"
|
||||
$env:RYD_LIVE_PRODUCTION_API="1"
|
||||
$env:RYD_CDP_ENDPOINT="http://127.0.0.1:9222"
|
||||
$env:RYD_LIVE_RUNTIME="userscript"
|
||||
$env:RYD_LIVE_EXPECTED_CHANNEL="@your-test-channel"
|
||||
$env:RYD_LIVE_WATCH_A="AAAAAAAAAAA"
|
||||
$env:RYD_LIVE_WATCH_B="BBBBBBBBBBB"
|
||||
$env:RYD_LIVE_SHORT="CCCCCCCCCCC"
|
||||
$env:RYD_LIVE_PLAYLIST_URL="https://www.youtube.com/watch?v=AAAAAAAAAAA&list=PLAYLIST_ID"
|
||||
# Optional overrides for the cold channel-navigation smoke. These are the defaults:
|
||||
$env:RYD_LIVE_NAV_CHANNEL_URL="https://www.youtube.com/@SmashTrash"
|
||||
$env:RYD_LIVE_NAV_SHORT="iKQhN7omLM4"
|
||||
# Optional; the consecutive watch-sidebar stress defaults to three hops and accepts 1 through 10.
|
||||
$env:RYD_LIVE_SIDEBAR_HOPS="3"
|
||||
npm run test:live:youtube
|
||||
```
|
||||
|
||||
The navigation smoke performs a real hard load and reload of `RYD_LIVE_NAV_CHANNEL_URL`, finds an exact visible link to
|
||||
`RYD_LIVE_NAV_SHORT`, and clicks that link. It fails rather than falling back to direct navigation when the configured
|
||||
channel no longer contains the exact card. It proves the channel-to-Short transition reused the same document, verifies
|
||||
that the selected runtime initialized the current Short (including exactly one visible synthetic control in userscript
|
||||
mode), clicks YouTube's visible **Next video** control, proves that transition also reused the document, and verifies a
|
||||
new current video ID and initialized control. The channel-to-Short check runs first in the fresh suite tab so earlier
|
||||
watch or Shorts visits cannot warm the page lifecycle it is meant to exercise.
|
||||
|
||||
YouTube can occasionally focus the visible **Next video** button without acting on its first trusted click. The live
|
||||
driver waits five seconds for that first click, prints `LIVE_CHECKPOINT shorts-next-control.retrying`, and makes exactly
|
||||
one more trusted click with the remaining 25-second navigation budget. If the URL still does not advance, the scenario
|
||||
fails; it never loops or clicks a reaction control as part of this retry.
|
||||
|
||||
After the Shorts URL advances, the driver deliberately leaves playback running while YouTube hydrates the new reel,
|
||||
the production `/votes` response arrives, and the current dislike control renders. It pauses only after those checks,
|
||||
so a newly selected Short may play briefly before the `LIVE_CHECKPOINT playback.paused` message appears.
|
||||
|
||||
The watch-sidebar stress starts with the allowlisted `RYD_LIVE_WATCH_A`, then takes the first eligible visible
|
||||
`#related` watch link on each page for the configured number of consecutive SPA hops. Previously visited IDs are
|
||||
skipped. Every hop waits for the exact production `/votes?videoId=<target>` response and a rendered dislike count,
|
||||
requires exactly one visible ratio bar for the selected runtime with valid reaction-control geometry, and samples that
|
||||
same bar and count for four seconds to catch delayed YouTube pruning. It never clicks Like or Dislike. Deterministic
|
||||
evidence paths are overwritten on each run at
|
||||
`test-results/live-youtube/sidebar-stress/{runtime}-sidebar-hop-{01..N}.png`. The same scenario runs in userscript and
|
||||
extension mode.
|
||||
|
||||
Every non-voting live scenario installs a BrowserContext deny route before it starts and aborts every production
|
||||
`POST /interact/*` request. The accompanying request observer intentionally does not require a page frame, so attempts
|
||||
from an extension or service worker also fail the scenario. The guard applies to the entire attached browser context;
|
||||
do not use another tab in that Brave profile to react to a video while the smoke is running.
|
||||
|
||||
Automatic media-ended transitions for both watch pages and Shorts stay in the deterministic hermetic Playwright suite.
|
||||
This production smoke intentionally exercises the visible Shorts **Next video** control only: live autoplay timing,
|
||||
recommendation queues, ads, and account experiments are not stable enough to make an exact production transition a
|
||||
reliable gate. The existing two-item playlist smoke continues to cover an explicit watch-page SPA transition.
|
||||
|
||||
The default channel dataset can drift as its public page changes. Override both variables with a channel URL and Short
|
||||
that are deliberately kept together. The channel URL is restricted to a plain HTTPS `youtube.com/@handle` page or its
|
||||
`featured`, `shorts`, or `videos` tab; the target must be an 11-character video ID.
|
||||
|
||||
An additional cold channel-to-watch scenario is available only when its exact link is deterministic on the configured
|
||||
channel page. Opt in with an 11-character ID; otherwise that scenario is skipped:
|
||||
|
||||
```powershell
|
||||
$env:RYD_LIVE_NAV_WATCH="DDDDDDDDDDD"
|
||||
```
|
||||
|
||||
For the interactive Brave run, use `npm run test:live:youtube:interactive`. Before requesting any reaction approval,
|
||||
it runs the read-only scenarios plus responsive visual checks. Enter `SKIP` at the prompt to finish without reactions.
|
||||
The visual pass checks the watch-page ratio bar at widths 1280, 768, and 390. In userscript mode it also checks the
|
||||
modern Shorts synthetic dislike control, its geometry, and its rendered count at those widths. In extension mode it
|
||||
checks the active reel's native Like/Dislike pair at all three widths: exact action-host, button, and icon sizes;
|
||||
typography; spacing; common reel ownership; ordering; and viewport containment. Cropped evidence images are written
|
||||
under `test-results/live-youtube/responsive/`. If YouTube's native Like/Dislike pill is horizontally clipped by its own
|
||||
mobile page overflow, the ratio bar may share only that same native left/right footprint; any extra overflow introduced
|
||||
by the RYD bar still fails.
|
||||
|
||||
The interactive runner prints `LIVE_STAGE_START`, `LIVE_STAGE_COMPLETE`, and `LIVE_CHECKPOINT` records while it works.
|
||||
In particular, `LIVE_CHECKPOINT playback.paused` means the runner deliberately paused the current YouTube video while
|
||||
validating it; a stationary frame after that message is expected and is not evidence that Brave froze. Navigation,
|
||||
account, runtime, control, and production `/votes` waits have their own checkpoints, so the last line identifies the
|
||||
pending operation.
|
||||
|
||||
If a scenario fails, the runner records page errors, unhandled promise rejections, console errors, and the latest RYD
|
||||
API request outcomes before closing its test tab. It writes a JSON snapshot under
|
||||
`test-results/live-youtube/diagnostics/` and prints its absolute path as `LIVE_FAILURE_SNAPSHOT`. The snapshot includes
|
||||
the URL, runtime markers, Shorts renderer IDs and links, action-bar and synthetic-control ownership, video paused state,
|
||||
and recent API paths/statuses. Anonymous identity and proof-related query values are redacted. Preserve this file when
|
||||
reporting a live-only failure; ordinary direct interactive runs otherwise have no Playwright trace.
|
||||
|
||||
Use `RYD_LIVE_RUNTIME="extension"` after manually switching the enabled runtime to execute the same smoke against the
|
||||
extension. The expected version defaults to the local userscript candidate version or root package version; set
|
||||
`RYD_LIVE_EXPECTED_VERSION` only when deliberately validating another installed build.
|
||||
|
||||
## Optional production reaction matrix
|
||||
|
||||
The reaction test is skipped by default. It covers all six Like/Dislike state transitions on `RYD_LIVE_WATCH_B` and the
|
||||
allowlisted Short, asserts one logical production handshake for every transition, and returns each video to its initial
|
||||
reaction state. A handshake contains one to three matching `/interact/vote` puzzle requests followed by exactly one
|
||||
matching successful `/interact/confirmVote`. Any fourth vote request, changed identity/video/value, extra confirmation,
|
||||
or other interaction traffic fails the run. It does not retry cleanup blindly if the state cannot be verified.
|
||||
If click dispatch, the post-click state wait, or a handshake fails after a vote attempt while the UI already appears to
|
||||
be back at its initial state, cleanup does not trust the UI alone: it confirms an away-and-back reaction round trip with
|
||||
the same anonymous identity. A failed cleanup confirmation or identity mismatch reports the exact video URL for manual
|
||||
restoration.
|
||||
|
||||
The matrix also captures the initial state and every post-transition state, for seven watch images and seven Shorts
|
||||
images. Before each screenshot it reads both `aria-pressed` values, verifies the exact expected mutually-exclusive
|
||||
state, and requires a numeric dislike count. Watch captures additionally require a visible, non-overlapping ratio bar
|
||||
with sane geometry. Userscript Shorts captures reuse the strict native-vs-synthetic control geometry checks, including
|
||||
the 48x78 action host, 24x24 icon, typography, spacing, active-reel ownership, and duplicate-control checks. Evidence is
|
||||
written with deterministic names under
|
||||
`test-results/live-youtube/reactions/{runtime}/{watch|short}-{0..6}-{neutral|liked|disliked}.png`. A failed visual check
|
||||
still enters the same verified restoration path before the scenario reports the failure.
|
||||
|
||||
The exact live-build marker proves that the freshly generated test build is present and that the opposite runtime is
|
||||
absent. It cannot detect an additional normal build of the same runtime, so the manual single-runtime preparation above
|
||||
is mandatory.
|
||||
|
||||
Only after approving those real YouTube and production RYD writes, create a runtime-and-video-specific token immediately
|
||||
before the run. It expires after two minutes and is consumed once locally, so the userscript token cannot silently
|
||||
authorize a later extension run.
|
||||
|
||||
```powershell
|
||||
$env:RYD_LIVE_VOTES="$env:RYD_LIVE_RUNTIME`:$env:RYD_LIVE_WATCH_B`:$([DateTimeOffset]::UtcNow.ToUnixTimeSeconds())"
|
||||
npm run test:live:youtube
|
||||
Remove-Item Env:RYD_LIVE_VOTES
|
||||
```
|
||||
|
||||
After the live run, turn off **Allow remote debugging for this browser instance** or restart the test Brave profile.
|
||||
@@ -0,0 +1,358 @@
|
||||
const fs = require("node:fs");
|
||||
const path = require("node:path");
|
||||
|
||||
const API_ORIGIN = "https://returnyoutubedislikeapi.com";
|
||||
const UNHANDLED_REJECTION_PREFIX = "__RYD_LIVE_UNHANDLED_REJECTION__";
|
||||
const MAX_BROWSER_SIGNALS = 50;
|
||||
const MAX_API_REQUESTS = 50;
|
||||
|
||||
function serializeError(error) {
|
||||
if (!error) return null;
|
||||
if (typeof error === "string") return { message: error, name: "Error", stack: null };
|
||||
return {
|
||||
message: String(error.message ?? error),
|
||||
name: String(error.name ?? "Error"),
|
||||
stack: typeof error.stack === "string" ? error.stack : null,
|
||||
};
|
||||
}
|
||||
|
||||
function installUnhandledRejectionListener(prefix) {
|
||||
if (globalThis.__rydLiveUnhandledRejectionListenerInstalled) return;
|
||||
globalThis.__rydLiveUnhandledRejectionListenerInstalled = true;
|
||||
globalThis.addEventListener("unhandledrejection", (event) => {
|
||||
const reason = event.reason;
|
||||
let message;
|
||||
try {
|
||||
if (reason instanceof Error)
|
||||
message = `${reason.name}: ${reason.message}${reason.stack ? `\n${reason.stack}` : ""}`;
|
||||
else if (typeof reason === "string") message = reason;
|
||||
else message = JSON.stringify(reason);
|
||||
} catch {
|
||||
message = String(reason);
|
||||
}
|
||||
console.error(`${prefix}${message ?? "Unknown rejection"}`);
|
||||
});
|
||||
}
|
||||
|
||||
function readLivePageState() {
|
||||
const readRect = (element) => {
|
||||
const rect = element.getBoundingClientRect();
|
||||
return {
|
||||
bottom: rect.bottom,
|
||||
height: rect.height,
|
||||
left: rect.left,
|
||||
right: rect.right,
|
||||
top: rect.top,
|
||||
width: rect.width,
|
||||
};
|
||||
};
|
||||
const isVisible = (element) => {
|
||||
const rect = element.getBoundingClientRect();
|
||||
const style = getComputedStyle(element);
|
||||
return (
|
||||
rect.width > 0 &&
|
||||
rect.height > 0 &&
|
||||
rect.bottom > 0 &&
|
||||
rect.right > 0 &&
|
||||
rect.top < innerHeight &&
|
||||
rect.left < innerWidth &&
|
||||
style.display !== "none" &&
|
||||
style.visibility !== "hidden"
|
||||
);
|
||||
};
|
||||
const actionBarSelector = "reel-action-bar-view-model, .slim-video-action-bar-actions";
|
||||
const syntheticSelector = "[data-ryd-synthetic-shorts-dislike]";
|
||||
const renderers = [...document.querySelectorAll("ytd-reel-video-renderer, ytm-reel-video-renderer")];
|
||||
|
||||
return {
|
||||
document: {
|
||||
readyState: document.readyState,
|
||||
title: document.title,
|
||||
url: location.href,
|
||||
viewport: { height: innerHeight, width: innerWidth },
|
||||
},
|
||||
runtimeMarkers: {
|
||||
extensionBuild: document.documentElement.getAttribute("data-ryd-extension-build"),
|
||||
extension: document.documentElement.getAttribute("data-ryd-extension-version"),
|
||||
userscriptBuild: document.documentElement.getAttribute("data-ryd-userscript-build"),
|
||||
userscript: document.documentElement.getAttribute("data-ryd-userscript-version"),
|
||||
},
|
||||
renderers: renderers.map((renderer, index) => ({
|
||||
actionBars: renderer.querySelectorAll(actionBarSelector).length,
|
||||
ariaHidden: renderer.getAttribute("aria-hidden"),
|
||||
index,
|
||||
isActive: renderer.getAttribute("is-active"),
|
||||
links: [...renderer.querySelectorAll('a[href*="/shorts/"]')].map((link) => ({
|
||||
href: link.getAttribute("href"),
|
||||
visible: isVisible(link),
|
||||
})),
|
||||
rect: readRect(renderer),
|
||||
syntheticControls: renderer.querySelectorAll(syntheticSelector).length,
|
||||
tagName: renderer.tagName.toLowerCase(),
|
||||
videoId: renderer.getAttribute("video-id"),
|
||||
visible: isVisible(renderer),
|
||||
})),
|
||||
actionBars: [...document.querySelectorAll(actionBarSelector)].map((actionBar, index) => ({
|
||||
index,
|
||||
nativeDislikes: actionBar.querySelectorAll("dislike-button-view-model, #dislike-button").length,
|
||||
nativeLikes: actionBar.querySelectorAll("like-button-view-model, #like-button").length,
|
||||
rect: readRect(actionBar),
|
||||
syntheticControls: actionBar.querySelectorAll(syntheticSelector).length,
|
||||
tagName: actionBar.tagName.toLowerCase(),
|
||||
videoId: actionBar.closest("ytd-reel-video-renderer, ytm-reel-video-renderer")?.getAttribute("video-id") ?? null,
|
||||
visible: isVisible(actionBar),
|
||||
})),
|
||||
syntheticControls: [...document.querySelectorAll(syntheticSelector)].map((control, index) => ({
|
||||
ariaPressed: control.querySelector("button")?.getAttribute("aria-pressed") ?? null,
|
||||
index,
|
||||
rect: readRect(control),
|
||||
text: (control.textContent ?? "").replace(/\s+/g, " ").trim(),
|
||||
videoId: control.getAttribute("data-ryd-video-id"),
|
||||
visible: isVisible(control),
|
||||
})),
|
||||
videos: [...document.querySelectorAll("video")].map((video, index) => ({
|
||||
currentTime: video.currentTime,
|
||||
ended: video.ended,
|
||||
index,
|
||||
paused: video.paused,
|
||||
readyState: video.readyState,
|
||||
rect: readRect(video),
|
||||
visible: isVisible(video),
|
||||
})),
|
||||
};
|
||||
}
|
||||
|
||||
function diagnosticApiUrl(value) {
|
||||
let url;
|
||||
try {
|
||||
url = new URL(value);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
if (url.origin !== API_ORIGIN) return null;
|
||||
|
||||
const query = {};
|
||||
for (const [name, requestValue] of url.searchParams) {
|
||||
query[name] = /auth|key|puzzle|secret|solution|token|user/i.test(name) ? "<redacted>" : requestValue;
|
||||
}
|
||||
return { pathname: url.pathname, query };
|
||||
}
|
||||
|
||||
function timestampForFilename(date) {
|
||||
return date.toISOString().replace(/[:.]/g, "-");
|
||||
}
|
||||
|
||||
class LiveRunDiagnostics {
|
||||
constructor(
|
||||
page,
|
||||
context,
|
||||
{
|
||||
clock = () => new Date(),
|
||||
fileSystem = fs,
|
||||
log = console.log,
|
||||
outputDirectory = path.resolve(__dirname, "../../../../test-results/live-youtube/diagnostics"),
|
||||
runtime = null,
|
||||
} = {},
|
||||
) {
|
||||
this.browserSignals = [];
|
||||
this.clock = clock;
|
||||
this.context = context;
|
||||
this.currentCheckpoint = null;
|
||||
this.currentStage = "startup";
|
||||
this.fileSystem = fileSystem;
|
||||
this.log = log;
|
||||
this.outputDirectory = outputDirectory;
|
||||
this.page = page;
|
||||
this.recentApiRequests = [];
|
||||
this.requestRecords = new WeakMap();
|
||||
this.runtime = runtime;
|
||||
this.started = false;
|
||||
|
||||
this.onConsole = this.onConsole.bind(this);
|
||||
this.onPageError = this.onPageError.bind(this);
|
||||
this.onRequest = this.onRequest.bind(this);
|
||||
this.onRequestFailed = this.onRequestFailed.bind(this);
|
||||
this.onResponse = this.onResponse.bind(this);
|
||||
}
|
||||
|
||||
now() {
|
||||
return this.clock().toISOString();
|
||||
}
|
||||
|
||||
appendCapped(collection, value, maximum) {
|
||||
collection.push(value);
|
||||
if (collection.length > maximum) collection.splice(0, collection.length - maximum);
|
||||
}
|
||||
|
||||
recordBrowserSignal(type, details) {
|
||||
const signal = {
|
||||
at: this.now(),
|
||||
checkpoint: this.currentCheckpoint,
|
||||
stage: this.currentStage,
|
||||
type,
|
||||
...details,
|
||||
};
|
||||
this.appendCapped(this.browserSignals, signal, MAX_BROWSER_SIGNALS);
|
||||
this.log(`LIVE_BROWSER_SIGNAL ${type} ${JSON.stringify(details)}`);
|
||||
}
|
||||
|
||||
onPageError(error) {
|
||||
this.recordBrowserSignal("pageerror", { error: serializeError(error) });
|
||||
}
|
||||
|
||||
onConsole(message) {
|
||||
if (message.type() !== "error") return;
|
||||
const text = message.text();
|
||||
const location = message.location?.() ?? {};
|
||||
if (text.startsWith(UNHANDLED_REJECTION_PREFIX)) {
|
||||
this.recordBrowserSignal("unhandledrejection", {
|
||||
location,
|
||||
message: text.slice(UNHANDLED_REJECTION_PREFIX.length),
|
||||
});
|
||||
return;
|
||||
}
|
||||
this.recordBrowserSignal("console.error", { location, message: text });
|
||||
}
|
||||
|
||||
onRequest(request) {
|
||||
const apiUrl = diagnosticApiUrl(request.url());
|
||||
if (!apiUrl) return;
|
||||
const record = {
|
||||
...apiUrl,
|
||||
at: this.now(),
|
||||
failure: null,
|
||||
method: request.method(),
|
||||
resourceType: typeof request.resourceType === "function" ? request.resourceType() : null,
|
||||
checkpoint: this.currentCheckpoint,
|
||||
stage: this.currentStage,
|
||||
status: null,
|
||||
};
|
||||
this.appendCapped(this.recentApiRequests, record, MAX_API_REQUESTS);
|
||||
this.requestRecords.set(request, record);
|
||||
}
|
||||
|
||||
onResponse(response) {
|
||||
const record = this.requestRecords.get(response.request());
|
||||
if (!record) return;
|
||||
record.status = response.status();
|
||||
}
|
||||
|
||||
onRequestFailed(request) {
|
||||
const record = this.requestRecords.get(request);
|
||||
if (!record) return;
|
||||
record.failure = request.failure()?.errorText ?? "Unknown request failure";
|
||||
}
|
||||
|
||||
async start() {
|
||||
if (this.started) return;
|
||||
this.started = true;
|
||||
this.page.on("console", this.onConsole);
|
||||
this.page.on("pageerror", this.onPageError);
|
||||
this.context.on("request", this.onRequest);
|
||||
this.context.on("requestfailed", this.onRequestFailed);
|
||||
this.context.on("response", this.onResponse);
|
||||
await this.page.addInitScript(installUnhandledRejectionListener, UNHANDLED_REJECTION_PREFIX);
|
||||
if (!this.page.isClosed()) {
|
||||
await this.page.evaluate(installUnhandledRejectionListener, UNHANDLED_REJECTION_PREFIX);
|
||||
}
|
||||
}
|
||||
|
||||
stop() {
|
||||
if (!this.started) return;
|
||||
this.started = false;
|
||||
this.page.off("console", this.onConsole);
|
||||
this.page.off("pageerror", this.onPageError);
|
||||
this.context.off("request", this.onRequest);
|
||||
this.context.off("requestfailed", this.onRequestFailed);
|
||||
this.context.off("response", this.onResponse);
|
||||
}
|
||||
|
||||
checkpoint(name, details = {}) {
|
||||
this.currentCheckpoint = name;
|
||||
this.log(`LIVE_CHECKPOINT ${name} ${JSON.stringify(details)}`);
|
||||
}
|
||||
|
||||
stageStarted(name) {
|
||||
this.currentCheckpoint = null;
|
||||
this.currentStage = name;
|
||||
this.log(`LIVE_STAGE_START ${name}`);
|
||||
}
|
||||
|
||||
stageCompleted(name, startedAt) {
|
||||
this.currentCheckpoint = null;
|
||||
this.currentStage = name;
|
||||
this.log(`LIVE_STAGE_COMPLETE ${name} durationMs=${Date.now() - startedAt}`);
|
||||
}
|
||||
|
||||
stageFailed(name, startedAt, error) {
|
||||
this.currentStage = name;
|
||||
this.log(
|
||||
`LIVE_STAGE_FAILED ${name} durationMs=${Date.now() - startedAt} error=${JSON.stringify(error?.message ?? String(error))}`,
|
||||
);
|
||||
}
|
||||
|
||||
async snapshot(error) {
|
||||
let pageState = null;
|
||||
let pageStateError = null;
|
||||
let url = null;
|
||||
try {
|
||||
url = this.page.url();
|
||||
} catch {
|
||||
// A disconnected page still produces a useful harness/request snapshot.
|
||||
}
|
||||
if (!this.page.isClosed()) {
|
||||
try {
|
||||
pageState = await this.page.evaluate(readLivePageState);
|
||||
} catch (snapshotError) {
|
||||
pageStateError = serializeError(snapshotError);
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
browserSignals: this.browserSignals,
|
||||
capturedAt: this.now(),
|
||||
currentCheckpoint: this.currentCheckpoint,
|
||||
currentStage: this.currentStage,
|
||||
error: serializeError(error),
|
||||
pageClosed: this.page.isClosed(),
|
||||
pageState,
|
||||
pageStateError,
|
||||
recentApiRequests: this.recentApiRequests,
|
||||
runtime: this.runtime,
|
||||
url,
|
||||
};
|
||||
}
|
||||
|
||||
async persistFailureSnapshot(error) {
|
||||
const snapshot = await this.snapshot(error);
|
||||
this.fileSystem.mkdirSync(this.outputDirectory, { recursive: true });
|
||||
const fileName = `failure-${timestampForFilename(this.clock())}.json`;
|
||||
const snapshotPath = path.join(this.outputDirectory, fileName);
|
||||
this.fileSystem.writeFileSync(snapshotPath, `${JSON.stringify(snapshot, null, 2)}\n`, "utf8");
|
||||
return snapshotPath;
|
||||
}
|
||||
}
|
||||
|
||||
async function runLoggedStage(diagnostics, name, action) {
|
||||
const startedAt = Date.now();
|
||||
diagnostics.stageStarted(name);
|
||||
try {
|
||||
const result = await action();
|
||||
diagnostics.stageCompleted(name, startedAt);
|
||||
return result;
|
||||
} catch (error) {
|
||||
diagnostics.stageFailed(name, startedAt, error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
API_ORIGIN,
|
||||
LiveRunDiagnostics,
|
||||
UNHANDLED_REJECTION_PREFIX,
|
||||
diagnosticApiUrl,
|
||||
installUnhandledRejectionListener,
|
||||
readLivePageState,
|
||||
runLoggedStage,
|
||||
serializeError,
|
||||
};
|
||||
@@ -0,0 +1,138 @@
|
||||
const readline = require("node:readline");
|
||||
const { chromium } = require("@playwright/test");
|
||||
const {
|
||||
createExtensionLiveRuntimeAdapter,
|
||||
createUserscriptLiveRuntimeAdapter,
|
||||
} = require("../../../e2e/live-runtime-adapter");
|
||||
const { createSharedLiveScenarioRunner } = require("../../../e2e/shared-live-scenarios");
|
||||
const { consumeLiveVoteApproval, hasFreshVoteApproval, readLiveOptions } = require("../../live/live-options");
|
||||
const { LiveRunDiagnostics, runLoggedStage } = require("./live-diagnostics");
|
||||
const { LiveYoutubeDriver, VoteTrafficRecorder } = require("./live-youtube-driver");
|
||||
|
||||
const scenarioRunner = createSharedLiveScenarioRunner();
|
||||
|
||||
function readApprovalLine() {
|
||||
const input = readline.createInterface({ input: process.stdin, terminal: false });
|
||||
return new Promise((resolve) => {
|
||||
input.once("line", (line) => {
|
||||
input.close();
|
||||
resolve(line.trim());
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
async function main() {
|
||||
const options = readLiveOptions();
|
||||
if (!options) throw new Error("Set RYD_LIVE_YOUTUBE=1 and the documented allowlist variables to opt in.");
|
||||
|
||||
let browser;
|
||||
let diagnostics;
|
||||
let page;
|
||||
try {
|
||||
console.log("WAITING_FOR_BRAVE_DEBUG_APPROVAL");
|
||||
browser = await chromium.connectOverCDP(options.cdpEndpoint, {
|
||||
isLocal: true,
|
||||
noDefaults: true,
|
||||
timeout: 120_000,
|
||||
});
|
||||
const [context] = browser.contexts();
|
||||
if (!context) throw new Error("The attached Chromium browser has no default context.");
|
||||
|
||||
page = await context.newPage();
|
||||
diagnostics = new LiveRunDiagnostics(page, context, { runtime: options.runtime });
|
||||
await diagnostics.start();
|
||||
const driver = new LiveYoutubeDriver(page, context, {
|
||||
reportProgress: (name, details) => diagnostics.checkpoint(name, details),
|
||||
});
|
||||
const createAdapter =
|
||||
options.runtime === "extension" ? createExtensionLiveRuntimeAdapter : createUserscriptLiveRuntimeAdapter;
|
||||
const runtimeAdapter = createAdapter({
|
||||
driver,
|
||||
expectedBuildId: options.expectedBuildId,
|
||||
expectedVersion: options.expectedVersion,
|
||||
});
|
||||
console.log("BRAVE_CONNECTED");
|
||||
|
||||
const readOnly = {};
|
||||
readOnly.channelShorts = await runLoggedStage(diagnostics, "read-only.channel-to-shorts-and-next", () =>
|
||||
scenarioRunner.run(runtimeAdapter, "channel-shorts-navigation", options),
|
||||
);
|
||||
if (options.navigation.watch) {
|
||||
readOnly.channelWatch = await runLoggedStage(diagnostics, "read-only.channel-to-watch", () =>
|
||||
scenarioRunner.run(runtimeAdapter, "channel-watch-navigation", options),
|
||||
);
|
||||
} else {
|
||||
readOnly.channelWatch = null;
|
||||
diagnostics.checkpoint("read-only.channel-to-watch.skipped", {
|
||||
reason: "RYD_LIVE_NAV_WATCH is not configured",
|
||||
});
|
||||
}
|
||||
readOnly.reload = await runLoggedStage(diagnostics, "read-only.reload", () =>
|
||||
scenarioRunner.run(runtimeAdapter, "reload", options),
|
||||
);
|
||||
readOnly.responsive = await runLoggedStage(diagnostics, "read-only.responsive-visual", () =>
|
||||
scenarioRunner.run(runtimeAdapter, "responsive-visual", options),
|
||||
);
|
||||
readOnly.short = await runLoggedStage(diagnostics, "read-only.short-render", () =>
|
||||
scenarioRunner.run(runtimeAdapter, "shorts-render", options),
|
||||
);
|
||||
readOnly.spa = await runLoggedStage(diagnostics, "read-only.playlist-spa", () =>
|
||||
scenarioRunner.run(runtimeAdapter, "spa-navigation", options),
|
||||
);
|
||||
readOnly.sidebarStress = await runLoggedStage(diagnostics, "read-only.sidebar-stress", () =>
|
||||
scenarioRunner.run(runtimeAdapter, "sidebar-navigation-stress", options),
|
||||
);
|
||||
readOnly.watch = await runLoggedStage(diagnostics, "read-only.watch-render", () =>
|
||||
scenarioRunner.run(runtimeAdapter, "watch-render", options),
|
||||
);
|
||||
console.log(`READ_ONLY_COMPLETE ${JSON.stringify(readOnly)}`);
|
||||
console.log(
|
||||
`READY_FOR_REACTION_APPROVAL runtime=${options.runtime} watch=${options.watchB} short=${options.short}`,
|
||||
);
|
||||
|
||||
diagnostics.checkpoint("reaction-approval.waiting", {
|
||||
instruction: "Enter SKIP to close the live-test tab without production reactions",
|
||||
});
|
||||
const approval = await readApprovalLine();
|
||||
if (approval === "SKIP") {
|
||||
console.log("REACTION_MATRIX_SKIPPED");
|
||||
return;
|
||||
}
|
||||
if (!hasFreshVoteApproval(approval, options.runtime, options.watchB, Date.now())) {
|
||||
throw new Error("The supplied live reaction approval is missing, expired, or does not match this run.");
|
||||
}
|
||||
|
||||
const reaction = await runLoggedStage(diagnostics, "reaction-matrix", () =>
|
||||
scenarioRunner.run(runtimeAdapter, "reaction-matrix", options, {
|
||||
createRecorder: (videoId) => new VoteTrafficRecorder(context, videoId),
|
||||
consumeVoteApproval: async () => {
|
||||
driver.assertCurrentVideo(options.watchB);
|
||||
await driver.assertRuntime(options.runtime, options.expectedVersion, options.expectedBuildId);
|
||||
if (!consumeLiveVoteApproval(approval, options.runtime, options.watchB)) {
|
||||
throw new Error("The live reaction approval expired or was already used. No reaction was clicked.");
|
||||
}
|
||||
},
|
||||
}),
|
||||
);
|
||||
console.log(`REACTION_MATRIX_COMPLETE ${JSON.stringify(reaction)}`);
|
||||
} catch (error) {
|
||||
if (diagnostics) {
|
||||
try {
|
||||
const snapshotPath = await diagnostics.persistFailureSnapshot(error);
|
||||
console.error(`LIVE_FAILURE_SNAPSHOT ${snapshotPath}`);
|
||||
} catch (snapshotError) {
|
||||
console.error(`LIVE_FAILURE_SNAPSHOT_FAILED ${snapshotError.message}`);
|
||||
}
|
||||
}
|
||||
throw error;
|
||||
} finally {
|
||||
diagnostics?.stop();
|
||||
if (page && !page.isClosed()) await page.close();
|
||||
if (browser) await browser.close();
|
||||
}
|
||||
}
|
||||
|
||||
main().catch((error) => {
|
||||
console.error(error);
|
||||
process.exitCode = 1;
|
||||
});
|
||||
@@ -0,0 +1,568 @@
|
||||
const assert = require("node:assert/strict");
|
||||
const fs = require("node:fs");
|
||||
const path = require("node:path");
|
||||
const { WATCH_RATIO_SOAK_DURATION_MS } = require("./live-youtube-driver");
|
||||
|
||||
const RESPONSIVE_VIEWPORTS = [
|
||||
{ height: 720, width: 1280 },
|
||||
{ height: 720, width: 768 },
|
||||
{ height: 844, width: 390 },
|
||||
];
|
||||
|
||||
const REACTION_CYCLES = {
|
||||
neutral: ["like", "like", "dislike", "like", "dislike", "dislike"],
|
||||
liked: ["like", "dislike", "like", "dislike", "dislike", "like"],
|
||||
disliked: ["like", "dislike", "dislike", "like", "like", "dislike"],
|
||||
};
|
||||
|
||||
function nextReactionState(state, action) {
|
||||
if (action === "like") return state === "liked" ? "neutral" : "liked";
|
||||
if (action === "dislike") return state === "disliked" ? "neutral" : "disliked";
|
||||
throw new Error(`Unsupported reaction action: ${action}`);
|
||||
}
|
||||
|
||||
function reactionValue(state) {
|
||||
if (state === "liked") return 1;
|
||||
if (state === "disliked") return -1;
|
||||
if (state === "neutral") return 0;
|
||||
throw new Error(`Unsupported reaction state: ${state}`);
|
||||
}
|
||||
|
||||
async function assertLivePreconditions(driver, options) {
|
||||
await driver.assertSignedIn(options.expectedChannel);
|
||||
await driver.assertRuntime(options.runtime, options.expectedVersion, options.expectedBuildId);
|
||||
}
|
||||
|
||||
async function runWatchRenderScenario(driver, options) {
|
||||
return driver.withNoProductionInteractions(async () => {
|
||||
await driver.openPlaylist(options.playlistUrl, options.watchA);
|
||||
await assertLivePreconditions(driver, options);
|
||||
return driver.waitForDislikeText();
|
||||
});
|
||||
}
|
||||
|
||||
async function runReloadScenario(driver, options) {
|
||||
return driver.withNoProductionInteractions(async () => {
|
||||
await driver.openPlaylist(options.playlistUrl, options.watchA);
|
||||
await assertLivePreconditions(driver, options);
|
||||
await driver.waitForDislikeText();
|
||||
await driver.reload(options.watchA);
|
||||
await assertLivePreconditions(driver, options);
|
||||
return driver.waitForDislikeText();
|
||||
});
|
||||
}
|
||||
|
||||
async function runSpaNavigationScenario(driver, options) {
|
||||
return driver.withNoProductionInteractions(async () => {
|
||||
await driver.openPlaylist(options.playlistUrl, options.watchA);
|
||||
await assertLivePreconditions(driver, options);
|
||||
const watchACount = await driver.waitForDislikeText();
|
||||
await driver.navigateWithinPlaylist(options.watchB);
|
||||
await assertLivePreconditions(driver, options);
|
||||
const watchBCount = await driver.waitForDislikeText({ differentFrom: watchACount });
|
||||
assert.match(watchACount, /\d/);
|
||||
assert.match(watchBCount, /\d/);
|
||||
assert.notEqual(
|
||||
watchBCount,
|
||||
watchACount,
|
||||
"Choose allowlisted playlist videos whose rendered dislike counts differ so stale SPA UI can be detected.",
|
||||
);
|
||||
return { watchACount, watchBCount };
|
||||
});
|
||||
}
|
||||
|
||||
async function runSidebarStressScenario(
|
||||
driver,
|
||||
options,
|
||||
{
|
||||
makeDirectory = (directory) => fs.mkdirSync(directory, { recursive: true }),
|
||||
outputDirectory = path.resolve(__dirname, "../../../../test-results/live-youtube/sidebar-stress"),
|
||||
readyTimeoutMs = 1_000,
|
||||
soakDurationMs = WATCH_RATIO_SOAK_DURATION_MS,
|
||||
} = {},
|
||||
) {
|
||||
const hopCount = options.sidebar?.hopCount;
|
||||
assert.ok(Number.isSafeInteger(hopCount) && hopCount > 0, "A positive sidebar stress hop count is required.");
|
||||
assert.ok(
|
||||
Number.isFinite(readyTimeoutMs) && readyTimeoutMs > 0,
|
||||
"A positive ratio-bar readiness budget is required.",
|
||||
);
|
||||
makeDirectory(outputDirectory);
|
||||
|
||||
return driver.withNoProductionInteractions(async () => {
|
||||
await driver.openWatch(options.watchA);
|
||||
await assertLivePreconditions(driver, options);
|
||||
const visitedVideoIds = [options.watchA];
|
||||
const hops = [];
|
||||
|
||||
for (let index = 0; index < hopCount; index += 1) {
|
||||
const { body, videoId } = await driver.navigateToRelatedWatch(visitedVideoIds);
|
||||
assert.equal(typeof body.dislikes, "number", `Sidebar hop ${index + 1} has no production dislike count.`);
|
||||
assert.ok(!visitedVideoIds.includes(videoId), `Sidebar hop ${index + 1} revisited ${videoId}.`);
|
||||
driver.assertCurrentVideo(videoId);
|
||||
await assertLivePreconditions(driver, options);
|
||||
|
||||
const screenshotPath = path.join(
|
||||
outputDirectory,
|
||||
`${options.runtime}-sidebar-hop-${String(index + 1).padStart(2, "0")}.png`,
|
||||
);
|
||||
const readinessStartedAt = Date.now();
|
||||
const visual = await driver.captureWatchRatioVisual(options.runtime, screenshotPath, {
|
||||
presenceTimeoutMs: readyTimeoutMs,
|
||||
});
|
||||
const readyLatencyMs = Date.now() - readinessStartedAt;
|
||||
assert.ok(
|
||||
readyLatencyMs <= readyTimeoutMs,
|
||||
`Sidebar hop ${index + 1} ratio bar took ${readyLatencyMs}ms; the budget is ${readyTimeoutMs}ms.`,
|
||||
);
|
||||
assert.match(visual.count, /\d/, `Sidebar hop ${index + 1} did not render a dislike count.`);
|
||||
const soak = await driver.soakWatchRatioVisual(options.runtime, {
|
||||
durationMs: soakDurationMs,
|
||||
expectedCount: visual.count,
|
||||
videoId,
|
||||
});
|
||||
|
||||
visitedVideoIds.push(videoId);
|
||||
hops.push({
|
||||
apiDislikes: body.dislikes,
|
||||
count: visual.count,
|
||||
readyLatencyMs,
|
||||
readyTimeoutMs,
|
||||
screenshotPath,
|
||||
soak,
|
||||
videoId,
|
||||
});
|
||||
}
|
||||
|
||||
return { hopCount, hops, outputDirectory, startVideoId: options.watchA };
|
||||
});
|
||||
}
|
||||
|
||||
async function runShortsRenderScenario(driver, options) {
|
||||
return driver.withNoProductionInteractions(async () => {
|
||||
await driver.openShort(options.short);
|
||||
await assertLivePreconditions(driver, options);
|
||||
return driver.waitForDislikeText();
|
||||
});
|
||||
}
|
||||
|
||||
async function runChannelShortsNavigationScenario(driver, options) {
|
||||
return driver.withNoProductionInteractions(async () => {
|
||||
await driver.navigateFromColdChannelToShort(options.navigation.channelUrl, options.navigation.short);
|
||||
await assertLivePreconditions(driver, options);
|
||||
const initial = await driver.assertCurrentShortsControl(options.navigation.short, options.runtime);
|
||||
|
||||
const nextVideoId = await driver.navigateToNextShort(options.navigation.short);
|
||||
await driver.assertRuntime(options.runtime, options.expectedVersion, options.expectedBuildId);
|
||||
const next = await driver.assertCurrentShortsControl(nextVideoId, options.runtime);
|
||||
await driver.pausePlayback();
|
||||
assert.notEqual(
|
||||
next.videoId,
|
||||
initial.videoId,
|
||||
"The Shorts Next video scenario did not change the current video ID.",
|
||||
);
|
||||
return { initial, next };
|
||||
});
|
||||
}
|
||||
|
||||
async function runChannelWatchNavigationScenario(driver, options) {
|
||||
if (!options.navigation.watch) {
|
||||
throw new Error("RYD_LIVE_NAV_WATCH is required for the optional channel-to-watch scenario.");
|
||||
}
|
||||
|
||||
return driver.withNoProductionInteractions(async () => {
|
||||
await driver.navigateFromColdChannelToWatch(options.navigation.channelUrl, options.navigation.watch);
|
||||
await assertLivePreconditions(driver, options);
|
||||
const count = await driver.waitForDislikeText();
|
||||
return { count, videoId: options.navigation.watch };
|
||||
});
|
||||
}
|
||||
|
||||
async function runResponsiveVisualScenario(
|
||||
driver,
|
||||
options,
|
||||
{
|
||||
makeDirectory = (directory) => fs.mkdirSync(directory, { recursive: true }),
|
||||
outputDirectory = path.resolve(__dirname, "../../../../test-results/live-youtube/responsive"),
|
||||
} = {},
|
||||
) {
|
||||
makeDirectory(outputDirectory);
|
||||
return driver.withNoProductionInteractions(async () => {
|
||||
const originalViewport = await driver.readViewportSize();
|
||||
const watch = [];
|
||||
const shorts = [];
|
||||
|
||||
try {
|
||||
await driver.setViewportSize(RESPONSIVE_VIEWPORTS[0]);
|
||||
await driver.openWatch(options.watchA);
|
||||
await assertLivePreconditions(driver, options);
|
||||
for (let index = 0; index < RESPONSIVE_VIEWPORTS.length; index += 1) {
|
||||
const viewport = RESPONSIVE_VIEWPORTS[index];
|
||||
if (index > 0) await driver.setViewportSize(viewport);
|
||||
await driver.waitForDislikeText();
|
||||
watch.push(
|
||||
await driver.captureWatchRatioVisual(
|
||||
options.runtime,
|
||||
path.join(outputDirectory, `${options.runtime}-watch-ratio-${viewport.width}.png`),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
await driver.setViewportSize(RESPONSIVE_VIEWPORTS[0]);
|
||||
await driver.openShort(options.short);
|
||||
await assertLivePreconditions(driver, options);
|
||||
for (let index = 0; index < RESPONSIVE_VIEWPORTS.length; index += 1) {
|
||||
const viewport = RESPONSIVE_VIEWPORTS[index];
|
||||
if (index > 0) await driver.setViewportSize(viewport);
|
||||
await driver.assertCurrentShortsControl(options.short, options.runtime);
|
||||
await driver.waitForDislikeText();
|
||||
const screenshotPath = path.join(outputDirectory, `${options.runtime}-shorts-control-${viewport.width}.png`);
|
||||
shorts.push(
|
||||
options.runtime === "userscript"
|
||||
? await driver.captureSyntheticShortsVisual(options.short, screenshotPath)
|
||||
: await driver.captureNativeShortsVisual(options.short, screenshotPath),
|
||||
);
|
||||
}
|
||||
} finally {
|
||||
await driver.setViewportSize(originalViewport);
|
||||
}
|
||||
|
||||
return {
|
||||
outputDirectory,
|
||||
shorts,
|
||||
shortsSkipped: null,
|
||||
watch,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
async function restoreReactionStateUnchecked(
|
||||
driver,
|
||||
recorder,
|
||||
options,
|
||||
videoId,
|
||||
initialState,
|
||||
expectedUserId,
|
||||
isShort,
|
||||
failedAttempt,
|
||||
) {
|
||||
try {
|
||||
driver.assertCurrentVideo(videoId);
|
||||
} catch {
|
||||
if (isShort) await driver.openShort(videoId);
|
||||
else await driver.openWatch(videoId);
|
||||
await assertLivePreconditions(driver, options);
|
||||
}
|
||||
|
||||
const currentState = await driver.readReactionState();
|
||||
if (currentState === initialState && !failedAttempt) return;
|
||||
|
||||
const attemptedUserId = failedAttempt?.userId;
|
||||
const assertCleanupUserId = (userId, roundTripUserId) => {
|
||||
assert.equal(typeof userId, "string", "The cleanup reaction has no anonymous RYD identity.");
|
||||
if (expectedUserId) {
|
||||
assert.equal(userId, expectedUserId, "The cleanup reaction used a different anonymous RYD identity.");
|
||||
}
|
||||
if (attemptedUserId) {
|
||||
assert.equal(userId, attemptedUserId, "The cleanup reaction did not use the failed attempt's RYD identity.");
|
||||
}
|
||||
if (roundTripUserId) {
|
||||
assert.equal(userId, roundTripUserId, "The cleanup round trip changed anonymous RYD identity.");
|
||||
}
|
||||
};
|
||||
const performCleanupTransition = async (action, targetState, roundTripUserId) => {
|
||||
const mark = recorder.mark();
|
||||
await driver.clickAction(videoId, action);
|
||||
await driver.waitForReactionState(targetState);
|
||||
const userId = await recorder.waitForHandshake(reactionValue(targetState), mark);
|
||||
assertCleanupUserId(userId, roundTripUserId);
|
||||
return userId;
|
||||
};
|
||||
|
||||
if (currentState === initialState) {
|
||||
const action = initialState === "liked" ? "like" : "dislike";
|
||||
const awayState = initialState === "neutral" ? "disliked" : "neutral";
|
||||
const awayUserId = await performCleanupTransition(action, awayState);
|
||||
await performCleanupTransition(action, initialState, awayUserId);
|
||||
return;
|
||||
}
|
||||
|
||||
const action =
|
||||
initialState === "neutral"
|
||||
? currentState === "liked"
|
||||
? "like"
|
||||
: "dislike"
|
||||
: initialState === "liked"
|
||||
? "like"
|
||||
: "dislike";
|
||||
await performCleanupTransition(action, initialState);
|
||||
}
|
||||
|
||||
async function restoreReactionState(
|
||||
driver,
|
||||
recorder,
|
||||
options,
|
||||
videoId,
|
||||
initialState,
|
||||
expectedUserId,
|
||||
isShort,
|
||||
failedAttempt,
|
||||
) {
|
||||
try {
|
||||
await restoreReactionStateUnchecked(
|
||||
driver,
|
||||
recorder,
|
||||
options,
|
||||
videoId,
|
||||
initialState,
|
||||
expectedUserId,
|
||||
isShort,
|
||||
failedAttempt,
|
||||
);
|
||||
} catch (error) {
|
||||
const url = isShort ? `https://www.youtube.com/shorts/${videoId}` : `https://www.youtube.com/watch?v=${videoId}`;
|
||||
throw new Error(`Automatic cleanup could not be verified. Manually restore ${url}. ${error.message}`, {
|
||||
cause: error,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
async function runReactionCycle(
|
||||
driver,
|
||||
recorder,
|
||||
options,
|
||||
{ beforeFirstAction, captureReactionVisual = null, isShort = false, videoId },
|
||||
) {
|
||||
if (isShort) await driver.openShort(videoId);
|
||||
else await driver.openWatch(videoId);
|
||||
await assertLivePreconditions(driver, options);
|
||||
await driver.waitForDislikeText();
|
||||
|
||||
const initialState = await driver.readReactionState();
|
||||
const actions = REACTION_CYCLES[initialState];
|
||||
assert.ok(actions, `Unsupported initial YouTube reaction state: ${initialState}`);
|
||||
|
||||
let authorized = false;
|
||||
let completed = false;
|
||||
let expectedUserId;
|
||||
let failedAttempt;
|
||||
let currentState = initialState;
|
||||
const evidencePaths = [];
|
||||
const captureEvidence = async (index) => {
|
||||
if (!captureReactionVisual) return;
|
||||
const screenshotPath = await captureReactionVisual({ index, state: currentState });
|
||||
assert.equal(typeof screenshotPath, "string", "The reaction visual capture did not return an evidence path.");
|
||||
evidencePaths.push(screenshotPath);
|
||||
};
|
||||
try {
|
||||
await captureEvidence(0);
|
||||
driver.assertCurrentVideo(videoId);
|
||||
await assertLivePreconditions(driver, options);
|
||||
if (beforeFirstAction) await beforeFirstAction();
|
||||
authorized = true;
|
||||
|
||||
for (let index = 0; index < actions.length; index += 1) {
|
||||
const action = actions[index];
|
||||
const expectedState = nextReactionState(currentState, action);
|
||||
const mark = recorder.mark();
|
||||
const value = reactionValue(expectedState);
|
||||
failedAttempt = { mark, userId: undefined, value };
|
||||
await driver.clickAction(videoId, action);
|
||||
await driver.waitForReactionState(expectedState);
|
||||
const userId = await recorder.waitForHandshake(value, mark);
|
||||
failedAttempt.userId = userId;
|
||||
if (expectedUserId) assert.equal(userId, expectedUserId, "The transition cycle changed anonymous RYD identity.");
|
||||
expectedUserId = userId;
|
||||
failedAttempt = undefined;
|
||||
currentState = expectedState;
|
||||
await driver.waitForDislikeText();
|
||||
await captureEvidence(index + 1);
|
||||
}
|
||||
|
||||
assert.equal(currentState, initialState, "The six-transition cycle did not return to its initial state.");
|
||||
completed = true;
|
||||
return { evidencePaths, initialState, userId: expectedUserId };
|
||||
} finally {
|
||||
if (authorized && !completed) {
|
||||
if (failedAttempt && !failedAttempt.userId && typeof recorder.voteUserId === "function") {
|
||||
try {
|
||||
failedAttempt.userId = recorder.voteUserId(failedAttempt.value, failedAttempt.mark);
|
||||
} catch {
|
||||
failedAttempt.userId = undefined;
|
||||
}
|
||||
}
|
||||
await restoreReactionState(
|
||||
driver,
|
||||
recorder,
|
||||
options,
|
||||
videoId,
|
||||
initialState,
|
||||
expectedUserId,
|
||||
isShort,
|
||||
failedAttempt,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function runProductionReactionMatrixScenario(
|
||||
driver,
|
||||
options,
|
||||
createRecorder,
|
||||
consumeVoteApproval,
|
||||
visualOptions = {},
|
||||
) {
|
||||
const makeDirectory = visualOptions.makeDirectory ?? ((directory) => fs.mkdirSync(directory, { recursive: true }));
|
||||
const outputDirectory =
|
||||
visualOptions.outputDirectory ??
|
||||
path.resolve(__dirname, "../../../../test-results/live-youtube/reactions", options.runtime);
|
||||
makeDirectory(outputDirectory);
|
||||
const captureFor =
|
||||
(kind, videoId, isShort) =>
|
||||
async ({ index, state }) => {
|
||||
const screenshotPath = path.join(outputDirectory, `${kind}-${index}-${state}.png`);
|
||||
const evidence = await driver.captureReactionStateVisual({
|
||||
expectedState: state,
|
||||
isShort,
|
||||
runtime: options.runtime,
|
||||
screenshotPath,
|
||||
videoId,
|
||||
});
|
||||
assert.equal(
|
||||
evidence?.screenshotPath,
|
||||
screenshotPath,
|
||||
`The ${kind} reaction capture did not write the requested evidence path.`,
|
||||
);
|
||||
return screenshotPath;
|
||||
};
|
||||
|
||||
const watchRecorder = createRecorder(options.watchB);
|
||||
let watchResult;
|
||||
try {
|
||||
watchResult = await runReactionCycle(driver, watchRecorder, options, {
|
||||
beforeFirstAction: consumeVoteApproval,
|
||||
captureReactionVisual: captureFor("watch", options.watchB, false),
|
||||
videoId: options.watchB,
|
||||
});
|
||||
} finally {
|
||||
watchRecorder.stop();
|
||||
}
|
||||
|
||||
const shortRecorder = createRecorder(options.short);
|
||||
try {
|
||||
const shortResult = await runReactionCycle(driver, shortRecorder, options, {
|
||||
captureReactionVisual: captureFor("short", options.short, true),
|
||||
isShort: true,
|
||||
videoId: options.short,
|
||||
});
|
||||
assert.equal(
|
||||
shortResult.userId,
|
||||
watchResult.userId,
|
||||
"Watch and Shorts votes used different anonymous RYD identities.",
|
||||
);
|
||||
return {
|
||||
evidencePaths: [...watchResult.evidencePaths, ...shortResult.evidencePaths],
|
||||
outputDirectory,
|
||||
short: shortResult,
|
||||
watch: watchResult,
|
||||
};
|
||||
} finally {
|
||||
shortRecorder.stop();
|
||||
}
|
||||
}
|
||||
|
||||
async function restoreNeutralStateUnchecked(driver, recorder, options, dislikeMark, expectedUserId) {
|
||||
let state;
|
||||
try {
|
||||
driver.assertCurrentVideo(options.watchB);
|
||||
state = await driver.readVoteState();
|
||||
} catch {
|
||||
await driver.openWatch(options.watchB);
|
||||
await assertLivePreconditions(driver, options);
|
||||
state = await driver.readVoteState();
|
||||
}
|
||||
|
||||
if (state === "false") {
|
||||
if (recorder.hasVote(-1, dislikeMark)) {
|
||||
throw new Error(
|
||||
`The YouTube button is neutral but the production -1 vote may remain. Manually verify and restore https://www.youtube.com/watch?v=${options.watchB}.`,
|
||||
);
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (state !== "true") {
|
||||
throw new Error(
|
||||
`Could not verify the YouTube dislike state. Manually restore https://www.youtube.com/watch?v=${options.watchB}.`,
|
||||
);
|
||||
}
|
||||
|
||||
const neutralMark = recorder.mark();
|
||||
await driver.clickDislike(options.watchB);
|
||||
await driver.waitForVoteState(false);
|
||||
const neutralUserId = await recorder.waitForHandshake(0, neutralMark);
|
||||
if (expectedUserId && neutralUserId !== expectedUserId) {
|
||||
throw new Error(
|
||||
`The neutral vote used a different identity from the dislike vote. Manually verify and restore https://www.youtube.com/watch?v=${options.watchB}.`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
async function restoreNeutralState(driver, recorder, options, dislikeMark, expectedUserId) {
|
||||
try {
|
||||
await restoreNeutralStateUnchecked(driver, recorder, options, dislikeMark, expectedUserId);
|
||||
} catch (error) {
|
||||
throw new Error(
|
||||
`Automatic cleanup could not be verified. Manually restore https://www.youtube.com/watch?v=${options.watchB}. ${error.message}`,
|
||||
{ cause: error },
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
async function runReversibleVoteScenario(driver, recorder, options, consumeVoteApproval) {
|
||||
await driver.openWatch(options.watchB);
|
||||
await assertLivePreconditions(driver, options);
|
||||
await driver.waitForDislikeText();
|
||||
const initialLikeState = await driver.readLikeState();
|
||||
const initialDislikeState = await driver.readVoteState();
|
||||
assert.equal(initialLikeState, "false", "The allowlisted vote video must not already be liked.");
|
||||
assert.equal(initialDislikeState, "false", "The allowlisted vote video must not already be disliked.");
|
||||
|
||||
const dislikeMark = recorder.mark();
|
||||
let cleanupRequired = false;
|
||||
let dislikeUserId;
|
||||
try {
|
||||
driver.assertCurrentVideo(options.watchB);
|
||||
await assertLivePreconditions(driver, options);
|
||||
await consumeVoteApproval();
|
||||
cleanupRequired = true;
|
||||
await driver.clickDislike(options.watchB);
|
||||
await driver.waitForVoteState(true);
|
||||
dislikeUserId = await recorder.waitForHandshake(-1, dislikeMark);
|
||||
} finally {
|
||||
if (cleanupRequired) {
|
||||
await restoreNeutralState(
|
||||
driver,
|
||||
recorder,
|
||||
options,
|
||||
dislikeMark,
|
||||
dislikeUserId || recorder.voteUserId(-1, dislikeMark),
|
||||
);
|
||||
}
|
||||
}
|
||||
await driver.waitForDislikeText();
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
RESPONSIVE_VIEWPORTS,
|
||||
runChannelShortsNavigationScenario,
|
||||
runChannelWatchNavigationScenario,
|
||||
runProductionReactionMatrixScenario,
|
||||
runReactionCycle,
|
||||
runReloadScenario,
|
||||
runReversibleVoteScenario,
|
||||
runResponsiveVisualScenario,
|
||||
runSidebarStressScenario,
|
||||
runShortsRenderScenario,
|
||||
runSpaNavigationScenario,
|
||||
runWatchRenderScenario,
|
||||
};
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,113 @@
|
||||
const { chromium, test } = require("@playwright/test");
|
||||
const {
|
||||
createExtensionLiveRuntimeAdapter,
|
||||
createUserscriptLiveRuntimeAdapter,
|
||||
} = require("../../../e2e/live-runtime-adapter");
|
||||
const { createSharedLiveScenarioRunner } = require("../../../e2e/shared-live-scenarios");
|
||||
const { consumeLiveVoteApproval, hasFreshVoteApproval, readLiveOptions } = require("../../live/live-options");
|
||||
const { LiveYoutubeDriver, VoteTrafficRecorder } = require("./live-youtube-driver");
|
||||
|
||||
const options = readLiveOptions();
|
||||
const scenarioRunner = createSharedLiveScenarioRunner();
|
||||
|
||||
test.describe("live YouTube RYD smoke", () => {
|
||||
test.skip(options === null, "Set RYD_LIVE_YOUTUBE=1 and the documented allowlist variables to opt in.");
|
||||
test.describe.configure({ mode: "serial" });
|
||||
|
||||
let browser;
|
||||
let context;
|
||||
let page;
|
||||
let driver;
|
||||
let runtimeAdapter;
|
||||
|
||||
test.beforeAll(async () => {
|
||||
try {
|
||||
browser = await chromium.connectOverCDP(options.cdpEndpoint, {
|
||||
isLocal: true,
|
||||
noDefaults: true,
|
||||
timeout: 15_000,
|
||||
});
|
||||
} catch (error) {
|
||||
throw new Error(
|
||||
`Could not attach to the running Brave/Chromium profile. Enable remote debugging at brave://inspect/#remote-debugging and set RYD_CDP_ENDPOINT to its explicit CDP endpoint, then retry. ${error.message}`,
|
||||
);
|
||||
}
|
||||
|
||||
[context] = browser.contexts();
|
||||
if (!context) throw new Error("The attached Brave/Chromium browser has no default context.");
|
||||
page = await context.newPage();
|
||||
driver = new LiveYoutubeDriver(page, context);
|
||||
const createAdapter =
|
||||
options.runtime === "extension" ? createExtensionLiveRuntimeAdapter : createUserscriptLiveRuntimeAdapter;
|
||||
runtimeAdapter = createAdapter({
|
||||
driver,
|
||||
expectedBuildId: options.expectedBuildId,
|
||||
expectedVersion: options.expectedVersion,
|
||||
});
|
||||
});
|
||||
|
||||
test.afterAll(async () => {
|
||||
if (page && !page.isClosed()) await page.close();
|
||||
if (browser) await browser.close();
|
||||
});
|
||||
|
||||
test(`${options?.runtime || "runtime"}: initializes after cold channel-to-Short and Next-video SPA navigation`, async () => {
|
||||
test.setTimeout(150_000);
|
||||
await scenarioRunner.run(runtimeAdapter, "channel-shorts-navigation", options);
|
||||
});
|
||||
|
||||
test(`${options?.runtime || "runtime"}: initializes after optional cold channel-to-watch SPA navigation`, async () => {
|
||||
test.setTimeout(120_000);
|
||||
test.skip(
|
||||
!options?.navigation.watch,
|
||||
"Set RYD_LIVE_NAV_WATCH only when the configured channel page contains an exact visible link to that video.",
|
||||
);
|
||||
await scenarioRunner.run(runtimeAdapter, "channel-watch-navigation", options);
|
||||
});
|
||||
|
||||
test(`${options?.runtime || "runtime"}: renders on a signed-in watch page`, async () => {
|
||||
await scenarioRunner.run(runtimeAdapter, "watch-render", options);
|
||||
});
|
||||
|
||||
test(`${options?.runtime || "runtime"}: reinitializes after reload`, async () => {
|
||||
await scenarioRunner.run(runtimeAdapter, "reload", options);
|
||||
});
|
||||
|
||||
test(`${options?.runtime || "runtime"}: reinitializes after real playlist SPA navigation`, async () => {
|
||||
await scenarioRunner.run(runtimeAdapter, "spa-navigation", options);
|
||||
});
|
||||
|
||||
test(`${options?.runtime || "runtime"}: survives consecutive real sidebar SPA navigations`, async () => {
|
||||
test.setTimeout(60_000 + options.sidebar.hopCount * 75_000);
|
||||
await scenarioRunner.run(runtimeAdapter, "sidebar-navigation-stress", options);
|
||||
});
|
||||
|
||||
test(`${options?.runtime || "runtime"}: renders on an allowlisted Short`, async () => {
|
||||
await scenarioRunner.run(runtimeAdapter, "shorts-render", options);
|
||||
});
|
||||
|
||||
test(`${options?.runtime || "runtime"}: preserves reaction UI geometry across responsive widths`, async () => {
|
||||
test.setTimeout(180_000);
|
||||
await scenarioRunner.run(runtimeAdapter, "responsive-visual", options);
|
||||
});
|
||||
|
||||
test(`${options?.runtime || "runtime"}: covers all reaction transitions on watch and Shorts`, async () => {
|
||||
test.setTimeout(0);
|
||||
const voteApproval = process.env.RYD_LIVE_VOTES;
|
||||
test.skip(
|
||||
!hasFreshVoteApproval(voteApproval, options.runtime, options.watchB, Date.now()),
|
||||
"Create the documented short-lived RYD_LIVE_VOTES token only after approving the real vote pair.",
|
||||
);
|
||||
|
||||
await scenarioRunner.run(runtimeAdapter, "reaction-matrix", options, {
|
||||
createRecorder: (videoId) => new VoteTrafficRecorder(context, videoId),
|
||||
consumeVoteApproval: async () => {
|
||||
driver.assertCurrentVideo(options.watchB);
|
||||
await driver.assertRuntime(options.runtime, options.expectedVersion, options.expectedBuildId);
|
||||
if (!consumeLiveVoteApproval(voteApproval, options.runtime, options.watchB)) {
|
||||
throw new Error("The live reaction approval expired or was already used. No reaction was clicked.");
|
||||
}
|
||||
},
|
||||
});
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user