mirror of
https://github.com/Alvin-Zilverstand/return-youtube-dislike.git
synced 2026-11-29 09:27:54 +01:00
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:
1 parent
3657de9b2c
commit
e500088e65
196 files changed
+39706
-2694
No files matched your search
@@ -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("&", "&").replaceAll('"', """);
|
||||
|
||||
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();
|
||||
}
|
||||
});
|
||||
}
|
||||
Reference in new issue
Block a user