fix(studio): a sealed preview that can't swap scenes reloads without asking first (#8544)

* fix(studio): a sealed preview that can't swap scenes reloads without asking first

* fix(studio): type the timeline message's scene-swap answer
This commit is contained in:
Miguel Ángel
2026-11-23 00:13:49 +00:00
committed by GitHub
parent e51b75208a
commit 35a0d81c2b
7 changed files with 77 additions and 5 deletions
@@ -222,6 +222,25 @@ describe("__hfSwapScenes", () => {
vi.restoreAllMocks();
});
// fails without the fix: no load said it, so a sealed Studio asked a swap of every one and waited for the refusal.
it("says in each timeline message whether this load can swap scenes", async () => {
const posted: Array<Record<string, unknown>> = [];
vi.spyOn(window.parent, "postMessage").mockImplementation((message: unknown) => {
if (typeof message === "object" && message !== null) posted.push(message as never);
});
const sceneSwap = () => posted.findLast((m) => m.type === "timeline")?.sceneSwap;
boot([A1, B], trackingRoot().root);
await tick();
expect(sceneSwap()).toBe(true);
window.__hfRuntimeTeardown?.();
posted.length = 0;
boot([A1, B], trackingRoot().root, (head) =>
head.replace(/<meta name="hf-scene-parts"[^>]*>/, ""),
);
await tick();
expect([sceneSwap(), typeof window.__hfSwapScenes]).toEqual([false, "undefined"]);
});
it("swaps only the edited scene: its DOM, style and timeline, keeping the time and the other scene", async () => {
const { root, children } = trackingRoot();
boot([A1, B], root);
+10 -4
View File
@@ -4106,6 +4106,13 @@ export function initSandboxRuntimeModular(): void {
let liveRootDurationOverrideSeconds = 0;
let lastPostedManifest = "";
let lastTimeline: ReturnType<typeof collectRuntimeTimelinePayload> | null = null;
// Only a preview served with a scene manifest can swap; elsewhere the caller reloads directly.
const scenesSwappable = readSceneParts(document) !== null;
const timelineMessage = (payload: ReturnType<typeof collectRuntimeTimelinePayload>) => ({
...payload,
assetsReady: assetsSettled,
sceneSwap: scenesSwappable,
});
const computeClipTreeSignature = (): string => {
let sig = "";
for (const el of document.querySelectorAll("[data-start]")) {
@@ -4178,7 +4185,7 @@ export function initSandboxRuntimeModular(): void {
}
lastTimeline = payload;
postRuntimeMessage({ ...payload, assetsReady: assetsSettled });
postRuntimeMessage(timelineMessage(payload));
if (!assetsReadyStarted) {
assetsReadyStarted = true;
settleFirstFrameCompositionReadiness(document, ({ timedOut }) => {
@@ -5040,8 +5047,7 @@ export function initSandboxRuntimeModular(): void {
await (windowWork ?? Promise.resolve());
}
};
// Only a preview served with a scene manifest can swap; elsewhere the caller reloads directly.
if (readSceneParts(document)) {
if (scenesSwappable) {
window.__hfSwapScenes = swapScenes;
window.__hfHoldScenes = holdScenes;
window.__hfParkedSceneMarkup = parkedSceneMarkup;
@@ -6887,7 +6893,7 @@ export function initSandboxRuntimeModular(): void {
},
onScrubAudio: scrubAudio.scrub,
onAnnounceTimeline: () => {
if (lastTimeline) postRuntimeMessage({ ...lastTimeline, assetsReady: assetsSettled });
if (lastTimeline) postRuntimeMessage(timelineMessage(lastTimeline));
},
onRequestPreviewFacts: () =>
postRuntimeMessage({
+1
View File
@@ -126,6 +126,7 @@ export type RuntimeTimelineMessage = RuntimeProtocolV1 & {
* the composition's assets have settled yet. Absent on older runtimes, whose
* parents must not wait for a message that never comes. */
assetsReady?: boolean;
sceneSwap?: boolean;
};
export type RuntimeDiagnosticMessage = {
@@ -5,6 +5,7 @@ import { usePlayerStore } from "../store/playerStore";
import { createTimelineElementFromManifestClip } from "../lib/timelineDOM";
import type { ClipManifestClip } from "../lib/playbackTypes";
import { createPreviewMessageHandler, type ClipManifestMessage } from "./previewMessageRouter";
import { sceneSwapFor } from "../sceneSwap";
import { detachedFakeIframe, serveEditingRequests } from "./timelinePlayerTestHarness";
const closers: Array<() => void> = [];
@@ -74,6 +75,24 @@ function handlerFor(frame: Record<string, unknown>, iframe: HTMLIFrameElement) {
);
}
describe("what a sealed frame's timeline message says about its load", () => {
it("takes each load's word on whether it can swap scenes", () => {
const frame: Record<string, unknown> = {};
const iframe = detachedFakeIframe(frame);
Object.defineProperty(frame, "document", {
get: () => {
throw new DOMException("blocked", "SecurityError");
},
});
const post = handlerFor(frame, iframe);
const timeline = { source: "hf-preview", type: "timeline", clips: [], durationInFrames: 300 };
post({ ...timeline, sceneSwap: false });
expect(sceneSwapFor(iframe)).toBeNull();
post({ ...timeline, sceneSwap: true });
expect(sceneSwapFor(iframe)).not.toBeNull();
});
});
describe("clip fields a preview frame sends", () => {
it("keeps only clips with numeric timing and a whole-number track from a timeline message", () => {
const frame: Record<string, unknown> = {};
@@ -25,6 +25,7 @@ import {
import { parseTimelineFromDOM } from "../lib/timelineDOM";
import { previewClipManifest, previewFrameOpaque } from "../lib/previewChannel";
import { wellFormedClips } from "../lib/manifestClips";
import { notePreviewSceneSwap } from "../sceneSwap";
import { frameOrigins } from "../lib/bridgePlayback";
/** What `processTimelineMessage` accepts — the clip-manifest postMessage. */
@@ -41,6 +42,7 @@ interface PreviewMessage {
source?: string;
type?: string;
clips?: unknown;
sceneSwap?: unknown;
isPlaying?: unknown;
copies?: unknown;
health?: unknown;
@@ -221,6 +223,7 @@ export function createPreviewMessageHandler(
return;
}
if (data.type === "timeline" && Array.isArray(data.clips)) {
if (iframe) notePreviewSceneSwap(iframe, data.sceneSwap);
const message = { ...data, clips: wellFormedClips(data.clips) };
handleTimelineMessage(deps, iframe, message as unknown as ClipManifestMessage, enriched);
}
@@ -14,6 +14,7 @@ vi.mock("../utils/studioApiFetch", () => ({ studioApiFetch }));
import {
markScenesStale,
notePreviewSceneSwap,
onPreviewContentReplaced,
SCENE_SWAP_MS,
sceneSwapFor,
@@ -61,6 +62,22 @@ it.each([
expect(replaced).not.toHaveBeenCalled();
});
// fails without the fix: Studio fetched the preview and asked anyway, and the refusal came 0.1-0.5 s later.
it("asks no swap of a sealed load that said it cannot swap, so the film reloads at once", () => {
const frame = document.createElement("iframe");
notePreviewSceneSwap(frame, false);
expect(sceneSwapFor(frame)).toBeNull();
expect(studioApiFetch).not.toHaveBeenCalled();
});
it("still asks a load that said it can swap, and an older runtime that said nothing", () => {
const [said, silent] = [document.createElement("iframe"), document.createElement("iframe")];
notePreviewSceneSwap(said, true);
notePreviewSceneSwap(silent, undefined);
expect(sceneSwapFor(said)).not.toBeNull();
expect(sceneSwapFor(silent)).not.toBeNull();
});
it("sends nothing when a newer edit superseded the fetched document", async () => {
await expect(sceneSwapFor(iframe)!("/preview/index.html", () => false)).rejects.toThrow(
"superseded",
+8 -1
View File
@@ -120,7 +120,14 @@ function reachableSwap(iframe: HTMLIFrameElement): ApplySwap | null {
return typeof swap === "function" ? (html, signal) => swap.call(win, html, signal) : null;
}
function sealedSwap(iframe: HTMLIFrameElement): ApplySwap {
const sceneSwapAnswers = new WeakMap<HTMLIFrameElement, boolean>();
export function notePreviewSceneSwap(iframe: HTMLIFrameElement, sceneSwap: unknown): void {
if (typeof sceneSwap === "boolean") sceneSwapAnswers.set(iframe, sceneSwap);
}
function sealedSwap(iframe: HTMLIFrameElement): ApplySwap | null {
if (sceneSwapAnswers.get(iframe) === false) return null;
return async (html) => {
const reply: unknown = await previewRequest(
iframe,