Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 19 additions & 0 deletions packages/core/src/runtime/init.swapScenes.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
14 changes: 10 additions & 4 deletions packages/core/src/runtime/init.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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]")) {
Expand Down Expand Up @@ -4178,7 +4185,7 @@ export function initSandboxRuntimeModular(): void {
}

lastTimeline = payload;
postRuntimeMessage({ ...payload, assetsReady: assetsSettled });
postRuntimeMessage(timelineMessage(payload));
if (!assetsReadyStarted) {
assetsReadyStarted = true;
settleFirstFrameCompositionReadiness(document, ({ timedOut }) => {
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -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({
Expand Down
1 change: 1 addition & 0 deletions packages/core/src/runtime/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 = {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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> = [];
Expand Down Expand Up @@ -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> = {};
Expand Down
3 changes: 3 additions & 0 deletions packages/studio/src/player/hooks/previewMessageRouter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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. */
Expand All @@ -41,6 +42,7 @@ interface PreviewMessage {
source?: string;
type?: string;
clips?: unknown;
sceneSwap?: unknown;
isPlaying?: unknown;
copies?: unknown;
health?: unknown;
Expand Down Expand Up @@ -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);
}
Expand Down
17 changes: 17 additions & 0 deletions packages/studio/src/player/sceneSwap.sealed.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ vi.mock("../utils/studioApiFetch", () => ({ studioApiFetch }));

import {
markScenesStale,
notePreviewSceneSwap,
onPreviewContentReplaced,
SCENE_SWAP_MS,
sceneSwapFor,
Expand Down Expand Up @@ -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",
Expand Down
9 changes: 8 additions & 1 deletion packages/studio/src/player/sceneSwap.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
Loading