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:
Anarios committed 2026-09-01 23:41:28 +02:00
1 parent 4e6dfd1977
commit 3657de9b2c
74 files changed
+23328 -588

No files matched your search

+71
View File
@@ -0,0 +1,71 @@
# Shared extension/userscript browser contract
`shared-live-scenarios.js` publishes the ordered behavioral scenario IDs used by both runtimes. The runtime adapters
bind the selected runtime, version, and exact generated live-build ID into the existing live driver while retaining
runtime-specific ratio-bar, tooltip, credential-store, transport, and Shorts-control capabilities.
`hermetic-artifact-smoke.js` makes three shared scenarios executable against both generated artifacts and one
extension-specific stale-response race executable against the generated MV3 artifact:
- `watch-render` verifies the first rendered count and visible ratio bar.
- `watch-spa-side-panel` clicks the related-video link from A to B using non-proportional 90/10 and 35/65 fixtures.
It retains hidden copies of A's initialized controls both before and inside the new current root, replaces B's action
container during settling, and then requires exactly one B-owned count/bar/tooltip with no RYD bars left in any
retained tree. Readiness must remain valid for 300 ms, after which the exact invariant is sampled continuously for
another second. The result includes first-valid latency and sample counts.
- `watch-spa-dislike-activation` reuses that exact A-to-B replacement setup, clicks the one visible B-owned Dislike
button once, and requires one ordered `/interact/vote` plus `/interact/confirmVote` chain for B with value `-1` and
the same confirmed 36-character user ID. Confirmation must return HTTP 200 with the literal JSON value `true`, and
the exact one-vote/one-confirmation invariant must remain stable for another second so a duplicated listener fails.
The userscript chain is observed through its routed fake backend; the extension chain is observed at the loopback MV3
background server. Both paths reject unexpected or escaped traffic and page errors, unhandled rejections, and console
errors.
- `extension-watch-spa-delayed-outgoing-failure` holds A's `/votes` response, navigates to B, releases A as malformed,
and requires B to initialize exactly once without ever showing A's error or data. This proves that navigation queued
during an in-flight initialization is not swallowed and that stale failures are as harmless as stale successes.
```powershell
node Extensions/e2e/hermetic-artifact-smoke.js
```
The userscript is injected into an isolated context with GM shims. The extension is loaded as a real unpacked MV3
artifact in an isolated persistent Chromium profile, and the smoke requires its service worker to start.
## Extension API safety
The extension background eagerly registers as soon as its service worker starts. That can happen before Playwright can
install a context route, so routing the production origin after `launchPersistentContext()` is not a safe hermetic
strategy.
The adapter therefore starts a loopback fake API first, copies the current `dist/chrome` artifact into an owned OS
temporary directory, replaces the exact production origin in the background bundle, and adds only the corresponding
loopback host permission. It refuses non-loopback origins or a missing replacement point. The content-script bundle is
left byte-for-byte intact: Chromium blocks HTTPS-page content scripts from reaching loopback under Private Network
Access, so a BrowserContext route fulfills its normal API-origin requests instead. That route is installed before any
YouTube page is created or navigated. The temporary background bundle also replaces the exact first-install changelog
listener with a no-op so a fresh profile cannot open the changelog and request its remote font before the catch-all is
ready. A missing exact listener fails preparation. The tracked build output is never modified. Both the derived
artifact and its browser profile are removed after the run.
A future dedicated Webpack test build can replace this derivation with the following equivalent hook:
1. Define an API-base compile constant only when a hermetic-build flag is enabled.
2. Reject a hermetic API base whose parsed hostname is not `127.0.0.1`, `::1`, or `localhost`.
3. Use that constant from `Extensions/combined/src/config.js` for both background and content-script bundles.
4. Add the loopback host match to the generated test manifest only; never to release manifests.
5. Start the fake server before building so its allocated origin is compiled into the artifact, then launch the
persistent context.
The artifact smoke is part of `npm run test:e2e:systematic` and `npm run test:all`. Its colocated Jest tests cover the
shared catalog, runtime binding, capability validation, loopback guard, derived-artifact transformation, signal
collection, and cleanup behavior. The browser run rejects stale/current ownership mistakes, missed initialization,
duplicate activation, unexpected traffic, console errors, page errors, unhandled rejections, and a missing auxiliary
extension script.
## Authenticated live-build identity
The authenticated Brave suite is intentionally separate from this hermetic runner. `build:live:userscript` and
`build:live:extension` generate a fresh 32-character build ID, compile it into the page marker, and write the same ID to
the runtime's `live-build.json`. The live suite reads that file and requires an exact marker match before every shared
scenario. Rebuilding without reinstalling or reloading the runtime therefore fails even when the semantic version did
not change. See `Extensions/UserScript/e2e/live/README.md` for the complete preparation and safety contract.
+122
View File
@@ -0,0 +1,122 @@
function defaultNow() {
return Date.now();
}
function defaultSleep(milliseconds) {
return new Promise((resolve) => setTimeout(resolve, milliseconds));
}
function validateTiming({ intervalMs, stableForMs, timeoutMs }) {
for (const [name, value] of Object.entries({ intervalMs, stableForMs, timeoutMs })) {
if (!Number.isFinite(value) || value < 0) {
throw new TypeError(`${name} must be a non-negative finite number.`);
}
}
if (intervalMs === 0) throw new TypeError("intervalMs must be greater than zero.");
if (stableForMs > timeoutMs) throw new TypeError("stableForMs cannot exceed timeoutMs.");
}
function compactSamples(samples, limit = 12) {
const selected = samples.length <= limit ? samples : [...samples.slice(0, 3), ...samples.slice(-(limit - 3))];
return selected.map(({ elapsedMs, ok, value }) => ({ elapsedMs, ok, value }));
}
async function waitForStableInvariant({
intervalMs = 50,
isValid,
label,
now = defaultNow,
read,
sleep = defaultSleep,
stableForMs = 500,
timeoutMs = 5_000,
}) {
if (typeof read !== "function") throw new TypeError("read must be a function.");
if (typeof isValid !== "function") throw new TypeError("isValid must be a function.");
if (typeof now !== "function") throw new TypeError("now must be a function.");
if (typeof sleep !== "function") throw new TypeError("sleep must be a function.");
if (typeof label !== "string" || label.trim() === "") throw new TypeError("label must be a non-empty string.");
validateTiming({ intervalMs, stableForMs, timeoutMs });
const startedAt = now();
let firstValidMs = null;
let stableSince = null;
let invalidSamples = 0;
const samples = [];
while (true) {
const value = await read();
const sampledAt = now();
const elapsedMs = sampledAt - startedAt;
const ok = Boolean(await isValid(value));
samples.push({ elapsedMs, ok, value });
if (ok) {
if (firstValidMs === null) firstValidMs = elapsedMs;
if (stableSince === null) stableSince = sampledAt;
if (sampledAt - stableSince >= stableForMs) {
return {
elapsedMs,
firstValidMs,
invalidSamples,
sampleCount: samples.length,
stableForMs: sampledAt - stableSince,
value,
};
}
} else {
invalidSamples += 1;
stableSince = null;
}
if (elapsedMs >= timeoutMs) {
const error = new Error(
`${label} did not remain valid for ${stableForMs}ms within ${timeoutMs}ms. ` +
`Samples: ${JSON.stringify(compactSamples(samples))}`,
);
error.samples = samples;
throw error;
}
await sleep(Math.min(intervalMs, timeoutMs - elapsedMs));
}
}
async function assertInvariantContinuously({
durationMs = 1_000,
intervalMs = 50,
isValid,
label,
now = defaultNow,
read,
sleep = defaultSleep,
}) {
if (typeof read !== "function") throw new TypeError("read must be a function.");
if (typeof isValid !== "function") throw new TypeError("isValid must be a function.");
if (typeof label !== "string" || label.trim() === "") throw new TypeError("label must be a non-empty string.");
validateTiming({ intervalMs, stableForMs: durationMs, timeoutMs: durationMs });
const startedAt = now();
const samples = [];
while (true) {
const value = await read();
const elapsedMs = now() - startedAt;
const ok = Boolean(await isValid(value));
samples.push({ elapsedMs, ok, value });
if (!ok) {
const error = new Error(
`${label} became invalid after ${elapsedMs}ms. Samples: ${JSON.stringify(compactSamples(samples))}`,
);
error.samples = samples;
throw error;
}
if (elapsedMs >= durationMs) {
return { elapsedMs, sampleCount: samples.length, value };
}
await sleep(Math.min(intervalMs, durationMs - elapsedMs));
}
}
module.exports = {
assertInvariantContinuously,
waitForStableInvariant,
};
@@ -0,0 +1,92 @@
const { assertInvariantContinuously, waitForStableInvariant } = require("./continuous-invariants");
function createClock() {
let time = 0;
return {
now: () => time,
sleep: async (milliseconds) => {
time += milliseconds;
},
};
}
describe("continuous browser invariants", () => {
test("reports readiness latency and requires an uninterrupted stable window", async () => {
const clock = createClock();
const values = [false, false, true, true, false, true, true, true];
let index = 0;
const result = await waitForStableInvariant({
intervalMs: 100,
isValid: Boolean,
label: "ratio bar",
now: clock.now,
read: async () => values[Math.min(index++, values.length - 1)],
sleep: clock.sleep,
stableForMs: 200,
timeoutMs: 1_000,
});
expect(result).toMatchObject({
elapsedMs: 700,
firstValidMs: 200,
invalidSamples: 3,
sampleCount: 8,
stableForMs: 200,
value: true,
});
});
test("includes sampled phase evidence when stability never arrives", async () => {
const clock = createClock();
let phase = "missing";
await expect(
waitForStableInvariant({
intervalMs: 100,
isValid: (sample) => sample.phase === "ready",
label: "destination ownership",
now: clock.now,
read: async () => ({ phase: (phase = phase === "missing" ? "ready" : "missing") }),
sleep: clock.sleep,
stableForMs: 200,
timeoutMs: 400,
}),
).rejects.toThrow(/destination ownership.*Samples:.*phase/);
});
test("continuous assertion rejects an invalid first sample", async () => {
const clock = createClock();
let calls = 0;
await expect(
assertInvariantContinuously({
durationMs: 200,
intervalMs: 100,
isValid: Boolean,
label: "settled watch UI",
now: clock.now,
read: async () => calls++ > 0,
sleep: clock.sleep,
}),
).rejects.toThrow(/settled watch UI became invalid after 0ms/);
});
test.each([
["negative timeout", { timeoutMs: -1 }],
["zero interval", { intervalMs: 0 }],
["stable duration beyond timeout", { stableForMs: 101, timeoutMs: 100 }],
])("rejects %s", async (_name, timing) => {
await expect(
waitForStableInvariant({
intervalMs: 10,
isValid: Boolean,
label: "invalid timing",
read: async () => true,
stableForMs: 10,
timeoutMs: 100,
...timing,
}),
).rejects.toThrow();
});
});
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,544 @@
const fs = require("node:fs");
const { EventEmitter } = require("node:events");
const os = require("node:os");
const path = require("node:path");
const {
ARTIFACT_SMOKE_SCENARIO_ID,
ARTIFACT_WATCH_SPA_SCENARIO_ID,
ARTIFACT_WATCH_SPA_VOTE_SCENARIO_ID,
SHARED_ARTIFACT_SCENARIO_IDS,
assertLoopbackOrigin,
createPageSignalCollector,
isArtifactVoteHandshakeValid,
isSpaDestinationValid,
prepareHermeticExtensionArtifact,
readArtifactVoteHandshake,
runArtifactWatchRenderScenario,
runArtifactWatchSpaScenario,
runArtifactWatchSpaVoteScenario,
} = require("./hermetic-artifact-smoke");
const PRODUCTION_API_ORIGIN = "https://returnyoutubedislikeapi.com";
const temporaryDirectories = [];
function createExtensionFixture() {
const directory = fs.mkdtempSync(path.join(os.tmpdir(), "ryd-mv3-source-fixture-"));
temporaryDirectories.push(directory);
fs.writeFileSync(
path.join(directory, "manifest.json"),
JSON.stringify({ host_permissions: ["*://returnyoutubedislikeapi.com/*"], manifest_version: 3 }),
);
fs.writeFileSync(
path.join(directory, "ryd.background.js"),
`fetch("${PRODUCTION_API_ORIGIN}/register")\napi.runtime.onInstalled.addListener((details) => {\n maybeShowChangelog(details);\n});`,
);
fs.writeFileSync(path.join(directory, "ryd.content-script.js"), `fetch("${PRODUCTION_API_ORIGIN}/votes")`);
fs.writeFileSync(path.join(directory, "menu-fixer.js"), "document.documentElement.dataset.menuFixerLoaded = 'true';");
return directory;
}
afterEach(() => {
for (const directory of temporaryDirectories.splice(0)) {
fs.rmSync(directory, { force: true, recursive: true });
}
});
test("the artifact smoke is the shared watch-render scenario", () => {
expect(ARTIFACT_SMOKE_SCENARIO_ID).toBe("watch-render");
expect(ARTIFACT_WATCH_SPA_SCENARIO_ID).toBe("watch-spa-side-panel");
expect(ARTIFACT_WATCH_SPA_VOTE_SCENARIO_ID).toBe("watch-spa-dislike-activation");
expect(SHARED_ARTIFACT_SCENARIO_IDS).toEqual([
"watch-render",
"watch-spa-side-panel",
"watch-spa-dislike-activation",
]);
});
function validSpaSnapshot() {
const outgoing = {
barCount: 0,
containerCount: 0,
controlVideoIds: ["abcdefghijk"],
hidden: true,
present: true,
wrapperCount: 0,
};
return {
actionHostCount: 1,
barOwnedByDestination: true,
containerOwnedByDestination: true,
count: "65",
currentVideoId: "zyxwvutsrqp",
destinationBarCount: 1,
destinationContainerCount: 1,
destinationControlCount: 1,
destinationWrapperCount: 1,
fillRatio: 0.35,
globalBarCount: 1,
globalContainerCount: 1,
globalWrapperCount: 1,
insideOutgoing: { ...outgoing },
retainedBefore: { ...outgoing },
retainedDestination: { ...outgoing, controlVideoIds: ["zyxwvutsrqp"] },
tooltipText: "35 / 65",
urlVideoId: "zyxwvutsrqp",
visibleContainer: true,
visibleFill: true,
};
}
const ARTIFACT_USER_ID = "A".repeat(36);
function validVoteHandshake(change = {}) {
return {
confirmation: {
body: { solution: "AAAAAA==", userId: ARTIFACT_USER_ID, videoId: "zyxwvutsrqp" },
responded: true,
responseBody: true,
responseStatus: 200,
},
confirmationCount: 1,
expectedValue: -1,
expectedVideoId: "zyxwvutsrqp",
interactionCount: 2,
interactionPaths: ["/interact/vote", "/interact/confirmVote"],
sharedUserId: ARTIFACT_USER_ID,
vote: {
body: { userId: ARTIFACT_USER_ID, value: -1, videoId: "zyxwvutsrqp" },
},
voteCount: 1,
...change,
};
}
test.each(["http://127.0.0.1:43127", "http://localhost:43127", "http://[::1]:43127"])(
"accepts a loopback-only API origin: %s",
(origin) => {
expect(assertLoopbackOrigin(origin)).toBe(origin);
},
);
test.each(["https://returnyoutubedislikeapi.com", "https://api.example.test", "http://192.168.1.20:43127"])(
"rejects a non-loopback API origin: %s",
(origin) => {
expect(() => assertLoopbackOrigin(origin)).toThrow("Refusing to prepare a hermetic extension artifact");
},
);
test("redirects eager MV3 background traffic while leaving routed content-script traffic intact", () => {
const sourceDirectory = createExtensionFixture();
const prepared = prepareHermeticExtensionArtifact(sourceDirectory, "http://127.0.0.1:43127");
temporaryDirectories.push(prepared.temporaryRoot);
expect(prepared.replacements).toEqual({ "ryd.background.js": 1, firstInstallChangelogListener: 1 });
expect(prepared.routedBundles).toEqual(["ryd.content-script.js"]);
expect(fs.readFileSync(path.join(prepared.extensionDirectory, "ryd.background.js"), "utf8")).toContain(
"http://127.0.0.1:43127/register",
);
expect(fs.readFileSync(path.join(prepared.extensionDirectory, "ryd.background.js"), "utf8")).toContain(
"api.runtime.onInstalled.addListener(() => {});",
);
expect(fs.readFileSync(path.join(prepared.extensionDirectory, "ryd.content-script.js"), "utf8")).toContain(
`${PRODUCTION_API_ORIGIN}/votes`,
);
expect(fs.readFileSync(path.join(prepared.extensionDirectory, "menu-fixer.js"), "utf8")).toContain("menuFixerLoaded");
expect(JSON.parse(fs.readFileSync(path.join(prepared.extensionDirectory, "manifest.json"), "utf8"))).toMatchObject({
host_permissions: expect.arrayContaining(["http://127.0.0.1/*"]),
manifest_version: 3,
});
expect(fs.readFileSync(path.join(sourceDirectory, "ryd.background.js"), "utf8")).toContain(PRODUCTION_API_ORIGIN);
});
test("rejects an extension artifact whose injected auxiliary script was dropped by the build", () => {
const sourceDirectory = createExtensionFixture();
fs.rmSync(path.join(sourceDirectory, "menu-fixer.js"));
expect(() => prepareHermeticExtensionArtifact(sourceDirectory, "http://127.0.0.1:43127")).toThrow(
/missing menu-fixer\.js/,
);
});
test.each(["userscript", "extension"])("runs one shared artifact scenario contract for %s", async (runtime) => {
const events = [];
const adapter = {
assertNoPageSignals: jest.fn(async (scenarioId) => events.push(`signals:${scenarioId}`)),
close: jest.fn(async () => events.push("close")),
openWatch: jest.fn(async (videoId) => events.push(`open:${videoId}`)),
runtime,
start: jest.fn(async () => events.push("start")),
waitForWatchResult: jest.fn(async (videoId) => ({
count: "25",
fillVisible: true,
rateBarVisible: true,
videoId,
})),
};
await expect(runArtifactWatchRenderScenario(adapter, { videoId: "abcdefghijk" })).resolves.toMatchObject({
count: "25",
runtime,
scenarioId: "watch-render",
videoId: "abcdefghijk",
});
expect(events).toEqual(["start", "open:abcdefghijk", "signals:watch-render", "close"]);
});
test.each(["userscript", "extension"])("runs the same continuous A-to-B SPA contract for %s", async (runtime) => {
const events = [];
const adapter = {
assertNoPageSignals: jest.fn(async (scenarioId) => events.push(`signals:${scenarioId}`)),
assertSpaNetwork: jest.fn(async () => ({ fromVideoRequests: 1, interactionRequests: 0, toVideoRequests: 1 })),
close: jest.fn(async () => events.push("close")),
navigateSpaWatch: jest.fn(async () => ({
destination: { destinationReplaced: true },
outgoing: { beforeBarCount: 1 },
})),
openSpaWatch: jest.fn(async (videoId) => events.push(`open:${videoId}`)),
readSpaWatchSnapshot: jest.fn(async () => validSpaSnapshot()),
runtime,
start: jest.fn(async () => events.push("start")),
waitForWatchResult: jest.fn(async (videoId) => ({ count: "10", fillRatio: 0.9, videoId })),
};
await expect(
runArtifactWatchSpaScenario(adapter, {
intervalMs: 1,
stabilityDurationMs: 0,
stableForMs: 0,
timeoutMs: 1,
}),
).resolves.toMatchObject({
destination: { count: "65", fillRatio: 0.35, videoId: "zyxwvutsrqp" },
initial: { count: "10", fillRatio: 0.9, videoId: "abcdefghijk" },
readiness: { maxFirstValidMs: 1_000 },
runtime,
scenarioId: "watch-spa-side-panel",
traffic: { fromVideoRequests: 1, interactionRequests: 0, toVideoRequests: 1 },
});
expect(adapter.navigateSpaWatch).toHaveBeenCalledWith("abcdefghijk", "zyxwvutsrqp");
expect(events).toEqual(["start", "open:abcdefghijk", "signals:watch-spa-side-panel", "close"]);
});
test("recognizes only one ordered, successful destination dislike handshake", () => {
const records = [
{ method: "POST", pathname: "/puzzle/registration" },
{
body: { userId: ARTIFACT_USER_ID, value: -1, videoId: "zyxwvutsrqp" },
method: "POST",
pathname: "/interact/vote",
},
{
body: { solution: "AAAAAA==", userId: ARTIFACT_USER_ID, videoId: "zyxwvutsrqp" },
method: "POST",
pathname: "/interact/confirmVote",
respondedAt: 123,
responseBody: true,
responseStatus: 200,
},
];
const handshake = readArtifactVoteHandshake(records, 1, "zyxwvutsrqp", -1);
expect(handshake).toEqual(validVoteHandshake());
expect(isArtifactVoteHandshakeValid(handshake)).toBe(true);
});
test.each([
["duplicate listener requests", (value) => ({ ...value, interactionCount: 4, voteCount: 2, confirmationCount: 2 })],
["reversed request order", (value) => ({ ...value, interactionPaths: ["/interact/confirmVote", "/interact/vote"] })],
[
"the wrong destination video",
(value) => ({ ...value, vote: { body: { ...value.vote.body, videoId: "abcdefghijk" } } }),
],
["the wrong vote value", (value) => ({ ...value, vote: { body: { ...value.vote.body, value: 1 } } })],
[
"different vote and confirmation identities",
(value) => ({
...value,
confirmation: {
...value.confirmation,
body: { ...value.confirmation.body, userId: "B".repeat(36) },
},
}),
],
["a malformed identity", (value) => ({ ...value, sharedUserId: "short-user" })],
["a false confirmation", (value) => ({ ...value, confirmation: { ...value.confirmation, responseBody: false } })],
[
"a failed confirmation status",
(value) => ({ ...value, confirmation: { ...value.confirmation, responseStatus: 500 } }),
],
[
"a malformed proof solution",
(value) => ({
...value,
confirmation: { ...value.confirmation, body: { ...value.confirmation.body, solution: "AA==" } },
}),
],
["an extra vote field", (value) => ({ ...value, vote: { body: { ...value.vote.body, duplicate: true } } })],
])("rejects a post-SPA vote handshake with %s", (_label, mutate) => {
expect(isArtifactVoteHandshakeValid(mutate(validVoteHandshake()))).toBe(false);
});
test.each(["userscript", "extension"])(
"runs one post-SPA dislike activation and confirmation contract for %s",
async (runtime) => {
const events = [];
const adapter = {
activateSpaDislike: jest.fn(async (videoId) => ({
ariaPressedBefore: "false",
interactionStartIndex: 7,
videoId,
})),
assertNoPageSignals: jest.fn(async (scenarioId) => events.push(`signals:${scenarioId}`)),
assertSpaVoteNetwork: jest.fn(async () => ({ fromVideoRequests: 1, toVideoRequests: 1 })),
close: jest.fn(async () => events.push("close")),
navigateSpaWatch: jest.fn(async () => ({
destination: { destinationReplaced: true },
outgoing: { beforeBarCount: 1 },
})),
openSpaWatch: jest.fn(async (videoId) => events.push(`open:${videoId}`)),
readSpaVoteHandshake: jest.fn(async () => validVoteHandshake()),
readSpaWatchSnapshot: jest.fn(async () => validSpaSnapshot()),
runtime,
start: jest.fn(async () => events.push("start")),
waitForWatchResult: jest.fn(async (videoId) => ({ count: "10", fillRatio: 0.9, videoId })),
};
await expect(
runArtifactWatchSpaVoteScenario(adapter, {
handshakeStableForMs: 0,
handshakeTimeoutMs: 1,
intervalMs: 1,
stabilityDurationMs: 0,
stableForMs: 0,
timeoutMs: 1,
}),
).resolves.toMatchObject({
activation: { ariaPressedBefore: "false", videoId: "zyxwvutsrqp" },
destination: { count: "65", fillRatio: 0.35, videoId: "zyxwvutsrqp" },
handshake: {
confirmationRequests: 1,
confirmationStatus: 200,
confirmed: true,
interactionRequests: 2,
userId: ARTIFACT_USER_ID,
value: -1,
videoId: "zyxwvutsrqp",
voteRequests: 1,
},
runtime,
scenarioId: "watch-spa-dislike-activation",
traffic: { confirmationRequests: 1, interactionRequests: 2, voteRequests: 1 },
});
expect(adapter.activateSpaDislike).toHaveBeenCalledTimes(1);
expect(adapter.activateSpaDislike).toHaveBeenCalledWith("zyxwvutsrqp");
expect(adapter.readSpaVoteHandshake).toHaveBeenCalledWith(7, "zyxwvutsrqp", -1);
expect(adapter.assertSpaVoteNetwork).toHaveBeenCalledWith("abcdefghijk", "zyxwvutsrqp", 7);
expect(events).toEqual(["start", "open:abcdefghijk", "signals:watch-spa-dislike-activation", "close"]);
},
);
test("rejects a duplicated post-SPA vote chain and still closes the adapter", async () => {
const duplicatedHandshake = validVoteHandshake({
confirmationCount: 2,
interactionCount: 4,
interactionPaths: ["/interact/vote", "/interact/confirmVote", "/interact/vote", "/interact/confirmVote"],
voteCount: 2,
});
const adapter = {
activateSpaDislike: jest.fn(async (videoId) => ({ interactionStartIndex: 0, videoId })),
assertNoPageSignals: jest.fn(),
assertSpaVoteNetwork: jest.fn(),
close: jest.fn(),
navigateSpaWatch: jest.fn(async () => ({
destination: { destinationReplaced: true },
outgoing: { beforeBarCount: 1 },
})),
openSpaWatch: jest.fn(),
readSpaVoteHandshake: jest.fn(async () => duplicatedHandshake),
readSpaWatchSnapshot: jest.fn(async () => validSpaSnapshot()),
runtime: "userscript",
start: jest.fn(),
waitForWatchResult: jest.fn(async (videoId) => ({ count: "10", fillRatio: 0.9, videoId })),
};
await expect(
runArtifactWatchSpaVoteScenario(adapter, {
handshakeStableForMs: 0,
handshakeTimeoutMs: 1,
intervalMs: 1,
stabilityDurationMs: 0,
stableForMs: 0,
timeoutMs: 1,
}),
).rejects.toThrow("post-SPA dislike handshake did not remain valid");
expect(adapter.assertSpaVoteNetwork).not.toHaveBeenCalled();
expect(adapter.assertNoPageSignals).not.toHaveBeenCalled();
expect(adapter.close).toHaveBeenCalledTimes(1);
});
test("rejects a destination that becomes correct after the explicit latency budget", async () => {
const adapter = {
assertNoPageSignals: jest.fn(),
assertSpaNetwork: jest.fn(),
close: jest.fn(),
navigateSpaWatch: jest.fn(async () => ({
destination: { destinationReplaced: true },
outgoing: { beforeBarCount: 1 },
})),
openSpaWatch: jest.fn(),
readSpaWatchSnapshot: jest.fn(async () => {
await new Promise((resolve) => setTimeout(resolve, 5));
return validSpaSnapshot();
}),
runtime: "userscript",
start: jest.fn(),
waitForWatchResult: jest.fn(async (videoId) => ({ count: "10", fillRatio: 0.9, videoId })),
};
await expect(
runArtifactWatchSpaScenario(adapter, {
intervalMs: 1,
maxFirstValidMs: 1,
stabilityDurationMs: 0,
stableForMs: 0,
timeoutMs: 20,
}),
).rejects.toThrow(/first became valid after .*the budget is 1ms/);
expect(adapter.close).toHaveBeenCalledTimes(1);
});
test.each([
["duplicate global bar", { globalBarCount: 2 }],
["stale outgoing bar", { insideOutgoing: { ...validSpaSnapshot().insideOutgoing, barCount: 1 } }],
["wrong destination ratio", { fillRatio: 0.9 }],
["wrong destination count", { count: "10" }],
])("rejects a settled SPA snapshot with %s", (_label, change) => {
expect(
isSpaDestinationValid(
{ ...validSpaSnapshot(), ...change },
{
expectedCount: 65,
expectedRatio: 0.35,
fromVideoId: "abcdefghijk",
toVideoId: "zyxwvutsrqp",
},
),
).toBe(false);
});
test("always closes an artifact adapter after a failed visual assertion", async () => {
const adapter = {
assertNoPageSignals: jest.fn(),
close: jest.fn(),
openWatch: jest.fn(),
runtime: "extension",
start: jest.fn(),
waitForWatchResult: jest.fn(async () => ({
count: "25",
fillVisible: true,
rateBarVisible: false,
videoId: "abcdefghijk",
})),
};
await expect(runArtifactWatchRenderScenario(adapter, { videoId: "abcdefghijk" })).rejects.toThrow(
"extension did not render a visible watch ratio bar",
);
expect(adapter.close).toHaveBeenCalledTimes(1);
});
test("turns an otherwise successful artifact result into a failure when the page emitted an error", async () => {
const adapter = {
assertNoPageSignals: jest.fn(async () => {
throw new Error("unexpected browser signals");
}),
close: jest.fn(),
openWatch: jest.fn(),
runtime: "userscript",
start: jest.fn(),
waitForWatchResult: jest.fn(async (videoId) => ({
count: "25",
fillVisible: true,
rateBarVisible: true,
videoId,
})),
};
await expect(runArtifactWatchRenderScenario(adapter, { videoId: "abcdefghijk" })).rejects.toThrow(
"unexpected browser signals",
);
expect(adapter.close).toHaveBeenCalledTimes(1);
});
function createPageDouble() {
const page = new EventEmitter();
page.addInitScript = jest.fn(async () => {});
page.evaluate = jest.fn(async (callback) => callback());
page.exposeBinding = jest.fn(async (name, callback) => {
page.exposedBinding = { callback, name };
});
return page;
}
function consoleMessage(
type,
text,
location = { columnNumber: 5, lineNumber: 4, url: "https://www.youtube.com/watch" },
) {
return {
location: () => location,
text: () => text,
type: () => type,
};
}
test.each(["userscript", "extension"])(
"collects clean page signals through one shared %s collector",
async (runtime) => {
const page = createPageDouble();
const collector = await createPageSignalCollector(page, runtime);
page.emit("console", consoleMessage("warning", "harmless warning"));
await expect(collector.assertClean("watch-render")).resolves.toEqual({
consoleErrors: [],
pageErrors: [],
runtime,
unhandledRejections: [],
});
expect(page.exposeBinding).toHaveBeenCalledWith("__rydArtifactReportUnhandledRejection", expect.any(Function));
expect(page.addInitScript).toHaveBeenCalledTimes(1);
},
);
test.each([
["console error", (page) => page.emit("console", consoleMessage("error", "fixture exploded")), "fixture exploded"],
[
"failed browser resource load",
(page) => page.emit("console", consoleMessage("error", "Failed to load resource: net::ERR_FILE_NOT_FOUND")),
"ERR_FILE_NOT_FOUND",
],
[
"failed console assertion",
(page) => page.emit("console", consoleMessage("assert", "bad assertion")),
"bad assertion",
],
["page error", (page) => page.emit("pageerror", new TypeError("page exploded")), "page exploded"],
[
"unhandled rejection",
(page) =>
page.exposedBinding.callback(
{ frame: { url: () => "https://www.youtube.com/watch?v=abcdefghijk" } },
{ message: "promise exploded", name: "Error", stack: "Error: promise exploded" },
),
"promise exploded",
],
])("fails a successful scenario on %s with diagnostics", async (_label, emitSignal, expectedDiagnostic) => {
const page = createPageDouble();
const collector = await createPageSignalCollector(page, "userscript");
emitSignal(page);
await expect(collector.assertClean("watch-render")).rejects.toThrow(
new RegExp(`userscript emitted unexpected browser signals.*${expectedDiagnostic}`, "s"),
);
});
+162
View File
@@ -0,0 +1,162 @@
const assert = require("node:assert/strict");
function deepFreeze(value) {
if (!value || typeof value !== "object" || Object.isFrozen(value)) return value;
Object.values(value).forEach(deepFreeze);
return Object.freeze(value);
}
const LIVE_RUNTIME_PROFILES = deepFreeze({
extension: {
capabilities: {
backgroundVoteTransport: true,
credentialStore: "browser.storage",
ownsShortsDislikeControl: false,
shortsControlModel: "native-youtube",
shortsVisualModel: "native-pair",
},
buildMarkerAttribute: "data-ryd-extension-build",
markerAttribute: "data-ryd-extension-version",
runtime: "extension",
selectors: {
rateBar: "#ryd-bar",
rateBarContainer: "#ryd-bar-container",
shortsDislikeControl: null,
tooltipContent: "#ryd-dislike-tooltip",
tooltipTrigger: ".ryd-tooltip",
},
},
userscript: {
capabilities: {
backgroundVoteTransport: false,
credentialStore: "gm-storage",
ownsShortsDislikeControl: true,
shortsControlModel: "synthetic-owned",
shortsVisualModel: "strict-synthetic",
},
buildMarkerAttribute: "data-ryd-userscript-build",
markerAttribute: "data-ryd-userscript-version",
runtime: "userscript",
selectors: {
rateBar: "#return-youtube-dislike-bar",
rateBarContainer: "#return-youtube-dislike-bar-container",
shortsDislikeControl: "[data-ryd-synthetic-shorts-dislike]",
tooltipContent: ".ryd-tooltip-label",
tooltipTrigger: ".ryd-tooltip",
},
},
});
function requireDriverMethod(driver, method, scenarioId = null) {
if (typeof driver?.[method] === "function") return;
const scenario = scenarioId ? ` for shared scenario ${scenarioId}` : "";
throw new TypeError(`The ${driver ? "live driver" : "missing driver"}${scenario} must implement ${method}().`);
}
function assertRuntimeArgument(value, expected, label) {
if (value === undefined) return;
assert.equal(value, expected, `${label} does not match the selected live runtime adapter.`);
}
function createRuntimeBoundDriver(driver, runtime, expectedVersion, expectedBuildId) {
return new Proxy(driver, {
get(target, property, receiver) {
if (property === "assertRuntime") {
return (requestedRuntime, requestedVersion, requestedBuildId) => {
assertRuntimeArgument(requestedRuntime, runtime, "The asserted runtime");
assertRuntimeArgument(requestedVersion, expectedVersion, "The asserted runtime version");
assertRuntimeArgument(requestedBuildId, expectedBuildId, "The asserted live build ID");
requireDriverMethod(target, "assertRuntime");
return target.assertRuntime(runtime, expectedVersion, expectedBuildId);
};
}
if (property === "assertCurrentShortsControl") {
return (videoId, requestedRuntime) => {
assertRuntimeArgument(requestedRuntime, runtime, "The Shorts-control runtime");
requireDriverMethod(target, "assertCurrentShortsControl");
return target.assertCurrentShortsControl(videoId, runtime);
};
}
if (property === "captureWatchRatioVisual") {
return (requestedRuntime, screenshotPath, options) => {
assertRuntimeArgument(requestedRuntime, runtime, "The watch-visual runtime");
requireDriverMethod(target, "captureWatchRatioVisual");
return options === undefined
? target.captureWatchRatioVisual(runtime, screenshotPath)
: target.captureWatchRatioVisual(runtime, screenshotPath, options);
};
}
if (property === "captureReactionStateVisual") {
return (request) => {
assertRuntimeArgument(request?.runtime, runtime, "The reaction-visual runtime");
requireDriverMethod(target, "captureReactionStateVisual");
return target.captureReactionStateVisual({ ...request, runtime });
};
}
const value = Reflect.get(target, property, receiver);
return typeof value === "function" ? value.bind(target) : value;
},
});
}
class LiveRuntimeAdapter {
constructor({ driver, expectedBuildId, expectedVersion, runtime }) {
const profile = LIVE_RUNTIME_PROFILES[runtime];
if (!profile) throw new TypeError(`Unsupported live runtime adapter: ${runtime}`);
if (!driver || (typeof driver !== "object" && typeof driver !== "function")) {
throw new TypeError("A live YouTube driver is required.");
}
if (typeof expectedVersion !== "string" || expectedVersion.trim() === "") {
throw new TypeError("A non-empty expected runtime version is required.");
}
if (!/^[a-f0-9]{32}$/.test(expectedBuildId)) {
throw new TypeError("The expected live build ID must be a 32-character lowercase hexadecimal value.");
}
this.capabilities = profile.capabilities;
this.driver = createRuntimeBoundDriver(driver, runtime, expectedVersion, expectedBuildId);
this.expectedBuildId = expectedBuildId;
this.expectedVersion = expectedVersion;
this.profile = profile;
this.runtime = runtime;
this.selectors = profile.selectors;
}
createScenarioOptions(options = {}) {
if (!options || typeof options !== "object" || Array.isArray(options)) {
throw new TypeError("Shared live scenario options must be an object.");
}
assertRuntimeArgument(options.runtime, this.runtime, "The configured scenario runtime");
assertRuntimeArgument(options.expectedBuildId, this.expectedBuildId, "The configured live build ID");
assertRuntimeArgument(options.expectedVersion, this.expectedVersion, "The configured scenario runtime version");
return {
...options,
expectedBuildId: this.expectedBuildId,
expectedVersion: this.expectedVersion,
runtime: this.runtime,
};
}
assertDriverMethods(methods, scenarioId) {
methods.forEach((method) => requireDriverMethod(this.driver, method, scenarioId));
}
}
function createExtensionLiveRuntimeAdapter(options) {
return new LiveRuntimeAdapter({ ...options, runtime: "extension" });
}
function createUserscriptLiveRuntimeAdapter(options) {
return new LiveRuntimeAdapter({ ...options, runtime: "userscript" });
}
module.exports = {
LIVE_RUNTIME_PROFILES,
LiveRuntimeAdapter,
createExtensionLiveRuntimeAdapter,
createUserscriptLiveRuntimeAdapter,
};
+199
View File
@@ -0,0 +1,199 @@
const defaultImplementations = require("../UserScript/e2e/live/live-scenarios");
const COMMON_PRECONDITION_METHODS = ["assertRuntime", "assertSignedIn"];
const SHARED_LIVE_SCENARIOS = Object.freeze([
{
driverMethods: [
...COMMON_PRECONDITION_METHODS,
"assertCurrentShortsControl",
"navigateFromColdChannelToShort",
"navigateToNextShort",
"pausePlayback",
"withNoProductionInteractions",
],
id: "channel-shorts-navigation",
implementation: "runChannelShortsNavigationScenario",
},
{
driverMethods: [
...COMMON_PRECONDITION_METHODS,
"navigateFromColdChannelToWatch",
"waitForDislikeText",
"withNoProductionInteractions",
],
id: "channel-watch-navigation",
implementation: "runChannelWatchNavigationScenario",
},
{
driverMethods: [
...COMMON_PRECONDITION_METHODS,
"openPlaylist",
"waitForDislikeText",
"withNoProductionInteractions",
],
id: "watch-render",
implementation: "runWatchRenderScenario",
},
{
driverMethods: [
...COMMON_PRECONDITION_METHODS,
"openPlaylist",
"reload",
"waitForDislikeText",
"withNoProductionInteractions",
],
id: "reload",
implementation: "runReloadScenario",
},
{
driverMethods: [
...COMMON_PRECONDITION_METHODS,
"navigateWithinPlaylist",
"openPlaylist",
"waitForDislikeText",
"withNoProductionInteractions",
],
id: "spa-navigation",
implementation: "runSpaNavigationScenario",
},
{
driverMethods: [
...COMMON_PRECONDITION_METHODS,
"assertCurrentVideo",
"captureWatchRatioVisual",
"navigateToRelatedWatch",
"openWatch",
"soakWatchRatioVisual",
"withNoProductionInteractions",
],
id: "sidebar-navigation-stress",
implementation: "runSidebarStressScenario",
},
{
driverMethods: [...COMMON_PRECONDITION_METHODS, "openShort", "waitForDislikeText", "withNoProductionInteractions"],
id: "shorts-render",
implementation: "runShortsRenderScenario",
},
{
driverMethods: [
...COMMON_PRECONDITION_METHODS,
"assertCurrentShortsControl",
"captureWatchRatioVisual",
"openWatch",
"readViewportSize",
"setViewportSize",
"waitForDislikeText",
"withNoProductionInteractions",
],
driverMethodsByCapability: {
"native-pair": ["captureNativeShortsVisual", "openShort"],
"strict-synthetic": ["captureSyntheticShortsVisual", "openShort"],
},
id: "responsive-visual",
implementation: "runResponsiveVisualScenario",
},
{
driverMethods: [
...COMMON_PRECONDITION_METHODS,
"assertCurrentVideo",
"captureReactionStateVisual",
"clickAction",
"openShort",
"openWatch",
"readReactionState",
"waitForDislikeText",
"waitForReactionState",
],
id: "reaction-matrix",
implementation: "runProductionReactionMatrixScenario",
},
]);
const SHARED_LIVE_SCENARIO_IDS = Object.freeze(SHARED_LIVE_SCENARIOS.map(({ id }) => id));
const SCENARIOS_BY_ID = new Map(SHARED_LIVE_SCENARIOS.map((scenario) => [scenario.id, scenario]));
function scenarioDriverMethods(scenario, adapter) {
const capabilityMethods = scenario.driverMethodsByCapability?.[adapter.capabilities.shortsVisualModel] ?? [];
return [...new Set([...scenario.driverMethods, ...capabilityMethods])];
}
function assertSharedLiveScenarioAdapter(adapter, scenarioIds = SHARED_LIVE_SCENARIO_IDS) {
if (
!adapter ||
typeof adapter.createScenarioOptions !== "function" ||
typeof adapter.assertDriverMethods !== "function"
) {
throw new TypeError("A LiveRuntimeAdapter is required to run shared live scenarios.");
}
scenarioIds.forEach((scenarioId) => {
const scenario = SCENARIOS_BY_ID.get(scenarioId);
if (!scenario) throw new TypeError(`Unknown shared live scenario: ${scenarioId}`);
adapter.assertDriverMethods(scenarioDriverMethods(scenario, adapter), scenarioId);
});
return [...scenarioIds];
}
function requireService(services, name, scenarioId) {
if (typeof services?.[name] === "function") return services[name];
throw new TypeError(`Shared scenario ${scenarioId} requires services.${name}().`);
}
function requireImplementation(implementations, scenario) {
const implementation = implementations?.[scenario.implementation];
if (typeof implementation !== "function") {
throw new TypeError(`Shared scenario ${scenario.id} has no ${scenario.implementation}() implementation.`);
}
return implementation;
}
function createSharedLiveScenarioRunner({ implementations = defaultImplementations } = {}) {
async function run(adapter, scenarioId, options = {}, services = {}) {
const scenario = SCENARIOS_BY_ID.get(scenarioId);
if (!scenario) throw new TypeError(`Unknown shared live scenario: ${scenarioId}`);
assertSharedLiveScenarioAdapter(adapter, [scenarioId]);
const implementation = requireImplementation(implementations, scenario);
const scenarioOptions = adapter.createScenarioOptions(options);
if (scenarioId === "responsive-visual") {
return implementation(adapter.driver, scenarioOptions, services.visualOptions);
}
if (scenarioId === "sidebar-navigation-stress") {
return implementation(adapter.driver, scenarioOptions, services.sidebarOptions);
}
if (scenarioId === "reaction-matrix") {
return implementation(
adapter.driver,
scenarioOptions,
requireService(services, "createRecorder", scenarioId),
requireService(services, "consumeVoteApproval", scenarioId),
services.visualOptions,
);
}
return implementation(adapter.driver, scenarioOptions);
}
async function runAll(adapter, options = {}, services = {}, scenarioIds = SHARED_LIVE_SCENARIO_IDS) {
assertSharedLiveScenarioAdapter(adapter, scenarioIds);
const results = [];
for (const scenarioId of scenarioIds) {
results.push({ id: scenarioId, result: await run(adapter, scenarioId, options, services) });
}
return results;
}
return Object.freeze({
ids: SHARED_LIVE_SCENARIO_IDS,
run,
runAll,
validateAdapter: assertSharedLiveScenarioAdapter,
});
}
module.exports = {
SHARED_LIVE_SCENARIO_IDS,
SHARED_LIVE_SCENARIOS,
assertSharedLiveScenarioAdapter,
createSharedLiveScenarioRunner,
};
@@ -0,0 +1,252 @@
const {
LIVE_RUNTIME_PROFILES,
createExtensionLiveRuntimeAdapter,
createUserscriptLiveRuntimeAdapter,
} = require("./live-runtime-adapter");
const {
SHARED_LIVE_SCENARIO_IDS,
assertSharedLiveScenarioAdapter,
createSharedLiveScenarioRunner,
} = require("./shared-live-scenarios");
const EXPECTED_SCENARIO_IDS = [
"channel-shorts-navigation",
"channel-watch-navigation",
"watch-render",
"reload",
"spa-navigation",
"sidebar-navigation-stress",
"shorts-render",
"responsive-visual",
"reaction-matrix",
];
const EXPECTED_BUILD_ID = "0123456789abcdef0123456789abcdef";
const ALL_DRIVER_METHODS = [
"assertCurrentShortsControl",
"assertCurrentVideo",
"assertRuntime",
"assertSignedIn",
"captureReactionStateVisual",
"captureNativeShortsVisual",
"captureSyntheticShortsVisual",
"captureWatchRatioVisual",
"clickAction",
"navigateFromColdChannelToShort",
"navigateFromColdChannelToWatch",
"navigateToNextShort",
"navigateToRelatedWatch",
"navigateWithinPlaylist",
"openPlaylist",
"openShort",
"openWatch",
"pausePlayback",
"readReactionState",
"readViewportSize",
"reload",
"setViewportSize",
"soakWatchRatioVisual",
"waitForDislikeText",
"waitForReactionState",
"withNoProductionInteractions",
];
function createDriver(overrides = {}) {
return {
...Object.fromEntries(ALL_DRIVER_METHODS.map((method) => [method, jest.fn()])),
...overrides,
};
}
function createAdapter(runtime, driver = createDriver(), expectedBuildId = EXPECTED_BUILD_ID) {
const options = { driver, expectedBuildId, expectedVersion: runtime === "userscript" ? "3.2.0" : "4.0.4" };
return runtime === "userscript"
? createUserscriptLiveRuntimeAdapter(options)
: createExtensionLiveRuntimeAdapter(options);
}
function createImplementations(events) {
const implementationNames = [
"runChannelShortsNavigationScenario",
"runChannelWatchNavigationScenario",
"runWatchRenderScenario",
"runReloadScenario",
"runSpaNavigationScenario",
"runSidebarStressScenario",
"runShortsRenderScenario",
"runResponsiveVisualScenario",
"runProductionReactionMatrixScenario",
];
return Object.fromEntries(
implementationNames.map((name) => [
name,
jest.fn(async (_driver, options) => {
events.push({ implementation: name, runtime: options.runtime });
return `${options.runtime}:${name}`;
}),
]),
);
}
describe("shared live runtime profiles", () => {
test("preserves each runtime's selectors and control-ownership capabilities", () => {
expect(LIVE_RUNTIME_PROFILES.userscript).toMatchObject({
capabilities: {
backgroundVoteTransport: false,
credentialStore: "gm-storage",
ownsShortsDislikeControl: true,
shortsControlModel: "synthetic-owned",
shortsVisualModel: "strict-synthetic",
},
buildMarkerAttribute: "data-ryd-userscript-build",
markerAttribute: "data-ryd-userscript-version",
selectors: {
rateBar: "#return-youtube-dislike-bar",
rateBarContainer: "#return-youtube-dislike-bar-container",
shortsDislikeControl: "[data-ryd-synthetic-shorts-dislike]",
},
});
expect(LIVE_RUNTIME_PROFILES.extension).toMatchObject({
capabilities: {
backgroundVoteTransport: true,
credentialStore: "browser.storage",
ownsShortsDislikeControl: false,
shortsControlModel: "native-youtube",
shortsVisualModel: "native-pair",
},
buildMarkerAttribute: "data-ryd-extension-build",
markerAttribute: "data-ryd-extension-version",
selectors: {
rateBar: "#ryd-bar",
rateBarContainer: "#ryd-bar-container",
shortsDislikeControl: null,
},
});
expect(Object.isFrozen(LIVE_RUNTIME_PROFILES.userscript.capabilities)).toBe(true);
expect(Object.isFrozen(LIVE_RUNTIME_PROFILES.extension.selectors)).toBe(true);
});
test.each(["userscript", "extension"])("binds runtime-sensitive driver calls for %s", async (runtime) => {
const driver = createDriver();
const adapter = createAdapter(runtime, driver);
await adapter.driver.assertRuntime(runtime, adapter.expectedVersion, adapter.expectedBuildId);
await adapter.driver.assertCurrentShortsControl("abcdefghijk", runtime);
await adapter.driver.captureWatchRatioVisual(runtime, "watch.png");
await adapter.driver.captureReactionStateVisual({
expectedState: "neutral",
isShort: false,
runtime,
screenshotPath: "reaction.png",
videoId: "abcdefghijk",
});
expect(driver.assertRuntime).toHaveBeenCalledWith(runtime, adapter.expectedVersion, adapter.expectedBuildId);
expect(driver.assertCurrentShortsControl).toHaveBeenCalledWith("abcdefghijk", runtime);
expect(driver.captureWatchRatioVisual).toHaveBeenCalledWith(runtime, "watch.png");
expect(driver.captureReactionStateVisual).toHaveBeenCalledWith(
expect.objectContaining({ runtime, videoId: "abcdefghijk" }),
);
});
test("rejects scenario options and calls for another runtime", async () => {
const adapter = createAdapter("userscript");
expect(() => adapter.createScenarioOptions({ runtime: "extension" })).toThrow(
"The configured scenario runtime does not match",
);
expect(() => adapter.driver.assertRuntime("extension", adapter.expectedVersion)).toThrow(
"The asserted runtime does not match",
);
});
test.each([undefined, "", "stale", "A".repeat(32)])(
"rejects a missing or malformed exact live build ID: %p",
(expectedBuildId) => {
expect(() =>
createUserscriptLiveRuntimeAdapter({
driver: createDriver(),
expectedBuildId,
expectedVersion: "3.2.0",
}),
).toThrow("expected live build ID must be a 32-character lowercase hexadecimal value");
},
);
test("binds the exact generated live build ID into runtime checks", async () => {
const driver = createDriver();
const expectedBuildId = "0123456789abcdef0123456789abcdef";
const adapter = createAdapter("userscript", driver, expectedBuildId);
await adapter.driver.assertRuntime("userscript", adapter.expectedVersion, expectedBuildId);
expect(driver.assertRuntime).toHaveBeenCalledWith("userscript", adapter.expectedVersion, expectedBuildId);
expect(adapter.createScenarioOptions()).toMatchObject({ expectedBuildId });
expect(() => adapter.driver.assertRuntime("userscript", adapter.expectedVersion, "f".repeat(32))).toThrow(
"live build ID does not match",
);
});
});
describe("shared live scenario contract", () => {
test("publishes one stable ordered scenario ID list", () => {
expect(SHARED_LIVE_SCENARIO_IDS).toEqual(EXPECTED_SCENARIO_IDS);
expect(Object.isFrozen(SHARED_LIVE_SCENARIO_IDS)).toBe(true);
});
test.each(["userscript", "extension"])("validates the complete contract for %s", (runtime) => {
const adapter = createAdapter(runtime);
expect(assertSharedLiveScenarioAdapter(adapter)).toEqual(EXPECTED_SCENARIO_IDS);
});
test("requires each runtime's Shorts visual model from the shared responsive scenario", () => {
const driver = createDriver();
delete driver.captureSyntheticShortsVisual;
expect(() => assertSharedLiveScenarioAdapter(createAdapter("userscript", driver), ["responsive-visual"])).toThrow(
"must implement captureSyntheticShortsVisual()",
);
expect(assertSharedLiveScenarioAdapter(createAdapter("extension", driver), ["responsive-visual"])).toEqual([
"responsive-visual",
]);
const extensionDriver = createDriver();
delete extensionDriver.captureNativeShortsVisual;
expect(() =>
assertSharedLiveScenarioAdapter(createAdapter("extension", extensionDriver), ["responsive-visual"]),
).toThrow("must implement captureNativeShortsVisual()");
});
test("executes the same scenario IDs through both runtime adapters", async () => {
const events = [];
const implementations = createImplementations(events);
const runner = createSharedLiveScenarioRunner({ implementations });
const services = {
consumeVoteApproval: jest.fn(),
createRecorder: jest.fn(),
visualOptions: { outputDirectory: "evidence" },
sidebarOptions: { outputDirectory: "sidebar-evidence" },
};
const userscriptResults = await runner.runAll(createAdapter("userscript"), {}, services);
const extensionResults = await runner.runAll(createAdapter("extension"), {}, services);
expect(userscriptResults.map(({ id }) => id)).toEqual(EXPECTED_SCENARIO_IDS);
expect(extensionResults.map(({ id }) => id)).toEqual(EXPECTED_SCENARIO_IDS);
expect(events.map(({ runtime }) => runtime)).toEqual([
...EXPECTED_SCENARIO_IDS.map(() => "userscript"),
...EXPECTED_SCENARIO_IDS.map(() => "extension"),
]);
expect(Object.values(implementations).every((implementation) => implementation.mock.calls.length === 2)).toBe(true);
});
test("rejects unknown IDs before invoking a scenario implementation", async () => {
const implementations = createImplementations([]);
const runner = createSharedLiveScenarioRunner({ implementations });
await expect(runner.run(createAdapter("userscript"), "not-a-scenario")).rejects.toThrow(
"Unknown shared live scenario: not-a-scenario",
);
expect(Object.values(implementations).every((implementation) => implementation.mock.calls.length === 0)).toBe(true);
});
});
+113
View File
@@ -0,0 +1,113 @@
const { NAVIGATION_MATRIX } = require("../UserScript/e2e/navigation-matrix");
const { SHARED_LIVE_SCENARIO_IDS } = require("./shared-live-scenarios");
const REQUIRED_SURFACE_PAIRS = ["watch->watch", "watch->shorts", "shorts->watch", "shorts->shorts"];
const REQUIRED_TRIGGERS = [
"autoplay-ended",
"direct-link",
"dom-corruption",
"dom-replacement",
"history-back-forward",
"next-control",
"sidebar-link",
];
const REQUIRED_DOM_FEATURES = [
"active-reel-switch",
"connected-collapsed-rate-bar",
"connected-hidden-rate-bar",
"delayed-hydration",
"hidden-outgoing-first",
"legacy-segmented-duplicate-ids",
"malformed-rate-bar",
"no-useful-control-mutation",
"positive-size-offscreen-outgoing-first",
"prune-current-bar",
"replace-controls",
"replace-current-action-container",
"reuse-exact-control-nodes",
"retain-hidden-outgoing",
"same-current-root",
"stripped-rate-bar-wrapper-class",
];
const REQUIRED_TIMINGS = [
"destination-count-gated",
"finish-before-hydration",
"no-navigate-finish",
"no-navigation-event",
"navigate-finish",
"same-video",
"settled",
];
const REQUIRED_SHARED_LIVE_SCENARIOS = [
"channel-shorts-navigation",
"channel-watch-navigation",
"watch-render",
"reload",
"spa-navigation",
"sidebar-navigation-stress",
"shorts-render",
"responsive-visual",
"reaction-matrix",
];
function collectCoverage(axis) {
return new Set(
NAVIGATION_MATRIX.flatMap((scenario) => {
const value = scenario.coverage[axis];
return Array.isArray(value) ? value : [value];
}),
);
}
describe("systematic browser coverage contract", () => {
test("keeps every declarative scenario uniquely identified and completely classified", () => {
expect(new Set(NAVIGATION_MATRIX.map(({ id }) => id)).size).toBe(NAVIGATION_MATRIX.length);
for (const scenario of NAVIGATION_MATRIX) {
expect(scenario).toEqual(
expect.objectContaining({
coverage: expect.objectContaining({
destination: expect.any(String),
dom: expect.any(Array),
origin: expect.any(String),
timing: expect.any(Array),
trigger: expect.any(String),
width: expect.any(String),
}),
destination: expect.objectContaining({ counts: expect.any(Object), kind: expect.any(String) }),
id: expect.any(String),
origin: expect.objectContaining({ counts: expect.any(Object), kind: expect.any(String) }),
viewport: expect.objectContaining({ height: expect.any(Number), width: expect.any(Number) }),
}),
);
}
});
test("covers every watch and Shorts direction and every required navigation trigger", () => {
const surfacePairs = new Set(
NAVIGATION_MATRIX.map(({ coverage }) => `${coverage.origin}->${coverage.destination}`),
);
REQUIRED_SURFACE_PAIRS.forEach((pair) => expect(surfacePairs).toContain(pair));
const triggers = collectCoverage("trigger");
REQUIRED_TRIGGERS.forEach((trigger) => expect(triggers).toContain(trigger));
});
test("keeps the retained, replacement, hydration, pruning, and event-order stress cells", () => {
const domFeatures = collectCoverage("dom");
REQUIRED_DOM_FEATURES.forEach((feature) => expect(domFeatures).toContain(feature));
const timings = collectCoverage("timing");
REQUIRED_TIMINGS.forEach((timing) => expect(timings).toContain(timing));
});
test("uses distinguishable ratios whenever a scenario changes videos", () => {
for (const scenario of NAVIGATION_MATRIX.filter(
({ destination, origin }) => destination.videoId !== origin.videoId,
)) {
const ratio = ({ likes, dislikes }) => likes / (likes + dislikes);
expect(ratio(scenario.origin.counts)).not.toBe(ratio(scenario.destination.counts));
}
});
test("keeps the same authenticated scenario catalog for both runtime adapters", () => {
expect(SHARED_LIVE_SCENARIO_IDS).toEqual(REQUIRED_SHARED_LIVE_SCENARIOS);
});
});