Prepare 4.0.5 Firefox update and Shorts fixes

Add Firefox data consent, repair contributor sign-in, and introduce optional Hide clutter buttons. Harden video navigation, voting, and action layouts with shared browser regression coverage and reproducible release packaging.
This commit is contained in:
Anarios committed 2026-09-06 12:51:12 +02:00
1 parent 3657de9b2c
commit e500088e65
196 files changed
+39706 -2694

No files matched your search

+54 -6
View File
@@ -23,13 +23,19 @@ extension-specific stale-response race executable against the generated MV3 arti
- `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.
- `extension-startup-resilience.e2e.js` leaves `/configs/selectors` pending forever and requires the manifest-injected
content script to initialize Watch from its bundled selectors within the startup budget. This prevents an optional
remote selector refresh from blocking every listener, count, and ratio bar in the extension.
```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.
artifact in an isolated persistent Chromium profile, and the smoke requires its service worker to start. The mobile
extension coverage launches that profile with an Android user agent, mobile metrics, and touch enabled; its Shorts
vote uses a real touchscreen tap and holds the exact one-vote/one-confirmation invariant after both touch and synthetic
click events have fired.
## Extension API safety
@@ -44,8 +50,25 @@ left byte-for-byte intact: Chromium blocks HTTPS-page content scripts from reach
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.
ready. A launch-time host resolver rule also denies every non-loopback hostname, closing the worker-startup window
before Playwright routing exists. 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.
The derived background bundle begins with a test-only runtime probe before any production bundle code. It records
worker exceptions, unhandled rejections, failed console assertions, errors, and warnings both in the worker and at the
loopback server. Every extension scenario checks this shared page-and-worker signal collector, including startup
signals that a listener attached after service-worker discovery would miss. A negative-control browser test rejects a
Promise inside the real MV3 worker and requires the guard to detect it. Both fake API transports validate CORS
preflights against the declared endpoint/method contract; an OPTIONS request to any other path is recorded and failed.
The extension build emits a root-only receipt with its mode and a deterministic hash of production inputs. The artifact
verifier requires a fresh production receipt, rejects inline development source maps, and SHA-256 compares each browser
bundle mirror with Webpack's root output. The direct extension Playwright command runs this verifier first, preventing
the suite from silently exercising a stale or watch-generated `dist/chrome` artifact.
Setting `RYD_EXTENSION_ARTIFACT` to another directory is rejected by the Playwright global setup unless
`RYD_E2E_ALLOW_CUSTOM_EXTENSION_ARTIFACT=1` is also set. Use that explicit bypass only for an intentional custom or
negative-control fixture; the selected directory still has to pass standalone production MV3 validation.
A future dedicated Webpack test build can replace this derivation with the following equivalent hook:
@@ -60,12 +83,37 @@ The artifact smoke is part of `npm run test:e2e:systematic` and `npm run test:al
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.
extension script. Both Playwright runtime suites also include a negative render oracle that substitutes a no-op runtime
artifact and requires the owned Dislike count and ratio bar assertions to fail, preventing the fixtures themselves from
creating a false green when either generated runtime stops executing.
## Authenticated live-build identity
The authenticated Brave suite is intentionally separate from this hermetic runner. `build:live:userscript` and
The authenticated Chromium 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.
not change. Its approved reaction phase additionally proves that a real playlist SPA transition from A to B produces
no interaction request by itself, then requires the reaction and cleanup handshakes to target B exactly, return 2xx,
confirm with literal `true`, and restore the initial reaction. See `Extensions/UserScript/e2e/live/README.md` for the
complete preparation and safety contract.
## Firefox changelog lifecycle
After a production build, run the native temporary-addon regression with the pinned Node runtime:
```powershell
$env:RYD_FIREFOX_CHANGELOG_LIFECYCLE = "1"
$env:RYD_FIREFOX_CHANGELOG_EXPECT_IMMEDIATE = "1"
node Extensions/e2e/firefox-consent-smoke.js
```
This uses an owned Firefox profile and a loopback API. A probe added only to the derived test extension records actual
`runtime.onInstalled` events and background restarts. The regression checks fresh installation, removal/reinstallation,
temporary reload with an unseen or pending changelog, and suppression after the changelog has been shown. It preserves
the production artifact and writes event, storage, and tab evidence to `test-results/firefox-consent-*/result.json`.
Unset both environment variables before running the packaged-install matrix. Omit only
`RYD_FIREFOX_CHANGELOG_EXPECT_IMMEDIATE` when recording the behavior of an older artifact: that mode records the
lifecycle outcome and does not require the temporary-reload fix. `ryd.background-changelog.spec.js` also covers normal
update deferral until browser startup and retry after tab creation fails.
+111
View File
@@ -0,0 +1,111 @@
const REACTION_GROUP_ID = "reactions";
const MORE_BUTTON_ID = "more";
const ACTION_GAP_PX = 8;
const REACTION_GROUP_WIDTH_PX = 232;
const MORE_BUTTON_WIDTH_PX = 48;
const OPTIONAL_ACTIONS = Object.freeze([
Object.freeze({ id: "share", label: "Share", width: 104 }),
Object.freeze({ id: "save", label: "Save", width: 88 }),
Object.freeze({ id: "thanks", label: "Thanks", width: 104 }),
Object.freeze({ id: "download", label: "Download", width: 112 }),
]);
const ACTION_OVERFLOW_SCENARIOS = Object.freeze([
Object.freeze({
availableWidth: 760,
expectedOverflow: Object.freeze([]),
expectedTopLevel: Object.freeze(["share", "save", "thanks", "download"]),
hideClutterButtons: false,
id: "roomy-keeps-every-optional-action",
}),
Object.freeze({
availableWidth: 680,
expectedOverflow: Object.freeze(["download"]),
expectedTopLevel: Object.freeze(["share", "save", "thanks"]),
hideClutterButtons: false,
id: "one-button-overflow-hides-one",
}),
Object.freeze({
availableWidth: 560,
expectedOverflow: Object.freeze(["thanks", "download"]),
expectedTopLevel: Object.freeze(["share", "save"]),
hideClutterButtons: false,
id: "two-button-overflow-hides-two",
}),
Object.freeze({
availableWidth: 450,
expectedOverflow: Object.freeze(["save", "thanks", "download"]),
expectedTopLevel: Object.freeze(["share"]),
hideClutterButtons: false,
id: "three-button-overflow-hides-three",
}),
Object.freeze({
availableWidth: 375,
expectedOverflow: Object.freeze(["share", "save", "thanks", "download"]),
expectedTopLevel: Object.freeze([]),
hideClutterButtons: false,
id: "narrow-action-allocation-overflows-every-optional-action",
}),
Object.freeze({
availableWidth: 760,
expectedOverflow: Object.freeze(["share", "save", "thanks", "download"]),
expectedTopLevel: Object.freeze([]),
hideClutterButtons: true,
id: "hide-clutter-keeps-only-reactions",
}),
]);
function requiredActionRowWidth(topLevelActionIds) {
const widths = topLevelActionIds.map((id) => {
const action = OPTIONAL_ACTIONS.find((candidate) => candidate.id === id);
if (!action) throw new TypeError(`Unknown optional action: ${id}`);
return action.width;
});
const itemCount = 2 + topLevelActionIds.length;
return (
REACTION_GROUP_WIDTH_PX +
MORE_BUTTON_WIDTH_PX +
widths.reduce((total, width) => total + width, 0) +
ACTION_GAP_PX * (itemCount - 1)
);
}
function assertActionOverflowScenario(snapshot, scenario, assert) {
assert.deepEqual(snapshot.topLevelActionIds, scenario.expectedTopLevel, `${scenario.id}: wrong top-level actions`);
assert.deepEqual(snapshot.overflowActionIds, scenario.expectedOverflow, `${scenario.id}: wrong overflow actions`);
assert.equal(snapshot.reactionGroupCount, 1, `${scenario.id}: the reaction group must remain top-level exactly once`);
assert.equal(snapshot.moreButtonCount, 1, `${scenario.id}: the More button must exist exactly once`);
assert.equal(snapshot.duplicateActionIds.length, 0, `${scenario.id}: an action was duplicated across the two menus`);
assert.deepEqual(
[...snapshot.topLevelActionIds, ...snapshot.overflowActionIds].sort(),
OPTIONAL_ACTIONS.map(({ id }) => id).sort(),
`${scenario.id}: an optional action disappeared`,
);
if (!scenario.hideClutterButtons) {
assert.ok(
requiredActionRowWidth(snapshot.topLevelActionIds) <= scenario.availableWidth,
`${scenario.id}: the selected top-level actions do not fit`,
);
if (snapshot.overflowActionIds.length > 0) {
const nextHiddenAction = snapshot.overflowActionIds[0];
assert.ok(
requiredActionRowWidth([...snapshot.topLevelActionIds, nextHiddenAction]) > scenario.availableWidth,
`${scenario.id}: more actions were hidden than necessary`,
);
}
}
}
module.exports = {
ACTION_GAP_PX,
ACTION_OVERFLOW_SCENARIOS,
MORE_BUTTON_ID,
MORE_BUTTON_WIDTH_PX,
OPTIONAL_ACTIONS,
REACTION_GROUP_ID,
REACTION_GROUP_WIDTH_PX,
assertActionOverflowScenario,
requiredActionRowWidth,
};
@@ -0,0 +1,50 @@
const assert = require("node:assert/strict");
const {
ACTION_OVERFLOW_SCENARIOS,
OPTIONAL_ACTIONS,
assertActionOverflowScenario,
requiredActionRowWidth,
} = require("./action-overflow-contract");
describe("action overflow E2E contract", () => {
test("locks explicit roomy, constrained, and opted-in clutter scenarios", () => {
expect(ACTION_OVERFLOW_SCENARIOS.map(({ id }) => id)).toEqual([
"roomy-keeps-every-optional-action",
"one-button-overflow-hides-one",
"two-button-overflow-hides-two",
"three-button-overflow-hides-three",
"narrow-action-allocation-overflows-every-optional-action",
"hide-clutter-keeps-only-reactions",
]);
});
test.each(ACTION_OVERFLOW_SCENARIOS.filter(({ hideClutterButtons }) => !hideClutterButtons))(
"$id is the maximal prefix that fits",
(scenario) => {
expect(requiredActionRowWidth(scenario.expectedTopLevel)).toBeLessThanOrEqual(scenario.availableWidth);
if (scenario.expectedOverflow.length > 0) {
expect(requiredActionRowWidth([...scenario.expectedTopLevel, scenario.expectedOverflow[0]])).toBeGreaterThan(
scenario.availableWidth,
);
}
},
);
test("the opt-in scenario moves every optional action under More", () => {
const scenario = ACTION_OVERFLOW_SCENARIOS.find(({ hideClutterButtons }) => hideClutterButtons);
expect(scenario.expectedTopLevel).toEqual([]);
expect(scenario.expectedOverflow).toEqual(OPTIONAL_ACTIONS.map(({ id }) => id));
});
test("the oracle rejects a false-green snapshot that hides every button at a constrained width", () => {
const scenario = ACTION_OVERFLOW_SCENARIOS.find(({ id }) => id === "one-button-overflow-hides-one");
const falseGreen = {
duplicateActionIds: [],
moreButtonCount: 1,
overflowActionIds: OPTIONAL_ACTIONS.map(({ id }) => id),
reactionGroupCount: 1,
topLevelActionIds: [],
};
expect(() => assertActionOverflowScenario(falseGreen, scenario, assert)).toThrow("wrong top-level actions");
});
});
@@ -0,0 +1,563 @@
const {
ACTION_GAP_PX,
MORE_BUTTON_WIDTH_PX,
OPTIONAL_ACTIONS,
REACTION_GROUP_WIDTH_PX,
requiredActionRowWidth,
} = require("../action-overflow-contract");
const DEFAULT_VIDEO_ID = "overflow001";
function createExtensionActionOverflowFixture({ initialVideoId = DEFAULT_VIDEO_ID } = {}) {
const configuration = JSON.stringify({
actionGap: ACTION_GAP_PX,
initialVideoId,
moreWidth: MORE_BUTTON_WIDTH_PX,
optionalActions: OPTIONAL_ACTIONS,
reactionWidth: REACTION_GROUP_WIDTH_PX,
});
return `<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Owned watch action overflow fixture</title>
<style>
:root {
--yt-spec-base-background: #0f0f0f;
--yt-spec-text-primary: #f1f1f1;
}
* { box-sizing: border-box; }
body {
background: var(--yt-spec-base-background);
color: var(--yt-spec-text-primary);
font: 14px Arial, Helvetica, sans-serif;
margin: 0;
min-height: 100vh;
padding: 28px;
}
ytd-watch-flexy { display: block; }
#player { background: #000; display: block; height: 180px; width: 320px; }
#top-row { margin-top: 20px; }
ytd-menu-renderer.ytd-watch-metadata {
align-items: flex-start;
display: flex;
gap: ${ACTION_GAP_PX}px;
min-height: 58px;
overflow: visible;
}
#top-level-buttons-computed {
align-items: flex-start;
display: flex;
flex: 0 0 auto;
gap: ${ACTION_GAP_PX}px;
min-height: 54px;
}
segmented-like-dislike-button-view-model {
display: block;
flex: 0 0 ${REACTION_GROUP_WIDTH_PX}px;
min-height: 48px;
width: ${REACTION_GROUP_WIDTH_PX}px;
}
segmented-like-dislike-button-view-model > yt-smartimation,
segmented-like-dislike-button-view-model #content,
segmented-like-dislike-button-view-model #wrapper {
display: flex;
height: 48px;
width: 100%;
}
like-button-view-model,
dislike-button-view-model {
display: block;
flex: 1 1 50%;
height: 48px;
min-width: 0;
}
button {
align-items: center;
background: #272727;
border: 0;
color: #f1f1f1;
display: flex;
font: 600 14px Arial, Helvetica, sans-serif;
gap: 7px;
height: 40px;
justify-content: center;
white-space: nowrap;
}
like-button-view-model button {
border-radius: 20px 0 0 20px;
width: 100%;
}
dislike-button-view-model button {
border-left: 1px solid #555;
border-radius: 0 20px 20px 0;
width: 100%;
}
[data-fixture-action] {
display: block;
flex: 0 0 auto;
height: 48px;
}
[data-fixture-action] > button {
border-radius: 20px;
width: 100%;
}
[data-fixture-more] {
border-radius: 50%;
flex: 0 0 ${MORE_BUTTON_WIDTH_PX}px;
font-size: 22px;
padding: 0;
width: ${MORE_BUTTON_WIDTH_PX}px;
}
[data-fixture-overflow-menu] {
background: #282828;
border-radius: 10px;
display: none;
padding: 8px;
position: absolute;
right: 0;
top: 52px;
z-index: 2;
}
[data-fixture-overflow-menu] [data-fixture-action] > button {
background: transparent;
border-radius: 0;
justify-content: flex-start;
}
[data-fixture-overflow-open="true"] [data-fixture-overflow-menu] { display: block; }
.fixture-icon {
fill: none;
height: 21px;
stroke: currentColor;
stroke-linecap: round;
stroke-linejoin: round;
stroke-width: 1.8;
width: 21px;
}
.fixture-preview-card {
background: #0f0f0f;
border: 1px solid #303030;
border-radius: 12px;
display: inline-block;
padding: 12px;
width: 294px;
}
.fixture-preview-title {
color: #aaa;
font-size: 12px;
font-weight: 700;
letter-spacing: .08em;
margin: 0 0 10px;
text-transform: uppercase;
}
.fixture-preview-card ytd-menu-renderer.ytd-watch-metadata {
gap: 6px;
width: 268px !important;
}
.fixture-preview-card #top-level-buttons-computed {
flex: 0 0 228px;
flex-wrap: wrap;
gap: 6px;
width: 228px;
}
.fixture-preview-card[data-fixture-preview-layout="after"] #top-level-buttons-computed {
flex-basis: 150px;
width: 150px;
}
.fixture-preview-card segmented-like-dislike-button-view-model {
flex-basis: 150px;
height: 36px;
min-height: 36px;
width: 150px;
}
.fixture-preview-card segmented-like-dislike-button-view-model > yt-smartimation,
.fixture-preview-card segmented-like-dislike-button-view-model #content,
.fixture-preview-card segmented-like-dislike-button-view-model #wrapper,
.fixture-preview-card like-button-view-model,
.fixture-preview-card dislike-button-view-model,
.fixture-preview-card [data-fixture-action] {
height: 36px;
min-height: 36px;
}
.fixture-preview-card button {
font-size: 12px;
gap: 4px;
height: 34px;
}
.fixture-preview-card .fixture-icon {
height: 17px;
width: 17px;
}
.fixture-preview-card [data-fixture-action="share"] { width: 62px !important; }
.fixture-preview-card [data-fixture-action="save"] { width: 54px !important; }
.fixture-preview-card [data-fixture-action="thanks"] { width: 62px !important; }
.fixture-preview-card [data-fixture-action="download"] { width: 78px !important; }
.fixture-preview-card [data-fixture-action] button {
font-size: 11px;
}
.fixture-preview-card [data-fixture-more] {
flex-basis: 34px;
font-size: 17px;
width: 34px;
}
</style>
</head>
<body>
<main id="fixture-root"></main>
<script>
(() => {
const configuration = ${configuration};
const fixtureRoot = document.querySelector("#fixture-root");
const activationLog = [];
let current = null;
let navigationCount = 0;
const icon = (kind) => {
const paths = {
download: '<path d="M12 3v12m0 0 4-4m-4 4-4-4M5 20h14"/>',
save: '<path d="M6 3h12v18l-6-4-6 4z"/>',
share: '<path d="M9 7l3-3 3 3M12 4v10M6 11H4v9h16v-9h-2"/>',
thanks: '<circle cx="12" cy="12" r="9"/><path d="M9 9.5c.5-2 5.5-2 6 0 .5 2-1.5 2.5-3 3.5-1.5 1-3.5 1.5-3 3.5.5 2 5.5 2 6 0"/>',
};
return '<svg class="fixture-icon" aria-hidden="true" viewBox="0 0 24 24">' + paths[kind] + '</svg>';
};
function reactionMarkup(videoId) {
return \`
<segmented-like-dislike-button-view-model data-fixture-reaction-group data-video-id="\${videoId}">
<yt-smartimation>
<div id="content"><div id="wrapper">
<like-button-view-model class="style-text">
<button type="button" aria-label="501 thousand likes" aria-pressed="false">
<svg class="fixture-icon" aria-hidden="true" viewBox="0 0 24 24"><path d="M8 21H4V9h4m2 12V9l4-7 2 1v5h5v5l-3 8z"/></svg>
<div class="ytSpecButtonShapeNextButtonTextContent"><span id="text" role="text">501K</span></div>
</button>
</like-button-view-model>
<dislike-button-view-model class="style-text">
<button type="button" aria-label="Dislike" aria-pressed="false">
<svg class="fixture-icon" aria-hidden="true" viewBox="0 0 24 24"><path d="M16 3h4v12h-4M14 3v12l-4 7-2-1v-5H3v-5l3-8z"/></svg>
<div class="ytSpecButtonShapeNextButtonTextContent"><span id="text" role="text">6.6K</span></div>
</button>
</dislike-button-view-model>
</div></div>
</yt-smartimation>
</segmented-like-dislike-button-view-model>\`;
}
function createOptionalAction(action) {
const host = document.createElement("button-view-model");
host.dataset.fixtureAction = action.id;
host.style.width = action.width + "px";
host.innerHTML = \`<button type="button" aria-label="\${action.label}">\${icon(action.id)}<span role="text">\${action.label}</span></button>\`;
host.querySelector("button").addEventListener("click", () => activationLog.push(action.id));
return host;
}
function topLevelActionId(model) {
return model?.fixtureActionId ?? null;
}
function flexibleActionId(model) {
return (
model?.fixtureActionId ??
model?.menuFlexibleItemRenderer?.topLevelButton?.fixtureActionId ??
null
);
}
function render(controller) {
const visibleIds = new Set(
(controller.data?.topLevelButtons ?? []).map(topLevelActionId).filter(Boolean),
);
for (const action of controller.flexAsTopLevelButtons) {
visibleIds.add(action.dataset.fixtureAction);
}
for (const action of controller.allActionButtons) {
(visibleIds.has(action.dataset.fixtureAction) ? current.topLevel : current.overflow).append(action);
}
current.menu.dataset.fixtureOverflowOpen = "false";
}
function makeController(actions, availableWidth, sourceData) {
const flexibleActions = actions.filter((action) => action.dataset.fixtureAction !== "share");
let data = sourceData;
let flexAsTopLevelButtons = [...flexibleActions];
const controller = {
allActionButtons: [...actions],
allFlexButtons: [...flexibleActions],
availableWidth,
nativeInvocationCount: 0,
sourceData,
};
Object.defineProperty(controller, "data", {
configurable: true,
enumerable: true,
get: () => data,
set: (value) => {
data = value;
const representedFlexibleIds = new Set((value?.flexibleItems ?? []).map(flexibleActionId).filter(Boolean));
flexAsTopLevelButtons = controller.allActionButtons.filter((action) =>
representedFlexibleIds.has(action.dataset.fixtureAction),
);
if (current?.controller === controller) render(controller);
},
});
Object.defineProperty(controller, "flexAsTopLevelButtons", {
configurable: true,
enumerable: true,
get: () => flexAsTopLevelButtons,
set: (value) => {
flexAsTopLevelButtons = Array.from(value ?? []);
if (current?.controller === controller) render(controller);
},
});
controller.maybeUpdateFlexibleMenuImpl = function nativeMaybeUpdateFlexibleMenuImpl() {
controller.nativeInvocationCount += 1;
render(controller);
const fixedIds = (controller.data?.topLevelButtons ?? []).map(topLevelActionId).filter(Boolean);
const nextFlexibleButtons = [...controller.flexAsTopLevelButtons];
while (
nextFlexibleButtons.length > 0 &&
globalThis.__actionOverflowRequiredWidth([
...fixedIds,
...nextFlexibleButtons.map((element) => element.dataset.fixtureAction),
]) > controller.availableWidth
) {
nextFlexibleButtons.pop();
}
if (nextFlexibleButtons.length === controller.flexAsTopLevelButtons.length) return;
controller.flexAsTopLevelButtons = nextFlexibleButtons;
// YouTube immediately measures again after changing the flexible
// suffix. The historical guard treated this normal second pass as
// an oscillation and emptied the complete suffix.
controller.maybeUpdateFlexibleMenuImpl();
};
return controller;
}
function mount(videoId = configuration.initialVideoId, availableWidth = 760) {
const watch = document.createElement("ytd-watch-flexy");
watch.setAttribute("video-id", videoId);
watch.innerHTML = '<div id="player" loading="false"></div><div id="top-row"></div>';
const menu = document.createElement("ytd-menu-renderer");
menu.className = "ytd-watch-metadata";
menu.style.width = availableWidth + "px";
menu.innerHTML = \`
<div id="top-level-buttons-computed">\${reactionMarkup(videoId)}</div>
<button type="button" data-fixture-more aria-label="More actions">•••</button>
<div data-fixture-overflow-menu aria-label="More actions menu"></div>\`;
watch.querySelector("#top-row").append(menu);
const actions = configuration.optionalActions.map(createOptionalAction);
const sourceData = {
topLevelButtons: [
{ segmentedLikeDislikeButtonViewModel: { likeButtonViewModel: {}, dislikeButtonViewModel: {} } },
{
fixtureActionId: "share",
buttonViewModel: {
iconName: "SHARE",
onTap: { commandMetadata: { webCommandMetadata: { sendPost: true } } },
text: { runs: [{ text: "Share" }] },
trackingParams: "owned-share-tracking",
},
},
],
flexibleItems: configuration.optionalActions
.filter((action) => action.id !== "share")
.map((action) => ({ fixtureActionId: action.id })),
};
const controller = makeController(actions, availableWidth, sourceData);
menu.polymerController = controller;
const originalMethod = controller.maybeUpdateFlexibleMenuImpl;
current = {
actions,
controller,
menu,
originalMethod,
overflow: menu.querySelector("[data-fixture-overflow-menu]"),
topLevel: menu.querySelector("#top-level-buttons-computed"),
videoId,
watch,
};
menu.querySelector("[data-fixture-more]").addEventListener("click", () => {
menu.dataset.fixtureOverflowOpen = String(menu.dataset.fixtureOverflowOpen !== "true");
});
render(controller);
fixtureRoot.replaceChildren(watch);
navigationCount += 1;
return navigationCount;
}
function isPatched() {
return Boolean(current && current.controller.maybeUpdateFlexibleMenuImpl !== current.originalMethod);
}
function settleLayout(availableWidth) {
if (!current) throw new Error("The action menu is not mounted.");
current.controller.availableWidth = availableWidth;
current.menu.style.width = availableWidth + "px";
current.controller.data = current.controller.sourceData;
current.controller.flexAsTopLevelButtons = [...current.controller.allFlexButtons];
current.controller.maybeUpdateFlexibleMenuImpl();
}
function resizeLayout(availableWidth) {
if (!current) throw new Error("The action menu is not mounted.");
current.controller.availableWidth = availableWidth;
current.menu.style.width = availableWidth + "px";
current.controller.maybeUpdateFlexibleMenuImpl();
}
function resizeLayoutAfterDataIdentityChurn(availableWidth) {
if (!current) throw new Error("The action menu is not mounted.");
current.controller.availableWidth = availableWidth;
current.menu.style.width = availableWidth + "px";
current.controller.data = { ...current.controller.data };
current.controller.maybeUpdateFlexibleMenuImpl();
}
function resizeLayoutWithoutNativeNotification(availableWidth) {
if (!current) throw new Error("The action menu is not mounted.");
current.controller.availableWidth = availableWidth;
current.menu.style.width = availableWidth + "px";
current.controller.data = { ...current.controller.data };
}
function navigate(videoId, availableWidth) {
document.dispatchEvent(new Event("yt-navigate-start", { bubbles: true }));
history.pushState({}, "", "/watch?v=" + videoId + "&rydOverflowFixture=1");
mount(videoId, availableWidth);
document.dispatchEvent(new Event("yt-navigate-finish", { bubbles: true }));
}
function snapshot() {
const topLevelActionIds = [...current.topLevel.querySelectorAll(":scope > [data-fixture-action]")].map(
(element) => element.dataset.fixtureAction,
);
const overflowActionIds = [...current.overflow.querySelectorAll(":scope > [data-fixture-action]")].map(
(element) => element.dataset.fixtureAction,
);
const duplicates = topLevelActionIds.filter((id) => overflowActionIds.includes(id));
const movedShareModel = current.controller.data?.flexibleItems?.find(
(item) => item?.menuFlexibleItemRenderer?.topLevelButton?.fixtureActionId === "share",
);
const sourceShareModel = current.controller.sourceData.topLevelButtons.find(
(model) => model.fixtureActionId === "share",
);
return {
activationLog: [...activationLog],
availableWidth: current.controller.availableWidth,
clutterShareCommandPreserved: Boolean(
movedShareModel &&
movedShareModel.menuFlexibleItemRenderer.menuItem.menuServiceItemRenderer.serviceEndpoint ===
sourceShareModel.buttonViewModel.onTap,
),
clutterShareModelPresent: Boolean(movedShareModel),
duplicateActionIds: duplicates,
globalActionCount: document.querySelectorAll("[data-fixture-action]").length,
menuCount: document.querySelectorAll("ytd-menu-renderer.ytd-watch-metadata").length,
moreButtonCount: current.menu.querySelectorAll(":scope > [data-fixture-more]").length,
nativeInvocationCount: current.controller.nativeInvocationCount,
navigationCount,
overflowActionIds,
patched: isPatched(),
reactionGroupCount: current.topLevel.querySelectorAll(":scope > [data-fixture-reaction-group]").length,
topLevelActionIds,
videoId: current.videoId,
};
}
function renderPreview(topLevelActionIds, title) {
if (!current) mount(configuration.initialVideoId, 760);
const desired = new Set(topLevelActionIds);
current.controller.data = current.controller.sourceData;
current.controller.flexAsTopLevelButtons = current.controller.allFlexButtons.filter((action) =>
desired.has(action.dataset.fixtureAction),
);
if (!desired.has("share")) {
current.controller.data = {
...current.controller.sourceData,
topLevelButtons: current.controller.sourceData.topLevelButtons.filter(
(model) => model.fixtureActionId !== "share",
),
};
}
current.menu.style.width = "760px";
const previewCard = current.menu.closest("#top-row");
previewCard.className = "fixture-preview-card";
previewCard.dataset.fixturePreviewLayout = topLevelActionIds.length === 0 ? "after" : "before";
previewCard.querySelector(".fixture-preview-title")?.remove();
const heading = document.createElement("p");
heading.className = "fixture-preview-title";
heading.textContent = title;
previewCard.prepend(heading);
return snapshot();
}
globalThis.__actionOverflowRequiredWidth = (topLevelActionIds) => {
const widths = topLevelActionIds.map(
(id) => configuration.optionalActions.find((action) => action.id === id).width,
);
const itemCount = 2 + topLevelActionIds.length;
return (
configuration.reactionWidth +
configuration.moreWidth +
widths.reduce((total, width) => total + width, 0) +
configuration.actionGap * (itemCount - 1)
);
};
globalThis.__actionOverflowFixture = {
isPatched,
mount,
navigate,
renderPreview,
resizeLayout,
resizeLayoutAfterDataIdentityChurn,
resizeLayoutWithoutNativeNotification,
settleLayout,
snapshot,
};
})();
</script>
</body>
</html>`;
}
module.exports = {
DEFAULT_VIDEO_ID,
createExtensionActionOverflowFixture,
requiredActionRowWidth,
};
@@ -0,0 +1,247 @@
const assert = require("node:assert/strict");
const path = require("node:path");
const { test, expect } = require("@playwright/test");
const {
ACTION_OVERFLOW_SCENARIOS,
OPTIONAL_ACTIONS,
assertActionOverflowScenario,
} = require("../action-overflow-contract");
const { HermeticExtensionArtifactAdapter, startHermeticApiServer } = require("../hermetic-artifact-smoke");
const { DEFAULT_VIDEO_ID, createExtensionActionOverflowFixture } = require("./extension-action-overflow-fixture");
const REPOSITORY_ROOT = path.resolve(__dirname, "../../..");
const EXTENSION_ARTIFACT = path.resolve(
process.env.RYD_EXTENSION_ARTIFACT || path.join(REPOSITORY_ROOT, "Extensions", "combined", "dist", "chrome"),
);
const DESTINATION_VIDEO_ID = "overflow002";
async function withOverflowFixture(testInfo, { hideClutterButtons = false } = {}, run) {
const apiServer = await startHermeticApiServer();
const adapter = new HermeticExtensionArtifactAdapter({
apiServer,
artifactDirectory: EXTENSION_ARTIFACT,
backendOptions: { countsByVideo: { [DEFAULT_VIDEO_ID]: { dislikes: 6600, likes: 501000 } } },
});
const unexpectedRequests = [];
let caughtError = null;
try {
await adapter.start();
await expect
.poll(() =>
adapter.worker.evaluate(async () => (await chrome.storage.sync.get(["hideClutterButtons"])).hideClutterButtons),
)
.toBe(false);
await adapter.worker.evaluate(
(enabled) => chrome.storage.sync.set({ hideClutterButtons: enabled }),
hideClutterButtons,
);
await expect
.poll(() =>
adapter.worker.evaluate(async () => (await chrome.storage.sync.get(["hideClutterButtons"])).hideClutterButtons),
)
.toBe(hideClutterButtons);
await adapter.context.route("https://www.youtube.com/**", async (route) => {
const request = route.request();
const url = new URL(request.url());
if (request.resourceType() === "document" && url.pathname === "/watch") {
await route.fulfill({
body: createExtensionActionOverflowFixture({ initialVideoId: url.searchParams.get("v") || DEFAULT_VIDEO_ID }),
contentType: "text/html; charset=utf-8",
status: 200,
});
return;
}
unexpectedRequests.push({ method: request.method(), resourceType: request.resourceType(), url: request.url() });
await route.abort("blockedbyclient");
});
await adapter.page.goto(`https://www.youtube.com/watch?v=${DEFAULT_VIDEO_ID}&rydOverflowFixture=1`, {
waitUntil: "domcontentloaded",
});
await adapter.page.waitForFunction(() => Boolean(globalThis.__actionOverflowFixture));
await adapter.page.waitForTimeout(250);
await adapter.page.evaluate(() => globalThis.__actionOverflowFixture.mount());
await adapter.page.waitForFunction(() => globalThis.__actionOverflowFixture.isPatched());
await run({ adapter, page: adapter.page });
expect(unexpectedRequests).toEqual([]);
await adapter.pageSignals.assertClean(testInfo.title);
} catch (error) {
caughtError = error;
throw error;
} finally {
if (caughtError && adapter.context) {
const screenshotPath = testInfo.outputPath("action-overflow-failure.png");
await adapter.page.screenshot({ fullPage: true, path: screenshotPath }).catch(() => {});
await testInfo.attach("action-overflow-page", { contentType: "image/png", path: screenshotPath }).catch(() => {});
}
await adapter.close().catch(() => {});
await apiServer.close().catch(() => {});
}
}
async function settleAndRead(page, scenario) {
await page.evaluate(
(availableWidth) => globalThis.__actionOverflowFixture.settleLayout(availableWidth),
scenario.availableWidth,
);
await expect
.poll(() => page.evaluate(() => globalThis.__actionOverflowFixture.snapshot()), {
message: `${scenario.id} did not settle to the expected minimal overflow`,
})
.toMatchObject({
availableWidth: scenario.availableWidth,
duplicateActionIds: [],
globalActionCount: OPTIONAL_ACTIONS.length,
menuCount: 1,
moreButtonCount: 1,
overflowActionIds: [...scenario.expectedOverflow],
patched: true,
reactionGroupCount: 1,
topLevelActionIds: [...scenario.expectedTopLevel],
});
await page.waitForTimeout(180);
const snapshot = await page.evaluate(() => globalThis.__actionOverflowFixture.snapshot());
assertActionOverflowScenario(snapshot, scenario, assert);
return snapshot;
}
test.describe("built extension watch action overflow", () => {
for (const scenario of ACTION_OVERFLOW_SCENARIOS.filter(({ hideClutterButtons }) => !hideClutterButtons)) {
test(`${scenario.id} hides exactly the minimum`, async ({}, testInfo) => {
await withOverflowFixture(testInfo, {}, async ({ page }) => {
await settleAndRead(page, scenario);
});
});
}
test("hide-clutter preference keeps only the reaction group top-level", async ({}, testInfo) => {
const scenario = ACTION_OVERFLOW_SCENARIOS.find(({ hideClutterButtons }) => hideClutterButtons);
const roomyScenario = ACTION_OVERFLOW_SCENARIOS.find(({ id }) => id === "roomy-keeps-every-optional-action");
await withOverflowFixture(testInfo, { hideClutterButtons: true }, async ({ adapter, page }) => {
await expect(page.locator("html")).toHaveAttribute("data-ryd-hide-clutter-buttons", "true");
const snapshot = await settleAndRead(page, scenario);
expect(snapshot).toMatchObject({
clutterShareCommandPreserved: true,
clutterShareModelPresent: true,
});
await page.locator("[data-fixture-more]").click();
const overflowMenu = page.locator("[data-fixture-overflow-menu]");
await expect(overflowMenu).toBeVisible();
await overflowMenu.locator('[data-fixture-action="share"] button').click();
await expect
.poll(() => page.evaluate(() => globalThis.__actionOverflowFixture.snapshot().activationLog))
.toEqual(["share"]);
await adapter.worker.evaluate(() => chrome.storage.sync.set({ hideClutterButtons: false }));
await expect(page.locator("html")).toHaveAttribute("data-ryd-hide-clutter-buttons", "false");
await settleAndRead(page, roomyScenario);
await adapter.worker.evaluate(() => chrome.storage.sync.set({ hideClutterButtons: true }));
await expect(page.locator("html")).toHaveAttribute("data-ryd-hide-clutter-buttons", "true");
await settleAndRead(page, scenario);
});
});
test("resize and navigation restore actions, recompute minimal overflow, and never duplicate controls", async ({}, testInfo) => {
const scenarios = Object.fromEntries(ACTION_OVERFLOW_SCENARIOS.map((scenario) => [scenario.id, scenario]));
await withOverflowFixture(testInfo, {}, async ({ page }) => {
await settleAndRead(page, scenarios["two-button-overflow-hides-two"]);
await settleAndRead(page, scenarios["roomy-keeps-every-optional-action"]);
await settleAndRead(page, scenarios["three-button-overflow-hides-three"]);
const destinationScenario = scenarios["one-button-overflow-hides-one"];
await page.evaluate(
({ availableWidth, videoId }) => globalThis.__actionOverflowFixture.navigate(videoId, availableWidth),
{ availableWidth: destinationScenario.availableWidth, videoId: DESTINATION_VIDEO_ID },
);
await page.waitForFunction(() => globalThis.__actionOverflowFixture.isPatched());
await settleAndRead(page, destinationScenario);
const destination = await page.evaluate(() => globalThis.__actionOverflowFixture.snapshot());
expect(destination).toMatchObject({
globalActionCount: OPTIONAL_ACTIONS.length,
menuCount: 1,
navigationCount: 2,
videoId: DESTINATION_VIDEO_ID,
});
await expect(page.locator("ytd-menu-renderer.ytd-watch-metadata")).toHaveCount(1);
await expect(page.locator("[data-fixture-action]")).toHaveCount(OPTIONAL_ACTIONS.length);
await expect(page.locator("segmented-like-dislike-button-view-model")).toHaveCount(1);
await expect(page.locator("[data-fixture-more]")).toHaveCount(1);
});
});
test("widening restores flexible actions without a model reset", async ({}, testInfo) => {
const narrowScenario = ACTION_OVERFLOW_SCENARIOS.find(({ id }) => id === "three-button-overflow-hides-three");
const widerScenario = ACTION_OVERFLOW_SCENARIOS.find(({ id }) => id === "one-button-overflow-hides-one");
await withOverflowFixture(testInfo, {}, async ({ page }) => {
await settleAndRead(page, narrowScenario);
await page.evaluate(
(availableWidth) => globalThis.__actionOverflowFixture.resizeLayout(availableWidth),
widerScenario.availableWidth,
);
await expect
.poll(() => page.evaluate(() => globalThis.__actionOverflowFixture.snapshot()), {
message: "widening did not restore optional actions before native fitting",
})
.toMatchObject({
overflowActionIds: [...widerScenario.expectedOverflow],
topLevelActionIds: [...widerScenario.expectedTopLevel],
});
const snapshot = await page.evaluate(() => globalThis.__actionOverflowFixture.snapshot());
assertActionOverflowScenario(snapshot, widerScenario, assert);
});
});
test("widening restores flexible actions after same-video menu data identity churn", async ({}, testInfo) => {
const narrowScenario = ACTION_OVERFLOW_SCENARIOS.find(({ id }) => id === "three-button-overflow-hides-three");
const widerScenario = ACTION_OVERFLOW_SCENARIOS.find(({ id }) => id === "one-button-overflow-hides-one");
await withOverflowFixture(testInfo, {}, async ({ page }) => {
await settleAndRead(page, narrowScenario);
await page.evaluate(
(availableWidth) => globalThis.__actionOverflowFixture.resizeLayoutAfterDataIdentityChurn(availableWidth),
widerScenario.availableWidth,
);
await expect
.poll(() => page.evaluate(() => globalThis.__actionOverflowFixture.snapshot()), {
message: "same-video menu data churn discarded optional actions before the wider layout",
})
.toMatchObject({
overflowActionIds: [...widerScenario.expectedOverflow],
topLevelActionIds: [...widerScenario.expectedTopLevel],
});
const snapshot = await page.evaluate(() => globalThis.__actionOverflowFixture.snapshot());
assertActionOverflowScenario(snapshot, widerScenario, assert);
});
});
test("a ResizeObserver refits actions when YouTube does not promptly notify its controller", async ({}, testInfo) => {
const narrowScenario = ACTION_OVERFLOW_SCENARIOS.find(({ id }) => id === "three-button-overflow-hides-three");
const widerScenario = ACTION_OVERFLOW_SCENARIOS.find(({ id }) => id === "one-button-overflow-hides-one");
await withOverflowFixture(testInfo, {}, async ({ page }) => {
await settleAndRead(page, narrowScenario);
await page.evaluate(
(availableWidth) => globalThis.__actionOverflowFixture.resizeLayoutWithoutNativeNotification(availableWidth),
widerScenario.availableWidth,
);
await expect
.poll(() => page.evaluate(() => globalThis.__actionOverflowFixture.snapshot()), {
message: "the observed action allocation changed without triggering a fresh fit",
timeout: 2_000,
})
.toMatchObject({
overflowActionIds: [...widerScenario.expectedOverflow],
topLevelActionIds: [...widerScenario.expectedTopLevel],
});
const snapshot = await page.evaluate(() => globalThis.__actionOverflowFixture.snapshot());
assertActionOverflowScenario(snapshot, widerScenario, assert);
});
});
});
@@ -0,0 +1,950 @@
const fs = require("node:fs");
const path = require("node:path");
const { test, expect } = require("@playwright/test");
const { HermeticExtensionArtifactAdapter, startHermeticApiServer } = require("../hermetic-artifact-smoke");
const {
EXTENSION_MATRIX_RUNTIME,
NAVIGATION_MATRIX,
installNavigationMatrixFixture,
} = require("../../UserScript/e2e/navigation-matrix");
const {
createNavigationRuntimeContractAdapter,
registerNavigationRuntimeContractScenarios,
runNavigationRuntimeContract,
} = require("../navigation-runtime-contract");
const { DEFAULT_VIDEO_IDS, createExtensionNavigationFixture } = require("./extension-navigation-fixture");
const { expectExtensionShortsVisualContract, readExtensionShortsVisualContract } = require("../shorts-visual-contract");
const { annotateVisualEvidence, captureOptionalVisualEvidence } = require("../visual-evidence");
const {
SHORTS_PLACEHOLDER_POOL_COUNTS,
installShortsPlaceholderPoolRoute,
runShortsPlaceholderPoolContract,
shortsPlaceholderPoolUrl,
} = require("../shorts-placeholder-pool-contract");
const REPOSITORY_ROOT = path.resolve(__dirname, "../../..");
const EXTENSION_ARTIFACT = path.resolve(
process.env.RYD_EXTENSION_ARTIFACT || path.join(REPOSITORY_ROOT, "Extensions", "combined", "dist", "chrome"),
);
const COUNTS = Object.freeze({
[DEFAULT_VIDEO_IDS.A]: Object.freeze({ dislikes: 11, likes: 89 }),
[DEFAULT_VIDEO_IDS.B]: Object.freeze({ dislikes: 35, likes: 65 }),
[DEFAULT_VIDEO_IDS.C]: Object.freeze({ dislikes: 70, likes: 30 }),
});
const INITIALIZATION_WARNING = "Initialization failed; retrying when the current controls are ready.";
const SHORTS_VISUAL_REVIEW_DIRECTORY = path.join(REPOSITORY_ROOT, "test-results", "visual-review", "extension");
const SYNTHETIC_SHORTS_STORAGE_PREFIX = "rydSyntheticDislikedShort:";
const SHORTS_TRANSITION_CASES = Object.freeze([
Object.freeze({
action: "like",
dislikesDelta: 0,
initialState: "neutral",
likesDelta: 1,
nextState: "liked",
value: 1,
}),
Object.freeze({
action: "like",
dislikesDelta: 0,
initialState: "liked",
likesDelta: -1,
nextState: "neutral",
value: 0,
}),
Object.freeze({
action: "like",
dislikesDelta: -1,
initialState: "disliked",
likesDelta: 1,
nextState: "liked",
value: 1,
}),
Object.freeze({
action: "dislike",
dislikesDelta: 1,
initialState: "neutral",
likesDelta: 0,
nextState: "disliked",
value: -1,
}),
Object.freeze({
action: "dislike",
dislikesDelta: -1,
initialState: "disliked",
likesDelta: 0,
nextState: "neutral",
value: 0,
}),
Object.freeze({
action: "dislike",
dislikesDelta: 1,
initialState: "liked",
likesDelta: -1,
nextState: "disliked",
value: -1,
}),
]);
async function captureShortsVisualReview(page, scenario) {
const outputPath = path.join(SHORTS_VISUAL_REVIEW_DIRECTORY, `${scenario.id}.png`);
return captureOptionalVisualEvidence({
capture: async (screenshotPath) => {
fs.mkdirSync(SHORTS_VISUAL_REVIEW_DIRECTORY, { recursive: true });
const renderer = page.locator(`ytd-reel-video-renderer[video-id="${scenario.destination.videoId}"][is-active]`);
await renderer.screenshot({ animations: "disabled", path: screenshotPath });
},
outputPath,
});
}
function videoCountsForScenario(scenario) {
return {
[scenario.origin.videoId]: scenario.origin.counts,
[scenario.destination.videoId]: scenario.destination.counts,
};
}
function testFailed(testInfo, caughtError) {
return Boolean(caughtError) || (testInfo.status && testInfo.status !== testInfo.expectedStatus);
}
async function attachFailureEvidence(runtime, testInfo) {
const screenshotPath = testInfo.outputPath("extension-navigation-failure.png");
try {
await runtime.page.screenshot({ fullPage: true, path: screenshotPath });
await testInfo.attach("extension-navigation-page", { contentType: "image/png", path: screenshotPath });
} catch {
// Preserve the original test failure if the page or context already closed.
}
}
async function withExtensionArtifact(testInfo, { countsByVideo, installRoute } = {}, run) {
if (!fs.existsSync(path.join(EXTENSION_ARTIFACT, "manifest.json"))) {
throw new Error(
`The generated Chrome extension artifact is missing at ${EXTENSION_ARTIFACT}. ` +
"Run the extension production build first or set RYD_EXTENSION_ARTIFACT.",
);
}
const apiServer = await startHermeticApiServer();
const adapter = new HermeticExtensionArtifactAdapter({
apiServer,
artifactDirectory: EXTENSION_ARTIFACT,
backendOptions: { countsByVideo },
});
const runtime = {
adapter,
apiServer,
caughtError: null,
initializationWarnings: [],
unexpectedFixtureRequests: [],
workerErrors: [],
};
try {
await adapter.start();
runtime.page = adapter.page;
runtime.page.on("console", (message) => {
if (message.type() === "warning" && message.text().includes(INITIALIZATION_WARNING)) {
runtime.initializationWarnings.push(message.text());
}
});
adapter.worker.on("console", (message) => {
if (["warning", "error", "assert"].includes(message.type())) runtime.workerErrors.push(message.text());
});
if (installRoute) await installRoute(runtime);
await run(runtime);
} catch (error) {
runtime.caughtError = error;
throw error;
} finally {
const failed = testFailed(testInfo, runtime.caughtError);
if (adapter.context && failed) await attachFailureEvidence(runtime, testInfo);
await adapter.close().catch(() => {});
await apiServer.close().catch(() => {});
}
}
async function assertHermeticRuntime(runtime, scenarioId) {
await runtime.adapter.pageSignals.assertClean(scenarioId);
expect(runtime.initializationWarnings, "initialization must wait for usable controls instead of throwing").toEqual(
[],
);
expect(runtime.workerErrors, "the MV3 background worker emitted a warning or error").toEqual([]);
expect(runtime.unexpectedFixtureRequests, "the owned fixture attempted unexpected YouTube requests").toEqual([]);
expect(runtime.adapter.backend.blockedRequests, "the content script escaped the hermetic route set").toEqual([]);
expect(runtime.apiServer.unexpectedRequests, "the MV3 background escaped the fake protocol").toEqual([]);
}
async function installOwnedLifecycleRoute(runtime) {
await runtime.adapter.context.route("https://www.youtube.com/**", async (route) => {
const request = route.request();
const url = new URL(request.url());
if (request.resourceType() === "document" && url.pathname === "/watch") {
await route.fulfill({
body: createExtensionNavigationFixture({
initialVideoId: url.searchParams.get("v") || DEFAULT_VIDEO_IDS.A,
likesByVideo: Object.fromEntries(Object.entries(COUNTS).map(([videoId, counts]) => [videoId, counts.likes])),
}),
contentType: "text/html; charset=utf-8",
status: 200,
});
return;
}
runtime.unexpectedFixtureRequests.push({
method: request.method(),
resourceType: request.resourceType(),
url: request.url(),
});
await route.abort("blockedbyclient");
});
}
async function installHrefIdentifiedShortsTopology(context) {
await context.addInitScript(
({ videoA, videoB }) => {
if (location.hostname !== "www.youtube.com") return;
document.addEventListener(
"DOMContentLoaded",
() => {
const params = new URL(location.href).searchParams;
if (params.get("rydHrefIdentifiedShorts") !== "1") return;
const rendererFor = (videoId) =>
Array.from(document.querySelectorAll("ytd-reel-video-renderer")).find((renderer) => {
const href = renderer.querySelector("a[href*='/shorts/']")?.getAttribute("href");
return href && new URL(href, location.href).pathname === `/shorts/${videoId}`;
});
for (const renderer of document.querySelectorAll("ytd-reel-video-renderer")) {
renderer.removeAttribute("is-active");
renderer.removeAttribute("video-id");
renderer.querySelector("#experiment-overlay")?.remove();
const sequence = renderer.parentElement;
sequence?.classList.remove("reel-video-in-sequence-new");
sequence?.querySelector(".reel-video-in-sequence-thumbnail")?.remove();
}
const next = document.querySelector("#short-next");
if (!next) throw new Error("The href-identified Shorts fixture has no next control.");
next.addEventListener(
"click",
(event) => {
event.preventDefault();
event.stopImmediatePropagation();
const outgoing = rendererFor(videoA);
const destination = rendererFor(videoB);
if (!outgoing || !destination) {
throw new Error("The href-identified Shorts fixture is missing a renderer.");
}
document.dispatchEvent(new Event("yt-navigate-start", { bubbles: true }));
history.pushState(
{},
"",
`/shorts/${videoB}?rydNavigationFixture=1&rydRuntime=extension&rydHrefIdentifiedShorts=1`,
);
outgoing.hidden = true;
destination.hidden = false;
const like = destination.querySelector('[data-fixture-role="like"]');
like?.classList.remove("style-default-active");
like?.classList.add("style-text");
like?.querySelector("button")?.setAttribute("aria-pressed", "false");
document.dispatchEvent(new Event("yt-navigate-finish", { bubbles: true }));
},
true,
);
},
{ once: true },
);
},
{ videoA: DEFAULT_VIDEO_IDS.A, videoB: DEFAULT_VIDEO_IDS.B },
);
}
async function installShortsNativeLikeBehavior(context, initialState) {
await context.addInitScript((state) => {
document.addEventListener(
"DOMContentLoaded",
() => {
const like = document.querySelector(
"ytd-reel-video-renderer[is-active] reel-action-bar-view-model like-button-view-model",
);
const button = like?.querySelector("button");
const count = like?.querySelector("#text, [role='text']");
if (!like || !button || !count) throw new Error("The Shorts transition fixture has no native Like action.");
const setLiked = (liked) => {
like.classList.toggle("style-default-active", liked);
like.classList.toggle("style-text", !liked);
button.setAttribute("aria-pressed", String(liked));
};
setLiked(state === "liked");
},
{ once: true },
);
}, initialState);
}
async function installShortsPremiumTeaserContainer(context) {
await context.addInitScript(() => {
document.addEventListener(
"DOMContentLoaded",
() => {
const secondary = document.createElement("aside");
secondary.id = "secondary";
const inner = document.createElement("div");
inner.id = "secondary-inner";
secondary.append(inner);
document.body.append(secondary);
},
{ once: true },
);
});
}
async function setStoredSyntheticShortsState(runtime, videoId, disliked) {
const key = `${SYNTHETIC_SHORTS_STORAGE_PREFIX}${videoId}`;
await runtime.adapter.worker.evaluate(
async ({ disliked: nextDisliked, key: storageKey }) => {
if (nextDisliked) await chrome.storage.local.set({ [storageKey]: true });
else await chrome.storage.local.remove([storageKey]);
},
{ disliked, key },
);
}
async function readStoredSyntheticShortsState(runtime, videoId) {
const key = `${SYNTHETIC_SHORTS_STORAGE_PREFIX}${videoId}`;
return runtime.adapter.worker.evaluate(
async (storageKey) => (await chrome.storage.local.get([storageKey]))[storageKey] === true,
key,
);
}
async function openLifecycleFixture(runtime, { delayed = false } = {}) {
const initial = delayed ? "&initial=delayed" : "";
await runtime.page.goto(`https://www.youtube.com/watch?v=${DEFAULT_VIDEO_IDS.A}&rydExtensionLifecycle=1${initial}`, {
waitUntil: "domcontentloaded",
});
await runtime.page.waitForFunction(() => Boolean(globalThis.__extensionLifecycleFixture));
}
function statsRequests(runtime, videoId) {
return runtime.adapter.backend.requestsFor("GET", "/votes").filter((request) => request.query.videoId === videoId);
}
async function collectMatrixFailureDiagnostics(runtime) {
return {
countRequestVideoIds: runtime.adapter.backend.requestsFor("GET", "/votes").map((request) => request.query.videoId),
initializationWarnings: [...runtime.initializationWarnings],
pageSignals: runtime.adapter.pageSignals.snapshot(),
probe: await runtime.page.evaluate(() => globalThis.__navigationMatrixProbe?.snapshot?.() ?? null),
shortsReadiness: await runtime.page.evaluate(() => {
const box = (element) => {
const rect = element?.getBoundingClientRect();
return rect
? {
bottom: rect.bottom,
height: rect.height,
left: rect.left,
right: rect.right,
top: rect.top,
width: rect.width,
}
: null;
};
return [...document.querySelectorAll(".reel-video-in-sequence-new")].map((container) => {
const renderer = container.querySelector("ytd-reel-video-renderer");
const overlay = renderer?.querySelector("#experiment-overlay");
return {
container: box(container),
overlayChildren: overlay?.childNodes.length ?? null,
overlayDisplay: overlay ? getComputedStyle(overlay).display : null,
renderer: box(renderer),
rendererActive: renderer?.hasAttribute("is-active") ?? false,
rendererHidden: renderer?.hidden ?? null,
videoId: renderer?.getAttribute("video-id") ?? null,
viewport: { height: innerHeight, width: innerWidth },
};
});
}),
};
}
async function readLifecycleSnapshot(page) {
return page.evaluate(() => globalThis.__extensionLifecycleFixture.snapshot());
}
async function expectNoSkeletonMisbind(runtime, videoId, { retainedBarCount = 0, statsRequestCount = 0 } = {}) {
await runtime.page.waitForTimeout(650);
const snapshot = await readLifecycleSnapshot(runtime.page);
expect(snapshot).toMatchObject({
currentBarCount: 0,
currentButtonCount: 0,
currentCount: "",
currentCountContainerCount: 0,
currentCountCreatedByRuntime: false,
currentNativeDislikeTextCount: 0,
currentVideoId: videoId,
hiddenDuplicateBarCount: 0,
phase: "skeleton",
retainedBarCount,
unrelatedBarCount: 0,
unrelatedLabels: ["Share", "Download"],
urlVideoId: videoId,
});
expect(snapshot.globalBarCount).toBe(retainedBarCount);
expect(snapshot.globalContainerCount).toBe(retainedBarCount);
expect(snapshot.globalWrapperCount).toBe(retainedBarCount);
await expect(runtime.page.locator("#ryd-bar:visible")).toHaveCount(0);
expect(statsRequests(runtime, videoId)).toHaveLength(statsRequestCount);
expect(runtime.initializationWarnings).toEqual([]);
}
async function expectCurrentSurface(runtime, videoId, counts, { soakMs = 650 } = {}) {
const page = runtime.page;
const currentHost = page.locator('[data-fixture-current-actions="true"]');
const likeButton = currentHost.locator('like-button-view-model [data-fixture-native-role="like"]');
const dislikeButton = currentHost.locator('dislike-button-view-model [data-fixture-native-role="dislike"]');
const currentCount = currentHost.locator(
'dislike-button-view-model [data-fixture-native-role="dislike"] .ytSpecButtonShapeNextButtonTextContent',
);
const currentCountText = currentCount.locator("#text");
const currentContainer = currentHost.locator("#ryd-bar-container");
const currentBar = currentHost.locator("#ryd-bar");
await expect(page).toHaveURL((url) => url.pathname === "/watch" && url.searchParams.get("v") === videoId);
await expect(currentHost).toHaveCount(1);
await expect(currentHost).toBeVisible();
await expect(
currentHost.locator(
"segmented-like-dislike-button-view-model > yt-smartimation > [data-fixture-smartimation-content-shell] > [data-fixture-smartimation-content] > like-button-view-model",
),
).toHaveCount(1);
await expect(
currentHost.locator(
"segmented-like-dislike-button-view-model > yt-smartimation > [data-fixture-smartimation-content-shell] > [data-fixture-smartimation-content] > dislike-button-view-model",
),
).toHaveCount(1);
await expect(currentHost).toHaveAttribute("data-fixture-native-dislike-text-count", "0");
await expect(currentCount).toHaveCount(1);
await expect(currentCountText).toHaveCount(1);
await expect(currentCountText).toHaveText(String(counts.dislikes));
await expect(likeButton).toHaveCount(1);
await expect(likeButton).toBeVisible();
await expect(dislikeButton).toHaveCount(1);
await expect(dislikeButton).toBeVisible();
await expect(currentHost.locator("like-button-view-model [role='text']")).toHaveText(String(counts.likes));
await expect(currentHost.locator(".ryd-tooltip")).toHaveCount(1);
await expect(currentContainer).toHaveCount(1);
await expect(currentContainer).toBeVisible();
await expect(currentBar).toHaveCount(1);
await expect(currentBar).toBeVisible();
await expect(currentHost.locator("#ryd-dislike-tooltip")).toContainText(`${counts.likes} / ${counts.dislikes}`);
const geometry = await currentHost.evaluate((host) => {
const container = host.querySelector("#ryd-bar-container");
const containerBox = container.getBoundingClientRect();
return {
containerHeight: containerBox.height,
containerWidth: containerBox.width,
};
});
expect(geometry.containerHeight).toBeGreaterThanOrEqual(2);
expect(geometry.containerWidth).toBeGreaterThan(0);
await expect
.poll(
() =>
currentHost.evaluate((host) => {
const containerBox = host.querySelector("#ryd-bar-container").getBoundingClientRect();
const fillBox = host.querySelector("#ryd-bar").getBoundingClientRect();
return containerBox.width > 0 ? fillBox.width / containerBox.width : null;
}),
{ message: "the visible rate-bar fill must settle to the current video's counts" },
)
.toBeCloseTo(counts.likes / (counts.likes + counts.dislikes), 2);
await expect(page.locator(".ryd-tooltip")).toHaveCount(1);
await expect(page.locator("#ryd-bar-container")).toHaveCount(1);
await expect(page.locator("#ryd-bar")).toHaveCount(1);
await expect(page.locator('[data-fixture-unrelated-actions="true"] #ryd-bar')).toHaveCount(0);
await expect(page.locator('[data-fixture-hidden-duplicate="true"] #ryd-bar')).toHaveCount(0);
await expect(page.locator('[data-fixture-retained-outgoing="true"] #ryd-bar')).toHaveCount(0);
await expect(page.locator('[data-fixture-unrelated-control="share"] span[role="text"]')).toHaveText("Share");
await expect(page.locator('[data-fixture-unrelated-control="download"] span[role="text"]')).toHaveText("Download");
await page.waitForTimeout(soakMs);
await expect(currentCount).toHaveText(String(counts.dislikes));
await expect(page.locator(".ryd-tooltip")).toHaveCount(1);
await expect(page.locator("#ryd-bar-container")).toHaveCount(1);
await expect(page.locator("#ryd-bar")).toHaveCount(1);
}
async function hydrateAndExpect(runtime, videoId, counts) {
await runtime.page.evaluate(() => globalThis.__extensionLifecycleFixture.hydratePending());
await expectCurrentSurface(runtime, videoId, counts);
}
async function replaceCurrentHostAndExpect(runtime, videoId, counts) {
const previousIdentity = (await readLifecycleSnapshot(runtime.page)).currentHostIdentity;
const replacementIdentity = await runtime.page.evaluate(() =>
globalThis.__extensionLifecycleFixture.replaceReadyHost(),
);
expect(replacementIdentity).not.toBe(previousIdentity);
await expectCurrentSurface(runtime, videoId, counts);
}
async function expectOneVoteAndConfirmation(runtime, videoId, value, activationTarget) {
const interactionStart = runtime.apiServer.records.length;
const target =
activationTarget ?? runtime.page.locator('[data-fixture-current-actions="true"] dislike-button-view-model button');
await target.click();
const readInteractions = () =>
runtime.apiServer.records
.slice(interactionStart)
.filter(
(record) =>
record.method !== "OPTIONS" && ["/interact/vote", "/interact/confirmVote"].includes(record.pathname),
);
await expect.poll(() => readInteractions().length).toBe(2);
await runtime.page.waitForTimeout(400);
const interactions = readInteractions();
expect(interactions.map((record) => record.pathname)).toEqual(["/interact/vote", "/interact/confirmVote"]);
expect(interactions[0].body).toEqual({
userId: expect.stringMatching(/^[A-Za-z0-9]{36}$/),
value,
videoId,
});
expect(interactions[1].body).toEqual({
solution: expect.any(String),
userId: interactions[0].body.userId,
videoId,
});
expect(Buffer.from(interactions[1].body.solution, "base64")).toHaveLength(4);
expect(interactions[1]).toMatchObject({ responseBody: true, responseStatus: 200 });
expect(readInteractions()).toHaveLength(2);
return interactions[0].body.userId;
}
test.describe("generated extension artifact Shorts placeholder pool", () => {
test("preserves every action through ten pre-rendered and recycled Next transitions", async ({}, testInfo) => {
test.setTimeout(45_000);
await withExtensionArtifact(
testInfo,
{
countsByVideo: SHORTS_PLACEHOLDER_POOL_COUNTS,
installRoute: async (runtime) => {
await installShortsPlaceholderPoolRoute(runtime.adapter.context, {
onUnexpectedRequest: (request) => runtime.unexpectedFixtureRequests.push(request),
});
},
},
async (runtime) => {
await runtime.page.setViewportSize({ height: 720, width: 1280 });
await runtime.page.goto(shortsPlaceholderPoolUrl(), { waitUntil: "domcontentloaded" });
const results = await runShortsPlaceholderPoolContract({
page: runtime.page,
readRequests: () => runtime.adapter.backend.requests,
runtimeName: "extension",
});
expect(results).toHaveLength(11);
expect(results.filter((result) => result.pixelOracle).map((result) => result.logicalIndex)).toEqual([0, 1, 10]);
expect(
runtime.apiServer.records.filter((record) =>
["/interact/vote", "/interact/confirmVote"].includes(record.pathname),
),
).toEqual([]);
await assertHermeticRuntime(runtime, "shorts-placeholder-pool-ten-next");
},
);
});
});
test.describe("generated extension artifact navigation matrix", () => {
registerNavigationRuntimeContractScenarios({
runtimeName: "extension",
register: ({ scenario, title }) => {
test(title, async ({}, testInfo) => {
await withExtensionArtifact(testInfo, { countsByVideo: videoCountsForScenario(scenario) }, async (runtime) => {
await runtime.page.setViewportSize(scenario.viewport);
await installNavigationMatrixFixture(runtime.adapter.context, scenario);
const pageKind = scenario.origin.kind;
const marker = "rydNavigationFixture=1&rydRuntime=extension";
const url =
pageKind === "shorts"
? `https://www.youtube.com/shorts/${scenario.origin.videoId}?${marker}`
: `https://www.youtube.com/watch?v=${scenario.origin.videoId}&${marker}`;
await runtime.page.goto(url, { waitUntil: "domcontentloaded" });
try {
const adapter = createNavigationRuntimeContractAdapter({
backend: runtime.adapter.backend,
matrixRuntime: EXTENSION_MATRIX_RUNTIME,
page: runtime.page,
readInteractionRecords: () => runtime.apiServer.records,
runtimeName: "extension",
});
await runNavigationRuntimeContract({
adapter,
afterNavigation: async () => {
if (!scenario.id.startsWith("short-next-short-active-reel")) return;
const shortsVisual = await readExtensionShortsVisualContract(
runtime.page,
scenario.destination.videoId,
);
expectExtensionShortsVisualContract(shortsVisual, scenario.destination.counts, scenario.viewport);
annotateVisualEvidence(testInfo, await captureShortsVisualReview(runtime.page, scenario));
},
scenario,
});
if (scenario.destination.kind === "shorts") {
await expect
.poll(() => readStoredSyntheticShortsState(runtime, scenario.destination.videoId))
.toBe(false);
}
} catch (error) {
error.message += `\nExtension navigation diagnostics: ${JSON.stringify(
await collectMatrixFailureDiagnostics(runtime),
)}`;
throw error;
}
await assertHermeticRuntime(runtime, scenario.id);
});
});
},
});
});
test.describe("generated extension artifact current Shorts topology", () => {
test("premium teaser and the Shorts renderer share one aggregate request per navigation", async ({}, testInfo) => {
const scenario = NAVIGATION_MATRIX.find(({ id }) => id === "short-next-short-active-reel");
await withExtensionArtifact(testInfo, { countsByVideo: videoCountsForScenario(scenario) }, async (runtime) => {
await runtime.page.setViewportSize(scenario.viewport);
await installShortsPremiumTeaserContainer(runtime.adapter.context);
await installNavigationMatrixFixture(runtime.adapter.context, scenario);
await runtime.page.goto(
`https://www.youtube.com/shorts/${scenario.origin.videoId}` +
"?rydNavigationFixture=1&rydRuntime=extension&rydPremiumTeaser=1",
{ waitUntil: "domcontentloaded" },
);
await expect(runtime.page.locator(".ryd-premium-teaser")).toHaveCount(1);
await expect(
runtime.page.locator(
`ytd-reel-video-renderer[video-id="${scenario.origin.videoId}"] [data-ryd-synthetic-shorts-dislike] #text`,
),
).toHaveText(String(scenario.origin.counts.dislikes));
expect(statsRequests(runtime, scenario.origin.videoId)).toHaveLength(1);
await runtime.page.locator("#short-next").click();
await expect(runtime.page).toHaveURL((url) => url.pathname === `/shorts/${scenario.destination.videoId}`);
await expect(
runtime.page.locator(
`ytd-reel-video-renderer[video-id="${scenario.destination.videoId}"] [data-ryd-synthetic-shorts-dislike] #text`,
),
).toHaveText(String(scenario.destination.counts.dislikes));
await expect(runtime.page.locator("#ryd-premium-teaser-dislikes")).toHaveText(
String(scenario.destination.counts.dislikes),
);
expect(statsRequests(runtime, scenario.origin.videoId)).toHaveLength(1);
expect(statsRequests(runtime, scenario.destination.videoId)).toHaveLength(1);
await runtime.page.waitForTimeout(650);
expect(statsRequests(runtime, scenario.destination.videoId)).toHaveLength(1);
await assertHermeticRuntime(runtime, "shorts-premium-teaser-request-coalescing");
});
});
test("href-only renderer identity initializes directly and after next-Short navigation", async ({}, testInfo) => {
await withExtensionArtifact(testInfo, { countsByVideo: COUNTS }, async (runtime) => {
await runtime.page.setViewportSize({ height: 720, width: 1280 });
await installHrefIdentifiedShortsTopology(runtime.adapter.context);
await runtime.page.goto(
`https://www.youtube.com/shorts/${DEFAULT_VIDEO_IDS.A}` +
"?rydNavigationFixture=1&rydRuntime=extension&rydHrefIdentifiedShorts=1",
{ waitUntil: "domcontentloaded" },
);
const rendererFor = (videoId) =>
runtime.page.locator("ytd-reel-video-renderer").filter({
has: runtime.page.locator(`a[href='/shorts/${videoId}']`),
});
const dislikeFor = (videoId) => rendererFor(videoId).locator("[data-ryd-synthetic-shorts-dislike]");
const rendererA = rendererFor(DEFAULT_VIDEO_IDS.A);
const rendererB = rendererFor(DEFAULT_VIDEO_IDS.B);
await expect(rendererA).toHaveCount(1);
await expect(rendererA).toBeVisible();
await expect(rendererA).not.toHaveAttribute("is-active", /.*/);
await expect(rendererA).not.toHaveAttribute("video-id", /.*/);
await expect(runtime.page.locator(".reel-video-in-sequence-new")).toHaveCount(0);
await expect(runtime.page.locator(".reel-video-in-sequence-thumbnail")).toHaveCount(0);
await expect(runtime.page.locator("#experiment-overlay")).toHaveCount(0);
await expect(dislikeFor(DEFAULT_VIDEO_IDS.A).locator("#text")).toHaveText(
String(COUNTS[DEFAULT_VIDEO_IDS.A].dislikes),
);
await expect(dislikeFor(DEFAULT_VIDEO_IDS.A)).toHaveAttribute("data-ryd-video-id", DEFAULT_VIDEO_IDS.A);
await expect(dislikeFor(DEFAULT_VIDEO_IDS.A).locator("button")).toBeEnabled();
await expect(rendererA.locator("reel-action-bar-view-model button:visible")).toHaveCount(6);
expect(statsRequests(runtime, DEFAULT_VIDEO_IDS.A)).toHaveLength(1);
expect(statsRequests(runtime, DEFAULT_VIDEO_IDS.B)).toHaveLength(0);
await runtime.page.locator("#short-next").click();
await expect(runtime.page).toHaveURL((url) => url.pathname === `/shorts/${DEFAULT_VIDEO_IDS.B}`);
await expect(rendererA).toBeHidden();
await expect(rendererB).toBeVisible();
await expect(rendererB).not.toHaveAttribute("is-active", /.*/);
await expect(rendererB).not.toHaveAttribute("video-id", /.*/);
await expect(dislikeFor(DEFAULT_VIDEO_IDS.B).locator("#text")).toHaveText(
String(COUNTS[DEFAULT_VIDEO_IDS.B].dislikes),
);
await expect(dislikeFor(DEFAULT_VIDEO_IDS.B)).toHaveAttribute("data-ryd-video-id", DEFAULT_VIDEO_IDS.B);
await expect(dislikeFor(DEFAULT_VIDEO_IDS.B).locator("button")).toBeEnabled();
await expect(rendererB.locator("reel-action-bar-view-model button:visible")).toHaveCount(6);
await expect(runtime.page.locator("[data-ryd-synthetic-shorts-dislike]:visible")).toHaveCount(1);
await expect(runtime.page.locator("dislike-button-view-model, #dislike-button")).toHaveCount(0);
expect(statsRequests(runtime, DEFAULT_VIDEO_IDS.A)).toHaveLength(1);
expect(statsRequests(runtime, DEFAULT_VIDEO_IDS.B)).toHaveLength(1);
expect(
runtime.apiServer.records.filter((record) =>
["/interact/vote", "/interact/confirmVote"].includes(record.pathname),
),
).toEqual([]);
await expectOneVoteAndConfirmation(
runtime,
DEFAULT_VIDEO_IDS.B,
-1,
dislikeFor(DEFAULT_VIDEO_IDS.B).locator("button"),
);
await expect(dislikeFor(DEFAULT_VIDEO_IDS.B).locator("#text")).toHaveText(
String(COUNTS[DEFAULT_VIDEO_IDS.B].dislikes + 1),
);
await expect(dislikeFor(DEFAULT_VIDEO_IDS.B).locator("button")).toHaveAttribute("aria-pressed", "true");
await expect(dislikeFor(DEFAULT_VIDEO_IDS.B)).toHaveClass(/style-default-active/);
await expect
.poll(() =>
runtime.adapter.worker.evaluate(async ({ key }) => (await chrome.storage.local.get([key]))[key], {
key: `rydSyntheticDislikedShort:${DEFAULT_VIDEO_IDS.B}`,
}),
)
.toBe(true);
await expect(rendererA).toBeHidden();
await expect(dislikeFor(DEFAULT_VIDEO_IDS.A).locator("#text")).not.toHaveText(
String(COUNTS[DEFAULT_VIDEO_IDS.B].dislikes + 1),
);
await assertHermeticRuntime(runtime, "href-only-current-shorts-topology");
});
});
});
test.describe("generated extension artifact synthetic Shorts vote transitions", () => {
for (const transition of SHORTS_TRANSITION_CASES) {
test(`${transition.initialState} + ${transition.action} -> ${transition.nextState}`, async ({}, testInfo) => {
await withExtensionArtifact(testInfo, { countsByVideo: COUNTS }, async (runtime) => {
const videoId = DEFAULT_VIDEO_IDS.A;
const initialCounts = COUNTS[videoId];
await runtime.page.setViewportSize({ height: 720, width: 1280 });
await installShortsNativeLikeBehavior(runtime.adapter.context, transition.initialState);
await setStoredSyntheticShortsState(runtime, videoId, transition.initialState === "disliked");
await runtime.page.goto(
`https://www.youtube.com/shorts/${videoId}?rydNavigationFixture=1&rydRuntime=extension`,
{ waitUntil: "domcontentloaded" },
);
const renderer = runtime.page.locator(`ytd-reel-video-renderer[video-id="${videoId}"][is-active]`);
const like = renderer.locator("like-button-view-model");
const likeButton = like.locator("button");
const likeCount = like.locator("#text, [role='text']");
const dislike = renderer.locator("[data-ryd-synthetic-shorts-dislike]");
const dislikeButton = dislike.locator("button");
const dislikeCount = dislike.locator("#text, [role='text']");
await expect(dislike).toHaveCount(1);
await expect(dislikeButton).toBeEnabled();
await expect(dislikeCount).toHaveText(String(initialCounts.dislikes));
await expect(likeCount).toHaveText(String(initialCounts.likes));
await expect(likeButton).toHaveAttribute("aria-pressed", String(transition.initialState === "liked"));
await expect(dislikeButton).toHaveAttribute("aria-pressed", String(transition.initialState === "disliked"));
await expect(renderer.locator("reel-action-bar-view-model button:visible")).toHaveCount(6);
const nativeReactionStatsBefore = await runtime.page.evaluate(() =>
globalThis.__navigationFixture.nativeReactionSnapshot(),
);
const activationTarget = transition.action === "like" ? likeButton : dislikeButton;
await expectOneVoteAndConfirmation(runtime, videoId, transition.value, activationTarget);
const expectedLikes = initialCounts.likes + transition.likesDelta;
const expectedDislikes = initialCounts.dislikes + transition.dislikesDelta;
await expect(likeCount).toHaveText(String(expectedLikes));
await expect(dislikeCount).toHaveText(String(expectedDislikes));
await expect(likeButton).toHaveAttribute("aria-pressed", String(transition.nextState === "liked"));
await expect(dislikeButton).toHaveAttribute("aria-pressed", String(transition.nextState === "disliked"));
await expect(dislike).toHaveClass(transition.nextState === "disliked" ? /style-default-active/ : /style-text/);
await expect
.poll(() => readStoredSyntheticShortsState(runtime, videoId))
.toBe(transition.nextState === "disliked");
await expect(renderer.locator("[data-ryd-synthetic-shorts-dislike]")).toHaveCount(1);
const nativeReactionStatsAfter = await runtime.page.evaluate(() =>
globalThis.__navigationFixture.nativeReactionSnapshot(),
);
const expectedNativeLikeActivations =
transition.action === "like" || (transition.action === "dislike" && transition.initialState === "liked")
? 1
: 0;
expect(nativeReactionStatsAfter.activations - nativeReactionStatsBefore.activations).toBe(
expectedNativeLikeActivations,
);
expect(nativeReactionStatsAfter.likeActivations - nativeReactionStatsBefore.likeActivations).toBe(
expectedNativeLikeActivations,
);
expect(nativeReactionStatsAfter.dislikeActivations - nativeReactionStatsBefore.dislikeActivations).toBe(0);
await assertHermeticRuntime(runtime, `synthetic-shorts-${transition.initialState}-${transition.action}`);
});
});
}
});
test.describe("generated extension artifact real watch topology", () => {
test("direct load waits through a native-button skeleton and initializes once after in-place hydration", async ({}, testInfo) => {
await withExtensionArtifact(
testInfo,
{ countsByVideo: COUNTS, installRoute: installOwnedLifecycleRoute },
async (runtime) => {
await openLifecycleFixture(runtime, { delayed: true });
await expectNoSkeletonMisbind(runtime, DEFAULT_VIDEO_IDS.A);
await hydrateAndExpect(runtime, DEFAULT_VIDEO_IDS.A, COUNTS[DEFAULT_VIDEO_IDS.A]);
expect(statsRequests(runtime, DEFAULT_VIDEO_IDS.A)).toHaveLength(1);
await assertHermeticRuntime(runtime, "direct-delayed-hydration");
},
);
});
test("recommendation navigation reuses A-owned controls instead of Share/Download or a hidden duplicate", async ({}, testInfo) => {
await withExtensionArtifact(
testInfo,
{ countsByVideo: COUNTS, installRoute: installOwnedLifecycleRoute },
async (runtime) => {
await openLifecycleFixture(runtime);
await expectCurrentSurface(runtime, DEFAULT_VIDEO_IDS.A, COUNTS[DEFAULT_VIDEO_IDS.A]);
const outgoing = await readLifecycleSnapshot(runtime.page);
await runtime.page.locator("#fixture-recommendation").click();
const skeleton = await readLifecycleSnapshot(runtime.page);
expect(skeleton.currentHostIdentity).toBe(outgoing.currentHostIdentity);
expect(skeleton.currentFixtureControlVideoId).toBe(DEFAULT_VIDEO_IDS.A);
expect(skeleton.phase).toBe("visible-outgoing");
await expectCurrentSurface(runtime, DEFAULT_VIDEO_IDS.B, COUNTS[DEFAULT_VIDEO_IDS.B]);
expect(statsRequests(runtime, DEFAULT_VIDEO_IDS.A)).toHaveLength(1);
expect(statsRequests(runtime, DEFAULT_VIDEO_IDS.B)).toHaveLength(1);
await expectOneVoteAndConfirmation(runtime, DEFAULT_VIDEO_IDS.B, -1);
await expect(
runtime.page.locator(
'[data-fixture-current-actions="true"] dislike-button-view-model .ytSpecButtonShapeNextButtonTextContent',
),
).toHaveText(String(COUNTS[DEFAULT_VIDEO_IDS.B].dislikes + 1));
await expect(
runtime.page.locator('[data-fixture-current-actions="true"] like-button-view-model [role="text"]'),
).toHaveText(String(COUNTS[DEFAULT_VIDEO_IDS.B].likes));
await assertHermeticRuntime(runtime, "recommendation-reused-controls");
},
);
});
test("SPA navigation waits for in-place native-button hydration without a second navigation event", async ({}, testInfo) => {
await withExtensionArtifact(
testInfo,
{ countsByVideo: COUNTS, installRoute: installOwnedLifecycleRoute },
async (runtime) => {
await openLifecycleFixture(runtime);
await expectCurrentSurface(runtime, DEFAULT_VIDEO_IDS.A, COUNTS[DEFAULT_VIDEO_IDS.A]);
const outgoing = await readLifecycleSnapshot(runtime.page);
await runtime.page.evaluate((videoId) => {
globalThis.__extensionLifecycleFixture.beginNavigation(videoId, {
mode: "reuse-in-place",
pushState: true,
trigger: "delayed-in-place",
});
}, DEFAULT_VIDEO_IDS.B);
const skeleton = await readLifecycleSnapshot(runtime.page);
expect(skeleton.currentHostIdentity).toBe(outgoing.currentHostIdentity);
await expectNoSkeletonMisbind(runtime, DEFAULT_VIDEO_IDS.B);
await hydrateAndExpect(runtime, DEFAULT_VIDEO_IDS.B, COUNTS[DEFAULT_VIDEO_IDS.B]);
expect(statsRequests(runtime, DEFAULT_VIDEO_IDS.A)).toHaveLength(1);
expect(statsRequests(runtime, DEFAULT_VIDEO_IDS.B)).toHaveLength(1);
await assertHermeticRuntime(runtime, "spa-delayed-in-place-hydration");
},
);
});
test("playlist host replacement recovers without a second navigation event and deduplicates listeners", async ({}, testInfo) => {
await withExtensionArtifact(
testInfo,
{ countsByVideo: COUNTS, installRoute: installOwnedLifecycleRoute },
async (runtime) => {
await openLifecycleFixture(runtime);
await expectCurrentSurface(runtime, DEFAULT_VIDEO_IDS.A, COUNTS[DEFAULT_VIDEO_IDS.A]);
await runtime.page.locator("#fixture-playlist").click();
await expectNoSkeletonMisbind(runtime, DEFAULT_VIDEO_IDS.B);
await hydrateAndExpect(runtime, DEFAULT_VIDEO_IDS.B, COUNTS[DEFAULT_VIDEO_IDS.B]);
expect(statsRequests(runtime, DEFAULT_VIDEO_IDS.B)).toHaveLength(1);
await replaceCurrentHostAndExpect(runtime, DEFAULT_VIDEO_IDS.B, COUNTS[DEFAULT_VIDEO_IDS.B]);
await replaceCurrentHostAndExpect(runtime, DEFAULT_VIDEO_IDS.B, COUNTS[DEFAULT_VIDEO_IDS.B]);
expect(statsRequests(runtime, DEFAULT_VIDEO_IDS.B)).toHaveLength(1);
await expectOneVoteAndConfirmation(runtime, DEFAULT_VIDEO_IDS.B, -1);
await expect(
runtime.page.locator(
'[data-fixture-current-actions="true"] dislike-button-view-model .ytSpecButtonShapeNextButtonTextContent',
),
).toHaveText(String(COUNTS[DEFAULT_VIDEO_IDS.B].dislikes + 1));
await expect(runtime.page.locator("#ryd-bar")).toHaveCount(1);
await assertHermeticRuntime(runtime, "playlist-replacement-and-vote");
},
);
});
test("history back and forward repeatedly replace controls without losing or duplicating the current surface", async ({}, testInfo) => {
await withExtensionArtifact(
testInfo,
{ countsByVideo: COUNTS, installRoute: installOwnedLifecycleRoute },
async (runtime) => {
await openLifecycleFixture(runtime);
await expectCurrentSurface(runtime, DEFAULT_VIDEO_IDS.A, COUNTS[DEFAULT_VIDEO_IDS.A]);
await runtime.page.locator("#fixture-history-next").click();
await expectNoSkeletonMisbind(runtime, DEFAULT_VIDEO_IDS.B);
await hydrateAndExpect(runtime, DEFAULT_VIDEO_IDS.B, COUNTS[DEFAULT_VIDEO_IDS.B]);
await runtime.page.goBack();
await expectNoSkeletonMisbind(runtime, DEFAULT_VIDEO_IDS.A, { statsRequestCount: 1 });
await hydrateAndExpect(runtime, DEFAULT_VIDEO_IDS.A, COUNTS[DEFAULT_VIDEO_IDS.A]);
await runtime.page.goForward();
await expectNoSkeletonMisbind(runtime, DEFAULT_VIDEO_IDS.B, { statsRequestCount: 1 });
await hydrateAndExpect(runtime, DEFAULT_VIDEO_IDS.B, COUNTS[DEFAULT_VIDEO_IDS.B]);
expect(statsRequests(runtime, DEFAULT_VIDEO_IDS.A)).toHaveLength(2);
expect(statsRequests(runtime, DEFAULT_VIDEO_IDS.B)).toHaveLength(2);
await expect(runtime.page.locator(".ryd-tooltip")).toHaveCount(1);
await expect(runtime.page.locator("#ryd-bar-container")).toHaveCount(1);
await expect(runtime.page.locator("#ryd-bar")).toHaveCount(1);
await assertHermeticRuntime(runtime, "history-back-forward-replacements");
},
);
});
});
@@ -0,0 +1,179 @@
const fs = require("node:fs");
const path = require("node:path");
const { test, expect } = require("@playwright/test");
const { VIDEO_A } = require("../../UserScript/e2e/harness");
const { HermeticExtensionArtifactAdapter, startHermeticApiServer } = require("../hermetic-artifact-smoke");
const {
EXTENSION_WATCH_VISUAL_PROFILE,
attachVisualFailureScreenshot,
expectNoStructuralLayoutShift,
expectWatchVisualState,
readWatchVisualContract,
waitForBarRatio,
} = require("../watch-visual-contract");
const { registerWatchVisualContract } = require("../watch-visual-scenarios");
const { annotateVisualEvidence, captureOptionalVisualEvidence } = require("../visual-evidence");
const REPOSITORY_ROOT = path.resolve(__dirname, "../../..");
const EXTENSION_ARTIFACT = path.resolve(
process.env.RYD_EXTENSION_ARTIFACT || path.join(REPOSITORY_ROOT, "Extensions", "combined", "dist", "chrome"),
);
const BASE_COUNTS = Object.freeze({ likes: 100, dislikes: 25 });
const VISUAL_REVIEW_DIRECTORY = path.join(REPOSITORY_ROOT, "test-results", "visual-review", "extension");
async function captureVisualReview(page, name) {
const outputPath = path.join(VISUAL_REVIEW_DIRECTORY, `${name}.png`);
return captureOptionalVisualEvidence({
capture: async (screenshotPath) => {
fs.mkdirSync(VISUAL_REVIEW_DIRECTORY, { recursive: true });
await page.locator("#top-row").screenshot({
animations: "disabled",
path: screenshotPath,
});
},
outputPath,
});
}
function nonPreflightRecords(records, startIndex = 0) {
return records.slice(startIndex).filter((record) => record.method !== "OPTIONS");
}
async function installCurrentDesktopLayoutMarker(context) {
await context.addInitScript(() => {
if (!location.hostname.endsWith("youtube.com")) return;
document.addEventListener(
"DOMContentLoaded",
() => {
if (document.getElementById("comment-teaser")) return;
const marker = document.createElement("div");
marker.id = "comment-teaser";
marker.hidden = true;
document.body.append(marker);
},
{ once: true },
);
});
}
async function withExtensionVisualFixture(testInfo, { initialState = "neutral", viewport }, run) {
if (!fs.existsSync(path.join(EXTENSION_ARTIFACT, "manifest.json"))) {
throw new Error(
`The generated Chrome extension artifact is missing at ${EXTENSION_ARTIFACT}. ` +
"Run the extension production build first or set RYD_EXTENSION_ARTIFACT.",
);
}
const apiServer = await startHermeticApiServer();
const adapter = new HermeticExtensionArtifactAdapter({
apiServer,
artifactDirectory: EXTENSION_ARTIFACT,
backendOptions: {
countsByVideo: { [VIDEO_A]: BASE_COUNTS },
fixture: { initialState, nativeDislikeText: false, roleAttribute: "data-fixture-role" },
},
});
const workerErrors = [];
let caughtError = null;
try {
await adapter.start();
adapter.worker.on("console", (message) => {
if (["assert", "error", "warning"].includes(message.type())) workerErrors.push(message.text());
});
await installCurrentDesktopLayoutMarker(adapter.context);
await adapter.page.setViewportSize({ height: viewport.height, width: viewport.width });
await adapter.openWatch(VIDEO_A);
await adapter.waitForWatchResult(VIDEO_A);
await expect
.poll(() => apiServer.records.filter((record) => record.pathname === "/puzzle/registration").length)
.toBe(2);
await run({ adapter, apiServer, page: adapter.page, workerErrors });
} catch (error) {
caughtError = error;
throw error;
} finally {
if (caughtError || (testInfo.status && testInfo.status !== testInfo.expectedStatus)) {
await attachVisualFailureScreenshot(testInfo, adapter.page, `${viewport.name}-${initialState}`).catch(() => {});
}
await adapter.close().catch(() => {});
await apiServer.close().catch(() => {});
}
}
async function assertCleanExtensionRuntime({ adapter, apiServer, workerErrors }, scenarioId) {
await adapter.assertNoPageSignals(scenarioId);
expect(workerErrors, "the MV3 background worker emitted browser warnings or errors").toEqual([]);
expect(adapter.backend.blockedRequests, "the content script escaped the hermetic route set").toEqual([]);
expect(apiServer.unexpectedRequests, "the MV3 background escaped the fake protocol").toEqual([]);
}
async function waitForOneVoteHandshake(apiServer, startIndex) {
const interactions = () =>
nonPreflightRecords(apiServer.records, startIndex).filter((record) =>
["/interact/vote", "/interact/confirmVote"].includes(record.pathname),
);
await expect.poll(() => interactions().length).toBe(2);
await new Promise((resolve) => setTimeout(resolve, 350));
return interactions();
}
function expectExactVoteHandshake(interactions, transition) {
expect(interactions.map(({ method, pathname }) => ({ method, pathname }))).toEqual([
{ method: "POST", pathname: "/interact/vote" },
{ method: "POST", pathname: "/interact/confirmVote" },
]);
expect(interactions[0].body).toEqual({
userId: expect.stringMatching(/^[A-Za-z0-9]{36}$/),
value: transition.value,
videoId: VIDEO_A,
});
expect(interactions[1].body).toEqual({
solution: expect.any(String),
userId: interactions[0].body.userId,
videoId: VIDEO_A,
});
expect(Buffer.from(interactions[1].body.solution, "base64")).toHaveLength(4);
expect(Number.isFinite(interactions[0].respondedAt), "the vote request must receive a response").toBe(true);
expect(interactions[0].responseStatus, "the vote response must be successful").toBeGreaterThanOrEqual(200);
expect(interactions[0].responseStatus, "the vote response must be successful").toBeLessThan(300);
expect(Number.isFinite(interactions[1].respondedAt), "the confirmation request must receive a response").toBe(true);
expect(interactions[1].responseStatus, "the confirmation response must be successful").toBeGreaterThanOrEqual(200);
expect(interactions[1].responseStatus, "the confirmation response must be successful").toBeLessThan(300);
expect(interactions[1].responseBody).toBe(true);
}
registerWatchVisualContract({
runtime: "extension",
test,
async runScenario({ scenario, testInfo }) {
const { transition, viewport } = scenario;
await withExtensionVisualFixture(testInfo, { initialState: transition.initialState, viewport }, async (runtime) => {
const before = await readWatchVisualContract(runtime.page, EXTENSION_WATCH_VISUAL_PROFILE);
expectWatchVisualState(before, transition.initialState, BASE_COUNTS, viewport, EXTENSION_WATCH_VISUAL_PROFILE);
const interactionStart = runtime.apiServer.records.length;
await runtime.page
.locator(`[${EXTENSION_WATCH_VISUAL_PROFILE.roleAttribute}="${transition.action}"] button`)
.click();
const interactions = await waitForOneVoteHandshake(runtime.apiServer, interactionStart);
const nextCounts = {
likes: BASE_COUNTS.likes + transition.likesDelta,
dislikes: BASE_COUNTS.dislikes + transition.dislikesDelta,
};
await waitForBarRatio(runtime.page, nextCounts, EXTENSION_WATCH_VISUAL_PROFILE);
const after = await readWatchVisualContract(runtime.page, EXTENSION_WATCH_VISUAL_PROFILE);
expectWatchVisualState(after, transition.nextState, nextCounts, viewport, EXTENSION_WATCH_VISUAL_PROFILE, {
assertTooltipText: false,
});
expectNoStructuralLayoutShift(before, after);
expectExactVoteHandshake(interactions, transition);
expect(runtime.adapter.backend.requestsFor("GET", "/votes")).toHaveLength(1);
expect(runtime.adapter.backend.requestsFor("POST", "/interact/vote")).toHaveLength(0);
expect(runtime.adapter.backend.requestsFor("POST", "/interact/confirmVote")).toHaveLength(0);
annotateVisualEvidence(testInfo, await captureVisualReview(runtime.page, scenario.id));
await assertCleanExtensionRuntime(runtime, scenario.id);
});
},
});
@@ -0,0 +1,157 @@
const fs = require("node:fs");
const path = require("node:path");
const { test, expect } = require("@playwright/test");
const { HermeticExtensionArtifactAdapter, startHermeticApiServer } = require("../hermetic-artifact-smoke");
const { annotateVisualEvidence, captureOptionalVisualEvidence } = require("../visual-evidence");
const REPOSITORY_ROOT = path.resolve(__dirname, "../../..");
const EXTENSION_ARTIFACT = path.resolve(
process.env.RYD_EXTENSION_ARTIFACT || path.join(REPOSITORY_ROOT, "Extensions", "combined", "dist", "chrome"),
);
const POPUP_VISUAL_REVIEW_PATH = path.join(
REPOSITORY_ROOT,
"test-results",
"visual-review",
"extension",
"hide-clutter-popup.png",
);
async function readStoredPreference(worker) {
return worker.evaluate(async () => (await chrome.storage.sync.get(["hideClutterButtons"])).hideClutterButtons);
}
async function openPopup(adapter) {
const page = adapter.page;
await page.setViewportSize({ height: 720, width: 360 });
await page.goto(`chrome-extension://${adapter.extensionId}/popup.html`, { waitUntil: "load" });
await page.locator("#advancedToggle").click();
await expect(page.locator("#advancedSettings")).toHaveCSS("opacity", "1");
return page;
}
test("built popup defaults hide-clutter off, persists it, and presents an accessible visual explanation", async ({}, testInfo) => {
const apiServer = await startHermeticApiServer();
const adapter = new HermeticExtensionArtifactAdapter({ apiServer, artifactDirectory: EXTENSION_ARTIFACT });
let caughtError = null;
try {
await adapter.start();
await adapter.worker.evaluate(() => chrome.storage.sync.remove(["hideClutterButtons"]));
await adapter.context.route("https://fonts.googleapis.com/**", (route) =>
route.fulfill({ body: "", contentType: "text/css; charset=utf-8", status: 200 }),
);
await adapter.context.route("https://fonts.gstatic.com/**", (route) =>
route.fulfill({ body: "", contentType: "font/woff2", status: 200 }),
);
await adapter.context.route("https://raw.githubusercontent.com/**", (route) =>
route.fulfill({
body: JSON.stringify({ version: "4.0.5" }),
contentType: "application/json; charset=utf-8",
status: 200,
}),
);
const page = await openPopup(adapter);
const checkbox = page.locator("#hide_clutter_buttons");
const settingLabel = page.locator('label[for="hide_clutter_buttons"].setting-row-label');
const help = page.locator("#hide_clutter_buttons_help");
const tooltip = page.locator("#hide_clutter_buttons_tooltip");
const before = tooltip.locator('[data-hide-clutter-example="before"]');
const after = tooltip.locator('[data-hide-clutter-example="after"]');
await expect(checkbox).not.toBeChecked();
await expect.poll(() => readStoredPreference(adapter.worker)).toBe(false);
await expect(help).toHaveAttribute("aria-describedby", "hide_clutter_buttons_tooltip");
expect(await help.evaluate((element) => element.tabIndex)).toBe(0);
await help.hover();
await expect(tooltip).toBeVisible();
await expect(before).toBeVisible();
await expect(after).toBeVisible();
await expect
.poll(() =>
page.evaluate(() =>
[...document.querySelectorAll("[data-hide-clutter-example]")].map((image) => ({
complete: image.complete,
naturalHeight: image.naturalHeight,
naturalWidth: image.naturalWidth,
})),
),
)
.toEqual([
{ complete: true, naturalHeight: 128, naturalWidth: 294 },
{ complete: true, naturalHeight: 108, naturalWidth: 294 },
]);
const renderedExamples = await page.evaluate(() =>
[...document.querySelectorAll("[data-hide-clutter-example]")].map((image) => {
const box = image.getBoundingClientRect();
const canvas = document.createElement("canvas");
canvas.width = image.naturalWidth;
canvas.height = image.naturalHeight;
const context = canvas.getContext("2d", { willReadFrequently: true });
context.drawImage(image, 0, 0);
const pixels = context.getImageData(10, 38, 155, 46).data;
let reactionInkPixels = 0;
for (let index = 0; index < pixels.length; index += 4) {
if (Math.max(pixels[index], pixels[index + 1], pixels[index + 2]) >= 30 && pixels[index + 3] > 0) {
reactionInkPixels += 1;
}
}
return {
naturalWidth: image.naturalWidth,
reactionInkPixels,
renderedWidth: box.width,
scale: box.width / image.naturalWidth,
};
}),
);
for (const example of renderedExamples) {
expect(example.renderedWidth).toBeGreaterThanOrEqual(220);
expect(example.scale).toBeGreaterThanOrEqual(0.75);
expect(example.reactionInkPixels).toBeGreaterThan(2_500);
}
const visualEvidence = await captureOptionalVisualEvidence({
capture: async (screenshotPath) => {
fs.mkdirSync(path.dirname(screenshotPath), { recursive: true });
await page.screenshot({ animations: "disabled", path: screenshotPath });
},
outputPath: POPUP_VISUAL_REVIEW_PATH,
});
annotateVisualEvidence(testInfo, visualEvidence);
const popoverBox = await tooltip.boundingBox();
expect(popoverBox).not.toBeNull();
expect(popoverBox.x).toBeGreaterThanOrEqual(0);
expect(popoverBox.x + popoverBox.width).toBeLessThanOrEqual(360);
await page.mouse.move(1, 1);
await help.focus();
await expect(help).toBeFocused();
await expect(tooltip).toBeVisible();
await settingLabel.click();
await expect(checkbox).toBeChecked();
await expect.poll(() => readStoredPreference(adapter.worker)).toBe(true);
await page.reload({ waitUntil: "load" });
await page.locator("#advancedToggle").click();
await expect(page.locator("#hide_clutter_buttons")).toBeChecked();
await page.locator('label[for="hide_clutter_buttons"].setting-row-label').click();
await expect(page.locator("#hide_clutter_buttons")).not.toBeChecked();
await expect.poll(() => readStoredPreference(adapter.worker)).toBe(false);
await adapter.pageSignals.assertClean(testInfo.title);
} catch (error) {
caughtError = error;
throw error;
} finally {
if (caughtError && adapter.context) {
const screenshotPath = testInfo.outputPath("hide-clutter-popup-failure.png");
await adapter.page.screenshot({ fullPage: true, path: screenshotPath }).catch(() => {});
await testInfo.attach("hide-clutter-popup", { contentType: "image/png", path: screenshotPath }).catch(() => {});
}
await adapter.close().catch(() => {});
await apiServer.close().catch(() => {});
}
});
@@ -0,0 +1,307 @@
const path = require("node:path");
const { test, expect } = require("@playwright/test");
const { VIDEO_A, VIDEO_B } = require("../../UserScript/e2e/harness");
const {
HermeticExtensionArtifactAdapter,
SPA_COUNTS,
isArtifactVoteHandshakeValid,
readArtifactVoteHandshake,
startHermeticApiServer,
} = require("../hermetic-artifact-smoke");
const { assertInvariantContinuously } = require("../continuous-invariants");
const EXTENSION_ARTIFACT = path.resolve(
process.env.RYD_EXTENSION_ARTIFACT || path.join(__dirname, "../../combined/dist/chrome"),
);
async function readCurrentWatch(adapter) {
return adapter.page.evaluate(() => {
const rendered = (element) => {
if (!element?.isConnected || element.closest("[hidden], [aria-hidden='true'], [inert]")) return false;
const box = element.getBoundingClientRect();
const style = getComputedStyle(element);
return box.width > 0 && box.height > 0 && style.display !== "none" && style.visibility !== "hidden";
};
const watch = [...document.querySelectorAll("ytd-watch-flexy, ytd-watch-grid")].find(rendered);
const actions = watch && [...watch.querySelectorAll("#top-level-buttons-computed")].find(rendered);
const dislike = actions?.querySelector("dislike-button-view-model");
const nativeButton = dislike?.querySelector("button");
const count = dislike?.querySelector(
"#text, [role='text'], .ytSpecButtonShapeNextButtonTextContent, .yt-spec-button-shape-next__button-text-content",
);
return {
count: count?.textContent?.trim() ?? "",
currentVideoId: watch?.getAttribute("video-id") ?? null,
nativeDislikePressed: nativeButton?.getAttribute("aria-pressed") ?? null,
nativeDislikeVisible: rendered(nativeButton),
ownedVisibleBarCount: [...(actions?.querySelectorAll("#ryd-bar") ?? [])].filter(rendered).length,
urlVideoId: new URL(location.href).searchParams.get("v"),
};
});
}
function voteDataRequests(adapter) {
return adapter.backend.requestsFor("GET", "/votes");
}
async function withExtension(testInfo, run, backendOptions = {}) {
const apiServer = await startHermeticApiServer();
const adapter = new HermeticExtensionArtifactAdapter({
apiServer,
artifactDirectory: EXTENSION_ARTIFACT,
backendOptions,
});
const heldRequests = [];
const deferVotes = () => {
const held = adapter.deferNextStatsRequest();
const pending = { held, seen: false };
void held.seen.then(() => {
pending.seen = true;
});
heldRequests.push(pending);
return held;
};
try {
await adapter.start();
adapter.page.setDefaultTimeout(5_000);
await run({ adapter, apiServer, deferVotes });
expect(adapter.backend.blockedRequests).toEqual([]);
expect(apiServer.unexpectedRequests).toEqual([]);
} catch (error) {
if (adapter.page && !adapter.page.isClosed()) {
await testInfo.attach("initialization-race", {
body: await adapter.page.screenshot(),
contentType: "image/png",
});
await testInfo.attach("initialization-race-diagnostics", {
body: JSON.stringify({
watch: await readCurrentWatch(adapter),
requests: voteDataRequests(adapter).map(({ at, query, respondedAt, responseStatus }) => ({
at,
query,
respondedAt,
responseStatus,
})),
interactions: apiServer.records
.filter(({ pathname }) => pathname.startsWith("/interact/"))
.map(({ pathname, body, respondedAt, responseStatus }) => ({
pathname,
videoId: body?.videoId,
value: body?.value,
respondedAt,
responseStatus,
})),
signals: adapter.pageSignals.snapshot(),
}),
contentType: "application/json",
});
}
throw error;
} finally {
// A navigation may cancel the browser request while its fake response is held.
// Unblock the route during teardown without requiring that cancelled response to finish.
for (const { held, seen } of heldRequests) {
if (!held.released && seen) {
held.release({ body: { dislikes: 999, likes: 1 } });
}
}
await adapter.close();
await apiServer.close();
}
}
async function expectWatchRemains(adapter, videoId, count) {
return assertInvariantContinuously({
durationMs: 1_000,
label: `Watch ${videoId} retains its current response`,
read: () => readCurrentWatch(adapter),
isValid: (snapshot) =>
snapshot.urlVideoId === videoId &&
snapshot.currentVideoId === videoId &&
snapshot.count === String(count) &&
snapshot.nativeDislikeVisible &&
snapshot.ownedVisibleBarCount === 1,
});
}
test("clearing a native Dislike clicked before initial counts settle submits a neutral vote", async ({}, testInfo) => {
await withExtension(testInfo, async ({ adapter, apiServer, deferVotes }) => {
const held = deferVotes();
await adapter.openWatch(VIDEO_A);
await expect.poll(() => voteDataRequests(adapter).length).toBe(1);
const dislike = adapter.page.locator("ytd-watch-flexy #top-row dislike-button-view-model button");
await dislike.click();
expect(await readCurrentWatch(adapter)).toMatchObject({ nativeDislikePressed: "true", ownedVisibleBarCount: 0 });
expect(apiServer.records.filter(({ pathname }) => pathname.startsWith("/interact/"))).toEqual([]);
held.release({ body: { dislikes: 25, likes: 100, rating: 4.5 } });
await adapter.waitForWatchResult(VIDEO_A);
expect(await readCurrentWatch(adapter)).toMatchObject({ nativeDislikePressed: "true" });
const interactionStart = apiServer.records.length;
await dislike.click();
expect(await readCurrentWatch(adapter)).toMatchObject({ nativeDislikePressed: "false" });
const readHandshake = () => readArtifactVoteHandshake(apiServer.records, interactionStart, VIDEO_A, 0);
await expect.poll(() => isArtifactVoteHandshakeValid(readHandshake())).toBe(true);
await assertInvariantContinuously({
durationMs: 1_000,
label: "Clearing the pending native Dislike submits exactly one neutral vote and confirmation",
read: readHandshake,
isValid: isArtifactVoteHandshakeValid,
});
expect(voteDataRequests(adapter)).toHaveLength(1);
await adapter.assertNoPageSignals("native-reaction-during-initial-votes");
});
});
test("destination initializes while the initial outgoing votes request remains pending", async ({}, testInfo) => {
await withExtension(
testInfo,
async ({ adapter, deferVotes }) => {
const held = deferVotes();
await adapter.openSpaWatch(VIDEO_A);
await expect.poll(() => voteDataRequests(adapter).length).toBe(1);
await adapter.navigateSpaWatchWhilePending(VIDEO_A, VIDEO_B);
const result = await adapter.waitForWatchResult(VIDEO_B);
expect(result.count).toBe(String(SPA_COUNTS[VIDEO_B].dislikes));
expect(held.released).toBe(false);
expect(voteDataRequests(adapter).map(({ query }) => query.videoId)).toEqual([VIDEO_A, VIDEO_B]);
await expectWatchRemains(adapter, VIDEO_B, SPA_COUNTS[VIDEO_B].dislikes);
held.release({ body: { dislikes: 999, likes: 1, rating: 1 } });
await expectWatchRemains(adapter, VIDEO_B, SPA_COUNTS[VIDEO_B].dislikes);
expect(voteDataRequests(adapter)).toHaveLength(2);
await adapter.assertNoPageSignals("pending-initial-votes-do-not-block-destination");
},
{ countsByVideo: SPA_COUNTS },
);
});
test("the watchdog initializes B with A pending when navigation emits no events", async ({}, testInfo) => {
await withExtension(
testInfo,
async ({ adapter, deferVotes }) => {
const held = deferVotes();
await adapter.openSpaWatch(VIDEO_A);
await expect.poll(() => voteDataRequests(adapter).length).toBe(1);
await adapter.page.evaluate((videoId) => {
globalThis.__navigationFixture.navigate("watch", videoId, { dispatchEvent: false });
}, VIDEO_B);
const result = await adapter.waitForWatchResult(VIDEO_B);
expect(result.count).toBe(String(SPA_COUNTS[VIDEO_B].dislikes));
expect(held.released).toBe(false);
expect(voteDataRequests(adapter).map(({ query }) => query.videoId)).toEqual([VIDEO_A, VIDEO_B]);
await expectWatchRemains(adapter, VIDEO_B, SPA_COUNTS[VIDEO_B].dislikes);
held.release({ body: { dislikes: 999, likes: 1, rating: 1 } });
await expectWatchRemains(adapter, VIDEO_B, SPA_COUNTS[VIDEO_B].dislikes);
expect(voteDataRequests(adapter)).toHaveLength(2);
await adapter.assertNoPageSignals("watchdog-recovers-pending-initial-votes-without-navigation-events");
},
{ countsByVideo: SPA_COUNTS },
);
});
test("navigation start does not restart outgoing A while the URL change is delayed", async ({}, testInfo) => {
await withExtension(
testInfo,
async ({ adapter, deferVotes }) => {
const held = deferVotes();
await adapter.openSpaWatch(VIDEO_A);
await expect.poll(() => voteDataRequests(adapter).length).toBe(1);
await adapter.page.evaluate(() => {
document.dispatchEvent(new Event("yt-navigate-start", { bubbles: true }));
});
await assertInvariantContinuously({
durationMs: 750,
label: "Navigation start suppresses outgoing requests before the URL changes",
read: async () => ({ watch: await readCurrentWatch(adapter), requestCount: voteDataRequests(adapter).length }),
isValid: ({ watch, requestCount }) =>
requestCount === 1 &&
watch.urlVideoId === VIDEO_A &&
watch.currentVideoId === VIDEO_A &&
watch.ownedVisibleBarCount === 0,
});
await adapter.page.evaluate((videoId) => {
globalThis.__navigationFixture.navigate("watch", videoId);
}, VIDEO_B);
const result = await adapter.waitForWatchResult(VIDEO_B);
expect(result.count).toBe(String(SPA_COUNTS[VIDEO_B].dislikes));
expect(held.released).toBe(false);
expect(voteDataRequests(adapter).map(({ query }) => query.videoId)).toEqual([VIDEO_A, VIDEO_B]);
held.release({ body: { dislikes: 999, likes: 1, rating: 1 } });
await expectWatchRemains(adapter, VIDEO_B, SPA_COUNTS[VIDEO_B].dislikes);
expect(voteDataRequests(adapter)).toHaveLength(2);
await adapter.assertNoPageSignals("navigation-start-does-not-restart-outgoing-initial-votes");
},
{ countsByVideo: SPA_COUNTS },
);
});
test("returning to A ignores the first A response still pending from before B", async ({}, testInfo) => {
await withExtension(
testInfo,
async ({ adapter, deferVotes }) => {
const firstA = deferVotes();
await adapter.openSpaWatch(VIDEO_A);
await expect.poll(() => voteDataRequests(adapter).length).toBe(1);
await adapter.navigateSpaWatchWhilePending(VIDEO_A, VIDEO_B);
await adapter.waitForWatchResult(VIDEO_B);
await adapter.page.evaluate((videoId) => {
document.dispatchEvent(new Event("yt-navigate-start", { bubbles: true }));
globalThis.__navigationFixture.navigate("watch", videoId);
}, VIDEO_A);
const result = await adapter.waitForWatchResult(VIDEO_A);
expect(result.count).toBe(String(SPA_COUNTS[VIDEO_A].dislikes));
expect(firstA.released).toBe(false);
expect(voteDataRequests(adapter).map(({ query }) => query.videoId)).toEqual([VIDEO_A, VIDEO_B, VIDEO_A]);
firstA.release({ body: { dislikes: 999, likes: 1, rating: 1 } });
await expectWatchRemains(adapter, VIDEO_A, SPA_COUNTS[VIDEO_A].dislikes);
expect(voteDataRequests(adapter)).toHaveLength(3);
await adapter.assertNoPageSignals("first-A-response-cannot-overwrite-returned-A");
},
{ countsByVideo: SPA_COUNTS },
);
});
test("HTTP 503 remains unavailable without automatic retries until a manual reload", async ({}, testInfo) => {
await withExtension(testInfo, async ({ adapter }) => {
adapter.backend.enqueue("GET", "/votes", { status: 503, body: { error: "test unavailable" } });
await adapter.openWatch(VIDEO_A);
await expect.poll(async () => (await readCurrentWatch(adapter)).count).toBe("Temporarily Unavailable");
expect(voteDataRequests(adapter)[0].responseStatus).toBe(503);
await assertInvariantContinuously({
durationMs: 2_500,
label: "HTTP 503 does not automatically retry across initialization watchdog cycles",
read: async () => ({ watch: await readCurrentWatch(adapter), requestCount: voteDataRequests(adapter).length }),
isValid: ({ watch, requestCount }) =>
requestCount === 1 &&
watch.count === "Temporarily Unavailable" &&
watch.nativeDislikeVisible &&
watch.ownedVisibleBarCount === 0,
});
await adapter.page.reload();
const result = await adapter.waitForWatchResult(VIDEO_A);
expect(result.count).toBe("25");
expect(voteDataRequests(adapter).map(({ responseStatus }) => responseStatus)).toEqual([503, 200]);
const { page } = adapter.pageSignals.snapshot();
expect(page.pageErrors).toEqual([]);
expect(page.unhandledRejections).toEqual([]);
expect(page.consoleErrors).toHaveLength(1);
expect(page.consoleErrors[0]).toMatchObject({
location: { url: voteDataRequests(adapter)[0].url },
text: "Failed to load resource: the server responded with a status of 503 (Service Unavailable)",
type: "error",
});
await adapter.workerSignals.assertClean("expected-503-without-retries");
});
});
@@ -0,0 +1,299 @@
const fs = require("node:fs");
const path = require("node:path");
const { devices, test, expect } = require("@playwright/test");
const {
HermeticExtensionArtifactAdapter,
isArtifactVoteHandshakeValid,
readArtifactVoteHandshake,
startHermeticApiServer,
} = require("../hermetic-artifact-smoke");
const { VIDEO_A, VIDEO_B, openNavigationFixture, openWatchFixture } = require("../../UserScript/e2e/harness");
const { LIVE_RUNTIME_PROFILES } = require("../live-runtime-adapter");
const REPOSITORY_ROOT = path.resolve(__dirname, "../../..");
const EXTENSION_ARTIFACT = path.resolve(
process.env.RYD_EXTENSION_ARTIFACT || path.join(REPOSITORY_ROOT, "Extensions", "combined", "dist", "chrome"),
);
const MOBILE_VIEWPORT = Object.freeze({ height: 844, width: 390 });
const MOBILE_CONTEXT_OPTIONS = Object.freeze({
deviceScaleFactor: 3,
hasTouch: true,
isMobile: true,
screen: MOBILE_VIEWPORT,
userAgent: devices["Pixel 5"].userAgent,
viewport: MOBILE_VIEWPORT,
});
const COUNTS = Object.freeze({
[VIDEO_A]: Object.freeze({ dislikes: 11, likes: 89 }),
[VIDEO_B]: Object.freeze({ dislikes: 35, likes: 65 }),
});
const CONSOLE_FAILURE_TYPES = new Set(["assert", "error", "warning"]);
function testFailed(testInfo, caughtError) {
return Boolean(caughtError) || (testInfo.status && testInfo.status !== testInfo.expectedStatus);
}
async function attachFailureEvidence(runtime, testInfo) {
const diagnostics = {
backgroundRequests: runtime.apiServer.records.map(({ body, method, pathname, query, responseStatus }) => ({
body,
method,
pathname,
query,
responseStatus,
})),
blockedRequests: runtime.adapter.backend?.blockedRequests ?? [],
pageSignals: runtime.adapter.pageSignals?.snapshot() ?? null,
routedRequests:
runtime.adapter.backend?.requests?.map(({ body, method, pathname, query, responseStatus }) => ({
body,
method,
pathname,
query,
responseStatus,
})) ?? [],
unexpectedBackgroundRequests: runtime.apiServer.unexpectedRequests,
workerConsoleFailures: runtime.workerConsoleFailures,
};
await testInfo.attach("mobile-extension-diagnostics", {
body: Buffer.from(JSON.stringify(diagnostics, null, 2)),
contentType: "application/json",
});
if (!runtime.page || runtime.page.isClosed()) return;
const screenshotPath = testInfo.outputPath("mobile-extension-failure.png");
await runtime.page.screenshot({ fullPage: true, path: screenshotPath }).catch(() => {});
if (fs.existsSync(screenshotPath)) {
await testInfo.attach("mobile-extension-page", { contentType: "image/png", path: screenshotPath });
}
}
async function withMobileExtension(testInfo, run) {
if (!fs.existsSync(path.join(EXTENSION_ARTIFACT, "manifest.json"))) {
throw new Error(
`The generated Chrome extension artifact is missing at ${EXTENSION_ARTIFACT}. ` +
"Run the extension production build first or set RYD_EXTENSION_ARTIFACT.",
);
}
const apiServer = await startHermeticApiServer();
const adapter = new HermeticExtensionArtifactAdapter({
apiServer,
artifactDirectory: EXTENSION_ARTIFACT,
backendOptions: { countsByVideo: COUNTS },
contextOptions: MOBILE_CONTEXT_OPTIONS,
});
const runtime = { adapter, apiServer, caughtError: null, page: null, workerConsoleFailures: [] };
try {
await adapter.start();
runtime.page = adapter.page;
adapter.worker.on("console", (message) => {
if (CONSOLE_FAILURE_TYPES.has(message.type())) {
runtime.workerConsoleFailures.push({ text: message.text(), type: message.type() });
}
});
await adapter.context.addInitScript(() => {
globalThis.__rydMobileActivationSignals = { click: 0, touchend: 0, touchstart: 0 };
for (const eventName of ["click", "touchend", "touchstart"]) {
document.addEventListener(
eventName,
(event) => {
if (event.target instanceof Element && event.target.closest("dislike-button-view-model")) {
globalThis.__rydMobileActivationSignals[eventName] += 1;
}
},
true,
);
}
});
const mobileRuntime = await runtime.page.evaluate(() => ({
coarsePointer: matchMedia("(pointer: coarse)").matches,
maxTouchPoints: navigator.maxTouchPoints,
userAgent: navigator.userAgent,
}));
expect(mobileRuntime.userAgent).toMatch(/Android/i);
expect(mobileRuntime.maxTouchPoints).toBeGreaterThan(0);
expect(mobileRuntime.coarsePointer).toBe(true);
await run(runtime);
await assertHermeticRuntime(runtime, testInfo.title);
} catch (error) {
runtime.caughtError = error;
throw error;
} finally {
if (adapter.context && testFailed(testInfo, runtime.caughtError)) {
await attachFailureEvidence(runtime, testInfo).catch(() => {});
}
await adapter.close().catch(() => {});
await apiServer.close().catch(() => {});
}
}
async function assertHermeticRuntime(runtime, scenarioId) {
await runtime.adapter.pageSignals.assertClean(scenarioId);
expect(runtime.workerConsoleFailures, "the MV3 background worker emitted a console failure").toEqual([]);
expect(runtime.adapter.backend.blockedRequests, "the page escaped the hermetic route set").toEqual([]);
expect(runtime.apiServer.unexpectedRequests, "the background worker escaped the fake protocol").toEqual([]);
}
async function expectVisibleReactionPair(root, { dislikes, likes }) {
const like = root.locator(":scope > like-button-view-model");
const dislike = root.locator(":scope > dislike-button-view-model");
const controls = root.locator(":scope > like-button-view-model, :scope > dislike-button-view-model");
const buttons = controls.locator("button");
await expect(root).toHaveCount(1);
await expect(root).toBeVisible();
await expect(controls, "the mobile reaction surface must contain exactly Like and Dislike").toHaveCount(2);
await expect(buttons, "each mobile reaction control must expose one activation button").toHaveCount(2);
await expect(like).toBeVisible();
await expect(dislike).toBeVisible();
await expect(like.locator("button")).toBeVisible();
await expect(dislike.locator("button")).toBeVisible();
await expect(like.locator("#text, [role='text']").first()).toHaveText(String(likes));
await expect(dislike.locator("#text, [role='text']").first()).toHaveText(String(dislikes));
await expect(like.locator("button")).toHaveAttribute("aria-label", /like/i);
await expect(dislike.locator("button")).toHaveAttribute("aria-label", /dislike/i);
const boxes = await buttons.evaluateAll((elements) =>
elements.map((element) => {
const box = element.getBoundingClientRect();
return { height: box.height, width: box.width };
}),
);
expect(boxes).toHaveLength(2);
for (const box of boxes) {
expect(box.height).toBeGreaterThan(0);
expect(box.width).toBeGreaterThan(0);
}
}
function statsRequests(runtime, videoId) {
return runtime.adapter.backend.requestsFor("GET", "/votes").filter((request) => request.query.videoId === videoId);
}
function interactionRecords(runtime, startIndex) {
return runtime.apiServer.records
.slice(startIndex)
.filter(
(record) => record.method === "POST" && ["/interact/vote", "/interact/confirmVote"].includes(record.pathname),
);
}
test.describe("generated extension artifact on the mobile YouTube hostname", () => {
test("direct mobile Watch renders the complete reaction surface at compact width", async ({}, testInfo) => {
await withMobileExtension(testInfo, async (runtime) => {
await openWatchFixture(runtime.page, VIDEO_A, { hostname: "m.youtube.com" });
await expect(runtime.page).toHaveURL(
(url) => url.hostname === "m.youtube.com" && url.searchParams.get("v") === VIDEO_A,
);
const mobileActionBar = runtime.page.locator('.slim-video-action-bar-actions[data-fixture-shell="mobile"]');
await expect(mobileActionBar).toBeVisible();
await expectVisibleReactionPair(mobileActionBar.locator(":scope > .segmented-buttons"), COUNTS[VIDEO_A]);
expect(statsRequests(runtime, VIDEO_A)).toHaveLength(1);
await expect(runtime.page.locator(".ryd-tooltip, #ryd-bar-container, #ryd-bar")).toHaveCount(0);
expect(interactionRecords(runtime, 0)).toHaveLength(0);
});
});
test("native-dependent mobile Shorts compatibility binds B and submits one dislike handshake", async ({}, testInfo) => {
await withMobileExtension(testInfo, async (runtime) => {
await openNavigationFixture(runtime.page, {
hostname: "m.youtube.com",
pageKind: "shorts",
videoId: VIDEO_A,
});
await expect(runtime.page).toHaveURL(
(url) => url.hostname === "m.youtube.com" && url.pathname === `/shorts/${VIDEO_A}`,
);
expect(LIVE_RUNTIME_PROFILES.extension.capabilities.shortsControlModelBySurface).toEqual({
desktop: "synthetic-owned",
mobile: "native-youtube-required",
});
expect(
await runtime.page.evaluate(() => globalThis.__navigationFixtureBaseline.renderedMobileShortsNativeDislikes),
"this scenario is native-host compatibility, not absent-native mobile coverage",
).toBe(1);
const rendererA = runtime.page.locator(`ytm-reel-video-renderer[video-id="${VIDEO_A}"]`);
await expect(rendererA).toHaveAttribute("is-active", "");
await expect(rendererA).toBeVisible();
await expectVisibleReactionPair(rendererA.locator("ytm-like-button-renderer"), COUNTS[VIDEO_A]);
await expect(rendererA.locator("[data-ryd-synthetic-shorts-dislike]")).toHaveCount(0);
expect(statsRequests(runtime, VIDEO_A)).toHaveLength(1);
await runtime.page.locator("#short-next").click();
await expect(runtime.page).toHaveURL(
(url) => url.hostname === "m.youtube.com" && url.pathname === `/shorts/${VIDEO_B}`,
);
const activeB = runtime.page.locator(`ytm-reel-video-renderer[video-id="${VIDEO_B}"][is-active]`);
await expect(runtime.page.locator("ytm-reel-video-renderer[is-active]")).toHaveCount(1);
await expect(runtime.page.locator("ytm-reel-video-renderer:visible")).toHaveCount(1);
await expect(rendererA).not.toHaveAttribute("is-active", "");
await expect(rendererA).toBeHidden();
await expect(activeB).toBeVisible();
const controlsB = activeB.locator("ytm-like-button-renderer");
await expectVisibleReactionPair(controlsB, COUNTS[VIDEO_B]);
await expect(activeB.locator("[data-ryd-synthetic-shorts-dislike]")).toHaveCount(0);
expect(statsRequests(runtime, VIDEO_A)).toHaveLength(1);
expect(statsRequests(runtime, VIDEO_B)).toHaveLength(1);
const interactionStartIndex = runtime.apiServer.records.length;
expect(interactionRecords(runtime, 0)).toHaveLength(0);
const dislikeButton = controlsB.locator(":scope > dislike-button-view-model button");
const dislikeBox = await dislikeButton.boundingBox();
expect(dislikeBox, "the active mobile Shorts Dislike button must have a tappable box").not.toBeNull();
await runtime.page.touchscreen.tap(dislikeBox.x + dislikeBox.width / 2, dislikeBox.y + dislikeBox.height / 2);
await expect
.poll(() =>
isArtifactVoteHandshakeValid(
readArtifactVoteHandshake(runtime.apiServer.records, interactionStartIndex, VIDEO_B, -1),
),
)
.toBe(true);
await runtime.page.waitForTimeout(400);
const handshake = readArtifactVoteHandshake(runtime.apiServer.records, interactionStartIndex, VIDEO_B, -1);
expect(handshake).toMatchObject({
confirmationCount: 1,
expectedValue: -1,
expectedVideoId: VIDEO_B,
interactionCount: 2,
interactionPaths: ["/interact/vote", "/interact/confirmVote"],
voteCount: 1,
});
expect(handshake.vote.body).toEqual({
userId: expect.stringMatching(/^[A-Za-z0-9]{36}$/),
value: -1,
videoId: VIDEO_B,
});
expect(handshake.vote).toMatchObject({ responded: true, responseStatus: 200 });
expect(handshake.confirmation.body).toEqual({
solution: expect.any(String),
userId: handshake.vote.body.userId,
videoId: VIDEO_B,
});
expect(Buffer.from(handshake.confirmation.body.solution, "base64")).toHaveLength(4);
expect(handshake.confirmation).toMatchObject({ responded: true, responseBody: true, responseStatus: 200 });
expect(interactionRecords(runtime, interactionStartIndex)).toHaveLength(2);
expect(interactionRecords(runtime, 0)).toHaveLength(2);
await expect
.poll(() => runtime.page.evaluate(() => ({ ...globalThis.__rydMobileActivationSignals })))
.toEqual({ click: 1, touchend: 1, touchstart: 1 });
expect(runtime.adapter.backend.requestsFor("POST", "/interact/vote")).toHaveLength(0);
expect(runtime.adapter.backend.requestsFor("POST", "/interact/confirmVote")).toHaveLength(0);
await expectVisibleReactionPair(controlsB, {
dislikes: COUNTS[VIDEO_B].dislikes + 1,
likes: COUNTS[VIDEO_B].likes,
});
await expect(rendererA.locator('[data-fixture-role="dislike"] #text')).toHaveText(
String(COUNTS[VIDEO_A].dislikes),
);
expect(statsRequests(runtime, VIDEO_A)).toHaveLength(1);
expect(statsRequests(runtime, VIDEO_B)).toHaveLength(1);
});
});
});
@@ -0,0 +1,493 @@
const DEFAULT_VIDEO_IDS = Object.freeze({
A: "abcdefghijk",
B: "zyxwvutsrqp",
C: "mnopqrstuvw",
});
function createExtensionNavigationFixture({ initialVideoId = DEFAULT_VIDEO_IDS.A, likesByVideo = {} } = {}) {
const configuration = JSON.stringify({ initialVideoId, likesByVideo, videoIds: DEFAULT_VIDEO_IDS });
return `<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Extension navigation lifecycle fixture</title>
<style>
:root {
--yt-spec-base-background: #0f0f0f;
--yt-spec-text-primary: #f1f1f1;
}
* {
box-sizing: border-box;
}
body {
background: var(--yt-spec-base-background);
color: var(--yt-spec-text-primary);
font: 14px Arial, sans-serif;
margin: 0;
min-height: 100vh;
padding: 24px;
}
[hidden] {
display: none !important;
}
ytd-watch-flexy {
display: block;
min-height: 420px;
width: min(920px, calc(100vw - 48px));
}
#player {
background: #000;
display: block;
height: 180px;
margin-bottom: 18px;
width: 320px;
}
ytd-menu-renderer.ytd-watch-metadata {
align-items: flex-start;
display: flex;
gap: 20px;
min-height: 82px;
width: 760px;
}
.fixture-action-host,
#flexible-item-buttons {
align-items: flex-start;
display: flex;
min-height: 54px;
position: relative;
}
.fixture-action-host {
width: 240px;
}
#flexible-item-buttons {
gap: 8px;
width: 220px;
}
segmented-like-dislike-button-view-model,
yt-smartimation,
[data-fixture-smartimation-content-shell] {
display: block;
min-height: 48px;
width: 184px;
}
[data-fixture-smartimation-content] {
align-items: flex-start;
display: flex;
min-height: 48px;
width: 184px;
}
like-button-view-model,
dislike-button-view-model,
button-view-model {
display: block;
min-height: 40px;
width: 88px;
}
button-view-model {
width: 100px;
}
button {
align-items: center;
background: #272727;
border: 0;
border-radius: 18px;
color: #f1f1f1;
display: flex;
height: 36px;
justify-content: center;
min-width: 80px;
padding: 0 12px;
}
.ytSpecButtonShapeNextButtonTextContent {
align-items: center;
display: flex;
min-height: 18px;
}
[data-fixture-icon] {
height: 20px;
width: 20px;
}
[data-fixture-touch-feedback] {
display: none;
}
.fixture-navigation {
display: flex;
gap: 12px;
margin-top: 24px;
}
.fixture-navigation a {
color: #3ea6ff;
}
</style>
</head>
<body>
<main id="fixture-root"></main>
<script>
(() => {
const configuration = ${configuration};
const fixtureRoot = document.querySelector("#fixture-root");
const transitionLog = [];
let currentVideoId = configuration.initialVideoId;
let hostSequence = 0;
let pendingHydration = null;
let phase = "booting";
const escapeAttribute = (value) => String(value).replaceAll("&", "&amp;").replaceAll('"', "&quot;");
function nativeButtonMarkup(role, videoId) {
if (role === "like") {
const likeCount = configuration.likesByVideo[videoId] ?? 100;
return \`
<toggle-button-view-model>
<button-view-model>
<button type="button" data-fixture-native-role="like" aria-label="\${likeCount} likes for \${escapeAttribute(videoId)}" aria-pressed="false">
<svg data-fixture-icon="like" aria-hidden="true" viewBox="0 0 24 24">
<path fill="currentColor" d="M8 21H5V9h3v12Zm2 0V9l4-7 2 1v5h5v5l-3 8h-8Z"></path>
</svg>
<div class="ytSpecButtonShapeNextButtonTextContent" data-fixture-provided-native-text><span id="text" role="text">\${likeCount}</span></div>
<span data-fixture-touch-feedback aria-hidden="true"></span>
</button>
</button-view-model>
</toggle-button-view-model>\`;
}
return \`
<toggle-button-view-model>
<button-view-model>
<button type="button" data-fixture-native-role="dislike" aria-label="Dislike \${escapeAttribute(videoId)}" aria-pressed="false">
<svg data-fixture-icon="dislike" aria-hidden="true" viewBox="0 0 24 24">
<path fill="currentColor" d="M16 3h3v12h-3V3Zm-2 0v12l-4 7-2-1v-5H3v-5l3-8h8Z"></path>
</svg>
<span data-fixture-touch-feedback aria-hidden="true"></span>
</button>
</button-view-model>
</toggle-button-view-model>\`;
}
function reactionGroupMarkup(videoId, hydrated) {
return \`
<segmented-like-dislike-button-view-model data-fixture-reaction-group data-fixture-control-video-id="\${escapeAttribute(videoId)}">
<yt-smartimation>
<div id="content" data-fixture-smartimation-content-shell>
<div id="wrapper" data-fixture-smartimation-content>
<like-button-view-model class="style-text" data-fixture-role="like">
\${hydrated ? nativeButtonMarkup("like", videoId) : ""}
</like-button-view-model>
<dislike-button-view-model class="style-text" data-fixture-role="dislike">
\${hydrated ? nativeButtonMarkup("dislike", videoId) : ""}
</dislike-button-view-model>
</div>
</div>
</yt-smartimation>
</segmented-like-dislike-button-view-model>\`;
}
function createActionHost(videoId, { hydrated = true } = {}) {
const host = document.createElement("div");
host.id = "top-level-buttons-computed";
host.className = "fixture-action-host";
host.dataset.fixtureCurrentActions = "true";
host.dataset.fixtureHostIdentity = String(++hostSequence);
host.innerHTML = reactionGroupMarkup(videoId, hydrated);
host.dataset.fixtureNativeDislikeTextCount = String(
host.querySelectorAll(
'dislike-button-view-model [data-fixture-native-role="dislike"] .ytSpecButtonShapeNextButtonTextContent',
).length,
);
return host;
}
function createUnrelatedGroup() {
const group = document.createElement("div");
group.id = "flexible-item-buttons";
group.dataset.fixtureUnrelatedActions = "true";
group.innerHTML = \`
<button-view-model data-fixture-unrelated-control="share">
<button type="button" aria-label="Share"><div><span role="text">Share</span></div></button>
</button-view-model>
<button-view-model data-fixture-unrelated-control="download">
<button type="button" aria-label="Download"><div><span role="text">Download</span></div></button>
</button-view-model>\`;
return group;
}
function createHiddenDuplicate(videoId) {
const duplicate = createActionHost(videoId, { hydrated: true });
duplicate.hidden = true;
duplicate.dataset.fixtureHiddenDuplicate = "true";
delete duplicate.dataset.fixtureCurrentActions;
return duplicate;
}
function currentRoot() {
return fixtureRoot.querySelector("ytd-watch-flexy");
}
function currentMenu() {
return currentRoot()?.querySelector("ytd-menu-renderer.ytd-watch-metadata");
}
function currentHost() {
return currentMenu()?.querySelector('[data-fixture-current-actions="true"]');
}
function installDecoys(videoId) {
const menu = currentMenu();
if (!menu) throw new Error("Cannot install decoys without a watch menu");
menu.querySelector('[data-fixture-unrelated-actions="true"]')?.remove();
menu.querySelector('[data-fixture-hidden-duplicate="true"]')?.remove();
menu.append(createUnrelatedGroup(), createHiddenDuplicate(videoId));
}
function renderShell(videoId, { delayed = false } = {}) {
fixtureRoot.innerHTML = \`
<ytd-watch-flexy video-id="\${escapeAttribute(videoId)}">
<div id="player" loading="false"></div>
<div id="top-row">
<ytd-menu-renderer class="ytd-watch-metadata"></ytd-menu-renderer>
</div>
<div id="retained-action-hosts" hidden></div>
<nav class="fixture-navigation" aria-label="Fixture navigation">
<a id="fixture-recommendation" href="/watch?v=\${configuration.videoIds.B}&rydExtensionLifecycle=1">Recommendation</a>
<a id="fixture-playlist" href="/watch?v=\${configuration.videoIds.B}&list=fixture&rydExtensionLifecycle=1">Playlist next</a>
<a id="fixture-history-next" href="/watch?v=\${configuration.videoIds.B}&rydExtensionLifecycle=1">History next</a>
</nav>
</ytd-watch-flexy>\`;
currentMenu().append(createActionHost(videoId, { hydrated: !delayed }));
installDecoys(videoId);
phase = delayed ? "skeleton" : "ready";
if (delayed) {
pendingHydration = () => hydrateHostInPlace(currentHost(), videoId);
}
}
function stripHostForHydration(host, videoId) {
host.querySelectorAll(".ryd-tooltip").forEach((element) => element.remove());
const group = host.querySelector("[data-fixture-reaction-group]");
group.dataset.fixtureControlVideoId = videoId;
for (const role of ["like", "dislike"]) {
const control = group.querySelector(\`[data-fixture-role="\${role}"]\`);
control.classList.remove("style-default-active");
control.classList.add("style-text");
control.replaceChildren();
}
host.dataset.fixtureHydrationState = "skeleton";
}
function hydrateHostInPlace(host, videoId) {
if (!host?.isConnected) throw new Error("Cannot hydrate a disconnected action host");
const group = host.querySelector("[data-fixture-reaction-group]");
group.dataset.fixtureControlVideoId = videoId;
for (const role of ["like", "dislike"]) {
const control = group.querySelector(\`[data-fixture-role="\${role}"]\`);
control.innerHTML = nativeButtonMarkup(role, videoId);
}
host.dataset.fixtureNativeDislikeTextCount = String(
host.querySelectorAll(
'dislike-button-view-model [data-fixture-native-role="dislike"] .ytSpecButtonShapeNextButtonTextContent',
).length,
);
host.dataset.fixtureHydrationState = "ready";
}
function updateNativeLikeCount(host, videoId) {
const likeCount = configuration.likesByVideo[videoId] ?? 100;
const likeButton = host.querySelector('[data-fixture-native-role="like"]');
likeButton?.setAttribute("aria-label", \`\${likeCount} likes for \${escapeAttribute(videoId)}\`);
const likeText = likeButton?.querySelector("#text, [role='text']");
if (likeText) likeText.textContent = String(likeCount);
}
function beginNavigation(videoId, { mode, pushState, trigger }) {
if (pendingHydration) throw new Error("A fixture hydration is already pending");
const root = currentRoot();
const menu = currentMenu();
const outgoingHost = currentHost();
if (!root || !menu || !outgoingHost) throw new Error("The outgoing watch controls are not ready");
document.dispatchEvent(new Event("yt-navigate-start", { bubbles: true }));
if (pushState) {
const list = trigger === "playlist" ? "&list=fixture" : "";
history.pushState(
{ videoId },
"",
\`/watch?v=\${videoId}\${list}&rydExtensionLifecycle=1\`,
);
}
currentVideoId = videoId;
root.setAttribute("video-id", videoId);
let destinationHost;
if (mode === "reuse-visible") {
destinationHost = outgoingHost;
updateNativeLikeCount(destinationHost, videoId);
} else if (mode === "reuse-in-place") {
destinationHost = outgoingHost;
stripHostForHydration(destinationHost, videoId);
pendingHydration = () => hydrateHostInPlace(destinationHost, videoId);
} else if (mode === "replace-host") {
outgoingHost.removeAttribute("id");
delete outgoingHost.dataset.fixtureCurrentActions;
outgoingHost.dataset.fixtureRetainedOutgoing = "true";
root.querySelector("#retained-action-hosts").append(outgoingHost);
destinationHost = createActionHost(videoId, { hydrated: false });
menu.prepend(destinationHost);
pendingHydration = () => {
const replacement = createActionHost(videoId, { hydrated: true });
destinationHost.replaceWith(replacement);
};
} else {
throw new Error(\`Unknown fixture hydration mode: \${mode}\`);
}
installDecoys(videoId);
phase = mode === "reuse-visible" ? "visible-outgoing" : "skeleton";
transitionLog.push({ mode, phase, trigger, videoId });
document.dispatchEvent(new Event("yt-navigate-finish", { bubbles: true }));
}
function hydratePending() {
if (!pendingHydration) throw new Error("No fixture hydration is pending");
const hydrate = pendingHydration;
pendingHydration = null;
hydrate();
phase = "hydrated";
transitionLog.push({ phase, videoId: currentVideoId });
}
function replaceReadyHost() {
if (pendingHydration) throw new Error("Cannot replace controls while hydration is pending");
const host = currentHost();
if (!host) throw new Error("The current fixture action host is missing");
const replacement = createActionHost(currentVideoId, { hydrated: true });
host.replaceWith(replacement);
transitionLog.push({ phase: "ready-host-replaced", videoId: currentVideoId });
return replacement.dataset.fixtureHostIdentity;
}
function snapshot() {
const root = currentRoot();
const host = currentHost();
const unrelated = root?.querySelector('[data-fixture-unrelated-actions="true"]');
const hiddenDuplicate = root?.querySelector('[data-fixture-hidden-duplicate="true"]');
const normalize = (element) => (element?.textContent ?? "").replace(/\\s+/g, " ").trim();
const currentCountContainer = host?.querySelector(
'dislike-button-view-model [data-fixture-native-role="dislike"] .ytSpecButtonShapeNextButtonTextContent',
);
return {
currentBarCount: host?.querySelectorAll("#ryd-bar").length ?? -1,
currentButtonCount: host?.querySelectorAll('[data-fixture-native-role="like"], [data-fixture-native-role="dislike"]').length ?? -1,
currentCount: normalize(currentCountContainer),
currentCountContainerCount:
host?.querySelectorAll(
'dislike-button-view-model [data-fixture-native-role="dislike"] .ytSpecButtonShapeNextButtonTextContent',
).length ?? -1,
currentCountCreatedByRuntime:
Boolean(currentCountContainer) && Number(host?.dataset.fixtureNativeDislikeTextCount ?? -1) === 0,
currentFixtureControlVideoId:
host?.querySelector("[data-fixture-reaction-group]")?.dataset.fixtureControlVideoId ?? null,
currentHostIdentity: host?.dataset.fixtureHostIdentity ?? null,
currentNativeDislikeTextCount: Number(host?.dataset.fixtureNativeDislikeTextCount ?? -1),
currentVideoId,
globalBarCount: document.querySelectorAll("#ryd-bar").length,
globalContainerCount: document.querySelectorAll("#ryd-bar-container").length,
globalWrapperCount: document.querySelectorAll(".ryd-tooltip").length,
hiddenDuplicateBarCount: hiddenDuplicate?.querySelectorAll("#ryd-bar").length ?? -1,
phase,
retainedBarCount: root?.querySelectorAll('[data-fixture-retained-outgoing="true"] #ryd-bar').length ?? 0,
transitionLog: transitionLog.map((entry) => ({ ...entry })),
unrelatedBarCount: unrelated?.querySelectorAll("#ryd-bar").length ?? -1,
unrelatedLabels: [...(unrelated?.querySelectorAll("span[role='text']") ?? [])].map(normalize),
urlVideoId: new URL(location.href).searchParams.get("v"),
};
}
fixtureRoot.addEventListener("click", (event) => {
const navigation = event.target.closest("a");
if (navigation) {
if (navigation.id === "fixture-recommendation") {
event.preventDefault();
beginNavigation(configuration.videoIds.B, {
mode: "reuse-visible",
pushState: true,
trigger: "recommendation",
});
} else if (navigation.id === "fixture-playlist") {
event.preventDefault();
beginNavigation(configuration.videoIds.B, {
mode: "replace-host",
pushState: true,
trigger: "playlist",
});
} else if (navigation.id === "fixture-history-next") {
event.preventDefault();
beginNavigation(configuration.videoIds.B, {
mode: "replace-host",
pushState: true,
trigger: "history-push",
});
}
return;
}
const reactionButton = event.target.closest("button[data-fixture-native-role]");
if (!reactionButton) return;
const role = reactionButton.dataset.fixtureNativeRole;
const group = reactionButton.closest("[data-fixture-reaction-group]");
const otherRole = role === "like" ? "dislike" : "like";
const pressed = reactionButton.getAttribute("aria-pressed") === "true";
reactionButton.setAttribute("aria-pressed", String(!pressed));
group
?.querySelector(\`button[data-fixture-native-role="\${otherRole}"]\`)
?.setAttribute("aria-pressed", "false");
});
addEventListener("popstate", (event) => {
const targetVideoId = event.state?.videoId ?? new URL(location.href).searchParams.get("v");
beginNavigation(targetVideoId, {
mode: "replace-host",
pushState: false,
trigger: "history-pop",
});
});
const initialUrl = new URL(location.href);
history.replaceState({ videoId: currentVideoId }, "", initialUrl);
renderShell(currentVideoId, { delayed: initialUrl.searchParams.get("initial") === "delayed" });
globalThis.__extensionLifecycleFixture = {
beginNavigation,
hydratePending,
replaceReadyHost,
snapshot,
videoIds: { ...configuration.videoIds },
};
})();
</script>
</body>
</html>`;
}
module.exports = {
DEFAULT_VIDEO_IDS,
createExtensionNavigationFixture,
};
@@ -0,0 +1,62 @@
const fs = require("node:fs");
const os = require("node:os");
const path = require("node:path");
const { test, expect } = require("@playwright/test");
const { VIDEO_A } = require("../../UserScript/e2e/harness");
const { HermeticExtensionArtifactAdapter, startHermeticApiServer } = require("../hermetic-artifact-smoke");
const REPOSITORY_ROOT = path.resolve(__dirname, "../../..");
const EXTENSION_ARTIFACT = path.resolve(
process.env.RYD_EXTENSION_ARTIFACT || path.join(REPOSITORY_ROOT, "Extensions", "combined", "dist", "chrome"),
);
const PRODUCTION_API_ORIGIN = "https://returnyoutubedislikeapi.com";
function removeOwnedOracleDirectory(directory) {
const resolved = path.resolve(directory);
expect(path.dirname(resolved)).toBe(path.resolve(os.tmpdir()));
expect(path.basename(resolved)).toMatch(/^ryd-render-oracle-/);
fs.rmSync(resolved, { force: true, recursive: true });
}
test("the render oracle rejects a generated extension whose content script does nothing", async () => {
expect(
fs.existsSync(path.join(EXTENSION_ARTIFACT, "manifest.json")),
`The generated Chrome extension artifact is missing at ${EXTENSION_ARTIFACT}`,
).toBe(true);
const oracleRoot = fs.mkdtempSync(path.join(os.tmpdir(), "ryd-render-oracle-"));
const brokenArtifact = path.join(oracleRoot, "extension");
fs.cpSync(EXTENSION_ARTIFACT, brokenArtifact, { recursive: true });
fs.writeFileSync(
path.join(brokenArtifact, "ryd.content-script.js"),
`void ${JSON.stringify(PRODUCTION_API_ORIGIN)};`,
);
const apiServer = await startHermeticApiServer();
const adapter = new HermeticExtensionArtifactAdapter({
apiServer,
artifactDirectory: brokenArtifact,
backendOptions: { fixture: { nativeDislikeText: false, roleAttribute: "data-fixture-role" } },
});
try {
await adapter.start();
adapter.page.setDefaultTimeout(1_500);
await adapter.openWatch(VIDEO_A);
await expect(adapter.waitForWatchResult(VIDEO_A)).rejects.toThrow(/Timeout|did not render/i);
await expect(adapter.page.locator("#ryd-bar-container")).toHaveCount(0);
await expect(adapter.page.locator("#ryd-bar")).toHaveCount(0);
await expect(
adapter.page.locator(
"dislike-button-view-model #text, " +
"dislike-button-view-model [role='text'], " +
"dislike-button-view-model .ytSpecButtonShapeNextButtonTextContent",
),
).toHaveCount(0);
} finally {
await adapter.close().catch(() => {});
await apiServer.close().catch(() => {});
removeOwnedOracleDirectory(oracleRoot);
}
});
@@ -0,0 +1,30 @@
const { test } = require("@playwright/test");
const { HermeticExtensionArtifactAdapter, SPA_COUNTS, startHermeticApiServer } = require("../hermetic-artifact-smoke");
const {
registerRuntimeResilienceContractScenarios,
runRuntimeResilienceContract,
} = require("../runtime-resilience-contract");
registerRuntimeResilienceContractScenarios({
runtimeName: "extension",
register: ({ scenario, title }) => {
test(title, async () => {
const apiServer = await startHermeticApiServer();
try {
await runRuntimeResilienceContract({
scenario,
createAdapter: ({ gateMode }) =>
new HermeticExtensionArtifactAdapter({
apiServer,
backendOptions: {
countsByVideo: SPA_COUNTS,
fixture: { signedIn: gateMode !== "signed-out" },
},
}),
});
} finally {
await apiServer.close();
}
});
},
});
@@ -0,0 +1,53 @@
const fs = require("node:fs");
const path = require("node:path");
const { test, expect } = require("@playwright/test");
const { VIDEO_A, openWatchFixture } = require("../../UserScript/e2e/harness");
const { HermeticExtensionArtifactAdapter, startHermeticApiServer } = require("../hermetic-artifact-smoke");
const REPOSITORY_ROOT = path.resolve(__dirname, "../../..");
const EXTENSION_ARTIFACT = path.resolve(
process.env.RYD_EXTENSION_ARTIFACT || path.join(REPOSITORY_ROOT, "Extensions", "combined", "dist", "chrome"),
);
test("bundled selectors initialize Watch when the remote selector request never settles", async () => {
expect(
fs.existsSync(path.join(EXTENSION_ARTIFACT, "manifest.json")),
`The generated Chrome extension artifact is missing at ${EXTENSION_ARTIFACT}`,
).toBe(true);
const apiServer = await startHermeticApiServer();
const adapter = new HermeticExtensionArtifactAdapter({
apiServer,
artifactDirectory: EXTENSION_ARTIFACT,
selectorResponse: () => new Promise(() => {}),
});
try {
await adapter.start();
adapter.page.setDefaultTimeout(4_000);
await openWatchFixture(adapter.page, VIDEO_A);
const result = await adapter.waitForWatchResult(VIDEO_A);
expect(result).toMatchObject({
actionSurfaceVisible: true,
count: "25",
countVisible: true,
fillVisible: true,
ownedByExpectedWatch: true,
rateBarVisible: true,
sameActionSurface: true,
videoId: VIDEO_A,
});
const selectorRequests = adapter.backend.requestsFor("GET", "/configs/selectors");
expect(selectorRequests).toHaveLength(1);
expect(selectorRequests[0].respondedAt).toBeUndefined();
expect(adapter.backend.requestsFor("GET", "/votes").map(({ query }) => query.videoId)).toEqual([VIDEO_A]);
expect(adapter.backend.blockedRequests).toEqual([]);
expect(apiServer.unexpectedRequests).toEqual([]);
await adapter.pageSignals.assertClean("hanging-selector-startup-fallback");
} finally {
await adapter.close().catch(() => {});
await apiServer.close().catch(() => {});
}
});
@@ -0,0 +1,39 @@
const fs = require("node:fs");
const path = require("node:path");
const { test, expect } = require("@playwright/test");
const { HermeticExtensionArtifactAdapter, startHermeticApiServer } = require("../hermetic-artifact-smoke");
const REPOSITORY_ROOT = path.resolve(__dirname, "../../..");
const EXTENSION_ARTIFACT = path.resolve(
process.env.RYD_EXTENSION_ARTIFACT || path.join(REPOSITORY_ROOT, "Extensions", "combined", "dist", "chrome"),
);
const INTENTIONAL_REJECTION = "intentional MV3 rejection probe";
test("the runtime guard detects an unhandled rejection in the real MV3 worker", async () => {
expect(
fs.existsSync(path.join(EXTENSION_ARTIFACT, "manifest.json")),
`The generated Chrome extension artifact is missing at ${EXTENSION_ARTIFACT}`,
).toBe(true);
const apiServer = await startHermeticApiServer();
const adapter = new HermeticExtensionArtifactAdapter({ apiServer, artifactDirectory: EXTENSION_ARTIFACT });
try {
await adapter.start();
await adapter.worker.evaluate((message) => {
void Promise.reject(new Error(message));
}, INTENTIONAL_REJECTION);
await expect
.poll(() => apiServer.workerSignals.some((signal) => signal.message === INTENTIONAL_REJECTION))
.toBe(true);
await expect(adapter.pageSignals.assertClean("intentional-worker-rejection-negative-control")).rejects.toThrow(
new RegExp(INTENTIONAL_REJECTION),
);
expect(apiServer.unexpectedRequests).toEqual([]);
expect(adapter.backend.blockedRequests).toEqual([]);
} finally {
await adapter.close().catch(() => {});
await apiServer.close().catch(() => {});
}
});
@@ -0,0 +1,128 @@
const { test, expect } = require("@playwright/test");
const { HermeticExtensionArtifactAdapter, startHermeticApiServer } = require("../hermetic-artifact-smoke");
const messages = require("../../combined/_locales/en/messages.json");
for (const scenario of ["success", "unavailable", "not_contributor", "wrong-state"]) {
test(`built popup GitHub login: ${scenario}`, async ({}, testInfo) => {
const apiServer = await startHermeticApiServer();
const adapter = new HermeticExtensionArtifactAdapter({ apiServer });
const diagnostics = [];
try {
await adapter.start();
adapter.page.on("pageerror", (error) => diagnostics.push(error.message));
adapter.page.on("console", (message) => {
if (message.type() === "error") diagnostics.push(message.text());
});
await adapter.worker.evaluate((scenario) => {
const originalFetch = globalThis.fetch.bind(globalThis);
const redirectUri = `https://${chrome.runtime.id}.chromiumapp.org/`;
const ledger = (globalThis.githubLoginFixture = { opens: 0, exchanges: 0, pkceVerified: false });
let challenge;
chrome.identity = {
getRedirectURL: () => redirectUri,
launchWebAuthFlow: ({ url }, callback) => {
ledger.opens++;
const authUrl = new URL(url);
const state = scenario === "wrong-state" ? "another-attempt" : authUrl.searchParams.get("state");
const responseUrl = `${redirectUri}?code=fixture-code&state=${state}`;
callback?.(responseUrl);
return Promise.resolve(responseUrl);
},
};
if (typeof browser !== "undefined") browser.identity = chrome.identity;
globalThis.fetch = async (url, options) => {
const parsed = new URL(url);
if (parsed.pathname === "/api/auth/github/login") {
if (scenario === "unavailable") return Response.json({ error: "github_not_configured" }, { status: 503 });
challenge = parsed.searchParams.get("codeChallenge");
const params = new URLSearchParams({
state: "fixture-state",
redirect_uri: redirectUri,
code_challenge: challenge,
code_challenge_method: "S256",
});
return Response.json({
authUrl: `https://github.com/login/oauth/authorize?${params}`,
state: "fixture-state",
redirectUri,
});
}
if (parsed.pathname === "/api/auth/github/exchange") {
ledger.exchanges++;
const body = JSON.parse(options.body);
const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(body.codeVerifier));
const actual = btoa(String.fromCharCode(...new Uint8Array(digest)))
.replace(/\+/g, "-")
.replace(/\//g, "_")
.replace(/=+$/, "");
ledger.pkceVerified =
actual === challenge && body.state === "fixture-state" && body.redirectUri === redirectUri;
if (!ledger.pkceVerified) return Response.json({ error: "github_invalid_state" }, { status: 400 });
if (scenario === "not_contributor") return Response.json({ error: "not_contributor" }, { status: 403 });
return Response.json({
success: true,
sessionToken: "fixture-session",
user: {
id: "gh_42",
fullName: "Test Contributor",
imageUrl: "",
hasActiveMembership: true,
membershipTier: "premium",
authProvider: "github",
githubLogin: "fixture-contributor",
},
});
}
return originalFetch(url, options);
};
}, scenario);
await adapter.page.goto(`chrome-extension://${adapter.extensionId}/popup.html`);
await adapter.page.evaluate(() => {
// Keep the browser/provider boundary deterministic; the bundled click handler still runs.
chrome.permissions.contains = (permissions, callback) => callback(true);
chrome.identity = { getRedirectURL: () => `https://${chrome.runtime.id}.chromiumapp.org/` };
});
const expectedMessage = {
unavailable: "githubLoginUnavailable",
not_contributor: "githubLoginNotContributor",
"wrong-state": "githubLoginExpired",
}[scenario];
const dialogs = [];
adapter.page.on("dialog", async (dialog) => {
dialogs.push(dialog.message());
await dialog.dismiss();
});
await adapter.page.locator("#github-login-btn").click();
if (expectedMessage) {
await expect.poll(() => dialogs).toEqual([messages[expectedMessage].message]);
await expect(adapter.page.locator("#patreon-logged-out")).toBeVisible();
} else {
await expect(adapter.page.locator("#patreon-logged-in")).toBeVisible();
await expect(adapter.page.locator("#patreon-user-name")).toHaveText("Test Contributor");
await adapter.page.screenshot({
path: testInfo.outputPath("github-contributor-signed-in.png"),
fullPage: true,
});
}
const evidence = await adapter.worker.evaluate(async () => ({
...globalThis.githubLoginFixture,
authenticated: (await chrome.storage.sync.get("patreonAuthenticated")).patreonAuthenticated === true,
}));
expect(evidence.opens).toBe(scenario === "unavailable" ? 0 : 1);
expect(evidence.exchanges).toBe(["success", "not_contributor"].includes(scenario) ? 1 : 0);
expect(evidence.authenticated).toBe(scenario === "success");
if (evidence.exchanges) expect(evidence.pkceVerified).toBe(true);
} catch (error) {
console.error(
JSON.stringify({
diagnostics,
ledger: await adapter.worker?.evaluate(() => globalThis.githubLoginFixture).catch(() => null),
}),
);
throw error;
} finally {
await adapter.close();
await apiServer.close();
}
});
}
@@ -0,0 +1,256 @@
const assert = require("node:assert/strict");
const crypto = require("node:crypto");
const fs = require("node:fs/promises");
const path = require("node:path");
const EVENT_KEY = "__rydTestInstalledEvents";
const RUNTIME_KEY = "__rydTestLifecycleRuntime";
const CHANGELOG_PATH = "/changelog/4/changelog_4.0.html";
const STORAGE_KEYS = ["lastShownChangelogVersion", "pendingChangelogVersion", EVENT_KEY, RUNTIME_KEY];
const delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
async function instrumentChangelogLifecycle({ derived, manifest, result }) {
const buildId = crypto.randomUUID();
const filename = "ryd.lifecycle-probe.js";
const probe = `(() => {
const buildId = ${JSON.stringify(buildId)};
const backgroundStartId = crypto.randomUUID();
const startedAt = new Date().toISOString();
browser.storage.local.set({ [${JSON.stringify(RUNTIME_KEY)}]: {
buildId, backgroundStartId, startedAt, version: browser.runtime.getManifest().version,
runtimeUrl: browser.runtime.getURL("")
}});
browser.runtime.onInstalled.addListener(details => {
browser.storage.local.get([${JSON.stringify(EVENT_KEY)}, "lastShownChangelogVersion"]).then(stored => {
const events = stored[${JSON.stringify(EVENT_KEY)}] || [];
events.push({
buildId, backgroundStartId, recordedAt: new Date().toISOString(),
reason: details.reason, temporary: details.temporary ?? null,
previousVersion: details.previousVersion ?? null,
shownAtInstall: stored.lastShownChangelogVersion ?? null,
version: browser.runtime.getManifest().version
});
return browser.storage.local.set({ [${JSON.stringify(EVENT_KEY)}]: events });
});
});
})();
`;
await fs.writeFile(path.join(derived, filename), probe);
manifest.background.scripts.unshift(filename);
result.changelogLifecycle = {
buildId,
instrumentation: {
filename,
sha256: crypto.createHash("sha256").update(probe).digest("hex"),
eventKey: EVENT_KEY,
runtimeKey: RUNTIME_KEY,
description:
"Test-only first background script records real onInstalled reason, temporary flag, previous version, and a background-start ID in owned local storage. Product handlers are unchanged.",
},
observations: [],
};
}
async function observeChangelogLifecycle({ driver, derived, manifest, result, until }) {
const lifecycle = result.changelogLifecycle;
const addonId = manifest.browser_specific_settings.gecko.id;
const expectImmediate = process.env.RYD_FIREFOX_CHANGELOG_EXPECT_IMMEDIATE === "1";
lifecycle.expectImmediateTemporaryReload = expectImmediate;
async function openPopup() {
await driver.context("chrome");
const uuid = await until(
() => driver.script(`return WebExtensionPolicy.getByID(arguments[0])?.mozExtensionHostname || false;`, [addonId]),
"temporary extension policy after lifecycle change",
);
await driver.context("content");
const previousHandlesResponse = await driver.command("WebDriver:GetWindowHandles");
const previousHandles = previousHandlesResponse.value || previousHandlesResponse;
await driver.context("chrome");
await driver.script(`
gBrowser.selectedTab = gBrowser.addTab("about:blank", {
triggeringPrincipal: Services.scriptSecurityManager.getSystemPrincipal()
});
`);
await driver.context("content");
const handlesResponse = await driver.command("WebDriver:GetWindowHandles");
const handles = handlesResponse.value || handlesResponse;
const handle = handles.find((candidate) => !previousHandles.includes(candidate));
assert(handle, "Lifecycle probe must own a fresh browser tab");
await driver.command("WebDriver:SwitchToWindow", { handle });
await driver.command("WebDriver:Navigate", { url: `moz-extension://${uuid}/popup.html` });
await until(
() => driver.script(`return typeof browser !== "undefined" && Boolean(browser.storage?.local);`),
"extension storage API in owned lifecycle popup",
);
}
async function storage() {
return driver.script(
`const done = arguments[arguments.length - 1]; browser.storage.local.get(arguments[0]).then(done);`,
[STORAGE_KEYS],
true,
);
}
async function snapshot(label, previousStartId) {
await openPopup();
const state = await until(async () => {
const value = await storage();
const runtime = value[RUNTIME_KEY];
const events = value[EVENT_KEY] || [];
return runtime?.buildId === lifecycle.buildId &&
runtime.backgroundStartId !== previousStartId &&
events.some((event) => event.backgroundStartId === runtime.backgroundStartId)
? value
: false;
}, `${label} instrumented onInstalled event`);
assert.equal(state[RUNTIME_KEY].version, manifest.version);
// Observe asynchronous product storage/tab work over a bounded interval; the
// baseline records its outcome without assuming that reload opens a tab.
await delay(500);
const settledState = await storage();
await driver.context("chrome");
const native = await driver.script(
`
const done = arguments[arguments.length - 1];
const { AddonManager } = ChromeUtils.importESModule("resource://gre/modules/AddonManager.sys.mjs");
AddonManager.getAddonByID(arguments[0]).then(addon => {
const uuid = WebExtensionPolicy.getByID(arguments[0]).mozExtensionHostname;
const changelogUrl = "moz-extension://" + uuid + arguments[1];
done({
id: addon.id, version: addon.version, temporarilyInstalled: addon.temporarilyInstalled,
sourceUri: addon.sourceURI?.spec || null,
changelogUrl,
changelogTabCount: Array.from(gBrowser.tabs).filter(tab => tab.linkedBrowser.currentURI.spec === changelogUrl).length
});
});
`,
[addonId, CHANGELOG_PATH],
true,
);
assert.equal(native.id, addonId);
assert.equal(native.version, manifest.version);
assert.equal(native.temporarilyInstalled, true);
const observation = { label, state: settledState, native };
lifecycle.observations.push(observation);
console.log("CHANGELOG LIFECYCLE", JSON.stringify(observation));
return observation;
}
async function clearShownAndCloseChangelog(label, { clearShown = true, seedPending = false } = {}) {
await openPopup();
if (clearShown)
await driver.script(
`const done = arguments[arguments.length - 1]; browser.storage.local.remove("lastShownChangelogVersion").then(() => browser.storage.local.get(arguments[0])).then(done);`,
[STORAGE_KEYS],
true,
);
if (seedPending)
await driver.script(
`const done = arguments[arguments.length - 1]; browser.storage.local.set({ pendingChangelogVersion: arguments[0] }).then(done);`,
[manifest.version],
true,
);
const clearedState = await storage();
if (clearShown) assert.equal(clearedState.lastShownChangelogVersion, undefined);
else assert.equal(clearedState.lastShownChangelogVersion, manifest.version);
if (seedPending) assert.equal(clearedState.pendingChangelogVersion, manifest.version);
await driver.context("chrome");
const closed = await driver.script(
`
const uuid = WebExtensionPolicy.getByID(arguments[0]).mozExtensionHostname;
const url = "moz-extension://" + uuid + arguments[1];
const tabs = Array.from(gBrowser.tabs).filter(tab => tab.linkedBrowser.currentURI.spec === url);
for (const tab of tabs) gBrowser.removeTab(tab, { animate: false });
return tabs.length;
`,
[addonId, CHANGELOG_PATH],
);
lifecycle.observations.push({ label, clearedState, closedChangelogTabs: closed });
// Keep Marionette's selected document outside the extension before its
// pages are destroyed by uninstall/reload.
await driver.context("content");
await driver.command("WebDriver:Navigate", { url: "about:blank" });
await driver.context("chrome");
}
async function reloadAddon() {
const reloaded = await driver.script(
`
const done = arguments[arguments.length - 1];
const { AddonManager } = ChromeUtils.importESModule("resource://gre/modules/AddonManager.sys.mjs");
AddonManager.getAddonByID(arguments[0]).then(addon => addon.reload()).then(() => done(true), error => done({error:String(error)}));
`,
[addonId],
true,
);
assert.equal(reloaded, true);
}
const fresh = await snapshot("fresh-install");
await clearShownAndCloseChangelog("before-remove-and-reinstall-with-shown-marker", { clearShown: false });
await driver.script(
`
const done = arguments[arguments.length - 1];
const { AddonManager } = ChromeUtils.importESModule("resource://gre/modules/AddonManager.sys.mjs");
AddonManager.getAddonByID(arguments[0]).then(addon => addon.uninstall()).then(() => done(true), error => done({error:String(error)}));
`,
[addonId],
true,
);
await until(
() => driver.script(`return !WebExtensionPolicy.getByID(arguments[0]);`, [addonId]),
"temporary extension removal",
);
const reinstalled = await driver.script(
`
const done = arguments[arguments.length - 1];
const { AddonManager } = ChromeUtils.importESModule("resource://gre/modules/AddonManager.sys.mjs");
const file = Cc["@mozilla.org/file/local;1"].createInstance(Ci.nsIFile);
file.initWithPath(arguments[0]);
AddonManager.installTemporaryAddon(file).then(addon => done({id:addon.id,version:addon.version}), error => done({error:String(error)}));
`,
[derived],
true,
);
assert(!reinstalled.error, reinstalled.error);
const afterReinstall = await snapshot("remove-and-reinstall", fresh.state[RUNTIME_KEY].backgroundStartId);
await clearShownAndCloseChangelog("before-reload-unseen");
await reloadAddon();
const afterUnseenReload = await snapshot("reload-unseen", afterReinstall.state[RUNTIME_KEY].backgroundStartId);
if (expectImmediate) {
const event = afterUnseenReload.state[EVENT_KEY].at(-1);
assert.equal(event.reason, "update");
assert.equal(event.temporary, true);
assert.equal(event.previousVersion, manifest.version);
assert.equal(afterUnseenReload.native.changelogTabCount, 1);
assert.equal(afterUnseenReload.state.lastShownChangelogVersion, manifest.version);
assert.equal(afterUnseenReload.state.pendingChangelogVersion, undefined);
await clearShownAndCloseChangelog("before-reload-already-seen", { clearShown: false });
await reloadAddon();
const afterSeenReload = await snapshot(
"reload-already-seen",
afterUnseenReload.state[RUNTIME_KEY].backgroundStartId,
);
assert.equal(afterSeenReload.native.changelogTabCount, 0);
assert.equal(afterSeenReload.state.lastShownChangelogVersion, manifest.version);
assert.equal(afterSeenReload.state.pendingChangelogVersion, undefined);
await clearShownAndCloseChangelog("before-reload-pending-only", { seedPending: true });
await reloadAddon();
const afterPendingReload = await snapshot(
"reload-pending-only",
afterSeenReload.state[RUNTIME_KEY].backgroundStartId,
);
assert.equal(afterPendingReload.native.changelogTabCount, 1);
assert.equal(afterPendingReload.state.lastShownChangelogVersion, manifest.version);
assert.equal(afterPendingReload.state.pendingChangelogVersion, undefined);
result.scenarios.push("unseen temporary reload opens exactly one changelog and consumes pending state");
result.scenarios.push("already-seen temporary reload opens no duplicate changelog");
result.scenarios.push("temporary reload recovers pending-only changelog state and records successful display");
}
result.scenarios.push("observed native temporary-addon changelog lifecycle after removal/reinstall and reload");
}
module.exports = { instrumentChangelogLifecycle, observeChangelogLifecycle };
+596
View File
@@ -0,0 +1,596 @@
const assert = require("node:assert/strict");
const fs = require("node:fs/promises");
const path = require("node:path");
const net = require("node:net");
const http = require("node:http");
const { spawn } = require("node:child_process");
const crypto = require("node:crypto");
// Run after the production build: node Extensions/e2e/firefox-consent-smoke.js
// RYD_FIREFOX_BINARY selects a portable browser. RYD_FIREFOX_PACKAGED=1 requires
// Developer Edition or Nightly and enables unsigned packages only in the owned profile.
// RYD_FIREFOX_CHANGELOG_LIFECYCLE=1 observes temporary install/reload events.
// RYD_FIREFOX_CHANGELOG_EXPECT_IMMEDIATE=1 also asserts immediate reload display and pending-state recovery.
const ROOT = path.resolve(__dirname, "../..");
const delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
async function until(operation, description, timeout = 10000) {
const deadline = Date.now() + timeout;
while (Date.now() < deadline) {
const result = await operation();
if (result) return result;
await delay(100);
}
throw new Error(`Timed out waiting for ${description}`);
}
class Marionette {
constructor(socket) {
this.socket = socket;
this.buffer = Buffer.alloc(0);
this.sequence = 0;
this.pending = new Map();
this.ready = new Promise((resolve) => (this.connected = resolve));
socket.on("data", (chunk) => {
this.buffer = Buffer.concat([this.buffer, chunk]);
while (this.buffer.includes(58)) {
const colon = this.buffer.indexOf(58);
const length = Number(this.buffer.subarray(0, colon).toString());
if (this.buffer.length < colon + 1 + length) return;
const message = JSON.parse(this.buffer.subarray(colon + 1, colon + 1 + length));
this.buffer = this.buffer.subarray(colon + 1 + length);
if (!Array.isArray(message)) this.connected(message);
else {
const [, id, error, result] = message;
const pending = this.pending.get(id);
if (!pending) continue;
this.pending.delete(id);
clearTimeout(pending.timer);
error ? pending.reject(new Error(JSON.stringify(error))) : pending.resolve(result);
}
}
});
socket.on("error", () => {});
}
command(name, parameters = {}) {
const id = ++this.sequence;
const message = JSON.stringify([0, id, name, parameters]);
return new Promise((resolve, reject) => {
const timer = setTimeout(() => reject(new Error(`Timed out: ${name}`)), 30000);
this.pending.set(id, { resolve, reject, timer });
this.socket.write(`${Buffer.byteLength(message)}:${message}`);
});
}
async script(script, args = [], async = false) {
const response = await this.command(async ? "WebDriver:ExecuteAsyncScript" : "WebDriver:ExecuteScript", {
script,
args,
newSandbox: false,
sandbox: null,
line: 1,
filename: "firefox-consent-smoke.js",
scriptTimeout: 25000,
});
return response.value;
}
async context(value) {
await this.command("Marionette:SetContext", { value });
}
async click(selector) {
const element = await this.command("WebDriver:FindElement", { using: "css selector", value: selector });
await this.command("WebDriver:ElementClick", { id: element.value["element-6066-11e4-a52e-4f735466cecf"] });
}
}
async function listen(server) {
await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve));
return server.address().port;
}
async function connect(port) {
for (let attempt = 0; attempt < 100; attempt++) {
try {
const socket = await new Promise((resolve, reject) => {
const client = net.connect(port, "127.0.0.1", () => resolve(client));
client.once("error", reject);
});
const driver = new Marionette(socket);
await driver.ready;
return driver;
} catch (_) {
await delay(200);
}
}
throw new Error("Firefox Marionette did not start");
}
async function run() {
const artifact = path.resolve(
process.env.RYD_FIREFOX_ARTIFACT || path.join(ROOT, "Extensions/combined/dist/firefox"),
);
const firefox = process.env.RYD_FIREFOX_BINARY || "C:\\Program Files\\Mozilla Firefox\\firefox.exe";
const packaged = process.env.RYD_FIREFOX_PACKAGED === "1";
const changelogLifecycle = process.env.RYD_FIREFOX_CHANGELOG_LIFECYCLE === "1";
assert(!(packaged && changelogLifecycle), "Changelog lifecycle reproduction requires a temporary addon");
const evidence = path.join(ROOT, "test-results", `firefox-consent-${new Date().toISOString().replace(/[:.]/g, "-")}`);
const profile = path.join(evidence, "profile");
const derived = path.join(evidence, "extension");
await fs.mkdir(profile, { recursive: true });
await fs.cp(artifact, derived, { recursive: true });
const manifest = JSON.parse(await fs.readFile(path.join(derived, "manifest.json"), "utf8"));
const requests = [];
const blocked = [];
const unexpectedRequests = [];
const result = {
artifact,
version: manifest.version,
scenarios: [],
screenshots: [],
requests,
blocked,
unexpectedRequests,
};
result.validationDepth =
"generated Firefox artifact with loopback API substitution, native optional consent, isolated temporary install";
result.limitations = [
"Temporary installation grants required categories without showing the install/update consent prompt.",
"Native arrow-panel text is captured from Firefox UI; headless screenshots do not capture the separate native panel.",
];
const server = http.createServer((request, response) => {
const url = new URL(request.url, `http://${request.headers.host}`);
requests.push({ method: request.method, path: url.pathname });
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Headers", "Content-Type");
response.setHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
response.setHeader("Content-Type", "application/json");
if (request.method === "OPTIONS") response.end();
else if (url.pathname === "/puzzle/registration")
response.end(
request.method === "POST" ? "true" : JSON.stringify({ challenge: "AAAAAAAAAAAAAAAAAAAAAA==", difficulty: 0 }),
);
else if (url.pathname === "/puzzle/registration/confirm") response.end("true");
else if (url.pathname.endsWith("/login")) {
response.end(
JSON.stringify({
authUrl: `${origin}/oauth-authorize?redirectUri=${encodeURIComponent(url.searchParams.get("redirectUri"))}`,
state: "fixture-state",
}),
);
} else if (url.pathname === "/oauth-authorize") {
response.writeHead(302, {
Location: `${url.searchParams.get("redirectUri")}?code=fixture-code&state=fixture-state`,
});
response.end();
} else if (url.pathname.endsWith("/exchange")) {
response.end(
JSON.stringify({
success: true,
sessionToken: "fixture-session-token",
user: { fullName: "Test member", membershipTier: "premium", hasActiveMembership: true },
}),
);
} else if (url.pathname === "/api/auth/verify")
response.end(JSON.stringify({ valid: true, membershipTier: "premium" }));
else {
unexpectedRequests.push({ method: request.method, path: url.pathname });
response.writeHead(404);
response.end("{}");
}
});
const port = await listen(server);
const origin = `http://127.0.0.1:${port}`;
const proxy = http.createServer((request, response) => {
blocked.push({ method: request.method, host: new URL(request.url).hostname });
response.writeHead(502);
response.end();
});
proxy.on("connect", (request, socket) => {
blocked.push({ method: "CONNECT", host: request.url });
socket.end("HTTP/1.1 502 Blocked by isolated test\r\n\r\n");
});
const proxyPort = await listen(proxy);
const sourceHashes = {
"manifest.json": crypto
.createHash("sha256")
.update(await fs.readFile(path.join(artifact, "manifest.json")))
.digest("hex"),
};
for (const filename of ["ryd.background.js", "ryd.content-script.js", "popup.js"]) {
const file = path.join(derived, filename);
const source = await fs.readFile(file, "utf8");
sourceHashes[filename] = crypto.createHash("sha256").update(source).digest("hex");
assert(
source.includes("https://returnyoutubedislikeapi.com"),
`${filename} must contain its production API origin`,
);
await fs.writeFile(file, source.replaceAll("https://returnyoutubedislikeapi.com", origin));
}
result.sourceHashes = sourceHashes;
if (changelogLifecycle)
await require("./firefox-changelog-lifecycle").instrumentChangelogLifecycle({ derived, manifest, result });
manifest.permissions.push(`${origin}/*`);
await fs.writeFile(path.join(derived, "manifest.json"), JSON.stringify(manifest, null, 2));
const portServer = net.createServer();
const marionettePort = await listen(portServer);
await new Promise((resolve) => portServer.close(resolve));
const prefs = {
"marionette.port": marionettePort,
"browser.shell.checkDefaultBrowser": false,
"browser.startup.homepage_override.mstone": "ignore",
"browser.startup.page": 0,
"startup.homepage_welcome_url": "about:blank",
"startup.homepage_welcome_url.additional": "",
"browser.newtabpage.enabled": false,
"browser.tabs.warnOnClose": false,
"datareporting.policy.dataSubmissionEnabled": false,
"toolkit.telemetry.enabled": false,
"app.update.disabledForTesting": true,
"network.proxy.type": 1,
"network.proxy.http": "127.0.0.1",
"network.proxy.http_port": proxyPort,
"network.proxy.ssl": "127.0.0.1",
"network.proxy.ssl_port": proxyPort,
"network.proxy.no_proxies_on": "127.0.0.1,localhost",
"network.proxy.failover_direct": false,
"network.trr.mode": 5,
"dom.security.https_only_mode": false,
"remote.active-protocols": 1,
};
if (packaged) prefs["xpinstall.signatures.required"] = false;
await fs.writeFile(
path.join(profile, "user.js"),
Object.entries(prefs)
.map(([key, value]) => `user_pref(${JSON.stringify(key)}, ${JSON.stringify(value)});`)
.join("\n"),
);
const child = spawn(
firefox,
["-headless", "-no-remote", "-profile", profile, "--marionette", "--remote-allow-system-access", "about:blank"],
{ windowsHide: true, stdio: ["ignore", "pipe", "pipe"] },
);
let firefoxLog = "";
child.stdout.on("data", (chunk) => (firefoxLog += chunk));
child.stderr.on("data", (chunk) => (firefoxLog += chunk));
let driver;
try {
driver = await connect(marionettePort);
result.session = await driver.command("WebDriver:NewSession", {
acceptInsecureCerts: true,
unhandledPromptBehavior: "dismiss and notify",
});
console.log(`Firefox ${result.session.capabilities.browserVersion}, extension ${manifest.version}`);
await driver.context("chrome");
await driver.script(`
window.__rydConsentDiagnostics = [];
window.__rydConsentListener = { observe(message) {
const text = message.message || "";
if (text.includes("moz-extension://")) window.__rydConsentDiagnostics.push(text);
}};
Services.console.registerListener(window.__rydConsentListener);
`);
const installed = packaged
? await require("./firefox-install-consent").validatePackagedConsent({
driver,
derived,
evidence,
manifest,
result,
requests,
})
: await driver.script(
`
const done = arguments[arguments.length - 1];
const { AddonManager } = ChromeUtils.importESModule("resource://gre/modules/AddonManager.sys.mjs");
const file = Cc["@mozilla.org/file/local;1"].createInstance(Ci.nsIFile);
file.initWithPath(arguments[0]);
AddonManager.installTemporaryAddon(file).then(addon => done({id:addon.id,version:addon.version}), error=>done({error:String(error)}));
`,
[derived],
true,
);
assert(!installed.error, installed.error);
result.installed = installed;
assert.equal(installed.version, manifest.version);
assert.equal(installed.id, manifest.browser_specific_settings.gecko.id);
const uuid = await driver.script(`return WebExtensionPolicy.getByID(arguments[0]).mozExtensionHostname;`, [
installed.id,
]);
if (!packaged) {
result.freshInstallChangelog = await until(
() =>
driver.script(
`
const url = "moz-extension://" + arguments[0] + "/changelog/4/changelog_4.0.html";
const tabs = Array.from(gBrowser.tabs).filter(tab => tab.linkedBrowser.currentURI.spec === url);
return tabs.length ? { url, tabCount: tabs.length } : false;
`,
[uuid],
),
"automatic changelog tab on a fresh temporary installation",
);
assert.equal(result.freshInstallChangelog.tabCount, 1);
result.scenarios.push("fresh temporary installation automatically opens one changelog tab");
}
await driver.context("content");
await driver.command("WebDriver:SetWindowRect", { width: 380, height: 900 });
await driver.command("WebDriver:Navigate", { url: `moz-extension://${uuid}/popup.html` });
result.initialPermissions = await driver.script(
`const done=arguments[arguments.length-1]; browser.permissions.getAll().then(done);`,
[],
true,
);
if (!packaged) {
result.freshInstallChangelog.storage = await until(
() =>
driver.script(
`const done=arguments[arguments.length-1]; browser.storage.local.get(["lastShownChangelogVersion", "pendingChangelogVersion"]).then(value=>done(value.lastShownChangelogVersion ? value : false));`,
[],
true,
),
"successful changelog display recorded in local storage",
);
assert.equal(result.freshInstallChangelog.storage.lastShownChangelogVersion, manifest.version);
}
const optional = manifest.browser_specific_settings.gecko.data_collection_permissions.optional;
assert.deepEqual(optional, ["authenticationInfo"]);
assert(optional.every((permission) => !result.initialPermissions.data_collection.includes(permission)));
for (const message of ["patreon_oauth_login", "github_oauth_login"]) {
const deniedMessage = await driver.script(
`const done=arguments[arguments.length-1]; browser.runtime.sendMessage({message:arguments[0]}).then(done);`,
[message],
true,
);
assert.equal(deniedMessage.success, false);
assert.match(deniedMessage.error, /consent removed|consent required/);
}
assert.equal(requests.filter((request) => request.path.startsWith("/api/auth/")).length, 0);
result.scenarios.push("background refuses authentication without optional consent");
await driver.script(
`const done=arguments[arguments.length-1]; browser.storage.sync.set({patreonAuthenticated:true,patreonUser:{fullName:"Cached test member",membershipTier:"premium",hasActiveMembership:true},patreonSessionToken:"fixture-cached-session-token"}).then(done);`,
[],
true,
);
await driver.command("WebDriver:Refresh");
await until(
() => driver.script(`return document.getElementById("patreon-logged-out").style.display === "block";`),
"cached session kept inactive without consent",
);
assert.equal(requests.filter((request) => request.path.startsWith("/api/auth/")).length, 0);
result.scenarios.push("cached account cannot verify or log in without consent");
await delay(1000);
await driver.script(
`const done=arguments[arguments.length-1]; browser.tabs.getCurrent().then(tab=>browser.tabs.update(tab.id,{active:true})).then(()=>done(true));`,
[],
true,
);
result.patreonPrivacyNote = await driver.script(`
const note = document.getElementById("patreon-privacy-note");
const login = document.getElementById("patreon-login-btn");
const rect = note.getBoundingClientRect();
return {
text: note.textContent.trim(),
describedBy: login.getAttribute("aria-describedby"),
visible: note.checkVisibility(),
withinViewport: rect.left >= 0 && rect.right <= innerWidth,
belowLogin: rect.top >= login.getBoundingClientRect().bottom,
fontSize: getComputedStyle(note).fontSize,
viewportWidth: innerWidth
};
`);
assert.equal(
result.patreonPrivacyNote.text,
"Patreon membership information is used to verify premium access. We do not receive your card or bank details.",
);
assert.equal(result.patreonPrivacyNote.describedBy, "patreon-privacy-note");
assert.equal(result.patreonPrivacyNote.visible, true);
assert.equal(result.patreonPrivacyNote.withinViewport, true);
assert.equal(result.patreonPrivacyNote.belowLogin, true);
const shot = await driver.command("WebDriver:TakeScreenshot", { full: true });
await fs.writeFile(path.join(evidence, "popup.png"), Buffer.from(shot.value, "base64"));
result.screenshots.push("popup.png");
await driver.click("#patreon-login-btn");
await driver.context("chrome");
result.nativePermissionPrompt = await until(
() =>
driver.script(
`const notification = document.getElementById("addon-webext-permissions-notification"); return document.getElementById("notification-popup")?.state === "open" && notification ? { heading:notification.getAttribute("endlabel"), data:document.getElementById("addon-webext-perm-list-data-collection").textContent, allow:notification.getAttribute("buttonlabel"), deny:notification.getAttribute("secondarybuttonlabel") } : false;`,
),
"native consent prompt",
);
console.log("NATIVE PROMPT", JSON.stringify(result.nativePermissionPrompt));
assert.match(result.nativePermissionPrompt.data, /authentication information/i);
assert.doesNotMatch(result.nativePermissionPrompt.data, /financial|payment/i);
// Native arrow panels live outside the headless compositor screenshot. Preserve their exact text instead.
await driver.script(
`document.querySelector("#addon-webext-permissions-notification .popup-notification-secondary-button").click();`,
);
await driver.context("content");
await until(async () => {
try {
await driver.command("WebDriver:GetAlertText");
return true;
} catch (_) {
return false;
}
}, "extension denial notice");
await driver.command("WebDriver:DismissAlert");
const denied = await driver.script(
`const done=arguments[arguments.length-1]; browser.permissions.contains({data_collection:arguments[0]}).then(done);`,
[optional],
true,
);
assert.equal(denied, false);
assert.equal(requests.filter((request) => request.path.startsWith("/api/auth/")).length, 0);
result.scenarios.push("native Deny prevents OAuth requests");
console.log("DENIAL PASSED");
await driver.click("#patreon-login-btn");
await driver.context("chrome");
await until(
() => driver.script(`return document.getElementById("notification-popup")?.state === "open";`),
"second consent prompt",
);
await driver.script(
`document.querySelector("#addon-webext-permissions-notification .popup-notification-primary-button").click();`,
);
await driver.context("content");
await until(
() => driver.script(`return document.getElementById("patreon-logged-in").style.display === "block";`),
"mock OAuth completion",
);
const granted = await driver.script(
`const done=arguments[arguments.length-1]; browser.permissions.contains({data_collection:arguments[0]}).then(done);`,
[optional],
true,
);
assert.equal(granted, true);
assert.equal(requests.filter((request) => request.path === "/api/auth/oauth/login").length, 1);
assert.equal(
requests.filter((request) => request.path === "/api/auth/oauth/exchange" && request.method === "POST").length,
1,
);
result.scenarios.push("native Allow completes generated Patreon OAuth against loopback");
assert.equal(
await driver.script(`return document.getElementById("patreon-privacy-note").checkVisibility();`),
false,
);
console.log("GRANT PASSED");
const grantShot = await driver.command("WebDriver:TakeScreenshot", { full: true });
await fs.writeFile(path.join(evidence, "popup-granted.png"), Buffer.from(grantShot.value, "base64"));
result.screenshots.push("popup-granted.png");
await driver.script(
`const done=arguments[arguments.length-1]; browser.permissions.remove({data_collection:arguments[0]}).then(done);`,
[optional],
true,
);
await until(
() =>
driver.script(
`const done=arguments[arguments.length-1]; browser.storage.sync.get(["patreonAuthenticated","patreonUser","patreonSessionToken"]).then(value=>done(Object.keys(value).length===0));`,
[],
true,
),
"stored authentication cleanup after revocation",
);
await until(
() => driver.script(`return document.getElementById("patreon-logged-out").style.display === "block";`),
"logged-out UI after revocation",
);
result.scenarios.push("native revocation removes stored authentication and logs out popup");
console.log("REVOCATION PASSED");
await driver.click("#github-login-btn");
await driver.context("chrome");
await until(
() => driver.script(`return document.getElementById("notification-popup")?.state === "open";`),
"GitHub consent prompt",
);
await driver.script(
`document.querySelector("#addon-webext-permissions-notification .popup-notification-primary-button").click();`,
);
await driver.context("content");
await until(
() => driver.script(`return document.getElementById("patreon-logged-in").style.display === "block";`),
"GitHub mock OAuth completion",
);
assert.equal(
requests.filter((request) => request.path === "/api/auth/github/login" && request.method === "GET").length,
1,
);
assert.equal(
requests.filter((request) => request.path === "/api/auth/github/exchange" && request.method === "POST").length,
1,
);
result.scenarios.push("native Allow completes generated GitHub OAuth against loopback");
await driver.script(
`const done=arguments[arguments.length-1]; browser.permissions.remove({data_collection:["authenticationInfo"]}).then(done);`,
[],
true,
);
await until(
() =>
driver.script(
`const done=arguments[arguments.length-1]; browser.storage.sync.get(["patreonAuthenticated","patreonUser","patreonSessionToken"]).then(value=>done(Object.keys(value).length===0));`,
[],
true,
),
"authentication permission revocation clears GitHub authentication",
);
await until(
() => driver.script(`return document.getElementById("patreon-logged-out").style.display === "block";`),
"GitHub logged-out UI after authentication permission revocation",
);
result.scenarios.push("revoking authentication category clears GitHub account state");
const revokeShot = await driver.command("WebDriver:TakeScreenshot", { full: true });
await fs.writeFile(path.join(evidence, "popup-revoked.png"), Buffer.from(revokeShot.value, "base64"));
result.screenshots.push("popup-revoked.png");
if (changelogLifecycle)
await require("./firefox-changelog-lifecycle").observeChangelogLifecycle({
driver,
derived,
manifest,
result,
until,
});
await driver.context("chrome");
result.diagnostics = await driver.script(
`Services.console.unregisterListener(window.__rydConsentListener); return window.__rydConsentDiagnostics;`,
);
for (const [filename, hash] of Object.entries(sourceHashes))
assert.equal(
crypto
.createHash("sha256")
.update(await fs.readFile(path.join(artifact, filename)))
.digest("hex"),
hash,
`Artifact changed during test: ${filename}`,
);
assert(
!blocked.some((request) => request.host.includes("returnyoutubedislikeapi.com")),
"Extension traffic escaped loopback substitution",
);
assert.deepEqual(unexpectedRequests, [], "Unexpected extension request");
result.passed = true;
} catch (error) {
result.error = String(error.stack || error);
throw error;
} finally {
if (driver) {
await driver.command("Marionette:Quit", { flags: ["eForceQuit"] }).catch(() => {});
driver.socket.destroy();
}
if (child.exitCode === null) child.kill();
await until(() => child.exitCode !== null || child.signalCode !== null, "owned Firefox process exit").catch(
() => {},
);
server.closeAllConnections();
proxy.closeAllConnections();
await Promise.all([
new Promise((resolve) => server.close(resolve)),
new Promise((resolve) => proxy.close(resolve)),
]);
await fs.writeFile(path.join(evidence, "firefox.log"), firefoxLog);
await fs.writeFile(path.join(evidence, "result.json"), JSON.stringify(result, null, 2));
for (const owned of [
profile,
derived,
path.join(evidence, "baseline"),
path.join(evidence, "current.xpi"),
path.join(evidence, "baseline.xpi"),
]) {
assert(path.resolve(owned).startsWith(`${path.resolve(evidence)}${path.sep}`));
await fs.rm(owned, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 }).catch(() => {});
}
console.log(`Evidence: ${evidence}`);
}
}
if (require.main === module)
run().catch((error) => {
console.error(error);
process.exitCode = 1;
});
module.exports = { Marionette, run };
+193
View File
@@ -0,0 +1,193 @@
const assert = require("node:assert/strict");
const fs = require("node:fs/promises");
const path = require("node:path");
async function waitFor(operation, description) {
const deadline = Date.now() + 15000;
while (Date.now() < deadline) {
const value = await operation();
if (value) return value;
await new Promise((resolve) => setTimeout(resolve, 100));
}
throw new Error(`Timed out waiting for ${description}`);
}
async function packageDirectory(driver, directory, output) {
return driver.script(
`
const folder = Cc["@mozilla.org/file/local;1"].createInstance(Ci.nsIFile);
folder.initWithPath(arguments[0]);
const output = Cc["@mozilla.org/file/local;1"].createInstance(Ci.nsIFile);
output.initWithPath(arguments[1]);
const writer = Cc["@mozilla.org/zipwriter;1"].createInstance(Ci.nsIZipWriter);
writer.open(output, 0x04 | 0x08 | 0x20);
function append(directory, prefix) {
for (const item of directory.directoryEntries) {
const file = item.QueryInterface(Ci.nsIFile);
const name = prefix + file.leafName;
if (file.isDirectory()) append(file, name + "/");
else writer.addEntryFile(name, Ci.nsIZipWriter.COMPRESSION_DEFAULT, file, false);
}
}
append(folder, "");
writer.close();
return true;
`,
[directory, output],
);
}
async function beginInstall(driver, xpi, update = false) {
await driver.script(
`
const done = arguments[arguments.length - 1];
const { AddonManager } = ChromeUtils.importESModule("resource://gre/modules/AddonManager.sys.mjs");
const file = Cc["@mozilla.org/file/local;1"].createInstance(Ci.nsIFile);
file.initWithPath(arguments[0]);
const update = arguments[1];
AddonManager.getInstallForFile(file).then(install => {
window.__rydPendingInstall = install;
window.__rydInstallError = null;
install.addListener({ onInstallFailed: () => {window.__rydInstallError = install.error; }});
AddonManager.installAddonFromAOMWithOptions(gBrowser.selectedBrowser, Services.io.newFileURI(file), install, {preferUpdateOverInstall:update});
done({state:install.state,error:install.error});
}, error => done({error:String(error)}));
`,
[xpi, update],
true,
);
if (update) {
await waitFor(
() =>
driver.script(`
const {ExtensionsUI} = ChromeUtils.importESModule("resource:///modules/ExtensionsUI.sys.mjs");
const update = [...ExtensionsUI.updates][0];
if (!update) return false;
ExtensionsUI.showUpdate(gBrowser, update);
return true;
`),
"native pending update notification",
);
}
return waitFor(
() =>
driver.script(`
const notification = document.getElementById("addon-webext-permissions-notification");
if (document.getElementById("notification-popup")?.state !== "open" || !notification) return false;
return {
heading: notification.getAttribute("endlabel"),
requiredData: document.getElementById("addon-webext-perm-list-data-collection")?.textContent,
optionalData: document.getElementById("addon-webext-perm-list-optional")?.textContent,
allow: notification.getAttribute("buttonlabel"),
deny: notification.getAttribute("secondarybuttonlabel")
};
`),
"native packaged permission prompt",
);
}
async function choose(driver, allow) {
await driver.script(`document.querySelector(arguments[0]).click();`, [
`#addon-webext-permissions-notification .popup-notification-${allow ? "primary" : "secondary"}-button`,
]);
}
async function installedAddon(driver, id) {
return driver.script(
`
const done = arguments[arguments.length - 1];
const {AddonManager} = ChromeUtils.importESModule("resource://gre/modules/AddonManager.sys.mjs");
AddonManager.getAddonByID(arguments[0]).then(addon => done(addon ? {id:addon.id,version:addon.version,active:addon.isActive} : null));
`,
[id],
true,
);
}
async function dismissFinishedNotice(driver) {
await driver.script(`
for (const notification of [...PopupNotifications._currentNotifications]) {
if (notification.id !== "addon-webext-permissions") PopupNotifications.remove(notification);
}
`);
}
async function validatePackagedConsent({ driver, derived, evidence, manifest, result, requests }) {
const id = manifest.browser_specific_settings.gecko.id;
const xpi = path.join(evidence, "current.xpi");
await packageDirectory(driver, derived, xpi);
result.packagedInstall = { unsignedDeveloperProfile: true, requiredPrompt: await beginInstall(driver, xpi) };
assert.match(result.packagedInstall.requiredPrompt.requiredData, /browsing activity/);
assert.match(result.packagedInstall.requiredPrompt.requiredData, /website activity/);
assert.match(result.packagedInstall.requiredPrompt.requiredData, /website content/);
assert.match(result.packagedInstall.requiredPrompt.requiredData, /personally identifying information/);
await choose(driver, false);
await waitFor(
() =>
driver.script(
`return window.__rydPendingInstall.state === ChromeUtils.importESModule("resource://gre/modules/AddonManager.sys.mjs").AddonManager.STATE_CANCELLED;`,
),
"cancelled fresh install",
);
assert.equal(await installedAddon(driver, id), null);
assert.equal(requests.length, 0);
result.scenarios.push("native required-consent denial prevents packaged extension installation and startup");
console.log("REQUIRED INSTALL DENIAL PASSED");
await beginInstall(driver, xpi);
await choose(driver, true);
await waitFor(async () => (await installedAddon(driver, id))?.active, "fresh packaged installation");
result.scenarios.push("native required-consent acceptance installs and starts packaged extension");
await dismissFinishedNotice(driver);
await driver.script(
`
const done = arguments[arguments.length-1];
const {AddonManager} = ChromeUtils.importESModule("resource://gre/modules/AddonManager.sys.mjs");
AddonManager.getAddonByID(arguments[0]).then(addon=>addon.uninstall()).then(()=>done(true));
`,
[id],
true,
);
const baseline = path.join(evidence, "baseline");
await fs.cp(derived, baseline, { recursive: true });
const priorManifest = JSON.parse(JSON.stringify(manifest));
priorManifest.version = "4.0.4";
delete priorManifest.browser_specific_settings.gecko.data_collection_permissions;
await fs.writeFile(path.join(baseline, "manifest.json"), JSON.stringify(priorManifest));
const baselineXpi = path.join(evidence, "baseline.xpi");
await packageDirectory(driver, baseline, baselineXpi);
await beginInstall(driver, baselineXpi);
await choose(driver, true);
await waitFor(async () => (await installedAddon(driver, id))?.version === "4.0.4", "baseline packaged installation");
await dismissFinishedNotice(driver);
result.packagedInstall.updateBaseline =
"Synthetic 4.0.4 package retaining current code and the prior release's absence of data_collection_permissions; fixed extension ID for unsigned update testing.";
result.packagedInstall.updatePrompt = await beginInstall(driver, xpi, true);
assert.match(result.packagedInstall.updatePrompt.requiredData, /browsing activity/);
await choose(driver, false);
await waitFor(
() =>
driver.script(
`return window.__rydPendingInstall.state === ChromeUtils.importESModule("resource://gre/modules/AddonManager.sys.mjs").AddonManager.STATE_CANCELLED;`,
),
"cancelled update",
);
assert.equal((await installedAddon(driver, id)).version, "4.0.4");
result.scenarios.push("native required-consent update denial preserves the installed previous version");
console.log("REQUIRED UPDATE DENIAL PASSED");
await beginInstall(driver, xpi, true);
await choose(driver, true);
await waitFor(
async () => (await installedAddon(driver, id))?.version === manifest.version,
"accepted packaged update",
);
await dismissFinishedNotice(driver);
result.scenarios.push("native required-consent update acceptance activates 4.0.5");
console.log("REQUIRED UPDATE ACCEPTANCE PASSED");
result.validationDepth =
"packaged Firefox Developer artifact with loopback API substitution, native required install/update and optional consent";
result.limitations = result.limitations.filter((value) => !value.startsWith("Temporary installation"));
return installedAddon(driver, id);
}
module.exports = { validatePackagedConsent };
@@ -0,0 +1,82 @@
const fs = require("node:fs");
const path = require("node:path");
const assert = require("node:assert/strict");
const { chromium } = require("@playwright/test");
const { OPTIONAL_ACTIONS } = require("./action-overflow-contract");
const { createExtensionActionOverflowFixture } = require("./extension/extension-action-overflow-fixture");
const REPOSITORY_ROOT = path.resolve(__dirname, "../..");
const OUTPUT_DIRECTORY = path.join(REPOSITORY_ROOT, "Extensions", "combined", "images");
const OUTPUTS = Object.freeze({
after: path.join(OUTPUT_DIRECTORY, "hide-clutter-after.png"),
before: path.join(OUTPUT_DIRECTORY, "hide-clutter-before.png"),
});
async function assertReactionPreview(page, label) {
const preview = await page.evaluate(() => {
const reaction = document.querySelector("[data-fixture-reaction-group]");
const box = reaction?.getBoundingClientRect();
return {
box: box ? { height: box.height, width: box.width } : null,
count: document.querySelectorAll("[data-fixture-reaction-group]").length,
texts: [...(reaction?.querySelectorAll("button [role='text']") ?? [])].map((element) =>
element.textContent.trim(),
),
visible: Boolean(box && box.width > 0 && box.height > 0 && getComputedStyle(reaction).display !== "none"),
};
});
assert.equal(preview.count, 1, `${label} preview must contain exactly one reaction group.`);
assert.equal(preview.visible, true, `${label} preview reaction group must be visible.`);
assert.deepEqual(preview.texts, ["501K", "6.6K"], `${label} preview lost its Like or Dislike count.`);
assert.ok(preview.box.width >= 140 && preview.box.height >= 32, `${label} preview reaction group is too small.`);
}
async function generateHideClutterTooltipAssets() {
fs.mkdirSync(OUTPUT_DIRECTORY, { recursive: true });
const browser = await chromium.launch({ headless: true });
try {
const page = await browser.newPage({
colorScheme: "dark",
deviceScaleFactor: 1,
reducedMotion: "reduce",
viewport: { height: 180, width: 840 },
});
await page.setContent(createExtensionActionOverflowFixture(), { waitUntil: "domcontentloaded" });
await page.evaluate(
({ ids, title }) => {
globalThis.__actionOverflowFixture.mount();
globalThis.__actionOverflowFixture.renderPreview(ids, title);
},
{ ids: OPTIONAL_ACTIONS.map(({ id }) => id), title: "Standard controls" },
);
await assertReactionPreview(page, "Before");
await page.locator(".fixture-preview-card").screenshot({
animations: "disabled",
path: OUTPUTS.before,
});
await page.evaluate(() => globalThis.__actionOverflowFixture.renderPreview([], "Hide clutter buttons"));
await assertReactionPreview(page, "After");
await page.locator(".fixture-preview-card").screenshot({
animations: "disabled",
path: OUTPUTS.after,
});
} finally {
await browser.close();
}
return { ...OUTPUTS };
}
if (require.main === module) {
generateHideClutterTooltipAssets()
.then((outputs) => process.stdout.write(`${JSON.stringify(outputs, null, 2)}\n`))
.catch((error) => {
process.stderr.write(`${error.stack ?? error.message}\n`);
process.exitCode = 1;
});
}
module.exports = {
OUTPUTS,
generateHideClutterTooltipAssets,
};
+49
View File
@@ -0,0 +1,49 @@
const assert = require("node:assert/strict");
const API_METHODS_BY_PATH = Object.freeze({
"/configs/selectors": Object.freeze(["GET"]),
"/interact/confirmVote": Object.freeze(["POST"]),
"/interact/vote": Object.freeze(["POST"]),
"/puzzle/registration": Object.freeze(["GET", "POST"]),
"/votes": Object.freeze(["GET"]),
});
const WORKER_SIGNAL_PATH = "/__ryd_e2e/worker-signal";
function allowedMethodsForPath(pathname) {
if (pathname === WORKER_SIGNAL_PATH) return ["POST"];
return API_METHODS_BY_PATH[pathname] ?? [];
}
function isAllowedApiPreflight(pathname, requestedMethod) {
if (typeof requestedMethod !== "string" || requestedMethod.trim() === "") return false;
return allowedMethodsForPath(pathname).includes(requestedMethod.toUpperCase());
}
function assertExactSuccessfulVotesTraffic(records, expectedVideoIds, label = "The hermetic runtime") {
assert.ok(Array.isArray(records), `${label} has no recorded API traffic.`);
assert.ok(Array.isArray(expectedVideoIds), `${label} has no expected /votes request sequence.`);
const votes = records.filter((record) => record.method === "GET" && record.pathname === "/votes");
assert.deepEqual(
votes.map((record) => record.query?.videoId),
expectedVideoIds,
`${label} emitted a missing, duplicate, or stale /votes request.`,
);
for (const [index, record] of votes.entries()) {
const videoId = expectedVideoIds[index];
assert.equal(record.responseStatus, 200, `${label} /votes request for ${videoId} did not receive HTTP 200.`);
assert.ok(
Number.isFinite(record.respondedAt),
`${label} /votes request for ${videoId} did not finish before the contract completed.`,
);
}
return votes;
}
module.exports = {
API_METHODS_BY_PATH,
WORKER_SIGNAL_PATH,
allowedMethodsForPath,
assertExactSuccessfulVotesTraffic,
isAllowedApiPreflight,
};
@@ -0,0 +1,35 @@
const { assertExactSuccessfulVotesTraffic } = require("./hermetic-api-contract");
const VIDEO_A = "abcdefghijk";
const VIDEO_B = "zyxwvutsrqp";
function votes(videoId, overrides = {}) {
return {
method: "GET",
pathname: "/votes",
query: { videoId },
respondedAt: 123,
responseStatus: 200,
...overrides,
};
}
test("accepts the exact ordered successful /votes sequence", () => {
const records = [
{ method: "GET", pathname: "/configs/selectors", responseStatus: 200 },
votes(VIDEO_A),
votes(VIDEO_B),
];
expect(assertExactSuccessfulVotesTraffic(records, [VIDEO_A, VIDEO_B])).toEqual(records.slice(1));
});
test.each([
["missing request", [votes(VIDEO_A)], /missing, duplicate, or stale/],
["duplicate request", [votes(VIDEO_A), votes(VIDEO_B), votes(VIDEO_B)], /missing, duplicate, or stale/],
["stale video ID", [votes(VIDEO_A), votes("stalevid001")], /missing, duplicate, or stale/],
["non-200 response", [votes(VIDEO_A), votes(VIDEO_B, { responseStatus: 204 })], /did not receive HTTP 200/],
["unfinished response", [votes(VIDEO_A), votes(VIDEO_B, { respondedAt: undefined })], /did not finish/],
])("rejects a %s", (_label, records, expectedError) => {
expect(() => assertExactSuccessfulVotesTraffic(records, [VIDEO_A, VIDEO_B], "Shared runtime")).toThrow(expectedError);
});
File diff suppressed because it is too large. Load diff
+526 -2
View File
@@ -1,21 +1,37 @@
const fs = require("node:fs");
const { EventEmitter } = require("node:events");
const http = require("node:http");
const os = require("node:os");
const path = require("node:path");
const { createFakeBackend } = require("../UserScript/e2e/harness");
const { WORKER_SIGNAL_PATH, isAllowedApiPreflight } = require("./hermetic-api-contract");
const {
ARTIFACT_BROWSER_SCENARIO_CATALOG,
ARTIFACT_EXTENSION_DELAYED_FAILURE_SCENARIO_ID,
ARTIFACT_SMOKE_SCENARIO_ID,
ARTIFACT_WATCH_SPA_CLONED_VOTE_SCENARIO_ID,
ARTIFACT_WATCH_SPA_SCENARIO_ID,
ARTIFACT_WATCH_SPA_VOTE_SCENARIO_ID,
HermeticExtensionArtifactAdapter,
SHARED_ARTIFACT_SCENARIO_IDS,
SHARED_ARTIFACT_RUNTIMES,
assertArtifactBrowserScenarioCatalog,
assertLoopbackOrigin,
createArtifactBrowserScenarioPlan,
createPageSignalCollector,
createSharedArtifactBackendOptions,
createWorkerSignalCollector,
isArtifactVoteHandshakeValid,
isSpaDestinationValid,
prepareHermeticExtensionArtifact,
readGeneratedMv3Contract,
readArtifactVoteHandshake,
runArtifactWatchRenderScenario,
runArtifactWatchSpaClonedVoteScenario,
runArtifactWatchSpaScenario,
runArtifactWatchSpaVoteScenario,
runExtensionDelayedOutgoingFailureScenario,
startHermeticApiServer,
} = require("./hermetic-artifact-smoke");
const PRODUCTION_API_ORIGIN = "https://returnyoutubedislikeapi.com";
@@ -26,13 +42,22 @@ function createExtensionFixture() {
temporaryDirectories.push(directory);
fs.writeFileSync(
path.join(directory, "manifest.json"),
JSON.stringify({ host_permissions: ["*://returnyoutubedislikeapi.com/*"], manifest_version: 3 }),
JSON.stringify({
background: { service_worker: "ryd.background.js" },
content_scripts: [
{ css: ["content-style.css"], js: ["ryd.content-script.js"], matches: ["*://www.youtube.com/*"] },
],
host_permissions: ["*://returnyoutubedislikeapi.com/*"],
manifest_version: 3,
version: "4.0.5",
}),
);
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, "content-style.css"), "#ryd-bar { display: block; }");
fs.writeFileSync(path.join(directory, "menu-fixer.js"), "document.documentElement.dataset.menuFixerLoaded = 'true';");
return directory;
}
@@ -45,13 +70,76 @@ afterEach(() => {
test("the artifact smoke is the shared watch-render scenario", () => {
expect(ARTIFACT_SMOKE_SCENARIO_ID).toBe("watch-render");
expect(ARTIFACT_WATCH_SPA_CLONED_VOTE_SCENARIO_ID).toBe("watch-spa-cloned-controls-immediate-dislike");
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",
"watch-spa-cloned-controls-immediate-dislike",
]);
expect(SHARED_ARTIFACT_RUNTIMES).toEqual(["userscript", "extension"]);
expect(ARTIFACT_BROWSER_SCENARIO_CATALOG).toEqual([
...SHARED_ARTIFACT_SCENARIO_IDS.map((id) => ({ id, runtimes: SHARED_ARTIFACT_RUNTIMES, shared: true })),
{
capability: "background",
id: ARTIFACT_EXTENSION_DELAYED_FAILURE_SCENARIO_ID,
runtimes: ["extension"],
shared: false,
},
]);
expect(assertArtifactBrowserScenarioCatalog()).toBe(ARTIFACT_BROWSER_SCENARIO_CATALOG);
expect(createArtifactBrowserScenarioPlan()).toEqual([
...SHARED_ARTIFACT_SCENARIO_IDS.flatMap((scenarioId) =>
SHARED_ARTIFACT_RUNTIMES.map((runtime) => ({ runtime, scenarioId })),
),
{ runtime: "extension", scenarioId: ARTIFACT_EXTENSION_DELAYED_FAILURE_SCENARIO_ID },
]);
});
test.each([
[
"a missing extension run from a core scenario",
(catalog) => {
catalog[0] = { ...catalog[0], runtimes: ["userscript"] };
},
/must run for userscript and extension/,
],
[
"a core scenario reclassified as extension-only",
(catalog) => {
catalog[0] = { ...catalog[0], capability: "background", runtimes: ["extension"], shared: false };
},
/must remain shared/,
],
[
"an undeclared extension-only capability",
(catalog) => {
catalog[catalog.length - 1] = { ...catalog.at(-1), capability: "mobile-layout" };
},
/must declare a supported capability/,
],
[
"an extension-only scenario registered for userscript",
(catalog) => {
catalog[catalog.length - 1] = { ...catalog.at(-1), runtimes: ["userscript", "extension"] };
},
/must run only for extension/,
],
[
"an unknown scenario presented as shared coverage",
(catalog) => {
catalog.push({ id: "uncatalogued-core-behavior", runtimes: ["userscript", "extension"], shared: true });
},
/must be added to the shared scenario contract/,
],
])("the artifact catalog rejects %s", (_label, mutateCatalog, message) => {
const catalog = ARTIFACT_BROWSER_SCENARIO_CATALOG.map((entry) => ({ ...entry, runtimes: [...entry.runtimes] }));
mutateCatalog(catalog);
expect(() => assertArtifactBrowserScenarioCatalog(catalog)).toThrow(message);
expect(() => createArtifactBrowserScenarioPlan(catalog)).toThrow(message);
});
function validSpaSnapshot() {
@@ -105,6 +193,9 @@ function validVoteHandshake(change = {}) {
sharedUserId: ARTIFACT_USER_ID,
vote: {
body: { userId: ARTIFACT_USER_ID, value: -1, videoId: "zyxwvutsrqp" },
responded: true,
responseBody: { challenge: "AAAAAAAAAAAAAAAAAAAAAA==", difficulty: 0 },
responseStatus: 200,
},
voteCount: 1,
...change,
@@ -125,6 +216,141 @@ test.each(["https://returnyoutubedislikeapi.com", "https://api.example.test", "h
},
);
test.each([
["/votes", "GET"],
["/puzzle/registration", "POST"],
["/interact/vote", "POST"],
[WORKER_SIGNAL_PATH, "POST"],
])("accepts a preflight only for a declared API method: %s %s", (pathname, method) => {
expect(isAllowedApiPreflight(pathname, method)).toBe(true);
});
test.each([
["/not-an-api", "POST"],
["/interact/vote", "GET"],
["/votes", "POST"],
["/votes", null],
])("rejects undeclared preflight traffic: %s %s", (pathname, method) => {
expect(isAllowedApiPreflight(pathname, method)).toBe(false);
});
function requestPreflight(origin, pathname, requestedMethod) {
const url = new URL(pathname, origin);
return new Promise((resolve, reject) => {
const request = http.request(
url,
{
headers: {
"access-control-request-method": requestedMethod,
origin: "https://www.youtube.com",
},
method: "OPTIONS",
},
(response) => {
response.resume();
response.once("end", () => resolve(response.statusCode));
},
);
request.once("error", reject);
request.end();
});
}
test("the loopback backend records and rejects an OPTIONS request to an unknown path", async () => {
const apiServer = await startHermeticApiServer();
try {
await expect(requestPreflight(apiServer.origin, "/interact/vote", "POST")).resolves.toBe(204);
await expect(requestPreflight(apiServer.origin, "/unexpected-preflight", "POST")).resolves.toBe(404);
expect(apiServer.records.map(({ method, pathname }) => ({ method, pathname }))).toEqual([
{ method: "OPTIONS", pathname: "/interact/vote" },
{ method: "OPTIONS", pathname: "/unexpected-preflight" },
]);
expect(apiServer.unexpectedRequests).toHaveLength(1);
expect(apiServer.unexpectedRequests[0]).toMatchObject({
method: "OPTIONS",
pathname: "/unexpected-preflight",
responseStatus: 404,
});
} finally {
await apiServer.close();
}
});
function createPreflightRoute(pathname, requestedMethod) {
const request = {
headers: () => ({ "access-control-request-method": requestedMethod }),
method: () => "OPTIONS",
resourceType: () => "fetch",
url: () => `https://returnyoutubedislikeapi.com${pathname}`,
};
return {
abort: jest.fn(async () => {}),
fulfill: jest.fn(async () => {}),
request: () => request,
};
}
function createWatchDocumentRoute() {
const request = {
resourceType: () => "document",
url: () => "https://www.youtube.com/watch?v=abcdefghijk",
};
return {
fulfill: jest.fn(async () => {}),
request: () => request,
};
}
test("shared artifact fixtures do not preseed runtime roles or a Dislike count container", async () => {
const backendOptions = createSharedArtifactBackendOptions({
countsByVideo: { abcdefghijk: { dislikes: 25, likes: 100 } },
});
expect(backendOptions.fixture).toEqual({
nativeDislikeText: false,
roleAttribute: "data-fixture-role",
});
const backend = createFakeBackend(backendOptions);
const route = createWatchDocumentRoute();
await backend.handle(route);
expect(route.fulfill).toHaveBeenCalledTimes(1);
const [{ body }] = route.fulfill.mock.calls[0];
const dislikeMarkup = body.match(/<dislike-button-view-model\b[\s\S]*?<\/dislike-button-view-model>/)?.[0];
expect(body).toContain('data-fixture-role="buttons"');
expect(body).not.toContain("data-ryd-role=");
expect(dislikeMarkup).toBeDefined();
expect(dislikeMarkup).not.toMatch(/id="text"|role="text"|ytSpecButtonShapeNextButtonTextContent/);
});
test("the routed fake backend records a valid preflight and blocks an unknown one", async () => {
const backend = createFakeBackend();
const valid = createPreflightRoute("/interact/confirmVote", "POST");
const invalid = createPreflightRoute("/unexpected-preflight", "POST");
await backend.handle(valid);
await backend.handle(invalid);
expect(valid.fulfill).toHaveBeenCalledWith(expect.objectContaining({ status: 204 }));
expect(valid.abort).not.toHaveBeenCalled();
expect(backend.preflightRequests).toEqual([
expect.objectContaining({
method: "OPTIONS",
pathname: "/interact/confirmVote",
requestedMethod: "POST",
}),
]);
expect(invalid.abort).toHaveBeenCalledWith("blockedbyclient");
expect(backend.blockedRequests).toEqual([
expect.objectContaining({
method: "OPTIONS",
pathname: "/unexpected-preflight",
requestedMethod: "POST",
}),
]);
});
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");
@@ -135,6 +361,10 @@ test("redirects eager MV3 background traffic while leaving routed content-script
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(
"__rydArtifactWorkerSignals",
);
expect(prepared.workerSignalEndpoint).toBe(`http://127.0.0.1:43127${WORKER_SIGNAL_PATH}`);
expect(fs.readFileSync(path.join(prepared.extensionDirectory, "ryd.background.js"), "utf8")).toContain(
"api.runtime.onInstalled.addListener(() => {});",
);
@@ -158,6 +388,18 @@ test("rejects an extension artifact whose injected auxiliary script was dropped
);
});
test("the direct MV3 adapter contract rejects a development bundle with an inline source map", () => {
const sourceDirectory = createExtensionFixture();
fs.appendFileSync(
path.join(sourceDirectory, "ryd.content-script.js"),
"\n//# sourceMappingURL=data:application/json;base64,e30=",
);
expect(() => readGeneratedMv3Contract(sourceDirectory)).toThrow(
"ryd.content-script.js contains an inline source map and is not a production bundle.",
);
});
test.each(["userscript", "extension"])("runs one shared artifact scenario contract for %s", async (runtime) => {
const events = [];
const adapter = {
@@ -167,9 +409,13 @@ test.each(["userscript", "extension"])("runs one shared artifact scenario contra
runtime,
start: jest.fn(async () => events.push("start")),
waitForWatchResult: jest.fn(async (videoId) => ({
actionSurfaceVisible: true,
count: "25",
countVisible: true,
fillVisible: true,
ownedByExpectedWatch: true,
rateBarVisible: true,
sameActionSurface: true,
videoId,
})),
};
@@ -183,6 +429,39 @@ test.each(["userscript", "extension"])("runs one shared artifact scenario contra
expect(events).toEqual(["start", "open:abcdefghijk", "signals:watch-render", "close"]);
});
test.each([
["a hidden action surface", { actionSurfaceVisible: false }],
["a hidden dislike count", { countVisible: false }],
["an outgoing watch root", { ownedByExpectedWatch: false }],
["a count and bar on different action surfaces", { sameActionSurface: false }],
["a missing numeric count", { count: "" }],
["a hidden ratio bar", { rateBarVisible: false }],
["a hidden ratio fill", { fillVisible: false }],
])("the watch-render oracle rejects %s", async (_label, mutation) => {
const adapter = {
assertNoPageSignals: jest.fn(async () => {}),
close: jest.fn(async () => {}),
openWatch: jest.fn(async () => {}),
runtime: "extension",
start: jest.fn(async () => {}),
waitForWatchResult: jest.fn(async (videoId) => ({
actionSurfaceVisible: true,
count: "25",
countVisible: true,
fillVisible: true,
ownedByExpectedWatch: true,
rateBarVisible: true,
sameActionSurface: true,
videoId,
...mutation,
})),
};
await expect(runArtifactWatchRenderScenario(adapter, { videoId: "abcdefghijk" })).rejects.toThrow();
expect(adapter.assertNoPageSignals).not.toHaveBeenCalled();
expect(adapter.close).toHaveBeenCalledTimes(1);
});
test.each(["userscript", "extension"])("runs the same continuous A-to-B SPA contract for %s", async (runtime) => {
const events = [];
const adapter = {
@@ -219,6 +498,121 @@ test.each(["userscript", "extension"])("runs the same continuous A-to-B SPA cont
expect(events).toEqual(["start", "open:abcdefghijk", "signals:watch-spa-side-panel", "close"]);
});
function createDelayedFailureAdapter(destinationRequestAt) {
const events = [];
const outgoingRequest = { seen: Promise.resolve(), release: jest.fn() };
return {
events,
assertNoPageSignals: jest.fn(async () => {}),
assertSpaNetwork: jest.fn(async () => ({ fromVideoRequests: 1, interactionRequests: 0, toVideoRequests: 1 })),
close: jest.fn(async () => events.push("close")),
deferNextStatsRequest: jest.fn(() => {
events.push("defer");
return outgoingRequest;
}),
navigateSpaWatchWhilePending: jest.fn(async () => ({
destination: { destinationReplaced: true, nativeHydrationStartedAt: 1000, nativeHydrationDelay: 750 },
outgoing: { beforeBarCount: 0 },
})),
openSpaWatch: jest.fn(async () => events.push("open")),
readDestinationDislikeTextHistory: jest.fn(async () => ["", "65"]),
readSpaWatchSnapshot: jest.fn(async () => validSpaSnapshot()),
readStatsRequestTimings: jest.fn(() => [{ at: destinationRequestAt, query: { videoId: "zyxwvutsrqp" } }]),
runtime: "extension",
setPremiumTeaserHidden: jest.fn(async (hidden) => events.push(`hide-teaser:${hidden}`)),
start: jest.fn(async () => events.push("start")),
waitForWatchResult: jest.fn(),
};
}
test("isolates main initialization request timing before loading the outgoing fixture", async () => {
const adapter = createDelayedFailureAdapter(1800);
await expect(runExtensionDelayedOutgoingFailureScenario(adapter)).resolves.toMatchObject({
destinationRequestReadyDelayMs: 50,
scenarioId: ARTIFACT_EXTENSION_DELAYED_FAILURE_SCENARIO_ID,
});
expect(adapter.events).toEqual(["start", "hide-teaser:true", "defer", "open", "close"]);
});
test("waits for the initial background preference write before hiding the teaser", async () => {
const previousChrome = globalThis.chrome;
const listeners = new Set();
let storedValue;
const sync = {
get: jest.fn(async () => ({ hidePremiumTeaser: storedValue })),
set: jest.fn(async ({ hidePremiumTeaser }) => {
storedValue = hidePremiumTeaser;
}),
};
globalThis.chrome = {
storage: {
sync,
onChanged: {
addListener: (listener) => listeners.add(listener),
removeListener: (listener) => listeners.delete(listener),
},
},
};
try {
const adapter = { worker: { evaluate: (callback, value) => callback(value) } };
const pending = HermeticExtensionArtifactAdapter.prototype.setPremiumTeaserHidden.call(adapter, true);
await Promise.resolve();
expect(sync.set).not.toHaveBeenCalled();
storedValue = false;
for (const listener of listeners) listener({ hidePremiumTeaser: { newValue: false } }, "sync");
await pending;
expect(sync.set).toHaveBeenCalledWith({ hidePremiumTeaser: true });
expect(storedValue).toBe(true);
expect(listeners.size).toBe(0);
} finally {
if (previousChrome === undefined) delete globalThis.chrome;
else globalThis.chrome = previousChrome;
}
});
test("arms delayed destination controls before the real navigation click can expose them", async () => {
const events = [];
const destination = { destinationReplaced: true, nativeHydrationStartedAt: 1000, nativeHydrationDelay: 750 };
const page = {
evaluate: jest
.fn()
.mockResolvedValueOnce({ beforeBarCount: 0 })
.mockImplementationOnce(async (_callback, options) => {
expect(options).toMatchObject({
beforeNavigation: true,
expectedVideoId: "zyxwvutsrqp",
nativeHydrationDelay: 750,
});
events.push("arm");
})
.mockImplementationOnce(async () => {
events.push("read");
return destination;
})
.mockResolvedValueOnce(undefined),
locator: jest.fn(() => ({ click: async () => events.push("click") })),
waitForFunction: jest.fn(async () => {}),
};
await expect(
HermeticExtensionArtifactAdapter.prototype.navigateSpaWatchWhilePending.call(
{ page },
"abcdefghijk",
"zyxwvutsrqp",
),
).resolves.toEqual({ destination, outgoing: { beforeBarCount: 0 } });
expect(events).toEqual(["arm", "click", "read"]);
});
test.each([
["a request before native controls hydrate", 1749, /before its controls hydrated/],
["a request beyond the initialization latency budget", 2001, /budget is 250ms/],
])("the isolated initialization scenario still rejects %s", async (_label, at, message) => {
const adapter = createDelayedFailureAdapter(at);
await expect(runExtensionDelayedOutgoingFailureScenario(adapter)).rejects.toThrow(message);
expect(adapter.assertSpaNetwork).not.toHaveBeenCalled();
expect(adapter.close).toHaveBeenCalledTimes(1);
});
test("recognizes only one ordered, successful destination dislike handshake", () => {
const records = [
{ method: "POST", pathname: "/puzzle/registration" },
@@ -226,6 +620,9 @@ test("recognizes only one ordered, successful destination dislike handshake", ()
body: { userId: ARTIFACT_USER_ID, value: -1, videoId: "zyxwvutsrqp" },
method: "POST",
pathname: "/interact/vote",
respondedAt: 122,
responseBody: { challenge: "AAAAAAAAAAAAAAAAAAAAAA==", difficulty: 0 },
responseStatus: 200,
},
{
body: { solution: "AAAAAA==", userId: ARTIFACT_USER_ID, videoId: "zyxwvutsrqp" },
@@ -261,7 +658,13 @@ test.each([
}),
],
["a malformed identity", (value) => ({ ...value, sharedUserId: "short-user" })],
["an unfinished vote response", (value) => ({ ...value, vote: { ...value.vote, responded: false } })],
["a failed vote status", (value) => ({ ...value, vote: { ...value.vote, responseStatus: 500 } })],
["a false confirmation", (value) => ({ ...value, confirmation: { ...value.confirmation, responseBody: false } })],
[
"an unfinished confirmation response",
(value) => ({ ...value, confirmation: { ...value.confirmation, responded: false } }),
],
[
"a failed confirmation status",
(value) => ({ ...value, confirmation: { ...value.confirmation, responseStatus: 500 } }),
@@ -278,6 +681,15 @@ test.each([
expect(isArtifactVoteHandshakeValid(mutate(validVoteHandshake()))).toBe(false);
});
test("accepts successful 2xx vote and confirmation responses", () => {
const handshake = validVoteHandshake({
confirmation: { ...validVoteHandshake().confirmation, responseStatus: 202 },
vote: { ...validVoteHandshake().vote, responseStatus: 201 },
});
expect(isArtifactVoteHandshakeValid(handshake)).toBe(true);
});
test.each(["userscript", "extension"])(
"runs one post-SPA dislike activation and confirmation contract for %s",
async (runtime) => {
@@ -323,7 +735,9 @@ test.each(["userscript", "extension"])(
userId: ARTIFACT_USER_ID,
value: -1,
videoId: "zyxwvutsrqp",
voteResponded: true,
voteRequests: 1,
voteStatus: 200,
},
runtime,
scenarioId: "watch-spa-dislike-activation",
@@ -337,6 +751,62 @@ test.each(["userscript", "extension"])(
},
);
test.each(["userscript", "extension"])(
"requires the first immediate click on cloned initialized controls for %s",
async (runtime) => {
const events = [];
const adapter = {
activateClonedSpaDislike: jest.fn(async (videoId) => ({
ariaPressedBefore: "false",
barCount: 1,
countAfterSynchronousClick: "66",
countBefore: "65",
countContainerCount: 1,
interactionStartIndex: 9,
presentationCloned: true,
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(
runArtifactWatchSpaClonedVoteScenario(adapter, {
handshakeStableForMs: 0,
handshakeTimeoutMs: 1,
intervalMs: 1,
stabilityDurationMs: 0,
stableForMs: 0,
timeoutMs: 1,
}),
).resolves.toMatchObject({
activation: { ariaPressedBefore: "false", presentationCloned: true, videoId: "zyxwvutsrqp" },
handshake: { interactionRequests: 2, value: -1, videoId: "zyxwvutsrqp" },
runtime,
scenarioId: "watch-spa-cloned-controls-immediate-dislike",
});
expect(adapter.activateClonedSpaDislike).toHaveBeenCalledWith("zyxwvutsrqp");
expect(adapter.readSpaVoteHandshake).toHaveBeenCalledWith(9, "zyxwvutsrqp", -1);
expect(events).toEqual([
"start",
"open:abcdefghijk",
"signals:watch-spa-cloned-controls-immediate-dislike",
"close",
]);
},
);
test("rejects a duplicated post-SPA vote chain and still closes the adapter", async () => {
const duplicatedHandshake = validVoteHandshake({
confirmationCount: 2,
@@ -434,9 +904,13 @@ test("always closes an artifact adapter after a failed visual assertion", async
runtime: "extension",
start: jest.fn(),
waitForWatchResult: jest.fn(async () => ({
actionSurfaceVisible: true,
count: "25",
countVisible: true,
fillVisible: true,
ownedByExpectedWatch: true,
rateBarVisible: false,
sameActionSurface: true,
videoId: "abcdefghijk",
})),
};
@@ -457,9 +931,13 @@ test("turns an otherwise successful artifact result into a failure when the page
runtime: "userscript",
start: jest.fn(),
waitForWatchResult: jest.fn(async (videoId) => ({
actionSurfaceVisible: true,
count: "25",
countVisible: true,
fillVisible: true,
ownedByExpectedWatch: true,
rateBarVisible: true,
sameActionSurface: true,
videoId,
})),
};
@@ -492,13 +970,54 @@ function consoleMessage(
};
}
function createWorkerDouble(signals = []) {
const worker = new EventEmitter();
worker.evaluate = jest.fn(async (callback, argument) => {
globalThis.__rydArtifactWorkerSignals = signals;
try {
return await callback(argument);
} finally {
delete globalThis.__rydArtifactWorkerSignals;
}
});
worker.url = () => "chrome-extension://abcdefghijklmnopabcdefghijklmnop/ryd.background.js";
return worker;
}
test("the worker collector fails on a captured unhandled rejection even without a console event", async () => {
const worker = createWorkerDouble([
{
at: 123,
details: {},
kind: "unhandledrejection",
message: "intentional worker promise rejection",
name: "Error",
stack: "Error: intentional worker promise rejection",
},
]);
const collector = createWorkerSignalCollector(worker, { workerSignals: [] });
await expect(collector.assertClean("worker-negative-control")).rejects.toThrow(
/extension MV3 worker emitted unexpected runtime signals.*intentional worker promise rejection/s,
);
});
test("the worker collector includes early console failures reported by the worker probe", async () => {
const worker = createWorkerDouble();
const collector = createWorkerSignalCollector(worker, {
workerSignals: [{ kind: "console-error", message: "startup exploded" }],
});
await expect(collector.assertClean("worker-startup")).rejects.toThrow(/startup exploded/);
});
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"));
page.emit("console", consoleMessage("info", "harmless information"));
await expect(collector.assertClean("watch-render")).resolves.toEqual({
consoleErrors: [],
@@ -513,6 +1032,11 @@ test.each(["userscript", "extension"])(
test.each([
["console error", (page) => page.emit("console", consoleMessage("error", "fixture exploded")), "fixture exploded"],
[
"console warning",
(page) => page.emit("console", consoleMessage("warning", "initialization retry failed")),
"initialization retry failed",
],
[
"failed browser resource load",
(page) => page.emit("console", consoleMessage("error", "Failed to load resource: net::ERR_FILE_NOT_FOUND")),
@@ -0,0 +1,26 @@
const fs = require("node:fs");
const { OUTPUTS } = require("./generate-hide-clutter-tooltip-assets");
function readPngDimensions(filePath) {
const bytes = fs.readFileSync(filePath);
expect(bytes.subarray(0, 8)).toEqual(Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]));
expect(bytes.subarray(12, 16).toString("ascii")).toBe("IHDR");
return { height: bytes.readUInt32BE(20), width: bytes.readUInt32BE(16) };
}
describe("hide-clutter tooltip assets", () => {
test.each(Object.entries(OUTPUTS))("%s is a readable owned screenshot with useful dimensions", (name, filePath) => {
expect(fs.existsSync(filePath)).toBe(true);
const dimensions = readPngDimensions(filePath);
expect(dimensions.width).toBeGreaterThanOrEqual(280);
expect(dimensions.width).toBeLessThanOrEqual(320);
expect(dimensions.height).toBeGreaterThanOrEqual(90);
expect(dimensions.height).toBeLessThanOrEqual(150);
expect(fs.statSync(filePath).size).toBeGreaterThan(3_000);
});
test("before and after are distinct images", () => {
expect(fs.readFileSync(OUTPUTS.before).equals(fs.readFileSync(OUTPUTS.after))).toBe(false);
expect(readPngDimensions(OUTPUTS.before).height).toBeGreaterThan(readPngDimensions(OUTPUTS.after).height);
});
});
+67 -9
View File
@@ -11,9 +11,13 @@ const LIVE_RUNTIME_PROFILES = deepFreeze({
capabilities: {
backgroundVoteTransport: true,
credentialStore: "browser.storage",
ownsShortsDislikeControl: false,
shortsControlModel: "native-youtube",
shortsVisualModel: "native-pair",
ownsShortsDislikeControl: true,
shortsControlModel: "synthetic-owned",
shortsControlModelBySurface: {
desktop: "synthetic-owned",
mobile: "native-youtube-required",
},
shortsVisualModel: "strict-synthetic",
},
buildMarkerAttribute: "data-ryd-extension-build",
markerAttribute: "data-ryd-extension-version",
@@ -21,7 +25,7 @@ const LIVE_RUNTIME_PROFILES = deepFreeze({
selectors: {
rateBar: "#ryd-bar",
rateBarContainer: "#ryd-bar-container",
shortsDislikeControl: null,
shortsDislikeControl: "[data-ryd-synthetic-shorts-dislike]",
tooltipContent: "#ryd-dislike-tooltip",
tooltipTrigger: ".ryd-tooltip",
},
@@ -32,6 +36,10 @@ const LIVE_RUNTIME_PROFILES = deepFreeze({
credentialStore: "gm-storage",
ownsShortsDislikeControl: true,
shortsControlModel: "synthetic-owned",
shortsControlModelBySurface: {
desktop: "synthetic-owned",
mobile: "native-youtube-required",
},
shortsVisualModel: "strict-synthetic",
},
buildMarkerAttribute: "data-ryd-userscript-build",
@@ -58,7 +66,7 @@ function assertRuntimeArgument(value, expected, label) {
assert.equal(value, expected, `${label} does not match the selected live runtime adapter.`);
}
function createRuntimeBoundDriver(driver, runtime, expectedVersion, expectedBuildId) {
function createRuntimeBoundDriver(driver, runtime, expectedVersion, expectedBuildId, capabilities) {
return new Proxy(driver, {
get(target, property, receiver) {
if (property === "assertRuntime") {
@@ -72,10 +80,46 @@ function createRuntimeBoundDriver(driver, runtime, expectedVersion, expectedBuil
}
if (property === "assertCurrentShortsControl") {
return (videoId, requestedRuntime) => {
return (videoId, requestedRuntime, assertionOptions) => {
assertRuntimeArgument(requestedRuntime, runtime, "The Shorts-control runtime");
requireDriverMethod(target, "assertCurrentShortsControl");
return target.assertCurrentShortsControl(videoId, runtime);
return assertionOptions === undefined
? target.assertCurrentShortsControl(videoId, runtime)
: target.assertCurrentShortsControl(videoId, runtime, assertionOptions);
};
}
if (property === "soakCurrentShortsControl") {
return (videoId, requestedRuntime, expectedDislikes, soakOptions) => {
assertRuntimeArgument(requestedRuntime, runtime, "The Shorts-control soak runtime");
requireDriverMethod(target, "soakCurrentShortsControl");
return target.soakCurrentShortsControl(videoId, runtime, expectedDislikes, soakOptions);
};
}
if (property === "assertCurrentWatchResult") {
return (videoId, requestedRuntime, expectedCounts, assertionOptions) => {
assertRuntimeArgument(requestedRuntime, runtime, "The Watch-result runtime");
requireDriverMethod(target, "assertCurrentWatchResult");
return assertionOptions === undefined
? target.assertCurrentWatchResult(videoId, runtime, expectedCounts)
: target.assertCurrentWatchResult(videoId, runtime, expectedCounts, assertionOptions);
};
}
if (property === "assertRenderedDislikeCount") {
return (renderedCount, dislikes, requestedRuntime) => {
assertRuntimeArgument(requestedRuntime, runtime, "The rendered-count runtime");
requireDriverMethod(target, "assertRenderedDislikeCount");
return target.assertRenderedDislikeCount(renderedCount, dislikes, runtime);
};
}
if (property === "assertDislikeCountChangesObservable") {
return (changes, requestedRuntime) => {
assertRuntimeArgument(requestedRuntime, runtime, "The reaction count-observability runtime");
requireDriverMethod(target, "assertDislikeCountChangesObservable");
return target.assertDislikeCountChangesObservable(changes, runtime);
};
}
@@ -92,8 +136,17 @@ function createRuntimeBoundDriver(driver, runtime, expectedVersion, expectedBuil
if (property === "captureReactionStateVisual") {
return (request) => {
assertRuntimeArgument(request?.runtime, runtime, "The reaction-visual runtime");
assertRuntimeArgument(
request?.shortsVisualModel,
capabilities.shortsVisualModel,
"The reaction-visual Shorts model",
);
requireDriverMethod(target, "captureReactionStateVisual");
return target.captureReactionStateVisual({ ...request, runtime });
return target.captureReactionStateVisual({
...request,
runtime,
shortsVisualModel: capabilities.shortsVisualModel,
});
};
}
@@ -117,8 +170,12 @@ class LiveRuntimeAdapter {
throw new TypeError("The expected live build ID must be a 32-character lowercase hexadecimal value.");
}
if (typeof driver.configureRequestAttributionRuntime === "function") {
driver.configureRequestAttributionRuntime(runtime);
}
this.capabilities = profile.capabilities;
this.driver = createRuntimeBoundDriver(driver, runtime, expectedVersion, expectedBuildId);
this.driver = createRuntimeBoundDriver(driver, runtime, expectedVersion, expectedBuildId, this.capabilities);
this.expectedBuildId = expectedBuildId;
this.expectedVersion = expectedVersion;
this.profile = profile;
@@ -135,6 +192,7 @@ class LiveRuntimeAdapter {
assertRuntimeArgument(options.expectedVersion, this.expectedVersion, "The configured scenario runtime version");
return {
...options,
capabilities: this.capabilities,
expectedBuildId: this.expectedBuildId,
expectedVersion: this.expectedVersion,
runtime: this.runtime,
@@ -0,0 +1,261 @@
const { expect } = require("@playwright/test");
const { isArtifactVoteHandshakeValid, readArtifactVoteHandshake } = require("./hermetic-artifact-smoke");
const {
NAVIGATION_MATRIX,
NO_DESTINATION_DISLIKE_POSTCONDITION,
getDestinationDislikePostconditionTarget,
runNavigationMatrixScenario,
} = require("../UserScript/e2e/navigation-matrix");
const DEFAULT_POST_ACTIVATION_QUIET_MS = 650;
const INTERACTION_PATHS = new Set(["/interact/vote", "/interact/confirmVote"]);
const NON_CURRENT_DUPLICATE_SCENARIO_IDS = Object.freeze([
"watch-sidebar-watch-same-root-hidden-first",
"watch-sidebar-watch-same-root-offscreen-first",
"watch-sidebar-watch-legacy-segmented-duplicate-ids",
]);
const SUPPORTED_RUNTIME_NAMES = Object.freeze(["userscript", "extension"]);
function registerNavigationRuntimeContractScenarios({ register, runtimeName }) {
if (!SUPPORTED_RUNTIME_NAMES.includes(runtimeName)) {
throw new TypeError(`Unsupported navigation contract runtime: ${runtimeName}`);
}
if (typeof register !== "function") {
throw new TypeError("The navigation runtime contract requires a scenario register callback.");
}
for (const scenario of NAVIGATION_MATRIX) {
register({
scenario,
title: `${runtimeName} navigation matrix: ${scenario.id}`,
});
}
}
function createNavigationRuntimeContractAdapter({
backend,
expectedCredentials,
expectedUserId = expectedCredentials?.userId,
matrixRuntime,
page,
postActivationQuietMs = DEFAULT_POST_ACTIVATION_QUIET_MS,
readCredentials,
readInteractionRecords,
runtimeName = matrixRuntime?.name,
}) {
if (!backend || !page || !matrixRuntime) {
throw new TypeError("The navigation runtime contract requires a backend, page, and matrix runtime.");
}
if (typeof readInteractionRecords !== "function") {
throw new TypeError("The navigation runtime contract requires readInteractionRecords().");
}
if (expectedCredentials !== undefined && typeof readCredentials !== "function") {
throw new TypeError("Expected credentials require a readCredentials() adapter.");
}
if (!Number.isFinite(postActivationQuietMs) || postActivationQuietMs < 0) {
throw new TypeError("postActivationQuietMs must be a non-negative finite number.");
}
return Object.freeze({
backend,
expectedCredentials,
expectedUserId,
matrixRuntime,
page,
postActivationQuietMs,
readCredentials,
readInteractionRecords,
runtimeName,
});
}
function interactionRecords(records) {
return records.filter((record) => record.method === "POST" && INTERACTION_PATHS.has(record.pathname));
}
async function expectCredentials(adapter) {
if (adapter.expectedCredentials === undefined) return;
expect(await adapter.readCredentials(), `${adapter.runtimeName} changed its persisted vote identity`).toEqual(
adapter.expectedCredentials,
);
}
async function expectNonCurrentDuplicateActivationIgnored(adapter, scenario, currentTarget) {
if (!NON_CURRENT_DUPLICATE_SCENARIO_IDS.includes(scenario.id)) return;
const currentRoot = adapter.page.locator(
`ytd-watch-flexy[video-id="${scenario.destination.videoId}"], ` +
`ytd-watch-grid[video-id="${scenario.destination.videoId}"]`,
);
const allDislikeButtons = currentRoot.locator('[data-fixture-role="dislike"] button');
const outgoingButton = currentRoot.locator(
'[data-fixture-matrix-hidden-outgoing="true"] [data-fixture-role="dislike"] button',
);
await expect(allDislikeButtons).toHaveCount(2);
await expect(outgoingButton).toHaveCount(1);
expect(
await allDislikeButtons
.first()
.evaluate((button) => button.matches('[data-fixture-matrix-hidden-outgoing="true"] *')),
`${adapter.runtimeName} fixture must put the non-current duplicate before the visible destination control`,
).toBe(true);
const currentCount = await currentTarget.count.textContent();
const currentDislikePressed = await currentTarget.button.getAttribute("aria-pressed");
const currentLikePressed = await currentTarget.likeButton.getAttribute("aria-pressed");
const interactionStartIndex = adapter.readInteractionRecords().length;
// Dispatch a real bubbling click even though the stale duplicate is hidden or
// offscreen. This models an unscoped first-match locator without allowing the
// test framework's actionability checks to silently retarget the current UI.
await outgoingButton.evaluate((button) => button.click());
await adapter.page.waitForTimeout(adapter.postActivationQuietMs);
await expect(outgoingButton).toHaveAttribute("aria-pressed", "true");
await expect(currentTarget.count).toHaveText(currentCount);
await expect(currentTarget.button).toHaveAttribute("aria-pressed", currentDislikePressed);
await expect(currentTarget.likeButton).toHaveAttribute("aria-pressed", currentLikePressed);
expect(
interactionRecords(adapter.readInteractionRecords().slice(interactionStartIndex)),
`${adapter.runtimeName} reacted to a non-current duplicate before the visible destination control`,
).toEqual([]);
await expectCredentials(adapter);
}
async function expectSuccessfulVoteActivation(adapter, videoId, value, activationTarget) {
const interactionStartIndex = adapter.readInteractionRecords().length;
await activationTarget.click();
const readHandshake = () =>
readArtifactVoteHandshake(adapter.readInteractionRecords(), interactionStartIndex, videoId, value);
await expect
.poll(
() => {
const handshake = readHandshake();
return handshake.interactionCount >= 2 && handshake.confirmation?.responded === true;
},
{
message: `${adapter.runtimeName} must complete exactly one ${value} vote and successful confirmation for ${videoId}`,
},
)
.toBe(true);
const handshake = readHandshake();
expect(
isArtifactVoteHandshakeValid(handshake),
`${adapter.runtimeName} emitted a duplicate, malformed, or failed vote chain for ${videoId}: ` +
JSON.stringify(handshake),
).toBe(true);
await adapter.page.waitForTimeout(adapter.postActivationQuietMs);
const settledHandshake = readHandshake();
expect(
isArtifactVoteHandshakeValid(settledHandshake),
`${adapter.runtimeName} emitted a late vote request for ${videoId}: ${JSON.stringify(settledHandshake)}`,
).toBe(true);
if (adapter.expectedUserId !== undefined) {
expect(settledHandshake.sharedUserId).toBe(adapter.expectedUserId);
}
return settledHandshake;
}
async function expectDestinationReactionContract(adapter, scenario) {
expect(
interactionRecords(adapter.readInteractionRecords()),
`${adapter.runtimeName} submitted a vote during navigation without an activation`,
).toEqual([]);
await expectCredentials(adapter);
const target = getDestinationDislikePostconditionTarget(adapter.page, adapter.matrixRuntime, scenario);
await expect(target.control).toHaveCount(1);
await expect(target.control).toBeVisible();
await expect(target.button).toHaveCount(1);
await expect(target.button).toBeVisible();
await expect(target.button).toBeEnabled();
await expect(target.count).toHaveCount(1);
await expect(target.count).toHaveText(target.expectedInitialDislikeCount);
await expect(target.likeButton).toHaveCount(1);
await expect(target.likeButton).toBeVisible();
await expect(target.likeButton).toBeEnabled();
await expect(target.likeCount).toHaveCount(1);
const initialNativeLikeCount = Number.parseInt(await target.likeCount.textContent(), 10);
expect(initialNativeLikeCount).toBeGreaterThanOrEqual(0);
const dislike = await expectSuccessfulVoteActivation(adapter, scenario.destination.videoId, -1, target.button);
await expect(target.count).toHaveText(target.expectedCount);
await expect(target.control).toBeVisible();
await expect(target.button).toHaveAttribute("aria-pressed", "true");
await expect(target.control).toHaveClass(/style-default-active/);
await expect(target.likeButton).toHaveAttribute("aria-pressed", "false");
await expect(target.likeControl).not.toHaveClass(/style-default-active/);
await expect(target.likeCount).toHaveText(String(initialNativeLikeCount));
await expectCredentials(adapter);
const like = await expectSuccessfulVoteActivation(adapter, scenario.destination.videoId, 1, target.likeButton);
expect(like.sharedUserId).toBe(dislike.sharedUserId);
await expect(target.count).toHaveText(target.expectedFinalDislikeCount);
await expect(target.control).toBeVisible();
await expect(target.likeCount).toHaveText(String(initialNativeLikeCount + 1));
await expect(target.likeButton).toHaveAttribute("aria-pressed", "true");
await expect(target.likeControl).toHaveClass(/style-default-active/);
await expect(target.button).toHaveAttribute("aria-pressed", "false");
await expect(target.control).not.toHaveClass(/style-default-active/);
await expectCredentials(adapter);
expect(interactionRecords(adapter.readInteractionRecords()).map((record) => record.pathname)).toEqual([
"/interact/vote",
"/interact/confirmVote",
"/interact/vote",
"/interact/confirmVote",
]);
return {
dislikeUserId: dislike.sharedUserId,
initialNativeLikeCount,
likeUserId: like.sharedUserId,
target,
};
}
async function runNavigationRuntimeContract({ adapter, afterNavigation, afterReactions, scenario }) {
let navigationHookCalled = false;
const runAfterNavigation = async () => {
if (navigationHookCalled) return;
navigationHookCalled = true;
await afterNavigation?.({ adapter, scenario });
};
await runNavigationMatrixScenario({
backend: adapter.backend,
beforeNonCurrentDuplicateDetach: async () => {
await runAfterNavigation();
const target = getDestinationDislikePostconditionTarget(adapter.page, adapter.matrixRuntime, scenario);
await expectNonCurrentDuplicateActivationIgnored(adapter, scenario, target);
},
page: adapter.page,
runtime: adapter.matrixRuntime,
scenario,
});
await runAfterNavigation();
if (scenario.postcondition === NO_DESTINATION_DISLIKE_POSTCONDITION) {
expect(
interactionRecords(adapter.readInteractionRecords()),
`${adapter.runtimeName} submitted a vote for an intentionally incomplete navigation surface`,
).toEqual([]);
await expectCredentials(adapter);
await afterReactions?.({ adapter, result: null, scenario });
return null;
}
const result = await expectDestinationReactionContract(adapter, scenario);
await afterReactions?.({ adapter, result, scenario });
return result;
}
module.exports = {
NON_CURRENT_DUPLICATE_SCENARIO_IDS,
createNavigationRuntimeContractAdapter,
expectNonCurrentDuplicateActivationIgnored,
expectDestinationReactionContract,
expectSuccessfulVoteActivation,
registerNavigationRuntimeContractScenarios,
runNavigationRuntimeContract,
};
@@ -0,0 +1,426 @@
const { NAVIGATION_MATRIX, NAVIGATION_SCENARIO_RUNNER_IDS } = require("../UserScript/e2e/navigation-matrix");
const {
NON_CURRENT_DUPLICATE_SCENARIO_IDS,
createNavigationRuntimeContractAdapter,
expectSuccessfulVoteActivation,
registerNavigationRuntimeContractScenarios,
} = require("./navigation-runtime-contract");
const USER_ID = "A".repeat(36);
const VIDEO_ID = "abcdefghijk";
function successfulInteractionRecords(value = -1) {
return [
{
body: { userId: USER_ID, value, videoId: VIDEO_ID },
method: "POST",
pathname: "/interact/vote",
respondedAt: Date.now(),
responseBody: { challenge: Buffer.alloc(16).toString("base64"), difficulty: 0 },
responseStatus: 200,
},
{
body: { solution: Buffer.alloc(4).toString("base64"), userId: USER_ID, videoId: VIDEO_ID },
method: "POST",
pathname: "/interact/confirmVote",
respondedAt: Date.now(),
responseBody: true,
responseStatus: 200,
},
];
}
function activationAdapter(records) {
return createNavigationRuntimeContractAdapter({
backend: {},
expectedUserId: USER_ID,
matrixRuntime: { name: "userscript" },
page: { waitForTimeout: jest.fn(async () => {}) },
postActivationQuietMs: 0,
readInteractionRecords: () => records,
});
}
function collectWrapperNavigationTitles(wrapperPath, runtimeName) {
const mockSharedRegistrationCalls = [];
const mockTitles = [];
const mockTest = (title) => mockTitles.push(title);
mockTest.describe = (_title, registerTests) => registerTests();
jest.resetModules();
jest.doMock("@playwright/test", () => ({ expect, test: mockTest }));
jest.doMock("./navigation-runtime-contract", () => {
const actualContract = jest.requireActual("./navigation-runtime-contract");
return {
...actualContract,
registerNavigationRuntimeContractScenarios(options) {
mockSharedRegistrationCalls.push(options.runtimeName);
return actualContract.registerNavigationRuntimeContractScenarios(options);
},
};
});
try {
jest.isolateModules(() => require(wrapperPath));
} finally {
jest.dontMock("@playwright/test");
jest.dontMock("./navigation-runtime-contract");
jest.resetModules();
}
return {
sharedRegistrationCalls: mockSharedRegistrationCalls,
titles: mockTitles.filter((title) => title.startsWith(`${runtimeName} navigation matrix:`)),
};
}
test.each(["userscript", "extension"])("registers every shared navigation scenario for %s", (runtimeName) => {
const registrations = [];
registerNavigationRuntimeContractScenarios({
register: (registration) => registrations.push(registration),
runtimeName,
});
expect(registrations.map(({ scenario }) => scenario.id)).toEqual(NAVIGATION_MATRIX.map(({ id }) => id));
expect(registrations.map(({ title }) => title)).toEqual(
NAVIGATION_MATRIX.map(({ id }) => `${runtimeName} navigation matrix: ${id}`),
);
});
test.each([
["userscript", "../UserScript/e2e/userscript-navigation-matrix.e2e"],
["extension", "./extension/extension-artifact-navigation.e2e"],
])("the %s Playwright wrapper registers the complete shared catalog", (runtimeName, wrapperPath) => {
const registration = collectWrapperNavigationTitles(wrapperPath, runtimeName);
expect(registration.sharedRegistrationCalls).toEqual([runtimeName]);
expect(registration.titles).toEqual(NAVIGATION_MATRIX.map(({ id }) => `${runtimeName} navigation matrix: ${id}`));
});
test("keeps one navigation runner for every shared scenario and no unused runners", () => {
expect([...NAVIGATION_SCENARIO_RUNNER_IDS].sort()).toEqual(NAVIGATION_MATRIX.map(({ id }) => id).sort());
});
test("keeps every hidden-first Watch duplicate in the shared runtime registrations", () => {
expect(NON_CURRENT_DUPLICATE_SCENARIO_IDS).toEqual([
"watch-sidebar-watch-same-root-hidden-first",
"watch-sidebar-watch-same-root-offscreen-first",
"watch-sidebar-watch-legacy-segmented-duplicate-ids",
]);
for (const scenarioId of NON_CURRENT_DUPLICATE_SCENARIO_IDS) {
const scenario = NAVIGATION_MATRIX.find(({ id }) => id === scenarioId);
expect(scenario).toMatchObject({ destination: { kind: "watch" }, origin: { kind: "watch" } });
expect(scenario.coverage.dom).toContain("rendered-destination-second");
}
});
test("keeps the reused Shorts renderer without a finish event in both runtime registrations", () => {
const scenarioId = "short-next-short-reuse-renderer-start-no-finish";
const scenario = NAVIGATION_MATRIX.find(({ id }) => id === scenarioId);
expect(scenario).toMatchObject({
coverage: {
dom: expect.arrayContaining([
"reuse-exact-renderer",
"reuse-exact-action-root",
"exact-href-identity",
"no-is-active",
]),
timing: expect.arrayContaining(["navigate-start-without-finish"]),
},
destination: {
kind: "shorts",
shortIdentity: "exact-href-without-active-or-video-id",
},
origin: { kind: "shorts" },
});
for (const runtimeName of ["userscript", "extension"]) {
const registrations = [];
registerNavigationRuntimeContractScenarios({
register: (registration) => registrations.push(registration),
runtimeName,
});
expect(
registrations.filter(({ scenario: registeredScenario }) => registeredScenario.id === scenarioId),
).toHaveLength(1);
}
});
test("keeps the exact current Shorts link authoritative over an unrelated description cross-link", () => {
const scenarioId = "short-next-short-exact-href-with-description-crosslink";
const scenario = NAVIGATION_MATRIX.find(({ id }) => id === scenarioId);
expect(scenario).toMatchObject({
coverage: {
dom: expect.arrayContaining([
"reuse-exact-renderer",
"reuse-exact-action-root",
"exact-href-identity",
"unrelated-description-short-link",
"no-is-active",
"no-video-id",
]),
timing: expect.arrayContaining(["navigate-start-without-finish"]),
},
destination: {
kind: "shorts",
shortIdentity: "exact-href-without-active-or-video-id",
unrelatedDescriptionShortVideoId: "FupY92jTfho",
},
origin: { kind: "shorts" },
postcondition: "single-destination-dislike",
});
for (const runtimeName of ["userscript", "extension"]) {
const registrations = [];
registerNavigationRuntimeContractScenarios({
register: (registration) => registrations.push(registration),
runtimeName,
});
expect(
registrations.filter(({ scenario: registeredScenario }) => registeredScenario.id === scenarioId),
).toHaveLength(1);
}
});
test("keeps the persistent data-null exact-href Shorts recovery in both runtime registrations", () => {
const scenarioId = "short-next-short-reuse-renderer-replace-action-root-exact-href-persistent-data-null";
const scenario = NAVIGATION_MATRIX.find(({ id }) => id === scenarioId);
expect(scenario).toMatchObject({
coverage: {
dom: expect.arrayContaining([
"reuse-exact-renderer",
"replace-action-root",
"exact-href-identity",
"no-is-active",
"no-video-id",
"complete-native-inventory",
"persistent-data-null-action-root",
]),
timing: expect.arrayContaining([
"navigate-start-without-finish",
"data-null-past-watchdog",
"stable-native-inventory",
]),
},
destination: {
kind: "shorts",
shortIdentity: "exact-href-without-active-or-video-id",
},
origin: { kind: "shorts" },
timing: { maxFirstValidMs: 2_500, unsafeWindowMs: 520 },
transition: {
actionRoot: "replace-complete-native-persistent-data-null",
navigateFinish: "none",
renderer: "reuse-exact-node",
},
});
for (const runtimeName of ["userscript", "extension"]) {
const registrations = [];
registerNavigationRuntimeContractScenarios({
register: (registration) => registrations.push(registration),
runtimeName,
});
expect(
registrations.filter(({ scenario: registeredScenario }) => registeredScenario.id === scenarioId),
).toHaveLength(1);
}
});
test("keeps the incomplete rendered-inventory persistent data-null surface inert in both runtimes", () => {
const scenarioId = "short-next-short-persistent-data-null-nonrendered-native-stays-inert";
const scenario = NAVIGATION_MATRIX.find(({ id }) => id === scenarioId);
expect(scenario).toMatchObject({
coverage: {
dom: expect.arrayContaining([
"reuse-exact-renderer",
"replace-action-root",
"exact-href-identity",
"no-is-active",
"no-video-id",
"incomplete-rendered-native-inventory",
"non-rendered-native-action",
"persistent-data-null-action-root",
"stable-action-root-geometry",
]),
timing: expect.arrayContaining([
"navigate-start-without-finish",
"data-null-past-watchdog",
"inert-beyond-fallback-window",
]),
},
destination: {
kind: "shorts",
shortIdentity: "exact-href-without-active-or-video-id",
},
origin: { kind: "shorts" },
postcondition: "no-destination-dislike",
timing: { inertForMs: 1_700 },
transition: {
actionRoot: "replace-incomplete-rendered-native-persistent-data-null",
navigateFinish: "none",
renderer: "reuse-exact-node",
},
});
for (const runtimeName of ["userscript", "extension"]) {
const registrations = [];
registerNavigationRuntimeContractScenarios({
register: (registration) => registrations.push(registration),
runtimeName,
});
expect(
registrations.filter(({ scenario: registeredScenario }) => registeredScenario.id === scenarioId),
).toHaveLength(1);
}
});
test("keeps the native-Dislike persistent data-null surface interactive in both runtimes", () => {
const scenarioId = "short-next-short-persistent-data-null-native-dislike";
const scenario = NAVIGATION_MATRIX.find(({ id }) => id === scenarioId);
expect(scenario).toMatchObject({
coverage: {
dom: expect.arrayContaining([
"reuse-exact-renderer",
"replace-action-root",
"exact-href-identity",
"no-is-active",
"no-video-id",
"native-dislike-present",
"no-synthetic-mutation",
"persistent-data-null-action-root",
]),
timing: expect.arrayContaining([
"navigate-start-without-finish",
"native-dislike-after-stability",
"native-dislike-without-synthetic-mutation",
]),
},
destination: {
kind: "shorts",
shortIdentity: "exact-href-without-active-or-video-id",
shortsDislikeControl: "native",
},
origin: { kind: "shorts" },
postcondition: "single-destination-dislike",
timing: { maxFirstValidMs: 2_500, unsafeWindowMs: 520 },
transition: {
actionRoot: "replace-native-dislike-persistent-data-null",
navigateFinish: "none",
renderer: "reuse-exact-node",
},
});
for (const runtimeName of ["userscript", "extension"]) {
const registrations = [];
registerNavigationRuntimeContractScenarios({
register: (registration) => registrations.push(registration),
runtimeName,
});
expect(
registrations.filter(({ scenario: registeredScenario }) => registeredScenario.id === scenarioId),
).toHaveLength(1);
}
});
test.each([
"short-next-short-replace-root-start-no-finish-staged-hydration",
"short-next-short-replace-root-repeated-start-no-finish-staged-hydration",
])("keeps the staged replacement-root deadlock regression in both runtime registrations: %s", (scenarioId) => {
const scenario = NAVIGATION_MATRIX.find(({ id }) => id === scenarioId);
expect(scenario).toMatchObject({
coverage: {
dom: expect.arrayContaining([
"replace-shorts-root",
"destination-action-root-absent",
"staged-data-null-action-root",
"complete-native-inventory-before-hydration",
]),
timing: expect.arrayContaining([
"navigate-start-without-finish",
"no-controls-over-500ms",
"data-null-over-stability-window",
]),
},
destination: { kind: "shorts" },
origin: { kind: "shorts" },
transition: {
actionRoot: "absent-then-empty-then-native-then-hydrated",
navigateFinish: "none",
root: "replace",
},
});
for (const runtimeName of ["userscript", "extension"]) {
const registrations = [];
registerNavigationRuntimeContractScenarios({
register: (registration) => registrations.push(registration),
runtimeName,
});
expect(
registrations.filter(({ scenario: registeredScenario }) => registeredScenario.id === scenarioId),
).toHaveLength(1);
}
});
test("budgets the deliberately delayed Shorts hydration without loosening the default navigation gate", () => {
const delayedShorts = NAVIGATION_MATRIX.find(({ id }) => id === "watch-direct-short-delayed");
const delayedWatch = NAVIGATION_MATRIX.find(({ id }) => id === "short-direct-watch-delayed");
expect(delayedShorts.timing).toEqual({ controlDelayMs: 600, maxFirstValidMs: 1_250 });
expect(delayedWatch.timing).toEqual({ controlDelayMs: 600 });
});
test("accepts one exact successful activation handshake", async () => {
const records = [];
const target = {
click: jest.fn(async () => records.push(...successfulInteractionRecords())),
};
await expect(expectSuccessfulVoteActivation(activationAdapter(records), VIDEO_ID, -1, target)).resolves.toMatchObject(
{
confirmationCount: 1,
interactionCount: 2,
sharedUserId: USER_ID,
voteCount: 1,
},
);
});
test.each([
["a duplicate chain", (records) => records.push(...successfulInteractionRecords())],
["a false confirmation", (records) => (records[1].responseBody = false)],
["the wrong video", (records) => (records[0].body.videoId = "zyxwvutsrqp")],
])("rejects %s", async (_label, corrupt) => {
const records = [];
const target = {
click: jest.fn(async () => {
records.push(...successfulInteractionRecords());
corrupt(records);
}),
};
await expect(expectSuccessfulVoteActivation(activationAdapter(records), VIDEO_ID, -1, target)).rejects.toThrow(
/duplicate, malformed, or failed vote chain/,
);
});
test("rejects an adapter that could not prove expected credential persistence", () => {
expect(() =>
createNavigationRuntimeContractAdapter({
backend: {},
expectedCredentials: { registrationConfirmed: true, userId: USER_ID },
matrixRuntime: { name: "userscript" },
page: {},
readInteractionRecords: () => [],
}),
).toThrow("Expected credentials require a readCredentials() adapter.");
});
@@ -0,0 +1,35 @@
const path = require("node:path");
const { verifyRequestedExtensionArtifact } = require("./verify-extension-artifact");
const ALLOW_CUSTOM_ARTIFACT_ENV = "RYD_E2E_ALLOW_CUSTOM_EXTENSION_ARTIFACT";
const REPOSITORY_EXTENSION_ARTIFACT = path.resolve(__dirname, "../combined/dist/chrome");
function selectedArtifact(env) {
const requested = env.RYD_EXTENSION_ARTIFACT?.trim();
return requested ? path.resolve(requested) : REPOSITORY_EXTENSION_ARTIFACT;
}
function verifyPlaywrightExtensionArtifact({
env = process.env,
verifyArtifact = verifyRequestedExtensionArtifact,
} = {}) {
const artifact = selectedArtifact(env);
const custom = artifact !== REPOSITORY_EXTENSION_ARTIFACT;
if (custom && env[ALLOW_CUSTOM_ARTIFACT_ENV] !== "1") {
throw new Error(
`Refusing to run extension Playwright against custom artifact ${artifact}. ` +
`Set ${ALLOW_CUSTOM_ARTIFACT_ENV}=1 only for an intentional custom or negative-control fixture.`,
);
}
return verifyArtifact(custom ? artifact : undefined);
}
async function playwrightExtensionGlobalSetup() {
verifyPlaywrightExtensionArtifact();
}
module.exports = playwrightExtensionGlobalSetup;
module.exports.ALLOW_CUSTOM_ARTIFACT_ENV = ALLOW_CUSTOM_ARTIFACT_ENV;
module.exports.REPOSITORY_EXTENSION_ARTIFACT = REPOSITORY_EXTENSION_ARTIFACT;
module.exports.selectedArtifact = selectedArtifact;
module.exports.verifyPlaywrightExtensionArtifact = verifyPlaywrightExtensionArtifact;
@@ -0,0 +1,69 @@
/**
* @jest-environment node
*/
const path = require("node:path");
const extensionPlaywrightConfig = require("../../playwright.extension.config");
const {
ALLOW_CUSTOM_ARTIFACT_ENV,
REPOSITORY_EXTENSION_ARTIFACT,
selectedArtifact,
verifyPlaywrightExtensionArtifact,
} = require("./playwright-extension-global-setup");
test("the extension Playwright config always runs the artifact freshness gate", () => {
expect(extensionPlaywrightConfig.globalSetup).toBe(require.resolve("./playwright-extension-global-setup"));
});
test("the default Playwright target receives full repository artifact verification", () => {
const verifyArtifact = jest.fn(() => ({ kind: "repository" }));
expect(verifyPlaywrightExtensionArtifact({ env: {}, verifyArtifact })).toEqual({ kind: "repository" });
expect(selectedArtifact({})).toBe(REPOSITORY_EXTENSION_ARTIFACT);
expect(verifyArtifact).toHaveBeenCalledWith(undefined);
});
test("a custom artifact cannot silently bypass the repository build receipt", () => {
const customArtifact = path.resolve("test-results", "intentional-broken-extension");
const verifyArtifact = jest.fn();
expect(() =>
verifyPlaywrightExtensionArtifact({
env: { RYD_EXTENSION_ARTIFACT: customArtifact },
verifyArtifact,
}),
).toThrow(new RegExp(`${ALLOW_CUSTOM_ARTIFACT_ENV}=1`));
expect(verifyArtifact).not.toHaveBeenCalled();
});
test("an explicit custom-fixture opt-in still runs standalone artifact validation", () => {
const customArtifact = path.resolve("test-results", "intentional-broken-extension");
const verifyArtifact = jest.fn(() => ({ kind: "custom" }));
expect(
verifyPlaywrightExtensionArtifact({
env: {
[ALLOW_CUSTOM_ARTIFACT_ENV]: "1",
RYD_EXTENSION_ARTIFACT: customArtifact,
},
verifyArtifact,
}),
).toEqual({ kind: "custom" });
expect(verifyArtifact).toHaveBeenCalledWith(customArtifact);
});
test("truthy-looking custom-fixture values do not weaken the explicit gate", () => {
const customArtifact = path.resolve("test-results", "intentional-broken-extension");
for (const value of ["true", "yes", "0"]) {
expect(() =>
verifyPlaywrightExtensionArtifact({
env: {
[ALLOW_CUSTOM_ARTIFACT_ENV]: value,
RYD_EXTENSION_ARTIFACT: customArtifact,
},
verifyArtifact: jest.fn(),
}),
).toThrow(new RegExp(`${ALLOW_CUSTOM_ARTIFACT_ENV}=1`));
}
});
@@ -0,0 +1,19 @@
const {
resolveRequestedUserscriptArtifact,
verifyRequestedUserscriptArtifact,
} = require("./verify-userscript-artifact");
function verifyPlaywrightUserscriptArtifact({
env = process.env,
verifyArtifact = verifyRequestedUserscriptArtifact,
} = {}) {
const artifactPath = resolveRequestedUserscriptArtifact(env.RYD_USERSCRIPT_ARTIFACT);
return verifyArtifact(artifactPath);
}
async function playwrightUserscriptGlobalSetup() {
verifyPlaywrightUserscriptArtifact();
}
module.exports = playwrightUserscriptGlobalSetup;
module.exports.verifyPlaywrightUserscriptArtifact = verifyPlaywrightUserscriptArtifact;
@@ -0,0 +1,108 @@
/**
* @jest-environment node
*/
const fs = require("node:fs");
const os = require("node:os");
const path = require("node:path");
const userscriptPlaywrightConfig = require("../../playwright.userscript.config");
const {
REPOSITORY_USERSCRIPT_ARTIFACT,
receiptPathForUserscriptArtifact,
resolveRequestedUserscriptArtifact,
} = require("./verify-userscript-artifact");
const { verifyPlaywrightUserscriptArtifact } = require("./playwright-userscript-global-setup");
const { createUserscriptBuildReceipt, writeUserscriptBuildReceipt } = require("../../userscript-build-receipt");
const REPOSITORY_ROOT = path.resolve(__dirname, "../..");
let temporaryDirectory;
function createCustomArtifact(name = "Return Youtube Dislike.user.js") {
const directory = fs.mkdtempSync(path.join(temporaryDirectory, "artifact-"));
const artifactPath = path.join(directory, name);
fs.writeFileSync(artifactPath, "generated userscript");
return artifactPath;
}
function writeMatchingReceipt(artifactPath) {
const receipt = createUserscriptBuildReceipt(REPOSITORY_ROOT, {
artifactPath,
liveTestBuild: false,
mode: "production",
});
return writeUserscriptBuildReceipt(receiptPathForUserscriptArtifact(artifactPath), artifactPath, receipt);
}
beforeEach(() => {
temporaryDirectory = fs.mkdtempSync(path.join(os.tmpdir(), "ryd-userscript-playwright-"));
});
afterEach(() => {
fs.rmSync(temporaryDirectory, { force: true, recursive: true });
});
test("the userscript Playwright config always runs the artifact freshness gate", () => {
expect(userscriptPlaywrightConfig.globalSetup).toBe(require.resolve("./playwright-userscript-global-setup"));
});
test("the default Playwright target receives exact repository artifact verification", () => {
const verifyArtifact = jest.fn(() => ({ kind: "repository" }));
expect(verifyPlaywrightUserscriptArtifact({ env: {}, verifyArtifact })).toEqual({ kind: "repository" });
expect(verifyArtifact).toHaveBeenCalledWith(REPOSITORY_USERSCRIPT_ARTIFACT);
});
test("the harness and freshness gate resolve the same custom artifact", () => {
const requestedArtifact = path.join(temporaryDirectory, "custom.user.js");
const previousArtifact = process.env.RYD_USERSCRIPT_ARTIFACT;
try {
process.env.RYD_USERSCRIPT_ARTIFACT = ` ${requestedArtifact} `;
jest.isolateModules(() => {
const { GENERATED_USERSCRIPT } = require("../UserScript/e2e/harness");
expect(GENERATED_USERSCRIPT).toBe(resolveRequestedUserscriptArtifact(requestedArtifact));
});
} finally {
if (previousArtifact === undefined) delete process.env.RYD_USERSCRIPT_ARTIFACT;
else process.env.RYD_USERSCRIPT_ARTIFACT = previousArtifact;
}
});
test("a custom artifact with its own matching receipt passes", () => {
const artifactPath = createCustomArtifact();
writeMatchingReceipt(artifactPath);
expect(verifyPlaywrightUserscriptArtifact({ env: { RYD_USERSCRIPT_ARTIFACT: artifactPath } })).toMatchObject({
artifactPath: expect.any(String),
artifactHash: expect.stringMatching(/^[a-f0-9]{64}$/),
});
});
test("an unreceipted custom artifact is rejected", () => {
const artifactPath = createCustomArtifact();
expect(() => verifyPlaywrightUserscriptArtifact({ env: { RYD_USERSCRIPT_ARTIFACT: artifactPath } })).toThrow(
/Missing userscript build receipt/,
);
});
test("a custom artifact changed after its receipt is rejected", () => {
const artifactPath = createCustomArtifact();
writeMatchingReceipt(artifactPath);
fs.writeFileSync(artifactPath, "stale generated userscript");
expect(() => verifyPlaywrightUserscriptArtifact({ env: { RYD_USERSCRIPT_ARTIFACT: artifactPath } })).toThrow(
/differs from its build receipt/,
);
});
test("a receipt copied from another artifact path is rejected", () => {
const firstArtifact = createCustomArtifact("first.user.js");
const secondArtifact = createCustomArtifact("second.user.js");
writeMatchingReceipt(firstArtifact);
fs.copyFileSync(receiptPathForUserscriptArtifact(firstArtifact), receiptPathForUserscriptArtifact(secondArtifact));
expect(() => verifyPlaywrightUserscriptArtifact({ env: { RYD_USERSCRIPT_ARTIFACT: secondArtifact } })).toThrow(
/belongs to a different artifact path/,
);
});
@@ -0,0 +1,256 @@
const { expect } = require("@playwright/test");
const { VIDEO_A, VIDEO_B } = require("../UserScript/e2e/harness");
const { SPA_COUNTS, isArtifactVoteHandshakeValid, readArtifactVoteHandshake } = require("./hermetic-artifact-smoke");
const INTERACTION_PATHS = new Set(["/interact/vote", "/interact/confirmVote"]);
const SUPPORTED_RUNTIME_NAMES = Object.freeze(["userscript", "extension"]);
const RUNTIME_RESILIENCE_SCENARIOS = Object.freeze([
Object.freeze({ id: "delayed-a-hydration-vs-b-activation", kind: "delayed-hydration" }),
Object.freeze({ id: "in-flight-a-vote-then-b-navigation", kind: "in-flight-vote" }),
Object.freeze({ id: "rejected-vote-and-confirmation-then-b-recovery", kind: "failure-recovery" }),
Object.freeze({ id: "signed-out-and-disabled-interaction-gate", kind: "interaction-gate" }),
]);
function registerRuntimeResilienceContractScenarios({ register, runtimeName }) {
if (!SUPPORTED_RUNTIME_NAMES.includes(runtimeName)) {
throw new TypeError(`Unsupported resilience contract runtime: ${runtimeName}`);
}
if (typeof register !== "function") {
throw new TypeError("The runtime resilience contract requires a scenario register callback.");
}
for (const scenario of RUNTIME_RESILIENCE_SCENARIOS) {
register({ scenario, title: `${runtimeName} resilience contract: ${scenario.id}` });
}
}
function interactionRecords(adapter) {
return adapter
.readInteractionRecords()
.filter((record) => record.method === "POST" && INTERACTION_PATHS.has(record.pathname));
}
function currentDislikeButton(adapter, videoId) {
return adapter.page.locator(
`ytd-watch-flexy[video-id="${videoId}"] [data-fixture-role="dislike"] button:visible, ` +
`ytd-watch-grid[video-id="${videoId}"] [data-fixture-role="dislike"] button:visible`,
);
}
async function clickCurrentDislike(adapter, videoId) {
const button = currentDislikeButton(adapter, videoId);
await expect(button, `${adapter.runtime} must expose one current Dislike button for ${videoId}`).toHaveCount(1);
await expect(button).toBeVisible();
await expect(button).toBeEnabled();
await button.click();
}
async function waitForRecordResponse(record, label) {
await expect.poll(() => record.respondedAt, { message: `${label} never received a response` }).toBeTruthy();
}
async function expectSuccessfulHandshake(adapter, startIndex, videoId, value) {
const read = () => readArtifactVoteHandshake(adapter.readInteractionRecords(), startIndex, videoId, value);
await expect
.poll(
() => {
const handshake = read();
return handshake.interactionCount >= 2 && handshake.confirmation?.responded === true;
},
{ message: `${adapter.runtime} did not complete the ${value} vote chain for ${videoId}` },
)
.toBe(true);
const handshake = read();
expect(isArtifactVoteHandshakeValid(handshake), JSON.stringify(handshake)).toBe(true);
return handshake;
}
async function assertRuntimeClean(adapter, scenarioId, { allowedConsoleErrors = [] } = {}) {
expect(adapter.backend.blockedRequests, `${adapter.runtime} escaped the hermetic page route set`).toEqual([]);
if (adapter.apiServer) {
expect(adapter.apiServer.unexpectedRequests, "the extension background escaped its hermetic API server").toEqual(
[],
);
}
if (allowedConsoleErrors.length === 0) {
await adapter.assertNoPageSignals(scenarioId);
return;
}
await adapter.page.evaluate(() => new Promise((resolve) => setTimeout(resolve, 0)));
await adapter.workerSignals?.refresh?.();
const snapshot = adapter.pageSignals.snapshot();
const pageSignals = snapshot.page ?? snapshot;
const workerSignals = snapshot.worker ?? null;
expect(pageSignals.pageErrors, `${adapter.runtime} emitted a page error during ${scenarioId}`).toEqual([]);
expect(
pageSignals.unhandledRejections,
`${adapter.runtime} emitted an unhandled rejection during ${scenarioId}`,
).toEqual([]);
if (workerSignals) {
expect(workerSignals.evaluationFailure).toBeNull();
expect(workerSignals.evaluatedSignals).toEqual([]);
expect(workerSignals.reportedSignals).toEqual([]);
}
const consoleSignals = [
...pageSignals.consoleErrors.map((signal) => signal.text),
...(workerSignals?.consoleFailures ?? []).map((signal) => signal.text),
];
expect(
consoleSignals.every((text) => allowedConsoleErrors.some((pattern) => pattern.test(text))),
`${adapter.runtime} emitted an unexpected console error during ${scenarioId}: ${JSON.stringify(consoleSignals)}`,
).toBe(true);
}
async function withAdapter(createAdapter, options, run) {
const adapter = await createAdapter(options);
try {
await adapter.start();
await run(adapter);
} finally {
await adapter.close().catch(() => {});
}
}
async function runDelayedHydrationContract(createAdapter, scenario) {
await withAdapter(createAdapter, { scenario }, async (adapter) => {
const outgoingStats = adapter.deferNextStatsRequest();
await adapter.openSpaWatch(VIDEO_A);
const outgoingRecord = await outgoingStats.seen;
expect(outgoingRecord.query.videoId).toBe(VIDEO_A);
await adapter.navigateSpaWatchWhilePending(VIDEO_A, VIDEO_B);
outgoingStats.release({ body: { ...SPA_COUNTS[VIDEO_A], rating: 4.5 }, status: 200 });
const destination = await adapter.waitForWatchResult(VIDEO_B);
expect(destination).toMatchObject({ count: String(SPA_COUNTS[VIDEO_B].dislikes), videoId: VIDEO_B });
expect(await adapter.readDestinationDislikeTextHistory()).not.toContain(String(SPA_COUNTS[VIDEO_A].dislikes));
const interactionStartIndex = adapter.readInteractionRecords().length;
await clickCurrentDislike(adapter, VIDEO_B);
const handshake = await expectSuccessfulHandshake(adapter, interactionStartIndex, VIDEO_B, -1);
expect(handshake.sharedUserId).toMatch(/^[0-9A-Za-z-]{30,}$/);
expect(interactionRecords(adapter).map((record) => record.body.videoId)).toEqual([VIDEO_B, VIDEO_B]);
const stats = adapter.readStatsRequestTimings();
expect(stats.map((record) => record.query.videoId)).toEqual([VIDEO_A, VIDEO_B]);
expect(stats.every((record) => record.respondedAt)).toBe(true);
await assertRuntimeClean(adapter, scenario.id);
});
}
async function runInFlightVoteContract(createAdapter, scenario) {
await withAdapter(createAdapter, { scenario }, async (adapter) => {
await adapter.openSpaWatch(VIDEO_A);
await adapter.waitForWatchResult(VIDEO_A);
const outgoingConfirmation = adapter.deferInteractionResponse("/interact/confirmVote");
await clickCurrentDislike(adapter, VIDEO_A);
const outgoingConfirmationRecord = await outgoingConfirmation.seen;
expect(outgoingConfirmationRecord.body).toMatchObject({ videoId: VIDEO_A });
expect(outgoingConfirmationRecord.respondedAt).toBeUndefined();
await adapter.navigateSpaWatch(VIDEO_A, VIDEO_B);
await adapter.waitForWatchResult(VIDEO_B);
const destinationStartIndex = adapter.readInteractionRecords().length;
await clickCurrentDislike(adapter, VIDEO_B);
const destinationHandshake = await expectSuccessfulHandshake(adapter, destinationStartIndex, VIDEO_B, -1);
expect(outgoingConfirmationRecord.respondedAt).toBeUndefined();
outgoingConfirmation.release({ body: true, status: 200 });
await waitForRecordResponse(outgoingConfirmationRecord, `${adapter.runtime} video A confirmation`);
const records = interactionRecords(adapter);
expect(records.map((record) => record.pathname)).toEqual([
"/interact/vote",
"/interact/confirmVote",
"/interact/vote",
"/interact/confirmVote",
]);
expect(records.map((record) => record.body.videoId)).toEqual([VIDEO_A, VIDEO_A, VIDEO_B, VIDEO_B]);
expect(records[2].at).toBeLessThan(outgoingConfirmationRecord.respondedAt);
expect(new Set(records.map((record) => record.body.userId))).toEqual(new Set([destinationHandshake.sharedUserId]));
await assertRuntimeClean(adapter, scenario.id);
});
}
async function runFailureRecoveryContract(createAdapter, scenario) {
await withAdapter(createAdapter, { scenario }, async (adapter) => {
adapter.enqueueInteractionResponse("/interact/vote", {
body: { error: "intentional vote rejection" },
status: 500,
});
await adapter.openSpaWatch(VIDEO_A);
await adapter.waitForWatchResult(VIDEO_A);
await clickCurrentDislike(adapter, VIDEO_A);
await expect.poll(() => interactionRecords(adapter).length).toBe(1);
const rejectedVote = interactionRecords(adapter)[0];
await waitForRecordResponse(rejectedVote, `${adapter.runtime} rejected vote`);
expect(rejectedVote).toMatchObject({ pathname: "/interact/vote", responseStatus: 500 });
expect(rejectedVote.body).toMatchObject({ videoId: VIDEO_A, value: -1 });
adapter.enqueueInteractionResponse("/interact/confirmVote", { body: false, status: 200 });
await clickCurrentDislike(adapter, VIDEO_A);
await expect.poll(() => interactionRecords(adapter).length).toBe(3);
const rejectedConfirmation = interactionRecords(adapter)[2];
await waitForRecordResponse(rejectedConfirmation, `${adapter.runtime} rejected confirmation`);
expect(rejectedConfirmation).toMatchObject({
pathname: "/interact/confirmVote",
responseBody: false,
responseStatus: 200,
});
expect(interactionRecords(adapter)[1].body).toMatchObject({ videoId: VIDEO_A, value: 0 });
await adapter.navigateSpaWatch(VIDEO_A, VIDEO_B);
await adapter.waitForWatchResult(VIDEO_B);
const destinationStartIndex = adapter.readInteractionRecords().length;
await clickCurrentDislike(adapter, VIDEO_B);
const destinationHandshake = await expectSuccessfulHandshake(adapter, destinationStartIndex, VIDEO_B, -1);
const records = interactionRecords(adapter);
expect(records.map((record) => `${record.pathname}:${record.body.videoId}`)).toEqual([
`/interact/vote:${VIDEO_A}`,
`/interact/vote:${VIDEO_A}`,
`/interact/confirmVote:${VIDEO_A}`,
`/interact/vote:${VIDEO_B}`,
`/interact/confirmVote:${VIDEO_B}`,
]);
expect(new Set(records.map((record) => record.body.userId))).toEqual(new Set([destinationHandshake.sharedUserId]));
await assertRuntimeClean(adapter, scenario.id, { allowedConsoleErrors: [/status of 500/i] });
});
}
async function runInteractionGateContract(createAdapter, scenario) {
for (const gateMode of ["signed-out", "disabled"]) {
await withAdapter(createAdapter, { gateMode, scenario }, async (adapter) => {
if (gateMode === "disabled") await adapter.setVoteSubmissionDisabled(true);
await adapter.openWatch(VIDEO_A);
await adapter.waitForWatchResult(VIDEO_A);
await clickCurrentDislike(adapter, VIDEO_A);
await adapter.page.waitForTimeout(250);
expect(interactionRecords(adapter), `${adapter.runtime} bypassed the ${gateMode} interaction gate`).toEqual([]);
await assertRuntimeClean(adapter, `${scenario.id}-${gateMode}`);
});
}
}
const SCENARIO_RUNNERS = Object.freeze({
"delayed-hydration": runDelayedHydrationContract,
"failure-recovery": runFailureRecoveryContract,
"in-flight-vote": runInFlightVoteContract,
"interaction-gate": runInteractionGateContract,
});
async function runRuntimeResilienceContract({ createAdapter, scenario }) {
if (typeof createAdapter !== "function") {
throw new TypeError("The runtime resilience contract requires createAdapter().");
}
const runner = SCENARIO_RUNNERS[scenario?.kind];
if (!runner) throw new TypeError(`Unknown runtime resilience scenario: ${scenario?.kind}`);
await runner(createAdapter, scenario);
}
module.exports = {
RUNTIME_RESILIENCE_SCENARIOS,
registerRuntimeResilienceContractScenarios,
runRuntimeResilienceContract,
};
@@ -0,0 +1,270 @@
/**
* @jest-environment node
*/
const assert = require("node:assert/strict");
const fs = require("node:fs");
const path = require("node:path");
const { NAVIGATION_MATRIX } = require("../UserScript/e2e/navigation-matrix");
const {
ARTIFACT_BROWSER_SCENARIO_CATALOG,
SHARED_ARTIFACT_SCENARIO_IDS,
createArtifactBrowserScenarioPlan,
} = require("./hermetic-artifact-smoke");
const { SHORTS_PLACEHOLDER_POOL_HOPS } = require("./shorts-placeholder-pool-contract");
const { RUNTIME_RESILIENCE_SCENARIOS } = require("./runtime-resilience-contract");
const { WATCH_VISUAL_SCENARIOS } = require("./watch-visual-scenarios");
const REPOSITORY_ROOT = path.resolve(__dirname, "../..");
const SHARED_BROWSER_RUNTIMES = Object.freeze(["userscript", "extension"]);
const PLAYWRIGHT_CONFIGS = Object.freeze({
extension: require(path.join(REPOSITORY_ROOT, "playwright.extension.config.js")),
userscript: require(path.join(REPOSITORY_ROOT, "playwright.userscript.config.js")),
});
const WRAPPERS = Object.freeze({
extension: Object.freeze({
navigation: path.join(__dirname, "extension", "extension-artifact-navigation.e2e.js"),
resilience: path.join(__dirname, "extension", "extension-runtime-resilience.e2e.js"),
shorts: path.join(__dirname, "extension", "extension-artifact-navigation.e2e.js"),
watch: path.join(__dirname, "extension", "extension-artifact-visual.e2e.js"),
}),
userscript: Object.freeze({
navigation: path.join(__dirname, "..", "UserScript", "e2e", "userscript-navigation-matrix.e2e.js"),
resilience: path.join(__dirname, "..", "UserScript", "e2e", "userscript-runtime-resilience.e2e.js"),
shorts: path.join(__dirname, "..", "UserScript", "e2e", "userscript-shorts-placeholder-pool.e2e.js"),
watch: path.join(__dirname, "..", "UserScript", "e2e", "userscript-state-visual-contract.e2e.js"),
}),
});
const RENDER_ORACLES = Object.freeze({
extension: path.join(__dirname, "extension", "extension-render-oracle.e2e.js"),
userscript: path.join(__dirname, "..", "UserScript", "e2e", "userscript-render-oracle.e2e.js"),
});
function wrapperSource(runtime, contract) {
return fs.readFileSync(WRAPPERS[runtime][contract], "utf8");
}
function expectOneSharedCall(source, moduleName, callName) {
expect(source).toMatch(new RegExp(`require\\(["'][^"']*${moduleName}["']\\)`));
expect(source.match(new RegExp(`\\b${callName}\\s*\\(`, "g"))).toHaveLength(1);
}
function registeredTestTitles(wrapperPath) {
const titles = [];
const fakeTest = (title) => titles.push(title);
fakeTest.describe = (_title, registerTests) => registerTests();
fakeTest.describe.configure = jest.fn();
jest.resetModules();
jest.doMock("@playwright/test", () => ({ expect, test: fakeTest }));
try {
jest.isolateModules(() => require(wrapperPath));
} finally {
jest.dontMock("@playwright/test");
jest.resetModules();
}
return titles;
}
function sharedCoreScenarioIds(runtime) {
if (!SHARED_BROWSER_RUNTIMES.includes(runtime)) {
throw new TypeError(`Unsupported shared browser runtime: ${runtime}`);
}
return [
...NAVIGATION_MATRIX.map(({ id }) => `navigation:${id}`),
...WATCH_VISUAL_SCENARIOS.map(({ id }) => `watch-visual:${id}`),
...RUNTIME_RESILIENCE_SCENARIOS.map(({ id }) => `resilience:${id}`),
`shorts-placeholder-pool:${SHORTS_PLACEHOLDER_POOL_HOPS}-hops`,
...ARTIFACT_BROWSER_SCENARIO_CATALOG.filter(({ runtimes, shared }) => shared && runtimes.includes(runtime)).map(
({ id }) => `artifact:${id}`,
),
];
}
function assertIdenticalSharedCoreCatalog(catalogByRuntime) {
for (const runtime of SHARED_BROWSER_RUNTIMES) {
const scenarioIds = catalogByRuntime[runtime];
assert.ok(Array.isArray(scenarioIds), `Missing shared browser scenario catalog for ${runtime}.`);
assert.equal(
new Set(scenarioIds).size,
scenarioIds.length,
`${runtime} shared browser scenario catalog contains duplicate IDs.`,
);
}
assert.deepEqual(
catalogByRuntime.extension,
catalogByRuntime.userscript,
"Userscript and extension must register the identical shared browser scenario catalog.",
);
return catalogByRuntime;
}
function assertWrapperDiscoveredByPlaywright(runtime, wrapperPath, configuration = PLAYWRIGHT_CONFIGS[runtime]) {
assert.ok(configuration, `Missing Playwright configuration for ${runtime}.`);
const testDirectory = path.resolve(REPOSITORY_ROOT, configuration.testDir);
const absoluteWrapperPath = path.resolve(wrapperPath);
const relativePath = path.relative(testDirectory, absoluteWrapperPath);
const normalizedRelativePath = relativePath.split(path.sep).join("/");
assert.ok(
relativePath &&
relativePath !== ".." &&
!relativePath.startsWith(`..${path.sep}`) &&
!path.isAbsolute(relativePath),
`${runtime} shared browser wrapper is outside its configured Playwright test directory: ${absoluteWrapperPath}`,
);
assert.equal(
configuration.testMatch,
"**/*.e2e.js",
`${runtime} Playwright testMatch no longer selects shared wrappers.`,
);
assert.match(
normalizedRelativePath,
/(?:^|\/)\w[^/]*\.e2e\.js$/,
`${absoluteWrapperPath} is not a Playwright E2E spec.`,
);
for (const ignoredPattern of [configuration.testIgnore].flat().filter(Boolean)) {
if (ignoredPattern === "**/live/**") {
assert.ok(
!normalizedRelativePath.split("/").includes("live"),
`${runtime} shared browser wrapper is excluded by Playwright testIgnore: ${absoluteWrapperPath}`,
);
}
}
assert.ok(fs.statSync(absoluteWrapperPath).isFile(), `${runtime} shared browser wrapper does not exist.`);
return normalizedRelativePath;
}
describe("shared browser-contract parity", () => {
test("userscript and extension expose one identical 50-scenario core browser catalog", () => {
const catalogByRuntime = Object.fromEntries(
SHARED_BROWSER_RUNTIMES.map((runtime) => [runtime, sharedCoreScenarioIds(runtime)]),
);
expect(assertIdenticalSharedCoreCatalog(catalogByRuntime)).toBe(catalogByRuntime);
expect(catalogByRuntime.userscript).toHaveLength(50);
expect(catalogByRuntime.userscript.filter((id) => id.startsWith("navigation:"))).toHaveLength(
NAVIGATION_MATRIX.length,
);
expect(catalogByRuntime.userscript.filter((id) => id.startsWith("watch-visual:"))).toHaveLength(18);
expect(catalogByRuntime.userscript.filter((id) => id.startsWith("resilience:"))).toHaveLength(4);
expect(catalogByRuntime.userscript.filter((id) => id.startsWith("artifact:"))).toEqual(
SHARED_ARTIFACT_SCENARIO_IDS.map((id) => `artifact:${id}`),
);
});
test("the parity gate fails when either artifact loses one shared core scenario", () => {
const catalogByRuntime = Object.fromEntries(
SHARED_BROWSER_RUNTIMES.map((runtime) => [runtime, sharedCoreScenarioIds(runtime)]),
);
catalogByRuntime.extension = catalogByRuntime.extension.filter(
(scenarioId) => scenarioId !== `artifact:${SHARED_ARTIFACT_SCENARIO_IDS[0]}`,
);
expect(() => assertIdenticalSharedCoreCatalog(catalogByRuntime)).toThrow(
"Userscript and extension must register the identical shared browser scenario catalog.",
);
});
test.each(SHARED_BROWSER_RUNTIMES)("%s Playwright config discovers every shared contract wrapper", (runtime) => {
const uniqueWrappers = [...new Set(Object.values(WRAPPERS[runtime]))];
expect(uniqueWrappers.map((wrapperPath) => assertWrapperDiscoveredByPlaywright(runtime, wrapperPath))).toHaveLength(
uniqueWrappers.length,
);
});
test("the wrapper-discovery gate rejects a shared wrapper from another runtime's test directory", () => {
expect(() => assertWrapperDiscoveredByPlaywright("extension", WRAPPERS.userscript.watch)).toThrow(
/outside its configured Playwright test directory/,
);
});
test.each(SHARED_BROWSER_RUNTIMES)("%s has a discovered no-op-artifact render oracle", (runtime) => {
const oraclePath = RENDER_ORACLES[runtime];
expect(assertWrapperDiscoveredByPlaywright(runtime, oraclePath)).toBe(
path
.relative(path.resolve(REPOSITORY_ROOT, PLAYWRIGHT_CONFIGS[runtime].testDir), oraclePath)
.split(path.sep)
.join("/"),
);
expect(registeredTestTitles(oraclePath)).toEqual([
`the render oracle rejects a generated ${runtime} whose ${
runtime === "extension" ? "content script" : "runtime body"
} does nothing`,
]);
});
test("the systematic command executes the catalogued artifact runner and both Playwright runtimes", () => {
const { scripts } = require(path.join(REPOSITORY_ROOT, "package.json"));
expect(scripts["test:e2e:artifacts"]).toBe(
"npm run check:extension-artifact && npm run check:userscript-artifact && node Extensions/e2e/hermetic-artifact-smoke.js",
);
expect(scripts["test:e2e:systematic"]).toContain("npm run test:e2e:artifacts");
expect(scripts["test:e2e:systematic"]).toContain("npm run test:e2e:extension:run");
expect(scripts["test:e2e:systematic"]).toContain("npm run test:e2e:userscript:run");
expect(scripts["test:all"]).toContain("npm run test:e2e:systematic");
expect(
createArtifactBrowserScenarioPlan().filter(({ scenarioId }) => SHARED_ARTIFACT_SCENARIO_IDS.includes(scenarioId)),
).toHaveLength(SHARED_ARTIFACT_SCENARIO_IDS.length * SHARED_BROWSER_RUNTIMES.length);
});
test.each(["userscript", "extension"])("%s registers the complete shared navigation matrix", (runtime) => {
expect(NAVIGATION_MATRIX.length).toBeGreaterThan(0);
expectOneSharedCall(
wrapperSource(runtime, "navigation"),
"navigation-runtime-contract",
"registerNavigationRuntimeContractScenarios",
);
expect(
registeredTestTitles(WRAPPERS[runtime].navigation).filter((title) =>
title.startsWith(`${runtime} navigation matrix:`),
),
).toEqual(NAVIGATION_MATRIX.map(({ id }) => `${runtime} navigation matrix: ${id}`));
});
test.each(["userscript", "extension"])("%s registers the complete shared Watch visual matrix", (runtime) => {
expect(WATCH_VISUAL_SCENARIOS).toHaveLength(18);
expectOneSharedCall(wrapperSource(runtime, "watch"), "watch-visual-scenarios", "registerWatchVisualContract");
expect(registeredTestTitles(WRAPPERS[runtime].watch)).toEqual(WATCH_VISUAL_SCENARIOS.map(({ id }) => id));
});
test.each(["userscript", "extension"])("%s gates successful Watch screenshots as visual evidence", (runtime) => {
const source = wrapperSource(runtime, "watch");
expectOneSharedCall(source, "visual-evidence", "captureOptionalVisualEvidence");
expect(source).toMatch(/\bannotateVisualEvidence\s*\(/);
expect(source).toContain("scenario.id");
if (runtime === "userscript") {
expect(source).toMatch(/["']visual-review["']\s*,\s*["']userscript["']/);
expect(source).toContain("getWatchNeutralBaselineId");
}
});
test.each(["userscript", "extension"])("%s registers the complete shared resilience matrix", (runtime) => {
expect(RUNTIME_RESILIENCE_SCENARIOS).toHaveLength(4);
expectOneSharedCall(
wrapperSource(runtime, "resilience"),
"runtime-resilience-contract",
"registerRuntimeResilienceContractScenarios",
);
expect(registeredTestTitles(WRAPPERS[runtime].resilience)).toEqual(
RUNTIME_RESILIENCE_SCENARIOS.map(({ id }) => `${runtime} resilience contract: ${id}`),
);
});
test.each(["userscript", "extension"])(
"%s invokes the shared ten-hop Shorts placeholder-pool contract",
(runtime) => {
expect(SHORTS_PLACEHOLDER_POOL_HOPS).toBeGreaterThanOrEqual(10);
expectOneSharedCall(
wrapperSource(runtime, "shorts"),
"shorts-placeholder-pool-contract",
"runShortsPlaceholderPoolContract",
);
expect(
registeredTestTitles(WRAPPERS[runtime].shorts).filter((title) =>
title.includes("ten pre-rendered and recycled Next transitions"),
),
).toHaveLength(1);
},
);
});
+69 -5
View File
@@ -10,16 +10,22 @@ const SHARED_LIVE_SCENARIOS = Object.freeze([
"navigateFromColdChannelToShort",
"navigateToNextShort",
"pausePlayback",
"soakCurrentShortsControl",
"withExactVotesRequest",
"withNoProductionInteractions",
],
driverMethodsByCapability: {
"native-pair": ["captureNativeShortsVisual"],
"strict-synthetic": ["captureSyntheticShortsVisual"],
},
id: "channel-shorts-navigation",
implementation: "runChannelShortsNavigationScenario",
},
{
driverMethods: [
...COMMON_PRECONDITION_METHODS,
"assertCurrentWatchResult",
"navigateFromColdChannelToWatch",
"waitForDislikeText",
"withNoProductionInteractions",
],
id: "channel-watch-navigation",
@@ -28,8 +34,8 @@ const SHARED_LIVE_SCENARIOS = Object.freeze([
{
driverMethods: [
...COMMON_PRECONDITION_METHODS,
"assertCurrentWatchResult",
"openPlaylist",
"waitForDislikeText",
"withNoProductionInteractions",
],
id: "watch-render",
@@ -38,9 +44,9 @@ const SHARED_LIVE_SCENARIOS = Object.freeze([
{
driverMethods: [
...COMMON_PRECONDITION_METHODS,
"assertCurrentWatchResult",
"openPlaylist",
"reload",
"waitForDislikeText",
"withNoProductionInteractions",
],
id: "reload",
@@ -49,18 +55,34 @@ const SHARED_LIVE_SCENARIOS = Object.freeze([
{
driverMethods: [
...COMMON_PRECONDITION_METHODS,
"assertCurrentWatchResult",
"navigateWithinPlaylist",
"openPlaylist",
"waitForDislikeText",
"withNoProductionInteractions",
],
id: "spa-navigation",
implementation: "runSpaNavigationScenario",
},
{
driverMethods: [
...COMMON_PRECONDITION_METHODS,
"assertRenderedDislikeCount",
"captureWatchActionTopologyVisual",
"navigateToRelatedWatch",
"openWatch",
"readViewportSize",
"setViewportSize",
"waitForDislikeText",
"withNoProductionInteractions",
],
id: "watch-action-topology",
implementation: "runWatchActionTopologyScenario",
},
{
driverMethods: [
...COMMON_PRECONDITION_METHODS,
"assertCurrentVideo",
"assertRenderedDislikeCount",
"captureWatchRatioVisual",
"navigateToRelatedWatch",
"openWatch",
@@ -71,7 +93,18 @@ const SHARED_LIVE_SCENARIOS = Object.freeze([
implementation: "runSidebarStressScenario",
},
{
driverMethods: [...COMMON_PRECONDITION_METHODS, "openShort", "waitForDislikeText", "withNoProductionInteractions"],
driverMethods: [
...COMMON_PRECONDITION_METHODS,
"assertCurrentShortsControl",
"openShort",
"reload",
"soakCurrentShortsControl",
"withNoProductionInteractions",
],
driverMethodsByCapability: {
"native-pair": ["captureNativeShortsVisual"],
"strict-synthetic": ["captureSyntheticShortsVisual"],
},
id: "shorts-render",
implementation: "runShortsRenderScenario",
},
@@ -79,6 +112,7 @@ const SHARED_LIVE_SCENARIOS = Object.freeze([
driverMethods: [
...COMMON_PRECONDITION_METHODS,
"assertCurrentShortsControl",
"assertRenderedDislikeCount",
"captureWatchRatioVisual",
"openWatch",
"readViewportSize",
@@ -97,6 +131,22 @@ const SHARED_LIVE_SCENARIOS = Object.freeze([
driverMethods: [
...COMMON_PRECONDITION_METHODS,
"assertCurrentVideo",
"clickAction",
"navigateWithinPlaylist",
"openPlaylist",
"readReactionState",
"waitForDislikeText",
"waitForReactionState",
],
id: "post-navigation-vote",
implementation: "runPostNavigationVoteScenario",
},
{
driverMethods: [
...COMMON_PRECONDITION_METHODS,
"assertCurrentVideo",
"assertDislikeCountChangesObservable",
"assertRenderedDislikeCount",
"captureReactionStateVisual",
"clickAction",
"openShort",
@@ -156,12 +206,26 @@ function createSharedLiveScenarioRunner({ implementations = defaultImplementatio
const implementation = requireImplementation(implementations, scenario);
const scenarioOptions = adapter.createScenarioOptions(options);
if (scenarioId === "channel-shorts-navigation") {
return implementation(adapter.driver, scenarioOptions, services.shortsNavigationOptions);
}
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 === "watch-action-topology") {
return implementation(adapter.driver, scenarioOptions, services.topologyOptions);
}
if (scenarioId === "post-navigation-vote") {
return implementation(
adapter.driver,
scenarioOptions,
requireService(services, "createRecorder", scenarioId),
requireService(services, "consumeVoteApproval", scenarioId),
);
}
if (scenarioId === "reaction-matrix") {
return implementation(
adapter.driver,
+131 -21
View File
@@ -15,9 +15,11 @@ const EXPECTED_SCENARIO_IDS = [
"watch-render",
"reload",
"spa-navigation",
"watch-action-topology",
"sidebar-navigation-stress",
"shorts-render",
"responsive-visual",
"post-navigation-vote",
"reaction-matrix",
];
const EXPECTED_BUILD_ID = "0123456789abcdef0123456789abcdef";
@@ -25,13 +27,18 @@ const EXPECTED_BUILD_ID = "0123456789abcdef0123456789abcdef";
const ALL_DRIVER_METHODS = [
"assertCurrentShortsControl",
"assertCurrentVideo",
"assertCurrentWatchResult",
"assertDislikeCountChangesObservable",
"assertRenderedDislikeCount",
"assertRuntime",
"assertSignedIn",
"captureReactionStateVisual",
"captureNativeShortsVisual",
"captureSyntheticShortsVisual",
"captureWatchActionTopologyVisual",
"captureWatchRatioVisual",
"clickAction",
"configureRequestAttributionRuntime",
"navigateFromColdChannelToShort",
"navigateFromColdChannelToWatch",
"navigateToNextShort",
@@ -45,9 +52,11 @@ const ALL_DRIVER_METHODS = [
"readViewportSize",
"reload",
"setViewportSize",
"soakCurrentShortsControl",
"soakWatchRatioVisual",
"waitForDislikeText",
"waitForReactionState",
"withExactVotesRequest",
"withNoProductionInteractions",
];
@@ -59,7 +68,7 @@ function createDriver(overrides = {}) {
}
function createAdapter(runtime, driver = createDriver(), expectedBuildId = EXPECTED_BUILD_ID) {
const options = { driver, expectedBuildId, expectedVersion: runtime === "userscript" ? "3.2.0" : "4.0.4" };
const options = { driver, expectedBuildId, expectedVersion: runtime === "userscript" ? "3.2.0" : "4.0.5" };
return runtime === "userscript"
? createUserscriptLiveRuntimeAdapter(options)
: createExtensionLiveRuntimeAdapter(options);
@@ -72,9 +81,11 @@ function createImplementations(events) {
"runWatchRenderScenario",
"runReloadScenario",
"runSpaNavigationScenario",
"runWatchActionTopologyScenario",
"runSidebarStressScenario",
"runShortsRenderScenario",
"runResponsiveVisualScenario",
"runPostNavigationVoteScenario",
"runProductionReactionMatrixScenario",
];
return Object.fromEntries(
@@ -96,6 +107,10 @@ describe("shared live runtime profiles", () => {
credentialStore: "gm-storage",
ownsShortsDislikeControl: true,
shortsControlModel: "synthetic-owned",
shortsControlModelBySurface: {
desktop: "synthetic-owned",
mobile: "native-youtube-required",
},
shortsVisualModel: "strict-synthetic",
},
buildMarkerAttribute: "data-ryd-userscript-build",
@@ -110,16 +125,20 @@ describe("shared live runtime profiles", () => {
capabilities: {
backgroundVoteTransport: true,
credentialStore: "browser.storage",
ownsShortsDislikeControl: false,
shortsControlModel: "native-youtube",
shortsVisualModel: "native-pair",
ownsShortsDislikeControl: true,
shortsControlModel: "synthetic-owned",
shortsControlModelBySurface: {
desktop: "synthetic-owned",
mobile: "native-youtube-required",
},
shortsVisualModel: "strict-synthetic",
},
buildMarkerAttribute: "data-ryd-extension-build",
markerAttribute: "data-ryd-extension-version",
selectors: {
rateBar: "#ryd-bar",
rateBarContainer: "#ryd-bar-container",
shortsDislikeControl: null,
shortsDislikeControl: "[data-ryd-synthetic-shorts-dislike]",
},
});
expect(Object.isFrozen(LIVE_RUNTIME_PROFILES.userscript.capabilities)).toBe(true);
@@ -130,23 +149,41 @@ describe("shared live runtime profiles", () => {
const driver = createDriver();
const adapter = createAdapter(runtime, driver);
expect(driver.configureRequestAttributionRuntime).toHaveBeenCalledWith(runtime);
await adapter.driver.assertRuntime(runtime, adapter.expectedVersion, adapter.expectedBuildId);
await adapter.driver.assertCurrentShortsControl("abcdefghijk", runtime);
const expectedCounts = { dislikes: 123, likes: 456 };
await adapter.driver.assertCurrentWatchResult("abcdefghijk", runtime, expectedCounts);
await adapter.driver.assertDislikeCountChangesObservable([{ after: 124, before: 123 }], runtime);
await adapter.driver.assertRenderedDislikeCount("123", 123, runtime);
await adapter.driver.soakCurrentShortsControl("abcdefghijk", runtime, 123, { durationMs: 10 });
await adapter.driver.captureWatchRatioVisual(runtime, "watch.png");
await adapter.driver.captureReactionStateVisual({
expectedCounts,
expectedState: "neutral",
isShort: false,
runtime,
screenshotPath: "reaction.png",
shortsVisualModel: adapter.capabilities.shortsVisualModel,
videoId: "abcdefghijk",
});
expect(driver.assertRuntime).toHaveBeenCalledWith(runtime, adapter.expectedVersion, adapter.expectedBuildId);
expect(driver.assertCurrentShortsControl).toHaveBeenCalledWith("abcdefghijk", runtime);
expect(driver.assertCurrentWatchResult).toHaveBeenCalledWith("abcdefghijk", runtime, expectedCounts);
expect(driver.assertDislikeCountChangesObservable).toHaveBeenCalledWith([{ after: 124, before: 123 }], runtime);
expect(driver.assertRenderedDislikeCount).toHaveBeenCalledWith("123", 123, runtime);
expect(driver.soakCurrentShortsControl).toHaveBeenCalledWith("abcdefghijk", runtime, 123, { durationMs: 10 });
expect(driver.captureWatchRatioVisual).toHaveBeenCalledWith(runtime, "watch.png");
expect(driver.captureReactionStateVisual).toHaveBeenCalledWith(
expect.objectContaining({ runtime, videoId: "abcdefghijk" }),
expect.objectContaining({
runtime,
shortsVisualModel: adapter.capabilities.shortsVisualModel,
videoId: "abcdefghijk",
}),
);
expect(adapter.createScenarioOptions()).toMatchObject({ capabilities: adapter.capabilities });
});
test("rejects scenario options and calls for another runtime", async () => {
@@ -158,6 +195,18 @@ describe("shared live runtime profiles", () => {
expect(() => adapter.driver.assertRuntime("extension", adapter.expectedVersion)).toThrow(
"The asserted runtime does not match",
);
expect(() => adapter.driver.soakCurrentShortsControl("abcdefghijk", "extension", 123)).toThrow(
"The Shorts-control soak runtime does not match",
);
expect(() =>
adapter.driver.captureReactionStateVisual({
expectedState: "neutral",
isShort: true,
runtime: "userscript",
shortsVisualModel: "native-pair",
videoId: "abcdefghijk",
}),
).toThrow("The reaction-visual Shorts model does not match");
});
test.each([undefined, "", "stale", "A".repeat(32)])(
@@ -199,23 +248,26 @@ describe("shared live scenario contract", () => {
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;
test.each(["channel-shorts-navigation", "responsive-visual"])(
"requires each runtime's Shorts visual model from shared scenario %s",
(scenarioId) => {
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",
]);
expect(() => assertSharedLiveScenarioAdapter(createAdapter("userscript", driver), [scenarioId])).toThrow(
"must implement captureSyntheticShortsVisual()",
);
expect(() => assertSharedLiveScenarioAdapter(createAdapter("extension", driver), [scenarioId])).toThrow(
"must implement captureSyntheticShortsVisual()",
);
const extensionDriver = createDriver();
delete extensionDriver.captureNativeShortsVisual;
expect(() =>
assertSharedLiveScenarioAdapter(createAdapter("extension", extensionDriver), ["responsive-visual"]),
).toThrow("must implement captureNativeShortsVisual()");
});
const driverWithoutNativeCapture = createDriver();
delete driverWithoutNativeCapture.captureNativeShortsVisual;
expect(
assertSharedLiveScenarioAdapter(createAdapter("extension", driverWithoutNativeCapture), [scenarioId]),
).toEqual([scenarioId]);
},
);
test("executes the same scenario IDs through both runtime adapters", async () => {
const events = [];
@@ -224,8 +276,10 @@ describe("shared live scenario contract", () => {
const services = {
consumeVoteApproval: jest.fn(),
createRecorder: jest.fn(),
shortsNavigationOptions: { outputDirectory: "shorts-evidence" },
visualOptions: { outputDirectory: "evidence" },
sidebarOptions: { outputDirectory: "sidebar-evidence" },
topologyOptions: { outputDirectory: "topology-evidence" },
};
const userscriptResults = await runner.runAll(createAdapter("userscript"), {}, services);
@@ -240,6 +294,62 @@ describe("shared live scenario contract", () => {
expect(Object.values(implementations).every((implementation) => implementation.mock.calls.length === 2)).toBe(true);
});
test.each(["userscript", "extension"])(
"routes the shared Shorts navigation evidence options through %s",
async (runtime) => {
const implementation = jest.fn(async () => "verified");
const runner = createSharedLiveScenarioRunner({
implementations: { runChannelShortsNavigationScenario: implementation },
});
const adapter = createAdapter(runtime);
const shortsNavigationOptions = { outputDirectory: "shorts-evidence" };
await expect(runner.run(adapter, "channel-shorts-navigation", {}, { shortsNavigationOptions })).resolves.toBe(
"verified",
);
expect(implementation).toHaveBeenCalledWith(
adapter.driver,
expect.objectContaining({ runtime }),
shortsNavigationOptions,
);
},
);
test.each(["userscript", "extension"])(
"routes the shared post-navigation vote services through %s",
async (runtime) => {
const implementation = jest.fn(async () => "verified");
const runner = createSharedLiveScenarioRunner({
implementations: { runPostNavigationVoteScenario: implementation },
});
const adapter = createAdapter(runtime);
const createRecorder = jest.fn();
const consumeVoteApproval = jest.fn();
await expect(
runner.run(adapter, "post-navigation-vote", {}, { createRecorder, consumeVoteApproval }),
).resolves.toBe("verified");
expect(implementation).toHaveBeenCalledWith(
adapter.driver,
expect.objectContaining({ runtime }),
createRecorder,
consumeVoteApproval,
);
},
);
test("requires both protected services before running the post-navigation vote", async () => {
const implementation = jest.fn();
const runner = createSharedLiveScenarioRunner({
implementations: { runPostNavigationVoteScenario: implementation },
});
await expect(
runner.run(createAdapter("extension"), "post-navigation-vote", {}, { createRecorder: jest.fn() }),
).rejects.toThrow("requires services.consumeVoteApproval()");
expect(implementation).not.toHaveBeenCalled();
});
test("rejects unknown IDs before invoking a scenario implementation", async () => {
const implementations = createImplementations([]);
const runner = createSharedLiveScenarioRunner({ implementations });
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,340 @@
const {
SHORTS_PLACEHOLDER_POOL_ACTION_ORDER,
SHORTS_PLACEHOLDER_POOL_COUNTS,
SHORTS_PLACEHOLDER_POOL_HOPS,
SHORTS_NATIVE_LIKE_PAINT_HOP,
SHORTS_PLACEHOLDER_POOL_SIZE,
SHORTS_PLACEHOLDER_POOL_VIDEO_IDS,
assertDuplicateSyntheticNormalization,
assertEventlessSameVideoReturnSafety,
assertNativeLikePaintHydrationSafety,
assertNativeDislikeCleanupSurface,
assertShortsPlaceholderPoolSurface,
createShortsPlaceholderPoolFixture,
} = require("./shorts-placeholder-pool-contract");
function validSurface(logicalIndex = 2) {
const videoId = SHORTS_PLACEHOLDER_POOL_VIDEO_IDS[logicalIndex];
const previousVideoId = SHORTS_PLACEHOLDER_POOL_VIDEO_IDS[logicalIndex - 1];
const hostBoxes = SHORTS_PLACEHOLDER_POOL_ACTION_ORDER.map((_, index) => ({
bottom: 150 + index * 70,
height: 70,
left: 400,
right: 448,
top: 80 + index * 70,
width: 48,
}));
const buttonBoxes = hostBoxes.map((host) => ({ ...host, bottom: host.top + 48, height: 48 }));
return {
actionBarBox: { bottom: 500, height: 420, left: 400, right: 448, top: 80, width: 48 },
actionBarDataReady: true,
actionBarPainted: "true",
actionBarVisible: true,
actions: [...SHORTS_PLACEHOLDER_POOL_ACTION_ORDER],
activeRenderers: 1,
buttonBoxes,
buttonEnabled: SHORTS_PLACEHOLDER_POOL_ACTION_ORDER.map(() => true),
buttonHitTested: SHORTS_PLACEHOLDER_POOL_ACTION_ORDER.map(() => true),
buttonTopHits: SHORTS_PLACEHOLDER_POOL_ACTION_ORDER.map(() => "button"),
buttonVisible: SHORTS_PLACEHOLDER_POOL_ACTION_ORDER.map(() => true),
dislikeCount: String(SHORTS_PLACEHOLDER_POOL_COUNTS[videoId].dislikes),
dislikeKind: "synthetic",
dislikePressed: "false",
fixture: {
activeVideoIds: [videoId],
corruptedVideoIds: [],
currentIndex: logicalIndex,
currentVideoId: videoId,
freshEpochViolations: [],
phaseObservations: [
{
actionBarDataReady: false,
candidateVideoIds: [previousVideoId, videoId].sort(),
hydrated: false,
inViewport: false,
meaningfulViewport: false,
phase: "route-current-active-offscreen",
syntheticCount: 0,
videoId,
viewportRatio: 0,
},
{
actionBarDataReady: false,
candidateVideoIds: [previousVideoId, videoId].sort(),
hydrated: false,
inViewport: true,
meaningfulViewport: false,
phase: "partial-active-ambiguous",
syntheticCount: 0,
videoId,
viewportRatio: 0.1,
},
{
actionBarDataReady: false,
candidateVideoIds: [videoId],
hydrated: false,
inViewport: true,
meaningfulViewport: true,
phase: "visible-active-data-null-after-timeout",
syntheticCount: 0,
videoId,
viewportRatio: 1,
},
],
prematureSyntheticInsertions: [],
seededNormalizationStates: [],
slotCount: SHORTS_PLACEHOLDER_POOL_SIZE,
transitioning: false,
},
hostBoxes,
hostVisible: SHORTS_PLACEHOLDER_POOL_ACTION_ORDER.map(() => true),
pathname: `/shorts/${videoId}`,
rendererBox: { bottom: 620, height: 620, left: 0, right: 460, top: 0, width: 460 },
rendererHydrated: "true",
rendererVideoId: videoId,
rendererVisible: true,
staleSyntheticOwners: [],
nativeDislikes: 0,
syntheticCount: String(SHORTS_PLACEHOLDER_POOL_COUNTS[videoId].dislikes),
syntheticElements: 1,
syntheticOwner: videoId,
syntheticPressed: "false",
visibleDocumentActionButtons: SHORTS_PLACEHOLDER_POOL_ACTION_ORDER.length,
visibleDocumentRenderers: 1,
visibleDocumentSynthetic: 1,
};
}
function validate(snapshot, logicalIndex = 2) {
const videoId = SHORTS_PLACEHOLDER_POOL_VIDEO_IDS[logicalIndex];
assertShortsPlaceholderPoolSurface(snapshot, {
counts: SHORTS_PLACEHOLDER_POOL_COUNTS[videoId],
logicalIndex,
videoId,
});
}
function validNativeCleanupSurface() {
const logicalIndex = 5;
const videoId = SHORTS_PLACEHOLDER_POOL_VIDEO_IDS[logicalIndex];
const snapshot = validSurface(logicalIndex);
snapshot.dislikeKind = "native";
snapshot.nativeDislikes = 1;
snapshot.syntheticCount = null;
snapshot.syntheticElements = 0;
snapshot.syntheticOwner = null;
snapshot.syntheticPressed = null;
snapshot.visibleDocumentSynthetic = 0;
snapshot.fixture.seededNormalizationStates.push({
nativeDislikes: 1,
phase: "native-and-multiple-synthetics",
syntheticCount: 3,
videoId,
});
return { logicalIndex, snapshot, videoId };
}
function validDuplicateNormalizationSurface() {
const logicalIndex = 3;
const videoId = SHORTS_PLACEHOLDER_POOL_VIDEO_IDS[logicalIndex];
const snapshot = validSurface(logicalIndex);
snapshot.fixture.seededNormalizationStates.push({
nativeDislikes: 0,
phase: "duplicate-synthetics",
syntheticCount: 2,
videoId,
});
return { logicalIndex, snapshot, videoId };
}
function validEventlessFixture() {
const logicalIndex = 7;
const videoId = SHORTS_PLACEHOLDER_POOL_VIDEO_IDS[logicalIndex];
const fixture = validSurface(logicalIndex).fixture;
for (const phase of ["eventless-pending-before-route-away", "eventless-same-video-return-fresh-epoch"]) {
fixture.phaseObservations.push({
actionBarDataReady: true,
candidateVideoIds: [videoId],
hydrated: true,
inViewport: true,
meaningfulViewport: true,
phase,
syntheticCount: 0,
videoId,
viewportRatio: 1,
});
}
return { fixture, logicalIndex, videoId };
}
function validNativeLikePaintObservations() {
const logicalIndex = SHORTS_NATIVE_LIKE_PAINT_HOP;
const videoId = SHORTS_PLACEHOLDER_POOL_VIDEO_IDS[logicalIndex];
return {
logicalIndex,
observations: [
{
actionBarDataReady: true,
nativeLikePaintedGraphicCount: 0,
nativeLikeSvgPresent: false,
phase: "native-like-button-shell-only",
syntheticCount: 0,
videoId,
},
{
actionBarDataReady: true,
nativeLikePaintedGraphicCount: 0,
nativeLikeSvgPresent: true,
phase: "native-like-empty-svg",
syntheticCount: 0,
videoId,
},
{
actionBarDataReady: true,
nativeLikePaintedGraphicCount: 1,
nativeLikeSvgPresent: true,
phase: "native-like-painted-svg",
syntheticCount: 0,
videoId,
},
],
videoId,
};
}
describe("shared Shorts placeholder-pool regression contract", () => {
test("crosses a ten-slot pre-render pool with at least ten Next transitions", () => {
expect(SHORTS_PLACEHOLDER_POOL_SIZE).toBe(10);
expect(SHORTS_PLACEHOLDER_POOL_HOPS).toBeGreaterThanOrEqual(10);
expect(SHORTS_PLACEHOLDER_POOL_VIDEO_IDS).toHaveLength(SHORTS_PLACEHOLDER_POOL_HOPS + 1);
expect(new Set(SHORTS_PLACEHOLDER_POOL_VIDEO_IDS).size).toBe(SHORTS_PLACEHOLDER_POOL_VIDEO_IDS.length);
expect(SHORTS_PLACEHOLDER_POOL_VIDEO_IDS.every((videoId) => /^[A-Za-z0-9_-]{11}$/.test(videoId))).toBe(true);
});
test("fixture models route-first activation, premature mutation, and physical-slot recycling", () => {
const fixture = createShortsPlaceholderPoolFixture();
expect(fixture).toContain('timeline.push({ phase: "navigate-finish-before-activation"');
expect(fixture).toContain('observePhase("partial-active-ambiguous"');
expect(fixture).toContain('observePhase("visible-active-data-null-after-timeout"');
expect(fixture).toContain("actionBar.data = null");
expect(fixture).toContain("setTimeout(resolve, 520)");
expect(fixture).toContain("actionBar.innerHTML = nativeActionsMarkup(nextVideoId)");
expect(fixture).toContain('phase: "native-like-button-shell-only"');
expect(fixture).toContain('phase: "native-like-empty-svg"');
expect(fixture).toContain('phase: "native-like-painted-svg"');
expect(fixture).toContain("seedNativeDislikeAndSyntheticDuplicates");
expect(fixture).toContain("seedSyntheticDuplicates");
expect(fixture).toContain("eventlessSameVideoReturn");
expect(fixture).toContain("futureIndex = nextIndex + config.poolSize - 1");
expect(fixture).toContain('actionBar.style.opacity = "0"');
});
test("holds synthetic insertion through native Like shell-only and empty-SVG hydration", () => {
const { logicalIndex, observations, videoId } = validNativeLikePaintObservations();
const snapshot = validSurface(logicalIndex);
snapshot.fixture.nativeLikePaintObservations = observations;
expect(() => assertNativeLikePaintHydrationSafety(snapshot.fixture, { logicalIndex, videoId })).not.toThrow();
expect(() => validate(snapshot, logicalIndex)).not.toThrow();
observations[1].syntheticCount = 1;
expect(() => assertNativeLikePaintHydrationSafety(snapshot.fixture, { logicalIndex, videoId })).toThrow(
/before the exact native Like icon painted/,
);
});
test("fixture inline lifecycle script is syntactically executable", () => {
const fixture = createShortsPlaceholderPoolFixture();
const inlineScript = fixture.match(/<script>([\s\S]+)<\/script>/)?.[1];
expect(inlineScript).toBeTruthy();
expect(() => new Function(inlineScript)).not.toThrow();
});
test("accepts a complete painted and current action stack", () => {
expect(() => validate(validSurface())).not.toThrow();
});
test("accepts cleanup from one native and three synthetic dislikes to one native dislike", () => {
const { logicalIndex, snapshot, videoId } = validNativeCleanupSurface();
expect(() => assertNativeDislikeCleanupSurface(snapshot, { logicalIndex, videoId })).not.toThrow();
});
test("accepts duplicate synthetic normalization back to one current control", () => {
const { logicalIndex, snapshot, videoId } = validDuplicateNormalizationSurface();
expect(() => assertDuplicateSyntheticNormalization(snapshot, { logicalIndex, videoId })).not.toThrow();
});
test("accepts an eventless same-video return only after a fresh stability epoch", () => {
const { fixture, logicalIndex, videoId } = validEventlessFixture();
expect(() => assertEventlessSameVideoReturnSafety(fixture, { logicalIndex, videoId })).not.toThrow();
fixture.freshEpochViolations.push({ videoId });
expect(() => assertEventlessSameVideoReturnSafety(fixture, { logicalIndex, videoId })).toThrow(
/reused stale pre-route stability evidence/,
);
});
test.each([
[
"missing actionBar.data hydration",
(snapshot) => {
snapshot.actionBarDataReady = false;
},
/actionBar.data is not hydrated/,
],
[
"missing native action",
(snapshot) => {
snapshot.actions.pop();
snapshot.hostBoxes.pop();
snapshot.buttonBoxes.pop();
},
/retain every native action/,
],
[
"duplicate synthetic controls after normalization",
(snapshot) => {
snapshot.syntheticElements = 2;
},
/did not normalize duplicate synthetic controls/,
],
[
"unpainted action bar despite non-zero descendants",
(snapshot) => {
snapshot.actionBarPainted = "false";
},
/painted state/,
],
[
"rectangular but non-hit-testable controls",
(snapshot) => {
snapshot.buttonHitTested[3] = false;
},
/not topmost\/hit-testable/,
],
[
"premature placeholder mutation",
(snapshot) => {
snapshot.fixture.prematureSyntheticInsertions.push({ videoId: snapshot.rendererVideoId });
},
/before the managed action bar reached hydration/,
],
[
"synthetic control during visible but unstable hydration",
(snapshot) => {
snapshot.fixture.phaseObservations[1].syntheticCount = 1;
},
/premature control mutation/,
],
[
"stale synthetic ownership",
(snapshot) => {
snapshot.syntheticOwner = SHORTS_PLACEHOLDER_POOL_VIDEO_IDS[0];
},
/targets a stale video/,
],
])("fails closed for %s", (_label, corrupt, expectedMessage) => {
const snapshot = validSurface();
corrupt(snapshot);
expect(() => validate(snapshot)).toThrow(expectedMessage);
});
});
+444
View File
@@ -0,0 +1,444 @@
const { expect } = require("@playwright/test");
const SHORTS_ACTION_ORDER = Object.freeze(["like", "dislike", "comments", "share", "remix", "sound"]);
const OWNED_DISLIKE_SELECTOR = "[data-ryd-synthetic-shorts-dislike]";
function expectClose(actual, expected, tolerance = 0.25) {
expect(Math.abs(actual - expected)).toBeLessThanOrEqual(tolerance);
}
function expectBox(box, width, height) {
expectClose(box.width, width);
expectClose(box.height, height);
}
function expectVisible(visibility) {
expect(visibility).toMatchObject({
intersectsViewport: true,
opacity: 1,
rendered: true,
visibility: "visible",
});
expect(visibility.display).not.toBe("none");
}
function expectZeroBox(box) {
expect(box).toEqual({
margin: ["0px", "0px", "0px", "0px"],
padding: ["0px", "0px", "0px", "0px"],
});
}
async function readExtensionShortsVisualContract(page, videoId) {
return page.evaluate(
({ expectedVideoId, ownedDislikeSelector }) => {
const required = (root, selector) => {
const element = root.querySelector(selector);
if (!element) throw new Error(`Missing Shorts visual-contract element: ${selector}`);
return element;
};
const rect = (element) => {
const bounds = element.getBoundingClientRect();
return {
bottom: bounds.bottom,
height: bounds.height,
left: bounds.left,
right: bounds.right,
top: bounds.top,
width: bounds.width,
};
};
const box = (element) => {
const style = getComputedStyle(element);
return {
margin: [style.marginTop, style.marginRight, style.marginBottom, style.marginLeft],
padding: [style.paddingTop, style.paddingRight, style.paddingBottom, style.paddingLeft],
};
};
const visibility = (element) => {
const bounds = element.getBoundingClientRect();
const style = getComputedStyle(element);
return {
display: style.display,
intersectsViewport:
bounds.width > 0 &&
bounds.height > 0 &&
bounds.bottom > 0 &&
bounds.right > 0 &&
bounds.top < innerHeight &&
bounds.left < innerWidth,
opacity: Number(style.opacity),
rendered: bounds.width > 0 && bounds.height > 0,
visibility: style.visibility,
};
};
const actionName = (host) => {
if (host.matches('[data-fixture-role="like"]')) return "like";
if (host.matches(ownedDislikeSelector)) return "dislike";
return host.getAttribute("data-fixture-control");
};
const readReaction = (actionBar, role) => {
const hostSelector =
role === "dislike" ? `:scope > ${ownedDislikeSelector}` : ':scope > [data-fixture-role="like"]';
const host = required(actionBar, hostSelector);
const slot = required(host, ":scope > label");
const button = required(slot, ":scope > button");
const icon = required(button, ".ytSpecButtonShapeNextIcon");
const svg = required(icon, "svg");
const label = required(slot, ".ytSpecButtonShapeWithLabelLabel");
const text = required(label, "#text");
const hostStyle = getComputedStyle(host);
const slotStyle = getComputedStyle(slot);
const labelStyle = getComputedStyle(label);
const buttonBounds = button.getBoundingClientRect();
const hitTarget = document.elementFromPoint(
buttonBounds.left + buttonBounds.width / 2,
buttonBounds.top + buttonBounds.height / 2,
);
return {
button: rect(button),
buttonBox: box(button),
buttonVisibility: visibility(button),
host: rect(host),
hostBox: box(host),
hostContentSize: { height: hostStyle.height, width: hostStyle.width },
hostVisibility: visibility(host),
hitTargetOwnedByButton: hitTarget === button || button.contains(hitTarget),
icon: rect(icon),
iconBox: box(icon),
iconVisibility: visibility(icon),
label: rect(label),
labelBox: box(label),
labelStyle: {
alignItems: labelStyle.alignItems,
fontSize: labelStyle.fontSize,
justifyContent: labelStyle.justifyContent,
lineHeight: labelStyle.lineHeight,
},
labelVisibility: visibility(label),
slot: rect(slot),
slotBox: box(slot),
slotStyle: {
alignItems: slotStyle.alignItems,
display: slotStyle.display,
flexDirection: slotStyle.flexDirection,
},
slotVisibility: visibility(slot),
svg: rect(svg),
svgBox: box(svg),
svgVisibility: visibility(svg),
text: rect(text),
textContent: text.textContent.replace(/\s+/g, " ").trim(),
textOwnedByLabel: label.contains(text),
textVisibility: visibility(text),
};
};
const renderer = document.querySelector(
`ytd-reel-video-renderer[video-id="${CSS.escape(expectedVideoId)}"][is-active]`,
);
if (!renderer) throw new Error(`Missing active Shorts renderer for ${expectedVideoId}.`);
const actionBar = required(renderer, "reel-action-bar-view-model");
const actionHosts = [...actionBar.children];
const rendererLink = required(renderer, ":scope > a[href*='/shorts/']");
const sequence = renderer.closest(".reel-video-in-sequence-new");
const allRenderers = [...document.querySelectorAll("ytd-reel-video-renderer")];
return {
actionBar: rect(actionBar),
actionBarBox: box(actionBar),
actionBarVisibility: visibility(actionBar),
actions: actionHosts.map((host) => {
const slot = required(host, ":scope > label");
const button = required(slot, ":scope > button");
const icon = required(button, ".ytSpecButtonShapeNextIcon");
const svg = required(icon, "svg");
const graphic = required(svg, "path");
const label = required(slot, ".ytSpecButtonShapeWithLabelLabel");
const text = required(label, "[role='text']");
const hostStyle = getComputedStyle(host);
const slotStyle = getComputedStyle(slot);
const labelStyle = getComputedStyle(label);
return {
button: rect(button),
buttonBox: box(button),
buttonVisibility: visibility(button),
host: rect(host),
hostBox: box(host),
hostContentSize: { height: hostStyle.height, width: hostStyle.width },
hostVisibility: visibility(host),
hitTargetOwnedByButton: (() => {
const bounds = button.getBoundingClientRect();
const hitTarget = document.elementFromPoint(
bounds.left + bounds.width / 2,
bounds.top + bounds.height / 2,
);
return hitTarget === button || button.contains(hitTarget);
})(),
graphic: {
bounds: { height: graphic.getBBox().height, width: graphic.getBBox().width },
fill: getComputedStyle(graphic).fill,
},
icon: rect(icon),
iconBox: box(icon),
iconVisibility: visibility(icon),
label: rect(label),
labelBox: box(label),
labelStyle: {
alignItems: labelStyle.alignItems,
fontSize: labelStyle.fontSize,
justifyContent: labelStyle.justifyContent,
lineHeight: labelStyle.lineHeight,
},
labelVisibility: visibility(label),
name: actionName(host),
slot: rect(slot),
slotBox: box(slot),
slotStyle: {
alignItems: slotStyle.alignItems,
display: slotStyle.display,
flexDirection: slotStyle.flexDirection,
},
slotVisibility: visibility(slot),
svg: rect(svg),
svgBox: box(svg),
svgVisibility: visibility(svg),
text: rect(text),
textContent: text.textContent.replace(/\s+/g, " ").trim(),
textOwnedByLabel: label.contains(text),
textVisibility: visibility(text),
};
}),
dislike: readReaction(actionBar, "dislike"),
documentScrollWidth: document.documentElement.scrollWidth,
fixtureBaseline: {
renderedDesktopShortsNativeDislikes:
globalThis.__navigationFixtureBaseline?.renderedDesktopShortsNativeDislikes ?? null,
},
identity: {
actionBarOwnedByRenderer: actionBar.parentElement === renderer,
currentPathname: location.pathname,
expectedVideoId,
rendererLinkPathname: new URL(rendererLink.href, location.href).pathname,
rendererVideoId: renderer.getAttribute("video-id"),
sequenceVideoId: sequence?.getAttribute("data-fixture-sequence-video-id") ?? null,
sequenceOwnedByShorts: sequence?.closest("ytd-shorts") !== null,
},
like: readReaction(actionBar, "like"),
renderer: rect(renderer),
renderers: allRenderers.map((candidate) => ({
actionBars: candidate.querySelectorAll("reel-action-bar-view-model").length,
active: candidate.hasAttribute("is-active"),
nativeDislikes: candidate.querySelectorAll(
`reel-action-bar-view-model > dislike-button-view-model:not(${ownedDislikeSelector})`,
).length,
ownedDislikes: candidate.querySelectorAll(`reel-action-bar-view-model > ${ownedDislikeSelector}`).length,
videoId: candidate.getAttribute("video-id"),
visibility: visibility(candidate),
})),
rendererVisibility: visibility(renderer),
unique: {
activeRenderers: document.querySelectorAll("ytd-reel-video-renderer[is-active]").length,
bars: document.querySelectorAll("#ryd-bar").length,
containers: document.querySelectorAll("#ryd-bar-container").length,
currentActionBars: renderer.querySelectorAll("reel-action-bar-view-model").length,
currentNativeDislikes: renderer.querySelectorAll(
`reel-action-bar-view-model > dislike-button-view-model:not(${ownedDislikeSelector})`,
).length,
currentOwnedDislikes: renderer.querySelectorAll(`reel-action-bar-view-model > ${ownedDislikeSelector}`)
.length,
currentLikes: renderer.querySelectorAll('[data-fixture-role="like"]').length,
renderers: allRenderers.length,
tooltips: document.querySelectorAll("#ryd-dislike-tooltip").length,
visibleActionBars: [...document.querySelectorAll("reel-action-bar-view-model")].filter(
(candidate) => visibility(candidate).intersectsViewport && visibility(candidate).display !== "none",
).length,
visibleOwnedDislikes: [...document.querySelectorAll(ownedDislikeSelector)].filter(
(candidate) => visibility(candidate).intersectsViewport && visibility(candidate).display !== "none",
).length,
wrappers: document.querySelectorAll(".ryd-tooltip").length,
},
viewport: { height: innerHeight, width: innerWidth },
};
},
{ expectedVideoId: videoId, ownedDislikeSelector: OWNED_DISLIKE_SELECTOR },
);
}
function expectReactionGeometry(reaction, count) {
expectBox(reaction.host, 48, 78);
expect(reaction.hostContentSize).toEqual({ height: "70px", width: "48px" });
expect(reaction.hostBox).toEqual({
margin: ["0px", "0px", "0px", "0px"],
padding: ["0px", "0px", "8px", "0px"],
});
expectBox(reaction.slot, 48, 70);
expectZeroBox(reaction.slotBox);
expect(reaction.slotStyle).toEqual({ alignItems: "center", display: "flex", flexDirection: "column" });
expectBox(reaction.button, 48, 48);
expect(reaction.buttonBox).toEqual({
margin: ["0px", "0px", "0px", "0px"],
padding: ["12px", "12px", "12px", "12px"],
});
expectBox(reaction.icon, 24, 24);
expectBox(reaction.svg, 24, 24);
expectZeroBox(reaction.iconBox);
expectZeroBox(reaction.svgBox);
expectBox(reaction.label, 48, 22);
expectZeroBox(reaction.labelBox);
expect(reaction.labelStyle).toEqual({
alignItems: "center",
fontSize: "12px",
justifyContent: "center",
lineHeight: "18px",
});
expect(reaction.textContent).toBe(String(count));
expect(reaction.hitTargetOwnedByButton).toBe(true);
expect(reaction.textOwnedByLabel).toBe(true);
for (const item of [
reaction.hostVisibility,
reaction.slotVisibility,
reaction.buttonVisibility,
reaction.iconVisibility,
reaction.svgVisibility,
reaction.labelVisibility,
reaction.textVisibility,
]) {
expectVisible(item);
}
const centerX = reaction.host.left + reaction.host.width / 2;
for (const item of [reaction.slot, reaction.button, reaction.icon, reaction.svg, reaction.label, reaction.text]) {
expectClose(item.left + item.width / 2, centerX);
}
expectClose(reaction.icon.top + reaction.icon.height / 2, reaction.button.top + reaction.button.height / 2);
expectClose(reaction.svg.top + reaction.svg.height / 2, reaction.button.top + reaction.button.height / 2);
expectClose(reaction.label.top, reaction.button.bottom);
}
function expectExtensionShortsVisualContract(snapshot, counts, viewport) {
expect(snapshot.viewport).toEqual({ height: viewport.height, width: viewport.width });
expect(snapshot.documentScrollWidth).toBeLessThanOrEqual(snapshot.viewport.width);
expect(snapshot.fixtureBaseline.renderedDesktopShortsNativeDislikes).toBe(0);
expect(snapshot.identity).toEqual({
actionBarOwnedByRenderer: true,
currentPathname: `/shorts/${snapshot.identity.expectedVideoId}`,
expectedVideoId: snapshot.identity.expectedVideoId,
rendererLinkPathname: `/shorts/${snapshot.identity.expectedVideoId}`,
rendererVideoId: snapshot.identity.expectedVideoId,
sequenceOwnedByShorts: true,
sequenceVideoId: snapshot.identity.expectedVideoId,
});
expect(snapshot.unique).toEqual({
activeRenderers: 1,
bars: 0,
containers: 0,
currentActionBars: 1,
currentNativeDislikes: 0,
currentLikes: 1,
currentOwnedDislikes: 1,
renderers: 2,
tooltips: 0,
visibleActionBars: 1,
visibleOwnedDislikes: 1,
wrappers: 0,
});
expect(snapshot.renderers).toHaveLength(2);
expect(snapshot.renderers.filter(({ active }) => active)).toHaveLength(1);
expect(snapshot.renderers.filter(({ visibility }) => visibility.intersectsViewport)).toHaveLength(1);
expect(snapshot.renderers.every(({ actionBars, nativeDislikes }) => actionBars === 1 && nativeDislikes === 0)).toBe(
true,
);
expect(snapshot.renderers.find(({ active }) => active)).toMatchObject({
ownedDislikes: 1,
videoId: snapshot.identity.expectedVideoId,
});
expectVisible(snapshot.rendererVisibility);
expectVisible(snapshot.actionBarVisibility);
expect(snapshot.renderer.left).toBeGreaterThanOrEqual(0);
expect(snapshot.renderer.right).toBeLessThanOrEqual(snapshot.viewport.width);
expect(snapshot.actionBar.left).toBeGreaterThanOrEqual(snapshot.renderer.left);
expect(snapshot.actionBar.right).toBeLessThanOrEqual(snapshot.renderer.right);
expect(snapshot.actionBarBox).toEqual({
margin: ["0px", "0px", "0px", "0px"],
padding: ["0px", "0px", "0px", "0px"],
});
expect(snapshot.actions.map(({ name }) => name)).toEqual(SHORTS_ACTION_ORDER);
expect(snapshot.actions.map(({ textContent }) => textContent)).toEqual([
String(counts.likes),
String(counts.dislikes),
"12",
"Share",
"Remix",
"Sound",
]);
expect(snapshot.actions).toHaveLength(6);
for (const [index, action] of snapshot.actions.entries()) {
for (const item of [
action.hostVisibility,
action.slotVisibility,
action.buttonVisibility,
action.iconVisibility,
action.svgVisibility,
action.labelVisibility,
action.textVisibility,
]) {
expectVisible(item);
}
expectBox(action.host, 48, 78);
expect(action.hostContentSize).toEqual({ height: "70px", width: "48px" });
expect(action.hostBox).toEqual({
margin: ["0px", "0px", "0px", "0px"],
padding: ["0px", "0px", "8px", "0px"],
});
expectBox(action.slot, 48, 70);
expectZeroBox(action.slotBox);
expect(action.slotStyle).toEqual({ alignItems: "center", display: "flex", flexDirection: "column" });
expectBox(action.button, 48, 48);
expect(action.buttonBox).toEqual({
margin: ["0px", "0px", "0px", "0px"],
padding: ["12px", "12px", "12px", "12px"],
});
expectBox(action.icon, 24, 24);
expectBox(action.svg, 24, 24);
expect(action.graphic.bounds.width).toBeGreaterThan(8);
expect(action.graphic.bounds.height).toBeGreaterThan(8);
expect(action.graphic.fill).not.toBe("none");
expect(action.graphic.fill).not.toBe("rgba(0, 0, 0, 0)");
expect(action.hitTargetOwnedByButton).toBe(true);
expectZeroBox(action.iconBox);
expectZeroBox(action.svgBox);
expectBox(action.label, 48, 22);
expectZeroBox(action.labelBox);
expect(action.labelStyle).toEqual({
alignItems: "center",
fontSize: "12px",
justifyContent: "center",
lineHeight: "18px",
});
expect(action.textOwnedByLabel).toBe(true);
expectClose(action.host.left + action.host.width / 2, snapshot.actionBar.left + snapshot.actionBar.width / 2);
const actionCenterX = action.host.left + action.host.width / 2;
for (const item of [action.slot, action.button, action.icon, action.svg, action.label, action.text]) {
expectClose(item.left + item.width / 2, actionCenterX);
}
expectClose(action.icon.top + action.icon.height / 2, action.button.top + action.button.height / 2);
expectClose(action.svg.top + action.svg.height / 2, action.button.top + action.button.height / 2);
expectClose(action.label.top, action.button.bottom);
expect(action.host.left).toBeGreaterThanOrEqual(0);
expect(action.host.right).toBeLessThanOrEqual(snapshot.viewport.width);
if (index > 0) expectClose(action.host.top, snapshot.actions[index - 1].host.bottom);
}
expectReactionGeometry(snapshot.like, counts.likes);
expectReactionGeometry(snapshot.dislike, counts.dislikes);
expectClose(snapshot.dislike.host.top, snapshot.like.host.bottom);
}
module.exports = {
SHORTS_ACTION_ORDER,
expectExtensionShortsVisualContract,
readExtensionShortsVisualContract,
};
@@ -1,5 +1,6 @@
const { NAVIGATION_MATRIX } = require("../UserScript/e2e/navigation-matrix");
const { SHARED_LIVE_SCENARIO_IDS } = require("./shared-live-scenarios");
const { LIVE_RUNTIME_PROFILES } = require("./live-runtime-adapter");
const REQUIRED_SURFACE_PAIRS = ["watch->watch", "watch->shorts", "shorts->watch", "shorts->shorts"];
const REQUIRED_TRIGGERS = [
@@ -8,35 +9,55 @@ const REQUIRED_TRIGGERS = [
"dom-corruption",
"dom-replacement",
"history-back-forward",
"navigate-start-only",
"next-control",
"sidebar-link",
];
const REQUIRED_DOM_FEATURES = [
"active-reel-switch",
"complete-native-inventory",
"connected-collapsed-rate-bar",
"connected-hidden-rate-bar",
"delayed-hydration",
"exact-href-identity",
"hidden-outgoing-first",
"incomplete-rendered-native-inventory",
"legacy-segmented-duplicate-ids",
"malformed-rate-bar",
"no-useful-control-mutation",
"no-is-active",
"no-synthetic-mutation",
"no-video-id",
"non-rendered-native-action",
"native-dislike-present",
"positive-size-offscreen-outgoing-first",
"persistent-data-null-action-root",
"prune-current-bar",
"replace-action-root",
"replace-controls",
"replace-current-action-container",
"replace-page-and-controls-after-start",
"reuse-exact-control-nodes",
"retain-hidden-outgoing",
"same-current-root",
"stable-action-root-geometry",
"stripped-rate-bar-wrapper-class",
"unrelated-description-short-link",
];
const REQUIRED_TIMINGS = [
"data-null-past-watchdog",
"destination-count-gated",
"finish-before-hydration",
"inert-beyond-fallback-window",
"native-dislike-after-stability",
"native-dislike-without-synthetic-mutation",
"no-navigate-finish",
"no-navigation-event",
"navigate-finish",
"navigate-start-without-finish",
"same-video",
"settled",
"stable-native-inventory",
];
const REQUIRED_SHARED_LIVE_SCENARIOS = [
"channel-shorts-navigation",
@@ -44,11 +65,14 @@ const REQUIRED_SHARED_LIVE_SCENARIOS = [
"watch-render",
"reload",
"spa-navigation",
"watch-action-topology",
"sidebar-navigation-stress",
"shorts-render",
"responsive-visual",
"post-navigation-vote",
"reaction-matrix",
];
const REQUIRED_POSTCONDITIONS = ["no-destination-dislike", "single-destination-dislike"];
function collectCoverage(axis) {
return new Set(
@@ -76,12 +100,19 @@ describe("systematic browser coverage contract", () => {
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) }),
postcondition: expect.any(String),
viewport: expect.objectContaining({ height: expect.any(Number), width: expect.any(Number) }),
}),
);
}
});
test("keeps both interactive and intentionally inert navigation postconditions", () => {
expect([...new Set(NAVIGATION_MATRIX.map(({ postcondition }) => postcondition))].sort()).toEqual(
REQUIRED_POSTCONDITIONS,
);
});
test("covers every watch and Shorts direction and every required navigation trigger", () => {
const surfacePairs = new Set(
NAVIGATION_MATRIX.map(({ coverage }) => `${coverage.origin}->${coverage.destination}`),
@@ -110,4 +141,14 @@ describe("systematic browser coverage contract", () => {
test("keeps the same authenticated scenario catalog for both runtime adapters", () => {
expect(SHARED_LIVE_SCENARIO_IDS).toEqual(REQUIRED_SHARED_LIVE_SCENARIOS);
});
test.each(["userscript", "extension"])(
"distinguishes owned desktop Shorts from native-dependent mobile compatibility for %s",
(runtime) => {
expect(LIVE_RUNTIME_PROFILES[runtime].capabilities.shortsControlModelBySurface).toEqual({
desktop: "synthetic-owned",
mobile: "native-youtube-required",
});
},
);
});
+255
View File
@@ -0,0 +1,255 @@
const assert = require("node:assert/strict");
const crypto = require("node:crypto");
const fs = require("node:fs");
const path = require("node:path");
const {
BUILD_RECEIPT_FILENAME,
BUILD_RECEIPT_SCHEMA_VERSION,
createExtensionBuildReceipt,
} = require("../../extension-build-receipt");
const REPOSITORY_ROOT = path.resolve(__dirname, "../..");
const DIST_ROOT = path.join(REPOSITORY_ROOT, "Extensions", "combined", "dist");
const PRODUCTION_API_ORIGIN = "https://returnyoutubedislikeapi.com";
const BROWSER_ARTIFACTS = Object.freeze([
Object.freeze({ directory: "chrome", manifestVersion: 3 }),
Object.freeze({ directory: "firefox", manifestVersion: 2 }),
Object.freeze({ directory: "safari", manifestVersion: 2 }),
]);
const REQUIRED_FILES = Object.freeze([
"content-style.css",
"manifest.json",
"menu-fixer.js",
"popup.html",
"ryd.background.js",
"ryd.content-script.js",
]);
const EMITTED_JS_FILES = Object.freeze(["popup.js", "ryd.background.js", "ryd.changelog.js", "ryd.content-script.js"]);
const FORBIDDEN_DIRECTORY_NAMES = new Set(["e2e", "playwright-report", "test-results"]);
const TEST_FILE_PATTERN = /(?:^|[.])(e2e|spec|test)\.[cm]?[jt]sx?$/i;
function listFiles(directory, relativeDirectory = "") {
const files = [];
for (const entry of fs.readdirSync(path.join(directory, relativeDirectory), { withFileTypes: true })) {
const relativePath = path.join(relativeDirectory, entry.name);
if (entry.isDirectory()) files.push(...listFiles(directory, relativePath));
else if (entry.isFile()) files.push(relativePath);
}
return files;
}
function verifyContentScriptManifest(manifest, browserDirectory) {
const contentScript = manifest.content_scripts?.find(
({ css = [], js = [] }) => js.includes("ryd.content-script.js") && css.includes("content-style.css"),
);
assert.ok(contentScript, `${browserDirectory} manifest does not load the built content script and stylesheet.`);
}
function manifestExposesWebAccessibleResource(manifest, resource) {
return (manifest.web_accessible_resources ?? []).some((entry) => {
if (typeof entry === "string") return entry === resource;
return Array.isArray(entry?.resources) && entry.resources.includes(resource);
});
}
function verifyPageWorldHelperManifest(manifest, browserDirectory) {
assert.ok(
manifestExposesWebAccessibleResource(manifest, "menu-fixer.js"),
`${browserDirectory} manifest does not expose menu-fixer.js to YouTube pages.`,
);
}
function verifyStandaloneMv3Artifact(artifactDirectory) {
const directory = path.resolve(artifactDirectory);
assert.ok(fs.statSync(directory).isDirectory(), `Missing custom extension artifact ${directory}.`);
const manifestPath = path.join(directory, "manifest.json");
assert.ok(fs.statSync(manifestPath).isFile(), `The custom extension artifact has no manifest.json.`);
const manifest = JSON.parse(fs.readFileSync(manifestPath, "utf8"));
assert.equal(manifest.manifest_version, 3, "The custom extension artifact must use Manifest V3.");
assert.equal(
manifest.background?.service_worker,
"ryd.background.js",
"The custom extension artifact must declare the built background worker.",
);
const contentScript = manifest.content_scripts?.find(
({ css = [], js = [] }) => js.includes("ryd.content-script.js") && css.includes("content-style.css"),
);
assert.ok(contentScript, "The custom extension artifact must declare its built content script and stylesheet.");
for (const asset of new Set([manifest.background.service_worker, ...contentScript.js])) {
assertProductionJavaScriptOutput(path.join(directory, asset), asset);
}
for (const asset of [manifest.background.service_worker, "ryd.content-script.js"]) {
assert.ok(
fs.readFileSync(path.join(directory, asset), "utf8").includes(PRODUCTION_API_ORIGIN),
`${asset} is not a production API artifact.`,
);
}
assert.ok(
fs.statSync(path.join(directory, "content-style.css")).isFile(),
"The custom extension artifact is missing content-style.css.",
);
return { directory, manifestVersion: manifest.manifest_version, version: manifest.version };
}
function verifyBrowserArtifact({ directory, manifestVersion }) {
const artifactDirectory = path.join(DIST_ROOT, directory);
assert.ok(fs.statSync(artifactDirectory).isDirectory(), `Missing generated ${directory} artifact.`);
for (const requiredFile of REQUIRED_FILES) {
assert.ok(
fs.statSync(path.join(artifactDirectory, requiredFile)).isFile(),
`${directory} is missing ${requiredFile}.`,
);
}
const manifest = JSON.parse(fs.readFileSync(path.join(artifactDirectory, "manifest.json"), "utf8"));
assert.equal(manifest.manifest_version, manifestVersion, `${directory} has the wrong manifest version.`);
assert.equal(
fs.existsSync(path.join(artifactDirectory, BUILD_RECEIPT_FILENAME)),
false,
`${directory} must not package the root-only build receipt.`,
);
verifyContentScriptManifest(manifest, directory);
verifyPageWorldHelperManifest(manifest, directory);
if (directory === "chrome") {
assert.equal(manifest.background?.service_worker, "ryd.background.js", "Chrome must load the built MV3 worker.");
}
for (const bundle of ["ryd.background.js", "ryd.content-script.js"]) {
assert.ok(
fs.readFileSync(path.join(artifactDirectory, bundle), "utf8").includes(PRODUCTION_API_ORIGIN),
`${directory}/${bundle} is not a production API artifact.`,
);
}
const files = listFiles(artifactDirectory);
const forbiddenFiles = files.filter((relativePath) => {
const segments = relativePath.split(path.sep).map((segment) => segment.toLowerCase());
return (
segments.some((segment) => FORBIDDEN_DIRECTORY_NAMES.has(segment)) ||
TEST_FILE_PATTERN.test(path.basename(relativePath)) ||
path.basename(relativePath).toLowerCase() === "live-build.json"
);
});
assert.deepEqual(
forbiddenFiles,
[],
`${directory} contains test-only or live-test files: ${forbiddenFiles.join(", ")}`,
);
return { directory, fileCount: files.length, manifestVersion };
}
function verifyBuildReceipt(distRoot = DIST_ROOT, repositoryRoot = REPOSITORY_ROOT) {
const receiptPath = path.join(distRoot, BUILD_RECEIPT_FILENAME);
assert.ok(
fs.existsSync(receiptPath) && fs.statSync(receiptPath).isFile(),
`Missing extension build receipt ${BUILD_RECEIPT_FILENAME}; run the production extension build before testing.`,
);
const receipt = JSON.parse(fs.readFileSync(receiptPath, "utf8"));
assert.equal(receipt.schemaVersion, BUILD_RECEIPT_SCHEMA_VERSION, "The extension build receipt schema is invalid.");
assert.equal(receipt.mode, "production", "The extension artifact was not produced in production mode.");
assert.equal(receipt.inputHashAlgorithm, "sha256", "The extension build receipt uses an unknown hash algorithm.");
const current = createExtensionBuildReceipt(repositoryRoot, "production");
assert.deepEqual(receipt.inputs, current.inputs, "Extension build inputs changed after the artifact was generated.");
assert.equal(
receipt.inputHash,
current.inputHash,
"Extension build inputs changed after the artifact was generated; rebuild before testing.",
);
return receipt;
}
function sha256(filePath) {
return crypto.createHash("sha256").update(fs.readFileSync(filePath)).digest("hex");
}
function assertProductionJavaScriptOutput(filePath, label = path.basename(filePath)) {
assert.ok(fs.statSync(filePath).isFile(), `Missing JavaScript output ${label}.`);
assert.equal(
fs.readFileSync(filePath, "utf8").includes("sourceMappingURL=data:"),
false,
`${label} contains an inline source map and is not a production bundle.`,
);
}
function verifyMirroredJavaScript(
distRoot = DIST_ROOT,
browserArtifacts = BROWSER_ARTIFACTS,
emittedJsFiles = EMITTED_JS_FILES,
) {
for (const bundle of emittedJsFiles) {
const rootBundle = path.join(distRoot, bundle);
assert.ok(fs.statSync(rootBundle).isFile(), `Missing emitted root bundle ${bundle}.`);
const rootHash = sha256(rootBundle);
for (const { directory } of browserArtifacts) {
const mirroredBundle = path.join(distRoot, directory, bundle);
assert.ok(fs.statSync(mirroredBundle).isFile(), `${directory} is missing mirrored bundle ${bundle}.`);
assert.equal(
sha256(mirroredBundle),
rootHash,
`${directory}/${bundle} is stale or differs from the emitted root bundle.`,
);
}
}
}
function verifyProductionJavaScript(
distRoot = DIST_ROOT,
browserArtifacts = BROWSER_ARTIFACTS,
emittedJsFiles = EMITTED_JS_FILES,
) {
for (const bundle of emittedJsFiles) {
const outputs = [
{ filePath: path.join(distRoot, bundle), label: bundle },
...browserArtifacts.map(({ directory }) => ({
filePath: path.join(distRoot, directory, bundle),
label: `${directory}/${bundle}`,
})),
];
for (const { filePath, label } of outputs) {
assertProductionJavaScriptOutput(filePath, label);
}
}
}
function verifyExtensionArtifacts() {
assert.ok(fs.statSync(DIST_ROOT).isDirectory(), `Missing extension build output: ${DIST_ROOT}`);
verifyBuildReceipt();
const results = BROWSER_ARTIFACTS.map(verifyBrowserArtifact);
verifyMirroredJavaScript();
verifyProductionJavaScript();
return results;
}
function verifyRequestedExtensionArtifact(requestedArtifact = process.env.RYD_EXTENSION_ARTIFACT) {
const repositoryChromeArtifact = path.join(DIST_ROOT, "chrome");
if (!requestedArtifact || path.resolve(requestedArtifact) === path.resolve(repositoryChromeArtifact)) {
return { kind: "repository", results: verifyExtensionArtifacts() };
}
return { kind: "custom", results: [verifyStandaloneMv3Artifact(requestedArtifact)] };
}
if (require.main === module) {
try {
const verification = verifyRequestedExtensionArtifact();
process.stdout.write(`Verified extension artifact: ${JSON.stringify(verification)}\n`);
} catch (error) {
process.stderr.write(`${error.stack ?? error.message}\n`);
process.exitCode = 1;
}
}
module.exports = {
EMITTED_JS_FILES,
assertProductionJavaScriptOutput,
manifestExposesWebAccessibleResource,
verifyBuildReceipt,
verifyExtensionArtifacts,
verifyMirroredJavaScript,
verifyProductionJavaScript,
verifyRequestedExtensionArtifact,
verifyStandaloneMv3Artifact,
};
@@ -0,0 +1,108 @@
/**
* @jest-environment node
*/
const fs = require("node:fs");
const os = require("node:os");
const path = require("node:path");
const {
EMITTED_JS_FILES,
manifestExposesWebAccessibleResource,
verifyMirroredJavaScript,
verifyProductionJavaScript,
verifyRequestedExtensionArtifact,
} = require("./verify-extension-artifact");
const BROWSER_DIRECTORIES = ["chrome", "firefox", "safari"];
const MANIFEST_DIRECTORY = path.resolve(__dirname, "../combined");
let temporaryRoot;
function readSourceManifest(browser) {
const source = fs.readFileSync(path.join(MANIFEST_DIRECTORY, `manifest-${browser}.json`), "utf8");
return JSON.parse(
source
.split(/\r?\n/)
.filter((line) => !line.trimStart().startsWith("//"))
.join("\n"),
);
}
function writeBundle(directory, bundle, contents) {
fs.mkdirSync(directory, { recursive: true });
fs.writeFileSync(path.join(directory, bundle), contents);
}
beforeEach(() => {
temporaryRoot = fs.mkdtempSync(path.join(os.tmpdir(), "ryd-artifact-verifier-"));
for (const bundle of EMITTED_JS_FILES) {
const contents = `generated ${bundle}`;
writeBundle(temporaryRoot, bundle, contents);
for (const directory of BROWSER_DIRECTORIES) {
writeBundle(path.join(temporaryRoot, directory), bundle, contents);
}
}
});
afterEach(() => {
fs.rmSync(temporaryRoot, { force: true, recursive: true });
});
test.each(BROWSER_DIRECTORIES)("%s manifest exposes the page-world menu helper", (browser) => {
expect(manifestExposesWebAccessibleResource(readSourceManifest(browser), "menu-fixer.js")).toBe(true);
});
test("rejects a stale browser bundle even when every expected file exists", () => {
expect(() => verifyMirroredJavaScript(temporaryRoot)).not.toThrow();
fs.writeFileSync(path.join(temporaryRoot, "chrome", "ryd.content-script.js"), "stale content script");
expect(() => verifyMirroredJavaScript(temporaryRoot)).toThrow(
"chrome/ryd.content-script.js is stale or differs from the emitted root bundle.",
);
});
test.each([
["root output", "ryd.background.js", "ryd.background.js"],
["browser mirror", path.join("safari", "popup.js"), "safari/popup.js"],
])("rejects an inline development source map in a %s", (_case, relativePath, expectedLabel) => {
expect(() => verifyProductionJavaScript(temporaryRoot)).not.toThrow();
fs.writeFileSync(
path.join(temporaryRoot, relativePath),
'console.log("development");\n//# sourceMappingURL=data:application/json;base64,e30=',
);
expect(() => verifyProductionJavaScript(temporaryRoot)).toThrow(
`${expectedLabel} contains an inline source map and is not a production bundle.`,
);
});
test("allows a custom production MV3 artifact without requiring repository mirrors", () => {
const customDirectory = path.join(temporaryRoot, "custom");
fs.mkdirSync(customDirectory, { recursive: true });
fs.writeFileSync(
path.join(customDirectory, "manifest.json"),
JSON.stringify({
background: { service_worker: "ryd.background.js" },
content_scripts: [
{ css: ["content-style.css"], js: ["ryd.content-script.js"], matches: ["*://www.youtube.com/*"] },
],
manifest_version: 3,
version: "4.0.5",
}),
);
fs.writeFileSync(
path.join(customDirectory, "ryd.background.js"),
'fetch("https://returnyoutubedislikeapi.com/puzzle/registration")',
);
fs.writeFileSync(
path.join(customDirectory, "ryd.content-script.js"),
'fetch("https://returnyoutubedislikeapi.com/votes")',
);
fs.writeFileSync(path.join(customDirectory, "content-style.css"), "#ryd-bar { display: block; }");
expect(verifyRequestedExtensionArtifact(customDirectory)).toEqual({
kind: "custom",
results: [{ directory: customDirectory, manifestVersion: 3, version: "4.0.5" }],
});
});
@@ -0,0 +1,76 @@
const path = require("node:path");
const {
USERSCRIPT_ARTIFACT_RELATIVE_PATH,
USERSCRIPT_BUILD_RECEIPT_FILENAME,
USERSCRIPT_BUILD_RECEIPT_RELATIVE_PATH,
USERSCRIPT_LIVE_ARTIFACT_RELATIVE_PATH,
USERSCRIPT_LIVE_BUILD_RECEIPT_RELATIVE_PATH,
verifyUserscriptBuildReceipt,
} = require("../../userscript-build-receipt");
const REPOSITORY_ROOT = path.resolve(__dirname, "../..");
const REPOSITORY_USERSCRIPT_ARTIFACT = path.join(REPOSITORY_ROOT, USERSCRIPT_ARTIFACT_RELATIVE_PATH);
const REPOSITORY_USERSCRIPT_BUILD_RECEIPT = path.join(REPOSITORY_ROOT, USERSCRIPT_BUILD_RECEIPT_RELATIVE_PATH);
function resolveRequestedUserscriptArtifact(requestedArtifact = process.env.RYD_USERSCRIPT_ARTIFACT) {
const normalizedRequest = requestedArtifact?.trim();
return normalizedRequest ? path.resolve(normalizedRequest) : REPOSITORY_USERSCRIPT_ARTIFACT;
}
function receiptPathForUserscriptArtifact(artifactPath) {
const resolvedArtifact = path.resolve(artifactPath);
if (path.relative(resolvedArtifact, REPOSITORY_USERSCRIPT_ARTIFACT) === "") {
return REPOSITORY_USERSCRIPT_BUILD_RECEIPT;
}
return path.join(path.dirname(resolvedArtifact), USERSCRIPT_BUILD_RECEIPT_FILENAME);
}
function verifyRequestedUserscriptArtifact(requestedArtifact = process.env.RYD_USERSCRIPT_ARTIFACT) {
const artifactPath = resolveRequestedUserscriptArtifact(requestedArtifact);
return verifyUserscriptBuildReceipt({
artifactPath,
liveTestBuild: false,
receiptPath: receiptPathForUserscriptArtifact(artifactPath),
repositoryRoot: REPOSITORY_ROOT,
});
}
function verifyGeneratedUserscriptArtifact({ expectedBuildId = "", liveTestBuild = false } = {}) {
const artifactRelativePath = liveTestBuild
? USERSCRIPT_LIVE_ARTIFACT_RELATIVE_PATH
: USERSCRIPT_ARTIFACT_RELATIVE_PATH;
const receiptRelativePath = liveTestBuild
? USERSCRIPT_LIVE_BUILD_RECEIPT_RELATIVE_PATH
: USERSCRIPT_BUILD_RECEIPT_RELATIVE_PATH;
return verifyUserscriptBuildReceipt({
artifactPath: path.join(REPOSITORY_ROOT, artifactRelativePath),
expectedBuildId,
liveTestBuild,
receiptPath: path.join(REPOSITORY_ROOT, receiptRelativePath),
repositoryRoot: REPOSITORY_ROOT,
});
}
if (require.main === module) {
try {
const liveTestBuild = process.argv.includes("--live");
const buildIdArgument = process.argv.find((argument) => argument.startsWith("--build-id="));
const expectedBuildId = buildIdArgument?.slice("--build-id=".length) ?? "";
const receipt = liveTestBuild
? verifyGeneratedUserscriptArtifact({ expectedBuildId, liveTestBuild })
: verifyRequestedUserscriptArtifact();
process.stdout.write(`Verified userscript artifact: ${JSON.stringify(receipt)}\n`);
} catch (error) {
process.stderr.write(`${error.stack ?? error.message}\n`);
process.exitCode = 1;
}
}
module.exports = {
REPOSITORY_USERSCRIPT_ARTIFACT,
REPOSITORY_USERSCRIPT_BUILD_RECEIPT,
receiptPathForUserscriptArtifact,
resolveRequestedUserscriptArtifact,
verifyGeneratedUserscriptArtifact,
verifyRequestedUserscriptArtifact,
};
+46
View File
@@ -0,0 +1,46 @@
const assert = require("node:assert/strict");
const VISUAL_CAPTURE_ENVIRONMENT_VARIABLE = "RYD_CAPTURE_VISUALS";
function visualCaptureIsEnabled(environment = process.env) {
return environment?.[VISUAL_CAPTURE_ENVIRONMENT_VARIABLE] === "1";
}
async function captureOptionalVisualEvidence({ capture, environment = process.env, outputPath }) {
if (!visualCaptureIsEnabled(environment)) {
return Object.freeze({ captured: false, outputPath: null, reason: "capture-disabled" });
}
if (typeof capture !== "function") throw new TypeError("Visual evidence capture must be a function.");
if (typeof outputPath !== "string" || outputPath.length === 0) {
throw new TypeError("Visual evidence outputPath must be a non-empty string.");
}
await capture(outputPath);
return Object.freeze({ captured: true, outputPath, reason: null });
}
function annotateVisualEvidence(testInfo, evidence) {
testInfo.annotations.push({
description: evidence.captured ? `captured:${evidence.outputPath}` : `not-captured:${evidence.reason}`,
type: "visual-evidence",
});
return evidence;
}
function assertVisualEvidenceCaptured(evidence, label = "Visual evidence") {
assert.equal(
evidence?.captured,
true,
`${label} was not captured. Structural browser assertions alone are not inspected screenshot evidence.`,
);
assert.equal(typeof evidence.outputPath, "string", `${label} has no screenshot path.`);
return evidence;
}
module.exports = {
VISUAL_CAPTURE_ENVIRONMENT_VARIABLE,
annotateVisualEvidence,
assertVisualEvidenceCaptured,
captureOptionalVisualEvidence,
visualCaptureIsEnabled,
};
+44
View File
@@ -0,0 +1,44 @@
/**
* @jest-environment node
*/
const {
annotateVisualEvidence,
assertVisualEvidenceCaptured,
captureOptionalVisualEvidence,
} = require("./visual-evidence");
test("capture-off results cannot be presented as inspected screenshot evidence", async () => {
const capture = jest.fn();
const testInfo = { annotations: [] };
const evidence = await captureOptionalVisualEvidence({
capture,
environment: {},
outputPath: "would-have-been.png",
});
annotateVisualEvidence(testInfo, evidence);
expect(capture).not.toHaveBeenCalled();
expect(evidence).toEqual({ captured: false, outputPath: null, reason: "capture-disabled" });
expect(testInfo.annotations).toEqual([{ description: "not-captured:capture-disabled", type: "visual-evidence" }]);
expect(() => assertVisualEvidenceCaptured(evidence, "Extension UI screenshot")).toThrow(
"Structural browser assertions alone are not inspected screenshot evidence.",
);
});
test("capture-on results carry the exact screenshot path", async () => {
const capture = jest.fn();
const evidence = await captureOptionalVisualEvidence({
capture,
environment: { RYD_CAPTURE_VISUALS: "1" },
outputPath: "captured.png",
});
expect(capture).toHaveBeenCalledWith("captured.png");
expect(assertVisualEvidenceCaptured(evidence)).toEqual({
captured: true,
outputPath: "captured.png",
reason: null,
});
});
+42
View File
@@ -0,0 +1,42 @@
const USER_ID_PATTERN = /^[A-Za-z0-9]{36}$/;
const FOUR_BYTE_PROOF_PATTERN = /^[A-Za-z0-9+/]{6}==$/;
function hasExactKeys(value, keys) {
return (
value !== null &&
typeof value === "object" &&
!Array.isArray(value) &&
Object.keys(value).sort().join(",") === [...keys].sort().join(",")
);
}
function isFourByteProofSolution(value) {
if (typeof value !== "string" || !FOUR_BYTE_PROOF_PATTERN.test(value)) return false;
try {
const bytes = Buffer.from(value, "base64");
return bytes.length === 4 && bytes.toString("base64") === value;
} catch {
return false;
}
}
function isVoteProtocolBodyPairValid(voteBody, confirmationBody, { value, videoId } = {}) {
const userId = voteBody?.userId;
return (
USER_ID_PATTERN.test(userId ?? "") &&
hasExactKeys(voteBody, ["userId", "value", "videoId"]) &&
voteBody.videoId === videoId &&
voteBody.value === value &&
hasExactKeys(confirmationBody, ["solution", "userId", "videoId"]) &&
confirmationBody.userId === userId &&
confirmationBody.videoId === videoId &&
isFourByteProofSolution(confirmationBody.solution)
);
}
module.exports = {
USER_ID_PATTERN,
hasExactKeys,
isFourByteProofSolution,
isVoteProtocolBodyPairValid,
};
@@ -0,0 +1,47 @@
const { hasExactKeys, isFourByteProofSolution, isVoteProtocolBodyPairValid } = require("./vote-protocol-contract");
const USER_ID = "A".repeat(36);
const VIDEO_ID = "abcdefghijk";
const SOLUTION = Buffer.alloc(4).toString("base64");
function validBodies() {
return {
confirmation: { solution: SOLUTION, userId: USER_ID, videoId: VIDEO_ID },
vote: { userId: USER_ID, value: -1, videoId: VIDEO_ID },
};
}
test("accepts only the exact vote and four-byte confirmation protocol bodies", () => {
const bodies = validBodies();
expect(isVoteProtocolBodyPairValid(bodies.vote, bodies.confirmation, { value: -1, videoId: VIDEO_ID })).toBe(true);
});
test.each([
["short user ID", ({ vote }) => ({ ...vote, userId: "short" })],
["extra vote key", ({ vote }) => ({ ...vote, unexpected: true })],
["wrong video", ({ vote }) => ({ ...vote, videoId: "lmnopqrstuv" })],
["wrong value", ({ vote }) => ({ ...vote, value: 1 })],
])("rejects a vote body with a %s", (_label, changeVote) => {
const bodies = validBodies();
bodies.vote = changeVote(bodies);
expect(isVoteProtocolBodyPairValid(bodies.vote, bodies.confirmation, { value: -1, videoId: VIDEO_ID })).toBe(false);
});
test.each([
["different user ID", ({ confirmation }) => ({ ...confirmation, userId: "B".repeat(36) })],
["extra confirmation key", ({ confirmation }) => ({ ...confirmation, unexpected: true })],
["wrong video", ({ confirmation }) => ({ ...confirmation, videoId: "lmnopqrstuv" })],
["short proof", ({ confirmation }) => ({ ...confirmation, solution: "AA==" })],
["non-canonical proof", ({ confirmation }) => ({ ...confirmation, solution: "AAAAAA==\n" })],
])("rejects a confirmation body with a %s", (_label, changeConfirmation) => {
const bodies = validBodies();
bodies.confirmation = changeConfirmation(bodies);
expect(isVoteProtocolBodyPairValid(bodies.vote, bodies.confirmation, { value: -1, videoId: VIDEO_ID })).toBe(false);
});
test("exact-key and proof helpers fail closed", () => {
expect(hasExactKeys({ a: 1, b: 2 }, ["b", "a"])).toBe(true);
expect(hasExactKeys({ a: 1, b: 2, c: 3 }, ["a", "b"])).toBe(false);
expect(isFourByteProofSolution(SOLUTION)).toBe(true);
expect(isFourByteProofSolution("not-base64")).toBe(false);
});
+504
View File
@@ -0,0 +1,504 @@
const { expect } = require("@playwright/test");
const { WATCH_REACTION_TRANSITIONS, WATCH_VISUAL_VIEWPORTS } = require("./watch-visual-scenarios");
const EXTENSION_WATCH_VISUAL_PROFILE = Object.freeze({
bar: "#ryd-bar",
container: "#ryd-bar-container",
dislikeText: ".ytSpecButtonShapeNextButtonTextContent",
initialNativeDislikeTextContainers: 0,
likeText: "#text",
roleAttribute: "data-fixture-role",
tooltip: "#ryd-dislike-tooltip",
tooltipDescription: null,
wrapper: ".ryd-tooltip",
});
const USERSCRIPT_WATCH_VISUAL_PROFILE = Object.freeze({
bar: "#return-youtube-dislike-bar",
container: "#return-youtube-dislike-bar-container",
dislikeText: "#text",
initialNativeDislikeTextContainers: 1,
likeText: "#text",
roleAttribute: "data-ryd-role",
tooltip: "#ryd-dislike-tooltip",
tooltipAppearance: Object.freeze({
fontSize: "12px",
lineHeight: "16px",
opacity: "0",
padding: Object.freeze(["6px", "8px", "6px", "8px"]),
position: "absolute",
visibility: "hidden",
}),
tooltipDescription: "ryd-dislike-tooltip",
wrapper: ".ryd-tooltip",
});
async function readWatchVisualContract(page, profile) {
return page.evaluate((selectors) => {
const required = (selector) => {
const element = document.querySelector(selector);
if (!element) throw new Error(`Missing visual-contract element: ${selector}`);
return element;
};
const rect = (element) => {
const bounds = element.getBoundingClientRect();
return {
bottom: bounds.bottom,
height: bounds.height,
left: bounds.left,
right: bounds.right,
top: bounds.top,
width: bounds.width,
};
};
const box = (element) => {
const style = getComputedStyle(element);
return {
margin: [style.marginTop, style.marginRight, style.marginBottom, style.marginLeft],
padding: [style.paddingTop, style.paddingRight, style.paddingBottom, style.paddingLeft],
};
};
const visibility = (element) => {
const bounds = element.getBoundingClientRect();
const style = getComputedStyle(element);
return {
display: style.display,
opacity: Number(style.opacity),
rendered: bounds.width > 0 && bounds.height > 0,
visibility: style.visibility,
};
};
const control = (role) => {
const roleSelector = `[${selectors.roleAttribute}="${role}"]`;
const outer = required(roleSelector);
const button = required(`${roleSelector} button`);
const icon = required(`${roleSelector} [data-fixture-icon]`);
const text = required(`${roleSelector} ${selectors[`${role}Text`]}`);
const buttonStyle = getComputedStyle(button);
const center = {
x: button.getBoundingClientRect().left + button.getBoundingClientRect().width / 2,
y: button.getBoundingClientRect().top + button.getBoundingClientRect().height / 2,
};
const hitTarget = document.elementFromPoint(center.x, center.y);
return {
ariaPressed: button.getAttribute("aria-pressed"),
backgroundColor: buttonStyle.backgroundColor,
button: rect(button),
buttonBox: box(button),
buttonVisibility: visibility(button),
classes: [...outer.classList].sort(),
color: buttonStyle.color,
icon: rect(icon),
iconBox: box(icon),
iconVisibility: visibility(icon),
hitTargetOwnedByButton: hitTarget === button || button.contains(hitTarget),
outer: rect(outer),
outerBox: box(outer),
text: rect(text),
textBox: box(text),
textContent: text.textContent.replace(/\s+/g, " ").trim(),
textOwnedByButton: button.contains(text),
textVisibility: visibility(text),
};
};
const surface = required("#top-level-buttons-computed");
const reactionGroup = required(`[${selectors.roleAttribute}="buttons"]`);
const likeOuter = required(`[${selectors.roleAttribute}="like"]`);
const dislikeOuter = required(`[${selectors.roleAttribute}="dislike"]`);
const smartimation = required(`[${selectors.roleAttribute}="buttons"] > yt-smartimation`);
const smartimationContentShell = required("[data-fixture-smartimation-content-shell]");
const smartimationContent = required("[data-fixture-smartimation-content]");
const topRow = required("#top-row");
const unrelatedActions = required("#flexible-item-buttons");
const currentVideoId = new URL(location.href).searchParams.get("v");
const watchRoot = surface.closest("ytd-watch-flexy, ytd-watch-grid");
const wrapper = required(selectors.wrapper);
const barContainer = required(selectors.container);
const bar = required(selectors.bar);
const tooltip = required(selectors.tooltip);
const reactionGroupStyle = getComputedStyle(reactionGroup);
const surfaceStyle = getComputedStyle(surface);
const topRowStyle = getComputedStyle(topRow);
const barStyle = getComputedStyle(bar);
const barContainerStyle = getComputedStyle(barContainer);
const tooltipStyle = getComputedStyle(tooltip);
const wrapperStyle = getComputedStyle(wrapper);
const actionSurfaces = [...document.querySelectorAll("#top-level-buttons-computed")];
const visibleActionSurfaces = actionSurfaces.filter((candidate) => visibility(candidate).rendered);
const zeroWidthActionSurfaces = actionSurfaces.filter((candidate) => candidate.getBoundingClientRect().width === 0);
const commentActionSurfaces = [...document.querySelectorAll("[data-fixture-comment-action-surface]")];
return {
bar: rect(bar),
barAppearance: {
backgroundColor: barStyle.backgroundColor,
borderRadius: barStyle.borderRadius,
},
barContainer: rect(barContainer),
barContainerAppearance: {
backgroundColor: barContainerStyle.backgroundColor,
borderRadius: barContainerStyle.borderRadius,
},
barVisibility: visibility(bar),
bodyBackgroundColor: getComputedStyle(document.body).backgroundColor,
buttons: rect(surface),
buttonsBox: box(surface),
buttonsGap: reactionGroupStyle.gap,
buttonsPosition: surfaceStyle.position,
commentActionSurfaces: {
bars: commentActionSurfaces.reduce(
(total, candidate) => total + candidate.querySelectorAll(selectors.bar).length,
0,
),
dislikeTextContainers: commentActionSurfaces.reduce(
(total, candidate) =>
total +
candidate.querySelectorAll(
"[data-fixture-comment-dislike] #text, " +
"[data-fixture-comment-dislike] [role='text'], " +
"[data-fixture-comment-dislike] .yt-spec-button-shape-next__button-text-content, " +
"[data-fixture-comment-dislike] .ytSpecButtonShapeNextButtonTextContent",
).length,
0,
),
reactionPairs: commentActionSurfaces.filter(
(candidate) =>
candidate.querySelector("[data-fixture-comment-like] button") &&
candidate.querySelector("[data-fixture-comment-dislike] button"),
).length,
surfaces: commentActionSurfaces.length,
wrappers: commentActionSurfaces.reduce(
(total, candidate) => total + candidate.querySelectorAll(selectors.wrapper).length,
0,
),
zeroWidth: commentActionSurfaces.filter((candidate) => candidate.getBoundingClientRect().width === 0).length,
},
documentScrollWidth: document.documentElement.scrollWidth,
dislike: control("dislike"),
fixtureBaseline: {
initialDislikeTextContainers: globalThis.__youtubeFixture?.initialDislikeTextContainers ?? null,
},
like: control("like"),
ownership: {
actionSurfaceOwnedByCurrentWatch: watchRoot?.getAttribute("video-id") === currentVideoId,
barOwnedByButtons: surface.contains(barContainer),
nativeControlsOwnedByReactionGroup:
reactionGroup.contains(likeOuter.querySelector("button")) &&
reactionGroup.contains(dislikeOuter.querySelector("button")),
reactionControlsOwnedByGroup:
smartimationContent.contains(likeOuter) &&
smartimationContent.contains(dislikeOuter) &&
likeOuter.closest("yt-smartimation") === smartimation &&
dislikeOuter.closest("yt-smartimation") === smartimation,
reactionGroupOwnedByButtons: reactionGroup.parentElement === surface,
topRowOwnedByCurrentWatch: topRow.closest("ytd-watch-flexy, ytd-watch-grid") === watchRoot,
tooltipDescribedBy: wrapper.getAttribute("aria-describedby"),
tooltipOwnedByButtons: surface.contains(tooltip),
tooltipRole: tooltip.getAttribute("role"),
wrapperOwnedByButtons: wrapper.parentElement === surface,
},
reactionGroup: rect(reactionGroup),
reactionGroupBox: box(reactionGroup),
smartimationTopology: {
dislikeNestedButton:
dislikeOuter.querySelector("toggle-button-view-model > button-view-model > button") !== null,
likeBeforeDislike:
likeOuter.parentElement === dislikeOuter.parentElement && likeOuter.nextElementSibling === dislikeOuter,
likeNestedButton: likeOuter.querySelector("toggle-button-view-model > button-view-model > button") !== null,
smartimationContentOwnedByShell: smartimationContent.parentElement === smartimationContentShell,
smartimationDirectChild: smartimation.parentElement === reactionGroup,
smartimationShellOwnedBySmartimation: smartimationContentShell.parentElement === smartimation,
},
topRow: rect(topRow),
topRowBox: box(topRow),
topRowStyle: {
borderBottomWidth: topRowStyle.borderBottomWidth,
paddingBottom: topRowStyle.paddingBottom,
},
tooltipText: tooltip.textContent.replace(/\s+/g, " ").trim(),
tooltipAppearance: {
fontSize: tooltipStyle.fontSize,
lineHeight: tooltipStyle.lineHeight,
opacity: tooltipStyle.opacity,
padding: box(tooltip).padding,
position: tooltipStyle.position,
visibility: tooltipStyle.visibility,
},
unique: {
actionSurfaces: document.querySelectorAll("#top-level-buttons-computed").length,
bars: document.querySelectorAll(selectors.bar).length,
containers: document.querySelectorAll(selectors.container).length,
dislikeControls: document.querySelectorAll(`[${selectors.roleAttribute}="dislike"]`).length,
likeControls: document.querySelectorAll(`[${selectors.roleAttribute}="like"]`).length,
tooltips: document.querySelectorAll(selectors.tooltip).length,
visibleActionSurfaces: visibleActionSurfaces.length,
watchRoots: document.querySelectorAll("ytd-watch-flexy, ytd-watch-grid").length,
wrappers: document.querySelectorAll(selectors.wrapper).length,
zeroWidthActionSurfaces: zeroWidthActionSurfaces.length,
},
unrelatedActions: {
labels: [...unrelatedActions.querySelectorAll("span[role='text']")].map((element) =>
element.textContent.trim(),
),
ownedBars: unrelatedActions.querySelectorAll(selectors.bar).length,
visibility: visibility(unrelatedActions),
},
viewport: { height: innerHeight, width: innerWidth },
wrapper: rect(wrapper),
wrapperAppearance: {
box: box(wrapper),
position: wrapperStyle.position,
},
wrapperVisibility: visibility(wrapper),
};
}, profile);
}
function expectClose(actual, expected, precision = 5) {
expect(actual).toBeCloseTo(expected, precision);
}
function parseComputedColor(value) {
const srgb = value.match(/^color\(srgb\s+([\d.]+)\s+([\d.]+)\s+([\d.]+)/);
if (srgb) return srgb.slice(1).map((channel) => Number(channel) * 255);
const rgb = value.match(/^rgba?\(([\d.]+)[, ]+([\d.]+)[, ]+([\d.]+)/);
if (rgb) return rgb.slice(1).map(Number);
throw new Error(`Unsupported computed color: ${value}`);
}
function relativeLuminance(color) {
const channels = parseComputedColor(color).map((channel) => {
const value = channel / 255;
return value <= 0.04045 ? value / 12.92 : ((value + 0.055) / 1.055) ** 2.4;
});
return 0.2126 * channels[0] + 0.7152 * channels[1] + 0.0722 * channels[2];
}
function contrastRatio(first, second) {
const firstLuminance = relativeLuminance(first);
const secondLuminance = relativeLuminance(second);
const light = Math.max(firstLuminance, secondLuminance);
const dark = Math.min(firstLuminance, secondLuminance);
return (light + 0.05) / (dark + 0.05);
}
function expectComputedColor(actual, expectedChannel) {
const channels = parseComputedColor(actual);
expect(channels).toHaveLength(3);
channels.forEach((channel) => expect(channel).toBeCloseTo(expectedChannel, 0));
}
function expectControlGeometry(control) {
expectClose(control.outer.width, 96);
expectClose(control.outer.height, 36);
expectClose(control.button.width, 96);
expectClose(control.button.height, 36);
expect(control.outerBox).toEqual({
margin: ["0px", "0px", "0px", "0px"],
padding: ["0px", "0px", "0px", "0px"],
});
expect(control.buttonBox).toEqual({
margin: ["0px", "0px", "0px", "0px"],
padding: ["0px", "12px", "0px", "12px"],
});
expect(control.iconBox).toEqual({
margin: ["0px", "0px", "0px", "0px"],
padding: ["0px", "0px", "0px", "0px"],
});
expect(control.textBox).toEqual({
margin: ["0px", "0px", "0px", "0px"],
padding: ["0px", "0px", "0px", "0px"],
});
expectClose(control.icon.width, 20);
expectClose(control.icon.height, 20);
expectClose(control.icon.top + control.icon.height / 2, control.button.top + control.button.height / 2);
expectClose(control.text.top + control.text.height / 2, control.button.top + control.button.height / 2);
expectClose(control.text.left - control.icon.right, 6);
expect(control.buttonVisibility).toEqual({
display: "inline-flex",
opacity: 1,
rendered: true,
visibility: "visible",
});
expect(control.iconVisibility).toMatchObject({ opacity: 1, rendered: true, visibility: "visible" });
expect(control.textVisibility).toMatchObject({ opacity: 1, rendered: true, visibility: "visible" });
}
function expectPressedState(control, pressed) {
expect(control.ariaPressed).toBe(String(pressed));
expect(control.classes).toEqual([pressed ? "style-default-active" : "style-text"]);
expect(control.backgroundColor).toBe(pressed ? "rgb(241, 241, 241)" : "rgb(39, 39, 39)");
expect(control.color).toBe(pressed ? "rgb(15, 15, 15)" : "rgb(241, 241, 241)");
}
function expectWatchVisualState(snapshot, state, counts, viewport, profile, { assertTooltipText = true } = {}) {
expect(snapshot.viewport).toEqual({ height: viewport.height, width: viewport.width });
expect(snapshot.documentScrollWidth).toBeLessThanOrEqual(snapshot.viewport.width);
expect(snapshot.fixtureBaseline.initialDislikeTextContainers).toBe(profile.initialNativeDislikeTextContainers);
expect(snapshot.commentActionSurfaces).toEqual({
bars: 0,
dislikeTextContainers: 0,
reactionPairs: 20,
surfaces: 20,
wrappers: 0,
zeroWidth: 20,
});
expect(snapshot.unique).toEqual({
actionSurfaces: 21,
bars: 1,
containers: 1,
dislikeControls: 1,
likeControls: 1,
tooltips: 1,
visibleActionSurfaces: 1,
watchRoots: 1,
wrappers: 1,
zeroWidthActionSurfaces: 20,
});
expect(snapshot.ownership).toEqual({
actionSurfaceOwnedByCurrentWatch: true,
barOwnedByButtons: true,
nativeControlsOwnedByReactionGroup: true,
reactionControlsOwnedByGroup: true,
reactionGroupOwnedByButtons: true,
topRowOwnedByCurrentWatch: true,
tooltipDescribedBy: profile.tooltipDescription,
tooltipOwnedByButtons: true,
tooltipRole: "tooltip",
wrapperOwnedByButtons: true,
});
expect(snapshot.smartimationTopology).toEqual({
dislikeNestedButton: true,
likeBeforeDislike: true,
likeNestedButton: true,
smartimationContentOwnedByShell: true,
smartimationDirectChild: true,
smartimationShellOwnedBySmartimation: true,
});
expect(snapshot.unrelatedActions).toMatchObject({ labels: ["Save", "Download"], ownedBars: 0 });
expect(snapshot.unrelatedActions.visibility).toMatchObject({ opacity: 1, rendered: true, visibility: "visible" });
if (assertTooltipText) expect(snapshot.tooltipText).toBe(`${counts.likes} / ${counts.dislikes}`);
if (profile.tooltipAppearance) expect(snapshot.tooltipAppearance).toEqual(profile.tooltipAppearance);
expect(snapshot.like.textContent).toBe(String(counts.likes));
expect(snapshot.dislike.textContent).toBe(String(counts.dislikes));
expect(snapshot.buttonsGap).toBe("0px");
expect(snapshot.buttonsPosition).toBe("relative");
expect(snapshot.buttonsBox).toEqual({
margin: ["0px", "0px", "0px", "0px"],
padding: ["0px", "0px", "0px", "0px"],
});
expect(snapshot.reactionGroupBox).toEqual(snapshot.buttonsBox);
expect(snapshot.topRowBox).toEqual({
margin: ["0px", "0px", "0px", "0px"],
padding: ["0px", "0px", "10px", "0px"],
});
expect(snapshot.topRowStyle).toEqual({ borderBottomWidth: "1px", paddingBottom: "10px" });
expect(snapshot.wrapperAppearance).toEqual({
box: {
margin: ["0px", "0px", "0px", "0px"],
padding: ["0px", "0px", "0px", "0px"],
},
position: "absolute",
});
expect(snapshot.wrapperVisibility).toEqual({ display: "block", opacity: 1, rendered: true, visibility: "visible" });
expect(snapshot.barVisibility).toEqual({ display: "block", opacity: 1, rendered: true, visibility: "visible" });
expect(snapshot.barContainerAppearance.borderRadius).toBe("2px");
expectComputedColor(snapshot.barContainerAppearance.backgroundColor, 139);
expect(snapshot.barAppearance).toEqual({
backgroundColor: "rgb(241, 241, 241)",
borderRadius: "2px",
});
expect(contrastRatio(snapshot.barContainerAppearance.backgroundColor, snapshot.bodyBackgroundColor)).toBeGreaterThan(
4.5,
);
expect(
contrastRatio(snapshot.barAppearance.backgroundColor, snapshot.barContainerAppearance.backgroundColor),
).toBeGreaterThan(2.5);
expectControlGeometry(snapshot.like);
expectControlGeometry(snapshot.dislike);
expect(snapshot.like.hitTargetOwnedByButton).toBe(true);
expect(snapshot.dislike.hitTargetOwnedByButton).toBe(true);
expect(snapshot.like.textOwnedByButton).toBe(true);
expect(snapshot.dislike.textOwnedByButton).toBe(true);
expectPressedState(snapshot.like, state === "liked");
expectPressedState(snapshot.dislike, state === "disliked");
expectClose(snapshot.like.outer.right, snapshot.dislike.outer.left);
expectClose(snapshot.wrapper.left, snapshot.like.outer.left);
expectClose(snapshot.wrapper.right, snapshot.dislike.outer.right);
expectClose(snapshot.wrapper.width, snapshot.like.outer.width + snapshot.dislike.outer.width);
expectClose(snapshot.wrapper.height, 2);
expectClose(snapshot.wrapper.top - Math.max(snapshot.like.outer.bottom, snapshot.dislike.outer.bottom), 8);
expectClose(snapshot.barContainer.width, snapshot.wrapper.width);
expectClose(snapshot.barContainer.height, 2);
expectClose(snapshot.bar.height, 2);
expectClose(snapshot.bar.width / snapshot.barContainer.width, counts.likes / (counts.likes + counts.dislikes), 3);
expect(snapshot.barContainer.width - snapshot.bar.width).toBeGreaterThan(24);
expect(snapshot.topRow.left).toBeGreaterThanOrEqual(0);
expect(snapshot.topRow.right).toBeLessThanOrEqual(snapshot.viewport.width);
expect(snapshot.wrapper.left).toBeGreaterThanOrEqual(snapshot.topRow.left);
expect(snapshot.wrapper.right).toBeLessThanOrEqual(snapshot.topRow.right);
}
function expectNoStructuralLayoutShift(before, after) {
const paths = [
["topRow"],
["buttons"],
["reactionGroup"],
["wrapper"],
["barContainer"],
["like", "outer"],
["like", "button"],
["dislike", "outer"],
["dislike", "button"],
];
const dimensions = ["top", "right", "bottom", "left", "width", "height"];
for (const path of paths) {
const beforeRect = path.reduce((value, key) => value[key], before);
const afterRect = path.reduce((value, key) => value[key], after);
for (const dimension of dimensions) {
expect(
Math.abs(afterRect[dimension] - beforeRect[dimension]),
`${path.join(".")}.${dimension}`,
).toBeLessThanOrEqual(0.25);
}
}
}
async function waitForBarRatio(page, counts, profile) {
const expectedRatio = counts.likes / (counts.likes + counts.dislikes);
await expect
.poll(() =>
page.locator(profile.bar).evaluate((bar) => {
const container = bar.parentElement;
return bar.getBoundingClientRect().width / container.getBoundingClientRect().width;
}),
)
.toBeCloseTo(expectedRatio, 3);
}
async function attachVisualFailureScreenshot(testInfo, page, name) {
let body;
try {
const scope = page.locator("#top-row");
body = (await scope.count()) > 0 ? await scope.screenshot({ animations: "disabled" }) : await page.screenshot();
} catch {
body = await page.screenshot().catch(() => null);
}
if (body) await testInfo.attach(`${name}-visual-contract-failure`, { body, contentType: "image/png" });
}
module.exports = {
EXTENSION_WATCH_VISUAL_PROFILE,
USERSCRIPT_WATCH_VISUAL_PROFILE,
WATCH_REACTION_TRANSITIONS,
WATCH_VISUAL_VIEWPORTS,
attachVisualFailureScreenshot,
contrastRatio,
expectNoStructuralLayoutShift,
expectWatchVisualState,
readWatchVisualContract,
waitForBarRatio,
};
+127
View File
@@ -0,0 +1,127 @@
const WATCH_VISUAL_RUNTIMES = Object.freeze(["userscript", "extension"]);
const WATCH_VISUAL_VIEWPORTS = Object.freeze([
Object.freeze({ name: "wide", width: 1280, height: 720 }),
Object.freeze({ name: "narrow", width: 768, height: 720 }),
Object.freeze({ name: "compact", width: 390, height: 844 }),
]);
const WATCH_REACTION_TRANSITIONS = Object.freeze([
Object.freeze({
action: "like",
initialState: "neutral",
nextState: "liked",
value: 1,
likesDelta: 1,
dislikesDelta: 0,
}),
Object.freeze({
action: "dislike",
initialState: "neutral",
nextState: "disliked",
value: -1,
likesDelta: 0,
dislikesDelta: 1,
}),
Object.freeze({
action: "like",
initialState: "liked",
nextState: "neutral",
value: 0,
likesDelta: -1,
dislikesDelta: 0,
}),
Object.freeze({
action: "dislike",
initialState: "liked",
nextState: "disliked",
value: -1,
likesDelta: -1,
dislikesDelta: 1,
}),
Object.freeze({
action: "like",
initialState: "disliked",
nextState: "liked",
value: 1,
likesDelta: 1,
dislikesDelta: -1,
}),
Object.freeze({
action: "dislike",
initialState: "disliked",
nextState: "neutral",
value: 0,
likesDelta: 0,
dislikesDelta: -1,
}),
]);
const WATCH_VISUAL_SCENARIOS = Object.freeze(
WATCH_VISUAL_VIEWPORTS.flatMap((viewport) =>
WATCH_REACTION_TRANSITIONS.map((transition) =>
Object.freeze({
id: `watch-${viewport.name}-${transition.initialState}-${transition.action}-${transition.nextState}`,
transition,
viewport,
}),
),
),
);
const WATCH_VISUAL_RUNTIME_REGISTRATIONS = Object.freeze(
Object.fromEntries(
WATCH_VISUAL_RUNTIMES.map((runtime) => [
runtime,
Object.freeze({
runtime,
scenarioIds: Object.freeze(WATCH_VISUAL_SCENARIOS.map(({ id }) => id)),
}),
]),
),
);
function getWatchVisualRuntimeRegistration(runtime) {
const registration = WATCH_VISUAL_RUNTIME_REGISTRATIONS[runtime];
if (!registration) throw new TypeError(`Unsupported Watch visual runtime: ${runtime}`);
return registration;
}
function getWatchNeutralBaselineId(scenario) {
if (!scenario?.transition || !scenario?.viewport) {
throw new TypeError("A Watch visual scenario is required.");
}
return scenario.transition.initialState === "neutral" && scenario.transition.action === "like"
? `watch-${scenario.viewport.name}-neutral`
: null;
}
function registerWatchVisualContract({ runScenario, runtime, test }) {
if (typeof test !== "function" || typeof test.describe !== "function") {
throw new TypeError("The Watch visual contract requires a Playwright-compatible test function.");
}
if (typeof runScenario !== "function") {
throw new TypeError("The Watch visual contract requires runScenario().");
}
const registration = getWatchVisualRuntimeRegistration(runtime);
test.describe(`${runtime} Watch visual contract`, () => {
for (const scenario of WATCH_VISUAL_SCENARIOS) {
test(scenario.id, async ({ context, page }, testInfo) =>
runScenario({ fixtures: { context, page }, registration, scenario, testInfo }),
);
}
});
return registration;
}
module.exports = {
WATCH_REACTION_TRANSITIONS,
WATCH_VISUAL_RUNTIMES,
WATCH_VISUAL_RUNTIME_REGISTRATIONS,
WATCH_VISUAL_SCENARIOS,
WATCH_VISUAL_VIEWPORTS,
getWatchNeutralBaselineId,
getWatchVisualRuntimeRegistration,
registerWatchVisualContract,
};
@@ -0,0 +1,100 @@
const fs = require("node:fs");
const path = require("node:path");
const {
WATCH_REACTION_TRANSITIONS,
WATCH_VISUAL_RUNTIMES,
WATCH_VISUAL_RUNTIME_REGISTRATIONS,
WATCH_VISUAL_SCENARIOS,
WATCH_VISUAL_VIEWPORTS,
getWatchNeutralBaselineId,
registerWatchVisualContract,
} = require("./watch-visual-scenarios");
const REQUIRED_VIEWPORTS = [
{ name: "wide", width: 1280, height: 720 },
{ name: "narrow", width: 768, height: 720 },
{ name: "compact", width: 390, height: 844 },
];
const REQUIRED_TRANSITIONS = [
["neutral", "like", "liked", 1],
["neutral", "dislike", "disliked", -1],
["liked", "like", "neutral", 0],
["liked", "dislike", "disliked", -1],
["disliked", "like", "liked", 1],
["disliked", "dislike", "neutral", 0],
];
const WRAPPER_SPECS = {
extension: path.join(__dirname, "extension", "extension-artifact-visual.e2e.js"),
userscript: path.join(__dirname, "..", "UserScript", "e2e", "userscript-state-visual-contract.e2e.js"),
};
function scenarioKey({ transition, viewport }) {
return [viewport.name, transition.initialState, transition.action, transition.nextState, transition.value].join(":");
}
describe("shared Watch visual scenario registration", () => {
test("keeps the complete three-width by six-transition product", () => {
expect(WATCH_VISUAL_VIEWPORTS).toEqual(REQUIRED_VIEWPORTS);
expect(
WATCH_REACTION_TRANSITIONS.map(({ initialState, action, nextState, value }) => [
initialState,
action,
nextState,
value,
]),
).toEqual(REQUIRED_TRANSITIONS);
const requiredKeys = REQUIRED_VIEWPORTS.flatMap((viewport) =>
REQUIRED_TRANSITIONS.map(([initialState, action, nextState, value]) =>
[viewport.name, initialState, action, nextState, value].join(":"),
),
);
expect(WATCH_VISUAL_SCENARIOS).toHaveLength(18);
expect(WATCH_VISUAL_SCENARIOS.map(scenarioKey)).toEqual(requiredKeys);
expect(new Set(WATCH_VISUAL_SCENARIOS.map(({ id }) => id)).size).toBe(18);
});
test("binds both runtimes to the identical immutable scenario ID catalog", () => {
const expectedIds = WATCH_VISUAL_SCENARIOS.map(({ id }) => id);
expect(WATCH_VISUAL_RUNTIMES).toEqual(["userscript", "extension"]);
for (const runtime of WATCH_VISUAL_RUNTIMES) {
expect(WATCH_VISUAL_RUNTIME_REGISTRATIONS[runtime]).toEqual({ runtime, scenarioIds: expectedIds });
expect(Object.isFrozen(WATCH_VISUAL_RUNTIME_REGISTRATIONS[runtime])).toBe(true);
expect(Object.isFrozen(WATCH_VISUAL_RUNTIME_REGISTRATIONS[runtime].scenarioIds)).toBe(true);
}
expect(WATCH_VISUAL_RUNTIME_REGISTRATIONS.userscript.scenarioIds).toEqual(
WATCH_VISUAL_RUNTIME_REGISTRATIONS.extension.scenarioIds,
);
});
test("selects exactly one neutral baseline capture per viewport", () => {
expect(WATCH_VISUAL_SCENARIOS.map(getWatchNeutralBaselineId).filter(Boolean)).toEqual([
"watch-wide-neutral",
"watch-narrow-neutral",
"watch-compact-neutral",
]);
expect(() => getWatchNeutralBaselineId(null)).toThrow("A Watch visual scenario is required.");
});
test.each(WATCH_VISUAL_RUNTIMES)("the %s registrar cannot filter or omit shared scenarios", (runtime) => {
const declared = [];
const fakeTest = (id, implementation) => declared.push({ id, implementation });
fakeTest.describe = (_name, declaration) => declaration();
const registration = registerWatchVisualContract({ runtime, test: fakeTest, runScenario: jest.fn() });
expect(registration).toBe(WATCH_VISUAL_RUNTIME_REGISTRATIONS[runtime]);
expect(declared.map(({ id }) => id)).toEqual(WATCH_VISUAL_RUNTIME_REGISTRATIONS[runtime].scenarioIds);
expect(declared.every(({ implementation }) => typeof implementation === "function")).toBe(true);
});
test.each(Object.entries(WRAPPER_SPECS))(
"%s wrapper delegates declaration to the shared registrar",
(runtime, specPath) => {
const source = fs.readFileSync(specPath, "utf8");
expect(source.match(/registerWatchVisualContract\s*\(\s*\{/g)).toHaveLength(1);
expect(source).toContain(`runtime: "${runtime}"`);
expect(source).not.toMatch(/for\s*\(const\s+(?:viewport|transition)\s+of\s+WATCH_/);
},
);
});