mirror of
https://github.com/heygen-com/hyperframes.git
synced 2026-11-25 08:32:45 +00:00
fix(player): a late timeline from the old film no longer keeps a switched player ready (#8500)
* test(player): a late timeline from the old document must not make the next load ready * fix(player): a late timeline from the old frame document no longer makes the next load ready * test(player): type the announce filter in the late timeline rows * test(player): a static ready at load still asks for the runtime's held timeline * fix(player): a static ready at load still asks the runtime for the timeline it held * test(player): a late message the left document stamped is dropped without waiting for load * fix(player): drop a late message from the left document, so the next is ready before its load * test(player): the late-timeline row replays the sealed document's own timeline * chore(player): the player's size budget sits 5% above its measured size again * test: runtime load draws no page randomness; Studio pins the announce capability * fix(core): the runtime's document id comes from its time origin, so renders keep their random draws * test(core): two documents loaded at one coarsened time get different runtime ids * fix(core): the runtime's document id is a random UUID where the browser has one
This commit is contained in:
@@ -575,3 +575,33 @@ describe("flash-elements", () => {
|
||||
expect(document.querySelector(".target")?.classList.contains("__hf-flash")).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("the runtime's document id", () => {
|
||||
afterEach(() => vi.restoreAllMocks());
|
||||
|
||||
// fails without the fix: a render seeds crypto.getRandomValues, so an id drawn there shifted the film's random draws.
|
||||
it("draws nothing from the page's random sources when the runtime loads", async () => {
|
||||
const values = vi.spyOn(crypto, "getRandomValues");
|
||||
const random = vi.spyOn(Math, "random");
|
||||
vi.resetModules();
|
||||
await import("./bridge");
|
||||
expect({ values: values.mock.calls.length, random: random.mock.calls.length }).toEqual({
|
||||
values: 0,
|
||||
random: 0,
|
||||
});
|
||||
});
|
||||
|
||||
// fails without the fix: a coarsened timeOrigin gave two quick documents one id, so the second was dropped.
|
||||
it("gives two documents loaded at the same coarsened time different ids", async () => {
|
||||
vi.spyOn(performance, "timeOrigin", "get").mockReturnValue(1_000);
|
||||
const post = vi.spyOn(window.parent, "postMessage").mockImplementation(() => {});
|
||||
const idOfNewDocument = async () => {
|
||||
vi.resetModules();
|
||||
const bridge = await import("./bridge");
|
||||
bridge.postRuntimeMessage({ source: "hf-preview", type: "timeline" } as never);
|
||||
return (post.mock.calls.at(-1)![0] as { documentId: string }).documentId;
|
||||
};
|
||||
const [first, second] = [await idOfNewDocument(), await idOfNewDocument()];
|
||||
expect(first).not.toBe(second);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -40,6 +40,7 @@ type BridgeDeps = {
|
||||
onSetCopiesAhead?: (on: boolean) => void;
|
||||
onRetryPreviewCopies?: () => void;
|
||||
onRequestPreviewFacts?: () => void;
|
||||
onAnnounceTimeline?: () => void;
|
||||
onScrubAudio?: (target: PreviewTarget | null, time: number | null, volume: number) => void;
|
||||
getCanonicalFps: () => number;
|
||||
};
|
||||
@@ -70,10 +71,13 @@ let markedForAnotherSite = false;
|
||||
const forAnotherSite = (): boolean =>
|
||||
(markedForAnotherSite ||= typeof document !== "undefined" && servedToAnotherSite(document));
|
||||
|
||||
const UNSEEDED_DOCUMENT_ID = crypto.randomUUID?.() ?? String(performance.timeOrigin);
|
||||
|
||||
export function postRuntimeMessage(payload: RuntimeOutboundMessage): void {
|
||||
if (forAnotherSite() && !ANOTHER_SITE_SEES.has(payload.type)) return;
|
||||
try {
|
||||
window.parent.postMessage({ ...payload, ...runtimeProtocolMetadata(runtimeProtocolFps) }, "*");
|
||||
const metadata = runtimeProtocolMetadata(runtimeProtocolFps);
|
||||
window.parent.postMessage({ ...payload, ...metadata, documentId: UNSEEDED_DOCUMENT_ID }, "*");
|
||||
} catch (err) {
|
||||
// Cross-frame posting can throw if the parent is gone or origin-isolated.
|
||||
swallow("bridge.postMessage", err);
|
||||
@@ -188,6 +192,7 @@ const CONTROL_HANDLERS = new Map<string, ControlHandler>(
|
||||
"set-copies-ahead": (data, deps) => deps.onSetCopiesAhead?.(data.on === true),
|
||||
"retry-preview-copies": (_d, deps) => deps.onRetryPreviewCopies?.(),
|
||||
"request-preview-facts": (_d, deps) => deps.onRequestPreviewFacts?.(),
|
||||
"announce-timeline": (_d, deps) => deps.onAnnounceTimeline?.(),
|
||||
"set-root-duration": (data, deps) => {
|
||||
const durationSeconds = readNumber(data.durationSeconds, 0);
|
||||
if (durationSeconds !== null) deps.onSetRootDuration(durationSeconds);
|
||||
|
||||
@@ -4063,6 +4063,7 @@ export function initSandboxRuntimeModular(): void {
|
||||
let assetsSettled = false;
|
||||
let liveRootDurationOverrideSeconds = 0;
|
||||
let lastPostedManifest = "";
|
||||
let lastTimeline: ReturnType<typeof collectRuntimeTimelinePayload> | null = null;
|
||||
const computeClipTreeSignature = (): string => {
|
||||
let sig = "";
|
||||
for (const el of document.querySelectorAll("[data-start]")) {
|
||||
@@ -4134,6 +4135,7 @@ export function initSandboxRuntimeModular(): void {
|
||||
clipTreeSignature = currentSignature;
|
||||
}
|
||||
|
||||
lastTimeline = payload;
|
||||
postRuntimeMessage({ ...payload, assetsReady: assetsSettled });
|
||||
if (!assetsReadyStarted) {
|
||||
assetsReadyStarted = true;
|
||||
@@ -6842,6 +6844,9 @@ export function initSandboxRuntimeModular(): void {
|
||||
noteDisplayScale(scale);
|
||||
},
|
||||
onScrubAudio: scrubAudio.scrub,
|
||||
onAnnounceTimeline: () => {
|
||||
if (lastTimeline) postRuntimeMessage({ ...lastTimeline, assetsReady: assetsSettled });
|
||||
},
|
||||
onRequestPreviewFacts: () =>
|
||||
postRuntimeMessage({
|
||||
source: "hf-preview",
|
||||
|
||||
@@ -11,6 +11,7 @@ export const RUNTIME_PROTOCOL_CAPABILITIES = [
|
||||
"composition-manifest-v1",
|
||||
"runtime-data",
|
||||
"play-range",
|
||||
"announce-timeline",
|
||||
] as const;
|
||||
|
||||
export type RuntimeProtocolFps = {
|
||||
|
||||
@@ -4108,6 +4108,100 @@ describe("HyperframesPlayer asset-ready gate", () => {
|
||||
player.remove();
|
||||
});
|
||||
|
||||
describe("a timeline between a navigation and the next document's load", () => {
|
||||
const protocol = (capabilities: string[]) => ({
|
||||
protocolVersion: 1,
|
||||
fps: { numerator: 30, denominator: 1 },
|
||||
capabilities,
|
||||
});
|
||||
async function navigatedUnreadable() {
|
||||
const player = (await createConnectedPlayer()) as PlayerInternal & {
|
||||
probe: { start(): void };
|
||||
_abandonComposition(reason: string): void;
|
||||
_getSameOriginIframeDocument(): Document | null;
|
||||
};
|
||||
const start = vi.spyOn(player.probe, "start");
|
||||
const sent = vi.spyOn(player.iframe.contentWindow!, "postMessage");
|
||||
vi.spyOn(player, "_getSameOriginIframeDocument").mockReturnValue(null);
|
||||
player._abandonComposition("navigated");
|
||||
return { player, start, sent };
|
||||
}
|
||||
const announced = (sent: { mock: { calls: unknown[][] } }) =>
|
||||
sent.mock.calls.filter(
|
||||
([data]) => (data as { action?: string })?.action === "announce-timeline",
|
||||
);
|
||||
|
||||
// fails without the fix: the old document's late timeline made the next sealed load skip its probe.
|
||||
it("drops a late message the left document stamped, and takes the next document's before its load", async () => {
|
||||
const { player, start } = await navigatedUnreadable();
|
||||
const stamped = (documentId: string) => ({
|
||||
type: "timeline",
|
||||
durationInFrames: 60,
|
||||
documentId,
|
||||
...protocol(["seconds-time", "announce-timeline"]),
|
||||
});
|
||||
post(player, stamped("old"));
|
||||
player.iframe.dispatchEvent(new Event("load"));
|
||||
post(player, stamped("old"));
|
||||
expect(player._ready).toBe(true);
|
||||
start.mockClear();
|
||||
|
||||
player._abandonComposition("navigated again");
|
||||
post(player, stamped("old"));
|
||||
expect(player._ready).toBe(false);
|
||||
post(player, stamped("new"));
|
||||
expect(player._ready).toBe(true);
|
||||
|
||||
player.iframe.dispatchEvent(new Event("load"));
|
||||
expect(start).not.toHaveBeenCalled();
|
||||
player.remove();
|
||||
});
|
||||
|
||||
it("asks a document that never stamped a message again, and only its answer makes it ready", async () => {
|
||||
const { player, start, sent } = await navigatedUnreadable();
|
||||
const capable = protocol(["seconds-time", "announce-timeline"]);
|
||||
post(player, { type: "timeline", durationInFrames: 60, ...capable });
|
||||
expect(player._ready).toBe(false);
|
||||
|
||||
player.iframe.dispatchEvent(new Event("load"));
|
||||
expect(start).toHaveBeenCalledOnce();
|
||||
expect(announced(sent)).toHaveLength(1);
|
||||
expect(player._ready).toBe(false);
|
||||
|
||||
post(player, { type: "timeline", durationInFrames: 60, ...capable });
|
||||
expect(player._ready).toBe(true);
|
||||
player.remove();
|
||||
});
|
||||
|
||||
it("takes a runtime's timeline as today when the runtime cannot be asked again", async () => {
|
||||
const { player, start, sent } = await navigatedUnreadable();
|
||||
post(player, { type: "timeline", durationInFrames: 60, ...protocol(["seconds-time"]) });
|
||||
|
||||
player.iframe.dispatchEvent(new Event("load"));
|
||||
expect(player._ready).toBe(true);
|
||||
expect(start).not.toHaveBeenCalled();
|
||||
expect(announced(sent)).toHaveLength(0);
|
||||
player.remove();
|
||||
});
|
||||
|
||||
it("keeps a static-composition ready at load and still asks for the runtime's timeline", async () => {
|
||||
const { player, sent } = await navigatedUnreadable();
|
||||
const capable = protocol(["seconds-time", "announce-timeline"]);
|
||||
post(player, { type: "static-composition", durationSeconds: 2, width: 640, height: 360 });
|
||||
post(player, { type: "timeline", durationInFrames: 60, ...capable });
|
||||
|
||||
player.iframe.dispatchEvent(new Event("load"));
|
||||
expect(player._ready).toBe(true);
|
||||
expect(announced(sent)).toHaveLength(1);
|
||||
|
||||
post(player, { type: "timeline", durationInFrames: 60, ...capable });
|
||||
expect((player as unknown as { _readyBeforeRuntime: boolean })._readyBeforeRuntime).toBe(
|
||||
false,
|
||||
);
|
||||
player.remove();
|
||||
});
|
||||
});
|
||||
|
||||
it("paints a document before its load when nothing first-frame is pending", async () => {
|
||||
const player = await createConnectedPlayer();
|
||||
player._ready = false;
|
||||
|
||||
@@ -134,6 +134,12 @@ class HyperframesPlayer extends HTMLElement {
|
||||
private _ready = false;
|
||||
private _readyBeforeRuntime = false;
|
||||
private _readyDocument: Document | null = null;
|
||||
private _awaitingLoad = false;
|
||||
private _documentId: string | null = null;
|
||||
private _leftDocumentId: string | null = null;
|
||||
private _leftDocumentUnknown = false;
|
||||
private _runtimeAnnounces = false;
|
||||
private _timelineHeldForLoad = false;
|
||||
private _connected = false;
|
||||
private _assetsReady = false;
|
||||
private _painted = false;
|
||||
@@ -1248,10 +1254,20 @@ class HyperframesPlayer extends HTMLElement {
|
||||
|
||||
private _onMessage(e: MessageEvent) {
|
||||
// The iframe window outlives its documents: a late composition message must not reach a video.
|
||||
if (this._videoSource || this.probe.failed) return;
|
||||
if (this._videoSource || this.probe.failed || this._fromLeftDocument(e)) return;
|
||||
this._applyThenEmit(() => this._handleRuntimeMessage(e));
|
||||
}
|
||||
|
||||
/** True for a message the document a host navigation left stamped; another stamp becomes the current document's. */
|
||||
private _fromLeftDocument(e: MessageEvent): boolean {
|
||||
const id =
|
||||
e.source === this.iframe.contentWindow && (e.data as { documentId?: unknown })?.documentId;
|
||||
if (typeof id !== "string") return false;
|
||||
if (id === this._leftDocumentId) return true;
|
||||
this._documentId = id;
|
||||
return false;
|
||||
}
|
||||
|
||||
private _handleRuntimeMessage(e: MessageEvent) {
|
||||
handleRuntimeMessage(e, this.iframe.contentWindow, {
|
||||
getPlaybackState: () => ({
|
||||
@@ -1298,6 +1314,9 @@ class HyperframesPlayer extends HTMLElement {
|
||||
setRuntimeOwnsPlayRange: (owns) => {
|
||||
this._runtimeOwnsPlayRange = owns;
|
||||
},
|
||||
setRuntimeAnnounces: (announces) => {
|
||||
this._runtimeAnnounces = announces;
|
||||
},
|
||||
shouldPromoteMediaAutoplayFallback: () => !this._isSlideshowPlayer(),
|
||||
setScenes: (scenes) => {
|
||||
this._scenes = scenes;
|
||||
@@ -1315,6 +1334,11 @@ class HyperframesPlayer extends HTMLElement {
|
||||
}
|
||||
|
||||
private _onRuntimeTimelineReady(duration: number, assetsReady: boolean | undefined) {
|
||||
const mayBeLeft = this._awaitingLoad && this._leftDocumentUnknown;
|
||||
if (mayBeLeft && this._runtimeAnnounces && !this._getSameOriginIframeDocument()) {
|
||||
this._timelineHeldForLoad = true;
|
||||
return;
|
||||
}
|
||||
if (this._ready && !this._readyBeforeRuntime) return;
|
||||
const alreadyReady = this._readyBeforeRuntime;
|
||||
this._readyBeforeRuntime = false;
|
||||
@@ -1483,6 +1507,11 @@ class HyperframesPlayer extends HTMLElement {
|
||||
this.probe.stop();
|
||||
this._ready = false;
|
||||
this._readyBeforeRuntime = false;
|
||||
this._awaitingLoad = true;
|
||||
this._timelineHeldForLoad = false;
|
||||
this._leftDocumentUnknown = this._documentId === null;
|
||||
this._leftDocumentId = this._documentId ?? this._leftDocumentId;
|
||||
this._documentId = null;
|
||||
this._readyDocument = null;
|
||||
this._invalidateAssetsWait();
|
||||
this._releaseDocument();
|
||||
@@ -1624,13 +1653,17 @@ class HyperframesPlayer extends HTMLElement {
|
||||
private _onIframeLoad() {
|
||||
// In video mode the iframe only ever loads about:blank; its load must not reset the video.
|
||||
if (!this._connected || this._videoSource) return;
|
||||
// The runtime posts its timeline once its scripts ran, before or after `load`, and every
|
||||
// host-initiated navigation clears `_ready` first. So a ready player already holds this
|
||||
// document's handshake (an opaque origin reads as null); a paused runtime never posts it again.
|
||||
// A runtime posts its timeline before or after `load`. One seen since a host navigation from a document that never
|
||||
// stamped a message may be that document's: an unreadable frame's runtime that can be asked again held it, and is
|
||||
// asked below; else it stands, as a paused runtime never posts again (an opaque origin reads null on both sides).
|
||||
const askAgain = this._timelineHeldForLoad;
|
||||
this._awaitingLoad = false;
|
||||
this._timelineHeldForLoad = false;
|
||||
const doc = this._getSameOriginIframeDocument();
|
||||
if (this._ready && doc === this._readyDocument) {
|
||||
// Its asset wait scanned at DOMContentLoaded; a script may have added first-frame media since.
|
||||
if (doc && this._hasPendingFirstFrameAssets(doc)) this._waitForAssetsReady(doc);
|
||||
if (askAgain) this._sendControl("announce-timeline");
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -1643,6 +1676,7 @@ class HyperframesPlayer extends HTMLElement {
|
||||
this._invalidateAssetsWait();
|
||||
this._releaseDocument();
|
||||
this.probe.start();
|
||||
if (askAgain) this._sendControl("announce-timeline");
|
||||
}
|
||||
|
||||
private _setupControls() {
|
||||
|
||||
@@ -58,6 +58,7 @@ export interface MessageHandlerCallbacks extends PlaybackStateCallbacks {
|
||||
setBuffering?: (buffering: boolean) => void;
|
||||
setRuntimeFps?: (fps: number) => void;
|
||||
setRuntimeOwnsPlayRange?: (owns: boolean) => void;
|
||||
setRuntimeAnnounces?: (announces: boolean) => void;
|
||||
/** Called with the scene list whenever a "timeline" message is received. */
|
||||
setScenes: (scenes: SceneRecord[]) => void;
|
||||
/** Return false to ignore the iframe runtime's audible-media autoplay fallback.
|
||||
@@ -88,6 +89,9 @@ export function handleRuntimeMessage(
|
||||
const ownsPlayRange =
|
||||
protocol.status === "supported" && protocol.metadata.capabilities.includes("play-range");
|
||||
callbacks.setRuntimeOwnsPlayRange?.(ownsPlayRange);
|
||||
callbacks.setRuntimeAnnounces?.(
|
||||
protocol.status === "supported" && protocol.metadata.capabilities.includes("announce-timeline"),
|
||||
);
|
||||
|
||||
if (data["type"] === "shader-transition-state") {
|
||||
const state: ShaderTransitionState =
|
||||
|
||||
@@ -47,6 +47,47 @@ try {
|
||||
true,
|
||||
"removing the policy must reload into the documented trusted mode",
|
||||
);
|
||||
|
||||
// fails without the fix: the old document's timeline, landing after a switch, made the new load skip its probe.
|
||||
const switched = await browser.newPage();
|
||||
await switched.evaluateOnNewDocument(() => {
|
||||
addEventListener("message", (event) => {
|
||||
const data = event.data as { source?: string; type?: string } | null;
|
||||
if (data?.source === "hf-preview" && data.type === "timeline")
|
||||
(window as { __lastTimeline?: unknown }).__lastTimeline = data;
|
||||
});
|
||||
});
|
||||
await switched.goto(`${server.origin}/host.html?fixture=gsap-heavy`, {
|
||||
waitUntil: "domcontentloaded",
|
||||
});
|
||||
await switched.waitForFunction(() => window.__playerReady === true, { timeout: 15_000 });
|
||||
await switched.evaluate(() => {
|
||||
(window as { __lastTimeline?: unknown }).__lastTimeline = undefined;
|
||||
document.querySelector("hyperframes-player")!.setAttribute("sandbox-origin", "opaque");
|
||||
});
|
||||
// The sealed document's own timeline, which comes after its static ready: the one a switch leaves behind.
|
||||
await switched.waitForFunction(
|
||||
() => (window as { __lastTimeline?: unknown }).__lastTimeline !== undefined,
|
||||
{ timeout: 15_000 },
|
||||
);
|
||||
const lateError = await switched.evaluate(async () => {
|
||||
const w = window as { __lastTimeline?: unknown; __playerError?: string };
|
||||
const player = document.querySelector("hyperframes-player")!;
|
||||
const frame = player.shadowRoot!.querySelector("iframe")!;
|
||||
w.__playerError = undefined;
|
||||
player.setAttribute("src", "/fixtures/sandbox-probe/index.html");
|
||||
dispatchEvent(
|
||||
new MessageEvent("message", { data: w.__lastTimeline, source: frame.contentWindow }),
|
||||
);
|
||||
const started = performance.now();
|
||||
while (performance.now() - started < 14_000 && w.__playerError === undefined)
|
||||
await new Promise((resolve) => setTimeout(resolve, 100));
|
||||
return w.__playerError ?? null;
|
||||
});
|
||||
assert.ok(
|
||||
lateError,
|
||||
"a sealed player switched to a film with no runtime must fail, even after a late old timeline",
|
||||
);
|
||||
} finally {
|
||||
await browser.close();
|
||||
await server.stop();
|
||||
|
||||
@@ -21,6 +21,7 @@ describe("Studio runtime protocol", () => {
|
||||
"composition-manifest-v1",
|
||||
"runtime-data",
|
||||
"play-range",
|
||||
"announce-timeline",
|
||||
],
|
||||
fps: { numerator: 60, denominator: 1 },
|
||||
timeSeconds: 1.25,
|
||||
|
||||
@@ -32,8 +32,8 @@
|
||||
"unpacked": 915000
|
||||
},
|
||||
"@hyperframes/player": {
|
||||
"packed": 162000,
|
||||
"unpacked": 554000
|
||||
"packed": 172000,
|
||||
"unpacked": 590000
|
||||
},
|
||||
"@hyperframes/producer": {
|
||||
"packed": 993551,
|
||||
|
||||
Reference in New Issue
Block a user