From ca91e800e2f22774bb4bed90b5b7f7f3cc0208b3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Miguel=20=C3=81ngel?= Date: Sat, 21 Nov 2026 00:30:03 +0000 Subject: [PATCH] fix(studio): a clip dropped on a sealed preview shows on the timeline (#8330) A reloaded film posts its clip list while it loads hidden, so the router, which only hears the live frame, drops it. A sealed frame then goes live with no way to read its manifest off the window, and the timeline keeps the old clips. The router now reads the clip list of a live frame it has not heard from: off the window, or over the editing port for a sealed frame. --- .../previewMessageRouter.manifest.test.ts | 39 +++++++ .../src/player/hooks/previewMessageRouter.ts | 52 ++++++--- ...useTimelinePlayer.reloadedTimeline.test.ts | 109 ++++++++++++++++++ 3 files changed, 183 insertions(+), 17 deletions(-) create mode 100644 packages/studio/src/player/hooks/useTimelinePlayer.reloadedTimeline.test.ts diff --git a/packages/studio/src/player/hooks/previewMessageRouter.manifest.test.ts b/packages/studio/src/player/hooks/previewMessageRouter.manifest.test.ts index fb826ff769..9f6438d5f6 100644 --- a/packages/studio/src/player/hooks/previewMessageRouter.manifest.test.ts +++ b/packages/studio/src/player/hooks/previewMessageRouter.manifest.test.ts @@ -66,3 +66,42 @@ describe("a state tick while the timeline is empty", () => { expect(processed).toHaveBeenCalledOnce(); }); }); + +it("asks a live opaque frame it has not heard from once, though its film has no clips", async () => { + usePlayerStore + .getState() + .setElements([{ id: "a", domId: "a", tag: "p", start: 0, duration: 2, track: 0 }]); + const frame: Record = {}; + const iframe = detachedFakeIframe(frame); + Object.defineProperty(frame, "document", { + get: () => { + throw new DOMException("blocked", "SecurityError"); + }, + }); + const asked = vi.fn(() => ({ clipManifest: { clips: [], durationInFrames: 60, scenes: [] } })); + closers.push(serveEditingRequests(frame, asked)); + const processed = vi.fn(); + const handle = createPreviewMessageHandler({ + iframeRef: { current: iframe }, + processTimelineMessageRef: { current: processed }, + enrichMissingCompositionsRef: { current: vi.fn() }, + lastTimelineMessageRef: { current: Date.now() }, + getAdapter: () => null, + syncTimelineElements: vi.fn(), + }); + const tick = () => + handle( + new MessageEvent("message", { + source: frame as unknown as Window, + origin: window.location.origin, + data: { source: "hf-preview", type: "state", isPlaying: false }, + }), + ); + tick(); + await vi.waitFor(() => expect(asked).toHaveBeenCalledOnce()); + await new Promise((resolve) => setTimeout(resolve, 20)); + tick(); + await new Promise((resolve) => setTimeout(resolve, 20)); + expect(asked).toHaveBeenCalledOnce(); + expect(processed).not.toHaveBeenCalled(); +}); diff --git a/packages/studio/src/player/hooks/previewMessageRouter.ts b/packages/studio/src/player/hooks/previewMessageRouter.ts index 3f8ce1ebc2..0522562486 100644 --- a/packages/studio/src/player/hooks/previewMessageRouter.ts +++ b/packages/studio/src/player/hooks/previewMessageRouter.ts @@ -86,53 +86,69 @@ function enrichDue(lastTimelineMessage: number, enriched: { at: number }): boole return true; } -/** Asks the runtime for its clip manifest, one request at a time, while the store has no elements. */ +interface Recovery { + asking: boolean; + heard: WeakSet; +} + +const timelineOwed = (iframe: HTMLIFrameElement | null, recovery: Recovery) => + usePlayerStore.getState().elements.length === 0 || + (iframe !== null && !recovery.heard.has(iframe)); + +function takeManifest( + deps: PreviewMessageRouterDeps, + iframe: HTMLIFrameElement, + recovery: Recovery, + manifest: ClipManifestMessage, +): void { + recovery.heard.add(iframe); + if (manifest.clips.length > 0) deps.processTimelineMessageRef.current(manifest); +} + +/** Asks the runtime for its clip manifest, one request at a time, while the frame still owes it. */ function recoverClipManifest( deps: PreviewMessageRouterDeps, iframe: HTMLIFrameElement, - recovery: { asking: boolean }, + recovery: Recovery, ): void { if (recovery.asking) return; recovery.asking = true; previewClipManifest(iframe) .then((manifest) => { const stillWanted = - usePlayerStore.getState().elements.length === 0 && + timelineOwed(iframe, recovery) && deps.iframeRef.current === iframe && !hasTimelinePerformanceFixtureLease(); - if (manifest && manifest.clips.length > 0 && stillWanted) - deps.processTimelineMessageRef.current(manifest); + if (manifest && stillWanted) takeManifest(deps, iframe, recovery, manifest); }) .catch(() => {}) .finally(() => (recovery.asking = false)); } -function recoverEmptyTimeline( +/** A reloaded frame posts its clip list while hidden, before it is the frame this router hears: read it once live. */ +function recoverTimeline( deps: PreviewMessageRouterDeps, iframe: HTMLIFrameElement | null, - recovery: { asking: boolean }, + recovery: Recovery, ): void { if (iframe && previewFrameOpaque(iframe)) return recoverClipManifest(deps, iframe, recovery); const manifest = (iframe?.contentWindow as IframeWindow | null)?.__clipManifest; - if (manifest && manifest.clips.length > 0) { - deps.processTimelineMessageRef.current(manifest); - } + if (iframe && manifest) takeManifest(deps, iframe, recovery, manifest); } /** - * A `state` tick doubles as a recovery hook: if the store still has no - * elements, read the manifest straight off the iframe, and if no `timeline` + * A `state` tick doubles as a recovery hook: if the live frame still owes its + * clip list (timelineOwed), read its manifest, and if no `timeline` * message has arrived recently, re-run enrichment (at most every 500 ms: it queries the whole document). */ function handleStateMessage( deps: PreviewMessageRouterDeps, iframe: HTMLIFrameElement | null, playingHoldsClipListPosts: boolean, - enriched: { at: number; asking: boolean }, + enriched: Recovery & { at: number }, ): void { try { - if (usePlayerStore.getState().elements.length === 0) - recoverEmptyTimeline(deps, iframe, enriched); + if (timelineOwed(iframe, enriched)) recoverTimeline(deps, iframe, enriched); if (!playingHoldsClipListPosts && enrichDue(deps.lastTimelineMessageRef.current, enriched)) { deps.enrichMissingCompositionsRef.current(); } @@ -148,8 +164,10 @@ function handleTimelineMessage( deps: PreviewMessageRouterDeps, iframe: HTMLIFrameElement | null, data: ClipManifestMessage, + recovery: Recovery, ): void { deps.lastTimelineMessageRef.current = Date.now(); + if (iframe) recovery.heard.add(iframe); deps.processTimelineMessageRef.current(data); deps.enrichMissingCompositionsRef.current(); if (usePlayerStore.getState().elements.length > 0) return; @@ -188,7 +206,7 @@ function applyStoreReport(data: PreviewMessage): boolean { export function createPreviewMessageHandler( deps: PreviewMessageRouterDeps, ): (e: MessageEvent) => void { - const enriched = { at: 0, asking: false }; + const enriched = { at: 0, asking: false, heard: new WeakSet() }; return (e: MessageEvent) => { const iframe = deps.iframeRef.current; const data = acceptedPreviewMessage(e, iframe); @@ -202,7 +220,7 @@ export function createPreviewMessageHandler( return; } if (data.type === "timeline" && Array.isArray(data.clips)) { - handleTimelineMessage(deps, iframe, data as unknown as ClipManifestMessage); + handleTimelineMessage(deps, iframe, data as unknown as ClipManifestMessage, enriched); } }; } diff --git a/packages/studio/src/player/hooks/useTimelinePlayer.reloadedTimeline.test.ts b/packages/studio/src/player/hooks/useTimelinePlayer.reloadedTimeline.test.ts new file mode 100644 index 0000000000..7dd6c14583 --- /dev/null +++ b/packages/studio/src/player/hooks/useTimelinePlayer.reloadedTimeline.test.ts @@ -0,0 +1,109 @@ +// @vitest-environment happy-dom +import { act } from "react"; +import { afterEach, expect, it, vi } from "vitest"; +import { usePlayerStore } from "../store/playerStore"; +import { + detachedFakeIframe, + makeAdapterWindow, + makeFakeIframe, + renderTimelinePlayerHarness, + resetPlayerStore, + serveEditingRequests, +} from "./timelinePlayerTestHarness"; + +globalThis.IS_REACT_ACT_ENVIRONMENT = true; + +const closers: Array<() => void> = []; +afterEach(() => { + closers.splice(0).forEach((close) => close()); + document.body.innerHTML = ""; + resetPlayerStore(); +}); + +const FILM = `

`; +const clip = (id: string, tagName: string, track: number) => ({ + id, + label: id, + start: 0, + duration: 2, + track, + kind: "element", + tagName, +}); +const RELOADED = { + source: "hf-preview", + type: "timeline", + durationInFrames: 60, + clips: [clip("a", "p", 0), clip("dropped", "video", 1)], +}; + +/** A reloaded film whose runtime holds RELOADED: on its window, and over its editing port once sealed. */ +function reloadedFilm() { + const { win } = makeAdapterWindow({ duration: 2 }); + const frame = win as unknown as Record; + const iframe = detachedFakeIframe(frame); + iframe.contentDocument!.body.innerHTML = FILM; + frame.__clipManifest = RELOADED; + const markup = { + html: `${FILM}`, + baseURI: "http://localhost/", + }; + closers.push( + serveEditingRequests(frame, (kind) => + kind === "runtime-snapshot" ? { clipManifest: RELOADED, clipParents: [] } : markup, + ), + ); + // A cross-origin window: reading its document or globals throws. + const seal = () => { + for (const key of ["document", "__clipManifest"]) + Object.defineProperty(frame, key, { + get: () => { + throw new DOMException("blocked", "SecurityError"); + }, + }); + }; + return { frame, iframe, seal }; +} + +it.each(["scriptable", "sealed"] as const)( + "a %s preview reloaded after a drop puts the dropped clip on the timeline", + async (mode) => { + const { getApi, root } = renderTimelinePlayerHarness(); + const live = makeFakeIframe(makeAdapterWindow({ duration: 2 }).win); + act(() => { + getApi().iframeRef.current = live; + getApi().onIframeLoad(); + }); + act(() => + usePlayerStore + .getState() + .setElements([{ id: "a", domId: "a", tag: "p", start: 0, duration: 2, track: 0 }]), + ); + act(() => getApi().refreshPlayer()); + const gen = getApi().previewSlots.find((slot) => slot.role === "shadow")!.gen; + const shadow = reloadedFilm(); + act(() => { + getApi().setShadowIframeNode(shadow.iframe); + getApi().onShadowIframeLoad(gen); + }); + // Sealed after its load, as useTimelinePlayer.sealedGestureHold.test.ts seals its frame: the harness has no + // playback bridge for an opaque load. + if (mode === "sealed") shadow.seal(); + act(() => getApi().onShadowReadyChange(gen, true)); + expect(getApi().iframeRef.current).toBe(shadow.iframe); + // On screen, a film ticks its state; its clip list went out while it loaded hidden. + act(() => { + window.dispatchEvent( + new MessageEvent("message", { + source: shadow.frame as unknown as Window, + origin: window.location.origin, + data: { source: "hf-preview", type: "state", isPlaying: false }, + }), + ); + }); + await vi.waitFor(() => + expect(usePlayerStore.getState().elements.map((element) => element.id)).toContain("dropped"), + ); + act(() => root.unmount()); + }, +);