Skip to content

Write HTML. Render video. Built for agents.

perf(runtime): a paused preview stops burning CPU (#3845)

Miguel Ángeld4fba55a4ee6
diff --git a/packages/core/src/runtime/init.test.ts b/packages/core/src/runtime/init.test.ts
index f692409a47..2bb0a83fdc 100644
--- a/packages/core/src/runtime/init.test.ts
+++ b/packages/core/src/runtime/init.test.ts
@@ -3792,9 +3792,31 @@ describe("derived duration floor recomputation", () => {
Object.defineProperty(media, "duration", { value: seconds, configurable: true });
};
- /** Drive the transport for `frames` animation frames and report the duration it settled on. */
- const runFrames = (frames: number): number => {
- for (let frame = 0; frame < frames; frame += 1) raf.step(16);
+ /**
+ * Drive the transport for `frames` animation frames and report the duration
+ * it settled on.
+ *
+ * Awaits a microtask first, and that is load-bearing rather than cosmetic:
+ * the transport parks itself when the editor is paused and settled, and what
+ * un-parks it for a DOM edit is a MutationObserver callback, which a browser
+ * delivers in a microtask before the next frame. Stepping the frame queue
+ * synchronously after an edit models a world where a paint can happen
+ * between a mutation and its observer, which cannot occur.
+ */
+ /**
+ * `window.__timelines` is a plain object: no observer and no event can
+ * report a change to it, so a parked transport only finds one on its own
+ * slow timer. A test has to wait for that timer the way the editor does.
+ */
+ const waitForParkedRegistryPoll = (): Promise<void> =>
+ new Promise((resolve) => setTimeout(resolve, 200));
+
+ const runFrames = async (frames: number): Promise<number> => {
+ for (let frame = 0; frame < frames; frame += 1) {
+ await Promise.resolve();
+ raf.step(16);
+ }
+ await Promise.resolve();
return window.__player!.getDuration();
};
@@ -3826,6 +3848,7 @@ describe("derived duration floor recomputation", () => {
delete window.__player;
delete window.__playerReady;
delete window.__renderReady;
+ delete window.__HF_EXPORT_RENDER_SEEK_CONFIG;
vi.restoreAllMocks();
window.requestAnimationFrame = originalRequestAnimationFrame;
window.cancelAnimationFrame = originalCancelAnimationFrame;
@@ -3838,16 +3861,16 @@ describe("derived duration floor recomputation", () => {
* still degrades linearly in production. Quadrupling the frame count must
* not change the derivation count at all.
*/
- it("derives the duration floor a fixed number of times however many frames elapse", () => {
+ it("derives the duration floor a fixed number of times however many frames elapse", async () => {
mountComposition(`<video data-start="0"></video>`);
setNativeDuration(document.querySelector("video")!, 10);
initSandboxRuntimeModular();
const afterStartup = derivations;
- expect(runFrames(25)).toBe(10);
+ expect(await runFrames(25)).toBe(10);
const afterShortRun = derivations - afterStartup;
- expect(runFrames(100)).toBe(10);
+ expect(await runFrames(100)).toBe(10);
const afterLongRun = derivations - afterStartup - afterShortRun;
// Four times the frames, the same amount of work. Before the cache both
@@ -3856,11 +3879,11 @@ describe("derived duration floor recomputation", () => {
expect(afterShortRun).toBe(0);
});
- it("does not re-derive for a DOM change that cannot affect the duration", () => {
+ it("does not re-derive for a DOM change that cannot affect the duration", async () => {
mountComposition(`<video data-start="0"></video>`);
setNativeDuration(document.querySelector("video")!, 10);
initSandboxRuntimeModular();
- runFrames(2);
+ await runFrames(2);
const before = derivations;
// A class and an inline transform are what an animating composition
@@ -3869,7 +3892,7 @@ describe("derived duration floor recomputation", () => {
document.querySelector("video")!.classList.add("is-visible");
document.querySelector("video")!.setAttribute("style", "opacity: 0.5");
- expect(runFrames(5)).toBe(10);
+ expect(await runFrames(5)).toBe(10);
expect(derivations).toBe(before);
});
});
@@ -3882,61 +3905,61 @@ describe("derived duration floor recomputation", () => {
* real), and the event that always accompanies it in a browser makes it
* fresh (proving the invalidation is real).
*/
- it("serves a stale duration for a silent metadata change and a fresh one once the event fires", () => {
+ it("serves a stale duration for a silent metadata change and a fresh one once the event fires", async () => {
mountComposition(`<video data-start="0"></video>`);
const video = document.querySelector("video")!;
setNativeDuration(video, 10);
initSandboxRuntimeModular();
- expect(runFrames(2)).toBe(10);
+ expect(await runFrames(2)).toBe(10);
// Half one: the input changed, nothing signalled it, the cache answers.
setNativeDuration(video, 30);
- expect(runFrames(2)).toBe(10);
+ expect(await runFrames(2)).toBe(10);
// Half two: the signal a real browser emits alongside that change.
video.dispatchEvent(new Event("durationchange"));
- expect(runFrames(1)).toBe(30);
+ expect(await runFrames(1)).toBe(30);
});
- it("re-derives when el.load() resets duration to NaN", () => {
+ it("re-derives when el.load() resets duration to NaN", async () => {
mountComposition(`<video data-start="0"></video>`);
const video = document.querySelector("video")!;
setNativeDuration(video, 10);
initSandboxRuntimeModular();
- expect(runFrames(2)).toBe(10);
+ expect(await runFrames(2)).toBe(10);
// What load() does: duration back to NaN, announced by `emptied`.
setNativeDuration(video, Number.NaN);
- expect(runFrames(2)).toBe(10);
+ expect(await runFrames(2)).toBe(10);
video.dispatchEvent(new Event("emptied"));
const before = derivations;
- runFrames(1);
+ await runFrames(1);
expect(derivations).toBeGreaterThan(before);
});
- it("re-derives when a timing attribute is edited", () => {
+ it("re-derives when a timing attribute is edited", async () => {
mountComposition(`<video data-start="0"></video>`);
setNativeDuration(document.querySelector("video")!, 10);
initSandboxRuntimeModular();
- expect(runFrames(2)).toBe(10);
+ expect(await runFrames(2)).toBe(10);
document.querySelector("video")!.setAttribute("data-duration", "25");
- expect(runFrames(1)).toBe(25);
+ expect(await runFrames(1)).toBe(25);
});
- it("re-derives when a clip is moved later on the timeline", () => {
+ it("re-derives when a clip is moved later on the timeline", async () => {
mountComposition(`<video data-start="0" data-duration="10"></video>`);
initSandboxRuntimeModular();
- expect(runFrames(2)).toBe(10);
+ expect(await runFrames(2)).toBe(10);
document.querySelector("video")!.setAttribute("data-start", "5");
- expect(runFrames(1)).toBe(15);
+ expect(await runFrames(1)).toBe(15);
});
- it("re-derives when a timed element is added after init", () => {
+ it("re-derives when a timed element is added after init", async () => {
mountComposition(`<video data-start="0" data-duration="10"></video>`);
initSandboxRuntimeModular();
- expect(runFrames(2)).toBe(10);
+ expect(await runFrames(2)).toBe(10);
// Nested compositions mount asynchronously, well after init — this is
// the ordinary case, not an edge case.
@@ -3945,19 +3968,19 @@ describe("derived duration floor recomputation", () => {
late.setAttribute("data-duration", "5");
document.querySelector("[data-composition-id]")!.append(late);
- expect(runFrames(1)).toBe(25);
+ expect(await runFrames(1)).toBe(25);
});
- it("re-derives when a timed element is removed", () => {
+ it("re-derives when a timed element is removed", async () => {
mountComposition(
`<video data-start="0" data-duration="10"></video>` +
`<audio id="tail" data-start="20" data-duration="5"></audio>`,
);
initSandboxRuntimeModular();
- expect(runFrames(2)).toBe(25);
+ expect(await runFrames(2)).toBe(25);
document.querySelector("#tail")!.remove();
- expect(runFrames(1)).toBe(10);
+ expect(await runFrames(1)).toBe(10);
});
/**
@@ -3966,15 +3989,16 @@ describe("derived duration floor recomputation", () => {
* already registered, so the cache compares a signature of the registry on
* every read. Nothing else in the invalidation set could catch this.
*/
- it("re-derives when a nested composition's registered timeline grows", () => {
+ it("re-derives when a nested composition's registered timeline grows", async () => {
mountComposition(`<div data-composition-id="scene" data-start="0" data-duration="10"></div>`);
window.__timelines = { ...window.__timelines, scene: createMockTimeline(10) };
initSandboxRuntimeModular();
- expect(runFrames(2)).toBe(10);
+ expect(await runFrames(2)).toBe(10);
window.__timelines = { ...window.__timelines, scene: createMockTimeline(40) };
const before = derivations;
- runFrames(1);
+ await waitForParkedRegistryPoll();
+ await runFrames(1);
expect(derivations).toBeGreaterThan(before);
});
@@ -3985,14 +4009,14 @@ describe("derived duration floor recomputation", () => {
* — would be handed the pre-edit value if the cache waited for the
* callback. It drains the queue on read instead.
*/
- it("reflects an edit read back in the same synchronous block", () => {
+ it("reflects an edit read back in the same synchronous block", async () => {
mountComposition(`<video data-start="0" data-duration="10"></video>`);
initSandboxRuntimeModular();
- expect(runFrames(2)).toBe(10);
+ expect(await runFrames(2)).toBe(10);
// No await, no microtask checkpoint between the write and the read.
document.querySelector("video")!.setAttribute("data-duration", "42");
- expect(runFrames(1)).toBe(42);
+ expect(await runFrames(1)).toBe(42);
});
});
@@ -4002,20 +4026,27 @@ describe("derived duration floor recomputation", () => {
* the same silent metadata change that is deliberately served stale to the
* editor must be seen immediately here.
*/
- it("never serves a cached duration once render capture has started", () => {
+ it("never serves a cached duration once render capture has started", async () => {
+ // Constructed the way a real render is: the producer injects this config
+ // into the page before it drives a single frame, and it is what tells the
+ // runtime an export is in charge of the frame loop. Without it the
+ // runtime is in Studio-fallback territory (`playbackAdapter` also calls
+ // renderSeek), where the loop is free to park and there is no per-frame
+ // derivation to count.
+ window.__HF_EXPORT_RENDER_SEEK_CONFIG = { mode: "seek" };
mountComposition(`<video data-start="0"></video>`);
const video = document.querySelector("video")!;
setNativeDuration(video, 10);
initSandboxRuntimeModular();
- expect(runFrames(2)).toBe(10);
+ expect(await runFrames(2)).toBe(10);
window.__player!.renderSeek(0);
setNativeDuration(video, 30);
// No `durationchange` dispatched, and the editor would still answer 10.
- expect(runFrames(1)).toBe(30);
+ expect(await runFrames(1)).toBe(30);
const before = derivations;
- runFrames(3);
+ await runFrames(3);
expect(derivations).toBeGreaterThan(before);
});
});
diff --git a/packages/core/src/runtime/init.timingResolver.test.ts b/packages/core/src/runtime/init.timingResolver.test.ts
index 8393c28089..3745fc683e 100644
--- a/packages/core/src/runtime/init.timingResolver.test.ts
+++ b/packages/core/src/runtime/init.timingResolver.test.ts
@@ -47,6 +47,11 @@ describe("runtime timing resolver scoping", () => {
});
afterEach(() => {
+ // The runtime holds a timer while its transport is parked. Abandoning an
+ // initialised runtime leaves that timer to fire after the environment is
+ // torn down, which vitest reports as an unhandled error in whichever file
+ // happens to be running at the time.
+ window.__hfRuntimeTeardown?.();
window.requestAnimationFrame = originalRequestAnimationFrame;
window.cancelAnimationFrame = originalCancelAnimationFrame;
mediaSpy.beforeSync = null;
diff --git a/packages/core/src/runtime/init.ts b/packages/core/src/runtime/init.ts
index b6da6517a8..fec231c865 100644
--- a/packages/core/src/runtime/init.ts
+++ b/packages/core/src/runtime/init.ts
@@ -55,7 +55,7 @@ import {
} from "../audioGroups";
import { clampNativeMediaVolume } from "../audioGain";
import { quantizeTimeToFrame, snapTimeToFrameBoundary } from "../inline-scripts/parityContract";
-import { STUDIO_MANUAL_EDIT_GESTURE_ATTR } from "../editing/draftMarkers";
+import { createManualEditGestureWatch } from "./manualEditGestureWatch";
import type {
RuntimeDeterministicAdapter,
RuntimeJson,
@@ -64,7 +64,12 @@ import type {
} from "./types";
import type { PlayerAPI } from "../core.types";
import { swallow } from "./diagnostics";
-import { shouldAttemptPeriodicTimelineBind } from "./timelineRebindPolicy";
+import {
+ CHANGE_DRIVEN_SERVICE_MIN_INTERVAL_MS,
+ MEDIA_BIND_INTERVAL_FRAMES,
+ TIMELINE_POST_INTERVAL_FRAMES,
+ shouldAttemptPeriodicTimelineBind,
+} from "./timelineRebindPolicy";
import { installStudioCustomEase } from "./customEase";
import { parseStrictFiniteTimingNumber, resolveMediaElementDurationSeconds } from "./playbackRate";
import { MEDIA_START_BASIS_ATTR } from "../mediaTiming";
@@ -944,6 +949,24 @@ export function initSandboxRuntimeModular(): void {
// derived-duration cache is bypassed entirely once it is set.
let renderCaptureSeekStarted = false;
+ /**
+ * An export render is driving frames deterministically.
+ *
+ * The PAIR, never `renderCaptureSeekStarted` alone: `renderSeek` is also what
+ * Studio's own preview falls back to for overhanging timelines
+ * (`playbackAdapter.createStaticSeekPlaybackAdapter`), so the flag alone
+ * latches on the first Studio scrub of such a project and stays true for the
+ * rest of that session. `__HF_EXPORT_RENDER_SEEK_CONFIG` is injected by the
+ * producer's page script before a single frame is driven, so the pair is
+ * true for a real render and nothing else.
+ *
+ * Two callers rely on this being one decision with one owner: the async
+ * metadata rebind, which must not race the capture loop, and the transport
+ * loop, which must not park while a render is in charge of frames.
+ */
+ const isExportRenderDrivingFrames = (): boolean =>
+ renderCaptureSeekStarted && window.__HF_EXPORT_RENDER_SEEK_CONFIG != null;
+
// The media and authored-composition duration floors are derived from the
// DOM and the timeline registry — never from the playhead — so they change
// only when the composition changes. transportTick asks for them on EVERY
@@ -997,8 +1020,19 @@ export function initSandboxRuntimeModular(): void {
// second cache checking for itself would be told nothing changed.
let compositionTimingRevision = 0;
+ // Restarts the transport loop when it has parked itself (see
+ // `scheduleNextTransportFrame`). Held as a reassignable binding because the
+ // invalidation hooks below are installed long before the transport exists,
+ // and reaching forward into its `const` would be a temporal-dead-zone throw
+ // during init.
+ let wakeTransport: () => void = () => {};
+
const invalidateCompositionTimingCaches = () => {
compositionTimingRevision += 1;
+ // The same records that stale the duration caches are what a parked
+ // transport is waiting for: a timing attribute edited, a sub-composition
+ // mounted, media metadata arriving. One signal, two readers.
+ wakeTransport();
};
const deriveDurationFloors = (): DurationFloors => ({
@@ -1069,13 +1103,20 @@ export function initSandboxRuntimeModular(): void {
return compositionTimingRevision;
};
- const resolveDurationFloors = (): DurationFloors => {
+ /**
+ * `revision` lets a caller that has ALREADY read the revision in this task
+ * hand it over instead of paying for a second read. Reading is not free —
+ * it rebuilds a signature over every registered timeline — and it is also
+ * what DRAINS the observer, so a second read in the same task is told
+ * nothing changed and the work is pure duplication.
+ */
+ const resolveDurationFloors = (revision?: number): DurationFloors => {
// The render path never reads a cached floor. Capture depends on the exact
// duration and a frame that rendered against a wrong one cannot be
// recovered, so it pays the full derivation on every frame exactly as
// before — a correct slow render beats a fast wrong one.
if (renderCaptureSeekStarted) return deriveDurationFloors();
- const revision = readCompositionTimingRevision();
+ revision ??= readCompositionTimingRevision();
if (durationFloorsCache && durationFloorsRevision === revision) return durationFloorsCache;
durationFloorsRevision = revision;
durationFloorsCache = deriveDurationFloors();
@@ -1085,10 +1126,11 @@ export function initSandboxRuntimeModular(): void {
const getSafeTimelineDurationSeconds = (
timeline: RuntimeTimelineLike | null,
fallback = 0,
+ timingRevision?: number,
): number => {
const timelineDuration = getTimelineDurationSeconds(timeline);
const { media: mediaFloor, authoredComposition: authoredCompositionFloor } =
- resolveDurationFloors();
+ resolveDurationFloors(timingRevision);
// Deliberately NOT cached: adapters infer their duration from live
// animation objects (CSS/WAAPI/Lottie), which can change without any DOM
// mutation or media event to observe. It is also a short loop over the
@@ -2006,12 +2048,11 @@ export function initSandboxRuntimeModular(): void {
// capture starts, so once frames are being driven there is nothing left
// for this self-correction to usefully do.
//
- // renderSeek is also the entrypoint Studio's own preview iframe falls
- // back to for overhanging timelines (useTimelinePlayer), so gate on
- // both signals — renderCaptureSeekStarted alone would silently disable
- // this self-correction for a live Studio scrub too, where duration
- // hasn't been pre-resolved by a probe stage and still needs it.
- if (renderCaptureSeekStarted && window.__HF_EXPORT_RENDER_SEEK_CONFIG) return;
+ // Gated on the pair rather than renderCaptureSeekStarted alone, because
+ // the flag alone would silently disable this self-correction for a live
+ // Studio scrub too, where duration hasn't been pre-resolved by a probe
+ // stage and still needs it. See isExportRenderDrivingFrames.
+ if (isExportRenderDrivingFrames()) return;
const resolution = resolveRootTimelineFromDocument();
if (!resolution.timeline) return;
const hasResolvedMediaFloor = isUsableTimelineDuration(
@@ -2532,6 +2573,11 @@ export function initSandboxRuntimeModular(): void {
};
const postState = (force: boolean) => {
+ // Every transport mutation — play, pause, seek, renderSeek, a control-bridge
+ // command, the player's own state posts — ends in a forced post. That makes
+ // this the one place a parked transport needs to hear about, instead of a
+ // wake call bolted onto each mutator (and forgotten on the next one).
+ if (force) wakeTransport();
const frame = Math.max(0, Math.round((state.currentTime || 0) * state.canonicalFps));
const now = Date.now();
const shouldPost =
@@ -3124,6 +3170,14 @@ export function initSandboxRuntimeModular(): void {
let lastTransportSeekTime = Number.NaN;
let lastTransportSeekTimeline: RuntimeTimelineLike | null = null;
let pausedSeekDeferredByManualGesture = false;
+ // Set while the transport is parked (see scheduleNextTransportFrame).
+ let transportParkTimerId: number | null = null;
+ let transportWakeRequested = false;
+ let parkedPollWitness = "";
+ let lastSeenTimingRevision = -1;
+ /** A composition change has been seen and not yet carried to consumers. */
+ let compositionChangePending = false;
+ let lastChangeDrivenServiceAtMs = Number.NEGATIVE_INFINITY;
const seekRuntimeTimeline = (
timeline: RuntimeTimelineLike,
@@ -3329,33 +3383,185 @@ export function initSandboxRuntimeModular(): void {
// paused gesture the draft writer owns the element's transform, so the
// per-frame transport re-seek must yield to it (see transportTick).
//
- // The query is document-global (fine for today's single-composition Studio;
+ // The watch is document-global (fine for today's single-composition Studio;
// revisit if a multi-composition editor needs to scope this to one root).
- // It only runs while the clock is paused — transportTick short-circuits on
- // isPlaying() — so it is off the playback hot path; one attribute selector
- // per paused frame is negligible.
+ // It used to be a `document.querySelector` on every paused frame, described
+ // here as negligible; measured, it was 1.8 ms/s on a 1689-element project and
+ // 3.0 ms/s — 6.4% of the whole paused main-thread budget — on a media-heavy
+ // one. An attribute-filtered observer answers the same question in O(edits),
+ // and its change callback is also what un-parks the transport when a drag
+ // starts or ends.
+ const manualEditGestureWatch = createManualEditGestureWatch(document, () => {
+ wakeTransport();
+ });
+ runtimeCleanupCallbacks.push(() => manualEditGestureWatch.disconnect());
const hasActiveStudioManualEditGesture = (): boolean => {
try {
- return document.querySelector(`[${STUDIO_MANUAL_EDIT_GESTURE_ATTR}]`) != null;
+ return manualEditGestureWatch.isActive();
} catch {
return false;
}
};
+ /**
+ * Nothing a tick would discover can change without one of the wake signals
+ * firing, so the loop may stand down until one does.
+ */
+ const canParkTransport = (): boolean =>
+ !clock.isPlaying() &&
+ !isExportRenderDrivingFrames() &&
+ // Without MutationObserver nothing can PUSH a DOM change: neither the
+ // composition-timing watcher nor the gesture watch attaches, and both fall
+ // back to answering from the document only when asked. Looking every frame
+ // is then the only correct behaviour, so such a host keeps the loop it had.
+ //
+ // Unreachable today, and the reason is worth recording rather than
+ // trusting: `createColorGradingRuntime` constructs a MutationObserver
+ // unconditionally earlier in this same init (colorGrading.ts, the
+ // `document.body` branch), so a host without one never gets as far as a
+ // running transport. This stays as the explicit statement of the
+ // invariant, one boolean, for the day that guard is added there.
+ manualEditGestureWatch.observing &&
+ // A drop/cancel owes one reconciling seek that has not happened yet.
+ !pausedSeekDeferredByManualGesture &&
+ // A composition change is owed a manifest post that the rate limit has
+ // deferred. Parking here would strand it until the next unrelated change,
+ // so the loop stays awake — for at most one cadence interval — until the
+ // post goes out.
+ !compositionChangePending &&
+ // The playhead and the bound timeline are both where the last seek left
+ // them, so re-seeking on the next frame would render the same frame again.
+ state.currentTime === lastTransportSeekTime &&
+ state.capturedTimeline === lastTransportSeekTimeline;
+
+ /**
+ * The parked loop. Two jobs the 60 Hz loop used to do implicitly:
+ *
+ * 1. Keep the control bridge's paused heartbeat on its documented interval
+ * (`state.bridgeMaxPostIntervalMs`) so a paused timeline still confirms
+ * its position to any listener.
+ * 2. Re-read everything nothing can push (`readParkedPollWitness`). Polling
+ * that 12 times a second instead of 60 is the whole reason the safety net
+ * exists.
+ */
+ /**
+ * Everything a parked transport still has to LOOK at, because no observer
+ * and no event can tell it.
+ *
+ * Two inputs qualify, and both are documented at their source:
+ * - the timeline registry, a plain object a composition script writes into
+ * (see `readCompositionTimingRevision`); and
+ * - the adapter duration floor, which adapters infer from live animation
+ * objects — CSS, WAAPI, Lottie — that can lengthen with no DOM mutation
+ * and no media event (see the comment on `resolveAdapterDurationFloorSeconds`
+ * in `getSafeTimelineDurationSeconds`).
+ *
+ * Calling `readCompositionTimingRevision` here is also what DRAINS the
+ * mutation observer, so a record that arrived without its callback running
+ * is caught on this path too.
+ */
+ const readParkedPollWitness = (): string =>
+ `${readCompositionTimingRevision()}|${resolveAdapterDurationFloorSeconds() ?? ""}`;
+
+ const armParkTimer = () => {
+ transportParkTimerId = window.setTimeout(
+ parkedTransportHeartbeat,
+ state.bridgeMaxPostIntervalMs,
+ );
+ };
+
+ const parkedTransportHeartbeat = () => {
+ transportParkTimerId = null;
+ if (state.tornDown) return;
+ // The page can go away with the timer still armed — an embedder discarding
+ // the frame, or a test environment torn down around an abandoned runtime.
+ // Stop rather than re-arm: there is nothing left to report a state change
+ // to, and every read below would throw on a missing global.
+ if (typeof window === "undefined" || typeof document === "undefined") return;
+ if (readParkedPollWitness() !== parkedPollWitness) {
+ // Through wakeTransport, not straight to rAF: reading the witness can
+ // itself wake us (the registry compare bumps the revision, and that
+ // invalidation hook calls wakeTransport).
+ wakeTransport();
+ return;
+ }
+ postState(false);
+ armParkTimer();
+ };
+
+ const scheduleNextTransportFrame = () => {
+ state.transportRafId = null;
+ if (state.tornDown) return;
+ const woken = transportWakeRequested;
+ transportWakeRequested = false;
+ if (woken || !canParkTransport()) {
+ state.transportRafId = window.requestAnimationFrame(transportTick);
+ return;
+ }
+ // Read fresh rather than reusing the tick's own `timingRevision`: the tick
+ // may have run postTimeline, which stamps authored-timing attributes the
+ // observer watches. Parking on the pre-postTimeline revision would make
+ // the very first heartbeat see a change and wake for the loop's own writes.
+ parkedPollWitness = readParkedPollWitness();
+ armParkTimer();
+ };
+
+ wakeTransport = () => {
+ if (state.tornDown) return;
+ // Inside a tick the tail is the only scheduler; setting the flag there is
+ // what stops it parking on work it has just been told about.
+ transportWakeRequested = true;
+ if (inTransportTick || state.transportRafId != null) return;
+ if (transportParkTimerId != null) {
+ window.clearTimeout(transportParkTimerId);
+ transportParkTimerId = null;
+ }
+ transportWakeRequested = false;
+ state.transportRafId = window.requestAnimationFrame(transportTick);
+ };
+
const transportTick = () => {
if (state.tornDown || inTransportTick) return;
inTransportTick = true;
try {
- state.transportRafId = window.requestAnimationFrame(transportTick);
transportTickCount += 1;
- // Slower operations: timeline binding (~every 60 frames / ~1s at 60fps)
+ // The three periodic jobs below fire on a frame counter, which is only a
+ // proxy for "the document may have changed since last time". The counter
+ // stops advancing while the loop is parked, so on THAT path the question
+ // is asked directly: the composition timing revision moves on exactly the
+ // inputs these three derive from.
+ //
+ // Only on that path. While the clock is playing the counter advances at
+ // frame rate and is already a good cadence, and raising it is a real
+ // regression: postTimeline walks the whole document, so a composition
+ // that mutates the DOM every frame would turn one post per 20 frames into
+ // one per frame. And the change-driven path is rate-limited to the same
+ // posts-per-second the counter yields at 60 Hz, so no consumer ever sees
+ // a faster cadence than the frame counter alone produced.
+ const timingRevision = readCompositionTimingRevision();
+ if (timingRevision !== lastSeenTimingRevision) {
+ lastSeenTimingRevision = timingRevision;
+ compositionChangePending = true;
+ }
+ const nowMs = Date.now();
+ const changeDrivenService =
+ compositionChangePending &&
+ !clock.isPlaying() &&
+ nowMs - lastChangeDrivenServiceAtMs >= CHANGE_DRIVEN_SERVICE_MIN_INTERVAL_MS;
+ if (changeDrivenService) lastChangeDrivenServiceAtMs = nowMs;
+
+ // Slower operations: timeline binding (~every 60 frames / ~1s at 60fps).
+ // `compositionChanged` goes IN to the policy, never around it: the policy
+ // owns the hold that keeps an async rebind off the first two seconds of
+ // playback, and ORing past it removed that hold.
if (
shouldAttemptPeriodicTimelineBind({
tick: transportTickCount,
isPlaying: clock.isPlaying(),
hasCapturedTimeline: state.capturedTimeline != null,
currentTimeSeconds: clock.now(),
+ compositionChanged: changeDrivenService,
})
) {
const prevTimeline = state.capturedTimeline;
@@ -3366,15 +3572,26 @@ export function initSandboxRuntimeModular(): void {
if (state.capturedTimeline && state.capturedTimeline !== prevTimeline) {
pauseTimelineIfPossible(state.capturedTimeline);
}
- const dur = getSafeTimelineDurationSeconds(state.capturedTimeline, 0);
+ const dur = getSafeTimelineDurationSeconds(state.capturedTimeline, 0, timingRevision);
if (dur > 0) clock.setDuration(dur);
postTimeline();
}
}
- if (transportTickCount % 20 === 0) {
+ if (changeDrivenService || transportTickCount % TIMELINE_POST_INTERVAL_FRAMES === 0) {
+ // The manifest is what carries a composition change to its consumers,
+ // so posting it is what discharges the pending flag — whichever path
+ // got here. Clearing it when the change is merely SEEN would drop it
+ // whenever the rate limit deferred the post.
+ //
+ // And clearing it AFTER the post, not before: postTimeline walks author
+ // DOM and can throw. The tail scheduler runs in this tick's `finally`
+ // either way, so clearing first would let it see nothing owed and park
+ // with the change undelivered — permanently, until some unrelated
+ // change happens to wake the loop again.
postTimeline();
+ compositionChangePending = false;
}
- if (transportTickCount % 30 === 0) {
+ if (changeDrivenService || transportTickCount % MEDIA_BIND_INTERVAL_FRAMES === 0) {
bindMediaMetadataListeners();
}
@@ -3382,7 +3599,7 @@ export function initSandboxRuntimeModular(): void {
// rebinds, live data-duration edits). Never shrink while playing — transient
// short reads cause reachedEnd() → playhead jumps to end (#1636).
if (state.capturedTimeline) {
- const dur = getSafeTimelineDurationSeconds(state.capturedTimeline, 0);
+ const dur = getSafeTimelineDurationSeconds(state.capturedTimeline, 0, timingRevision);
if (dur > 0 && (!clock.isPlaying() || dur >= clock.getDuration())) {
clock.setDuration(dur);
}
@@ -3492,6 +3709,10 @@ export function initSandboxRuntimeModular(): void {
postState(false);
} finally {
inTransportTick = false;
+ // Re-arm here, not at the top: the reached-end branch returns early and
+ // must still schedule, and the decision to park can only be made once
+ // the tick has settled the playhead.
+ scheduleNextTransportFrame();
}
};
@@ -3783,6 +4004,10 @@ export function initSandboxRuntimeModular(): void {
window.cancelAnimationFrame(state.transportRafId);
state.transportRafId = null;
}
+ if (transportParkTimerId != null) {
+ window.clearTimeout(transportParkTimerId);
+ transportParkTimerId = null;
+ }
state.transportClock = null;
webAudio.destroy();
if (metadataRebindDebounceTimerId != null) {
diff --git a/packages/core/src/runtime/manualEditGestureWatch.test.ts b/packages/core/src/runtime/manualEditGestureWatch.test.ts
new file mode 100644
index 0000000000..37144e0808
--- /dev/null
+++ b/packages/core/src/runtime/manualEditGestureWatch.test.ts
@@ -0,0 +1,90 @@
+import { afterEach, describe, expect, it, vi } from "vitest";
+import { STUDIO_MANUAL_EDIT_GESTURE_ATTR } from "../editing/draftMarkers";
+import { createManualEditGestureWatch } from "./manualEditGestureWatch";
+
+const flush = () => new Promise<void>((resolve) => queueMicrotask(() => resolve()));
+
+describe("manual-edit gesture watch", () => {
+ afterEach(() => {
+ document.body.innerHTML = "";
+ vi.restoreAllMocks();
+ });
+
+ it("reports a gesture and calls back when the marker appears and clears", async () => {
+ document.body.innerHTML = `<div id="a"></div>`;
+ const changes: number[] = [];
+ const watch = createManualEditGestureWatch(document, () => changes.push(1));
+ try {
+ expect(watch.observing).toBe(true);
+ expect(watch.isActive()).toBe(false);
+
+ const el = document.getElementById("a")!;
+ el.setAttribute(STUDIO_MANUAL_EDIT_GESTURE_ATTR, "token");
+ // Correct within the task, before the observer's microtask has run —
+ // and reading it must not swallow the change notification, because that
+ // notification is what un-parks the transport.
+ expect(watch.isActive()).toBe(true);
+ expect(changes.length).toBeGreaterThan(0);
+ await flush();
+
+ el.removeAttribute(STUDIO_MANUAL_EDIT_GESTURE_ATTR);
+ expect(watch.isActive()).toBe(false);
+ } finally {
+ watch.disconnect();
+ }
+ });
+
+ it("stops reporting a gesture whose element was torn out mid-drag", async () => {
+ document.body.innerHTML = `<div id="a"></div>`;
+ const watch = createManualEditGestureWatch(document, () => {});
+ try {
+ const el = document.getElementById("a")!;
+ el.setAttribute(STUDIO_MANUAL_EDIT_GESTURE_ATTR, "token");
+ expect(watch.isActive()).toBe(true);
+ // A hot reload during a drag: the marked element can never clear itself.
+ el.remove();
+ await flush();
+ expect(watch.isActive()).toBe(false);
+ } finally {
+ watch.disconnect();
+ }
+ });
+
+ it("seeds from a marker that was already on the document when it attached", () => {
+ document.body.innerHTML = `<div id="a" ${STUDIO_MANUAL_EDIT_GESTURE_ATTR}="token"></div>`;
+ const watch = createManualEditGestureWatch(document, () => {});
+ try {
+ expect(watch.isActive()).toBe(true);
+ } finally {
+ watch.disconnect();
+ }
+ });
+
+ it("reports observing:false, and keeps answering, where MutationObserver is absent", () => {
+ document.body.innerHTML = `<div id="a" ${STUDIO_MANUAL_EDIT_GESTURE_ATTR}="token"></div>`;
+ // A document whose view has no MutationObserver. `observing` false is the
+ // contract a caller reads before deciding it may stop asking: on this path
+ // `onChange` never fires, so nothing can be woken by a gesture.
+ const viewless = {
+ documentElement: document.documentElement,
+ defaultView: { MutationObserver: undefined },
+ querySelector: (s: string) => document.querySelector(s),
+ querySelectorAll: (s: string) => document.querySelectorAll(s),
+ } as unknown as Document;
+ const realObserver = globalThis.MutationObserver;
+ // @ts-expect-error stripping the capability under test
+ delete globalThis.MutationObserver;
+ try {
+ const changes: number[] = [];
+ const watch = createManualEditGestureWatch(viewless, () => changes.push(1));
+ expect(watch.observing).toBe(false);
+ expect(watch.isActive()).toBe(true);
+ document.getElementById("a")!.removeAttribute(STUDIO_MANUAL_EDIT_GESTURE_ATTR);
+ expect(watch.isActive()).toBe(false);
+ expect(changes).toHaveLength(0);
+ watch.disconnect();
+ } finally {
+ globalThis.MutationObserver = realObserver;
+ }
+ });
+});
diff --git a/packages/core/src/runtime/manualEditGestureWatch.ts b/packages/core/src/runtime/manualEditGestureWatch.ts
new file mode 100644
index 0000000000..6455039df7
--- /dev/null
+++ b/packages/core/src/runtime/manualEditGestureWatch.ts
@@ -0,0 +1,106 @@
+import { STUDIO_MANUAL_EDIT_GESTURE_ATTR } from "../editing/draftMarkers";
+
+export interface ManualEditGestureWatch {
+ /** True while any element in the document carries the gesture marker. */
+ isActive: () => boolean;
+ /**
+ * True when an observer is attached and `onChange` will therefore fire.
+ * False on the fallback below, where the answer is only ever produced when
+ * somebody asks — a caller that would otherwise stop asking must keep
+ * asking instead.
+ */
+ observing: boolean;
+ disconnect: () => void;
+}
+
+const SELECTOR = `[${STUDIO_MANUAL_EDIT_GESTURE_ATTR}]`;
+
+/**
+ * Live answer to "is the Studio mid-drag", without a whole-document query per
+ * frame.
+ *
+ * The marker is one attribute on one element for the length of a drag, so the
+ * set of marked elements changes a handful of times per gesture and never
+ * during playback — but the transport asked the document for it on every
+ * paused frame, which measured 1.8 ms/s on a large project and 3.0 ms/s (6.4%
+ * of the whole paused main-thread budget) on a media-heavy one. An
+ * attribute-filtered MutationObserver answers the same question in O(edits).
+ *
+ * `onChange` fires whenever the marker set may have changed, which is also the
+ * signal a parked transport needs to start ticking again.
+ */
+export function createManualEditGestureWatch(
+ doc: Document,
+ onChange: () => void,
+): ManualEditGestureWatch {
+ const Observer = doc.defaultView?.MutationObserver ?? globalThis.MutationObserver;
+ if (!Observer || !doc.documentElement) {
+ // No observer to trust: keep answering from the document, as before.
+ return {
+ isActive: () => doc.querySelector(SELECTOR) != null,
+ // Nothing to push from: `onChange` is never called on this path, so a
+ // caller that parks on it would never be woken by a gesture.
+ observing: false,
+ disconnect: () => {},
+ };
+ }
+
+ // Seeded from the document because an element could already be marked when a
+ // runtime re-initialises over a live Studio session; the observer only ever
+ // reports changes after it attaches.
+ const marked = new Set<Element>(doc.querySelectorAll(SELECTOR));
+
+ const ingest = (records: MutationRecord[]): void => {
+ for (const record of records) {
+ const target = record.target;
+ if (!(target instanceof Element)) continue;
+ if (target.hasAttribute(STUDIO_MANUAL_EDIT_GESTURE_ATTR)) marked.add(target);
+ else marked.delete(target);
+ }
+ };
+
+ const notify = (records: MutationRecord[]): void => {
+ if (records.length === 0) return;
+ ingest(records);
+ onChange();
+ };
+
+ const observer = new Observer(notify);
+ observer.observe(doc.documentElement, {
+ subtree: true,
+ attributes: true,
+ attributeFilter: [STUDIO_MANUAL_EDIT_GESTURE_ATTR],
+ });
+
+ return {
+ observing: true,
+ isActive: () => {
+ // Records are delivered in a microtask, so a caller reading back in the
+ // same synchronous block as the gesture's own attribute write would
+ // otherwise be served the pre-write answer. Draining here makes the
+ // watch correct within a task, not just across tasks.
+ //
+ // Through `notify`, because taking records SUPPRESSES the observer's own
+ // callback for them. Defensive rather than a fix for a live bug: there
+ // is exactly one caller of `isActive` today (`transportTick`), and a
+ // tick is its own task, so the observer's microtask has already run and
+ // called `onChange` before any drain happens here. Adding a second
+ // caller that ran earlier in the task would silently eat that callback,
+ // and the callback is what un-parks the transport.
+ notify(observer.takeRecords());
+ for (const element of marked) {
+ if (element.isConnected && element.hasAttribute(STUDIO_MANUAL_EDIT_GESTURE_ATTR)) {
+ return true;
+ }
+ // A marked element torn out of the document (hot reload mid-drag) can
+ // never clear its own marker.
+ marked.delete(element);
+ }
+ return false;
+ },
+ disconnect: () => {
+ observer.disconnect();
+ marked.clear();
+ },
+ };
+}
diff --git a/packages/core/src/runtime/timelineRebindPolicy.ts b/packages/core/src/runtime/timelineRebindPolicy.ts
index c3380bb224..8753f7270e 100644
--- a/packages/core/src/runtime/timelineRebindPolicy.ts
+++ b/packages/core/src/runtime/timelineRebindPolicy.ts
@@ -1,22 +1,42 @@
export const TIMELINE_REBIND_INTERVAL_FRAMES = 60;
export const PLAY_REBIND_HOLD_SECONDS = 2;
+/** How often the transport re-posts the clip manifest, in animation frames. */
+export const TIMELINE_POST_INTERVAL_FRAMES = 20;
+/** How often the transport re-binds metadata listeners, in animation frames. */
+export const MEDIA_BIND_INTERVAL_FRAMES = 30;
+/**
+ * The floor the change-driven (parked) path holds itself to, so a consumer
+ * never sees the manifest arrive faster than the frame counter alone produced
+ * it: `TIMELINE_POST_INTERVAL_FRAMES` frames at a 60 Hz display.
+ */
+export const CHANGE_DRIVEN_SERVICE_MIN_INTERVAL_MS = (1000 * TIMELINE_POST_INTERVAL_FRAMES) / 60;
export function shouldAttemptPeriodicTimelineBind(input: {
tick: number;
isPlaying: boolean;
hasCapturedTimeline: boolean;
currentTimeSeconds: number;
+ /**
+ * The transport saw a composition change this tick and would like a rebind
+ * sooner than the frame counter allows. It is an INPUT to this policy, never
+ * a way around it: the play hold below still wins. A caller that ORs its own
+ * trigger in front of this function has removed the hold, which exists so an
+ * async rebind cannot race the first two seconds of playback.
+ */
+ compositionChanged?: boolean;
}): boolean {
+ // The hold is the outer rule and applies to every trigger.
if (
- !Number.isInteger(input.tick) ||
- input.tick <= 0 ||
- input.tick % TIMELINE_REBIND_INTERVAL_FRAMES !== 0
- ) {
- return false;
- }
- return !(
input.isPlaying &&
input.hasCapturedTimeline &&
input.currentTimeSeconds < PLAY_REBIND_HOLD_SECONDS
+ ) {
+ return false;
+ }
+ if (input.compositionChanged === true) return true;
+ return (
+ Number.isInteger(input.tick) &&
+ input.tick > 0 &&
+ input.tick % TIMELINE_REBIND_INTERVAL_FRAMES === 0
);
}
diff --git a/packages/core/src/runtime/transportPark.test.ts b/packages/core/src/runtime/transportPark.test.ts
new file mode 100644
index 0000000000..0bca9df1f1
--- /dev/null
+++ b/packages/core/src/runtime/transportPark.test.ts
@@ -0,0 +1,423 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { initSandboxRuntimeModular } from "./init";
+import { STUDIO_MANUAL_EDIT_GESTURE_ATTR } from "../editing/draftMarkers";
+import type { RuntimeTimelineLike } from "./types";
+
+/**
+ * The transport parks itself when the editor is paused and settled. Everything
+ * it used to discover by looking again on the next frame has to arrive by some
+ * other route, and each of those routes gets a test here — one per row of the
+ * enumeration in the PR body. A loop that stops noticing one of them is a
+ * correctness regression no performance test would catch.
+ */
+
+const PARK_HEARTBEAT_MS = 80; // state.bridgeMaxPostIntervalMs
+
+function createManualRaf() {
+ let now = 0;
+ let nextId = 0;
+ const callbacks = new Map<number, FrameRequestCallback>();
+ return {
+ requestAnimationFrame: (callback: FrameRequestCallback) => {
+ nextId += 1;
+ callbacks.set(nextId, callback);
+ return nextId;
+ },
+ cancelAnimationFrame: (id: number) => {
+ callbacks.delete(id);
+ },
+ pending: () => callbacks.size,
+ step: (milliseconds = 16) => {
+ now += milliseconds;
+ const batch = Array.from(callbacks.entries());
+ callbacks.clear();
+ for (const [, callback] of batch) callback(now);
+ },
+ now: () => now,
+ };
+}
+
+function createMockTimeline(duration: number): RuntimeTimelineLike {
+ const state = { time: 0, paused: true, duration };
+ return {
+ play: () => {
+ state.paused = false;
+ },
+ pause: () => {
+ state.paused = true;
+ },
+ seek: (time?: number) => {
+ if (time !== undefined) state.time = time;
+ return state.time;
+ },
+ totalTime: (time?: number) => {
+ if (time !== undefined) state.time = time;
+ return state.time;
+ },
+ time: () => state.time,
+ duration: () => state.duration,
+ add: () => {},
+ paused: (value?: boolean) => {
+ if (typeof value === "boolean") state.paused = value;
+ return state.paused;
+ },
+ timeScale: () => {},
+ set: () => {},
+ getChildren: () => [],
+ };
+}
+
+/** MutationObserver records land in a microtask; nothing observes them sooner. */
+const flushObservers = () => new Promise<void>((resolve) => queueMicrotask(() => resolve()));
+
+describe("parked transport loop", () => {
+ const originalRaf = window.requestAnimationFrame;
+ const originalCancelRaf = window.cancelAnimationFrame;
+ let raf: ReturnType<typeof createManualRaf>;
+ let posted: Array<Record<string, unknown>>;
+
+ const mount = (bodyHtml = "") => {
+ document.body.innerHTML = `<div id="root" data-composition-id="main" data-root="true" data-start="0" data-duration="5">${bodyHtml}</div>`;
+ window.__timelines = { main: createMockTimeline(5) };
+ };
+
+ /** Run frames until nothing asks for another one. */
+ const settle = (maxFrames = 200): number => {
+ let frames = 0;
+ while (raf.pending() > 0 && frames < maxFrames) {
+ raf.step();
+ frames += 1;
+ }
+ return frames;
+ };
+
+ /**
+ * Park the transport AND drain init's own one-shot timers, several of which
+ * post state and would otherwise be mistaken for a heartbeat. Leaves exactly
+ * one timer pending: the parked heartbeat.
+ */
+ const quiesce = (): void => {
+ settle();
+ // Up to ~400 ms of 1 ms steps: the transport holds a deferred manifest
+ // post for one cadence interval before it may park.
+ for (let i = 0; i < 400; i += 1) {
+ if (raf.pending() === 0 && vi.getTimerCount() <= 1) return;
+ vi.advanceTimersByTime(1);
+ settle();
+ }
+ throw new Error(
+ `transport never quiesced (raf ${raf.pending()}, timers ${vi.getTimerCount()})`,
+ );
+ };
+
+ beforeEach(() => {
+ vi.useFakeTimers({
+ toFake: ["setTimeout", "clearTimeout", "setInterval", "clearInterval", "Date"],
+ });
+ document.body.innerHTML = "";
+ (globalThis as typeof globalThis & { CSS?: { escape?: (v: string) => string } }).CSS ??= {};
+ globalThis.CSS.escape ??= (value: string) => value;
+ raf = createManualRaf();
+ window.requestAnimationFrame = raf.requestAnimationFrame as typeof window.requestAnimationFrame;
+ window.cancelAnimationFrame = raf.cancelAnimationFrame as typeof window.cancelAnimationFrame;
+ posted = [];
+ vi.spyOn(window.parent, "postMessage").mockImplementation((message: unknown) => {
+ posted.push(message as Record<string, unknown>);
+ });
+ window.__timelines = {};
+ });
+
+ afterEach(() => {
+ window.__hfRuntimeTeardown?.();
+ document.body.innerHTML = "";
+ window.__timelines = {} as Record<string, RuntimeTimelineLike>;
+ delete window.__player;
+ delete window.__playerReady;
+ delete window.__HF_EXPORT_RENDER_SEEK_CONFIG;
+ delete (window as { __hfLottie?: unknown }).__hfLottie;
+ vi.restoreAllMocks();
+ vi.useRealTimers();
+ window.requestAnimationFrame = originalRaf;
+ window.cancelAnimationFrame = originalCancelRaf;
+ });
+
+ it("stops asking for animation frames once paused and settled", () => {
+ mount();
+ initSandboxRuntimeModular();
+ quiesce();
+ expect(raf.pending()).toBe(0);
+ // Exactly one thing still scheduled: the parked heartbeat.
+ expect(vi.getTimerCount()).toBe(1);
+ });
+
+ it("keeps asking for animation frames while playing", () => {
+ mount();
+ initSandboxRuntimeModular();
+ quiesce();
+ window.__player!.play();
+ // Every frame during playback re-arms: the loop must never park mid-play.
+ for (let i = 0; i < 10; i += 1) {
+ expect(raf.pending()).toBeGreaterThan(0);
+ raf.step();
+ }
+ expect(raf.pending()).toBeGreaterThan(0);
+ });
+
+ it("posts the paused bridge heartbeat on its documented interval while parked", () => {
+ mount();
+ initSandboxRuntimeModular();
+ quiesce();
+ const before = posted.filter((m) => m["type"] === "state").length;
+ for (let beat = 0; beat < 3; beat += 1) vi.advanceTimersByTime(PARK_HEARTBEAT_MS);
+ const after = posted.filter((m) => m["type"] === "state").length;
+ expect(after - before).toBe(3);
+ // Still parked: the heartbeat is a timer, not a frame.
+ expect(raf.pending()).toBe(0);
+ });
+
+ it("delivers a live data-duration edit while parked", async () => {
+ mount();
+ initSandboxRuntimeModular();
+ quiesce();
+
+ window.__timelines!["main"] = createMockTimeline(9);
+ document.getElementById("root")!.setAttribute("data-duration", "9");
+ await flushObservers();
+
+ settle();
+ expect(window.__player!.getDuration()).toBeCloseTo(9, 3);
+ });
+
+ it("delivers a timeline registered into window.__timelines, which no observer can see", () => {
+ mount();
+ window.__timelines = {};
+ initSandboxRuntimeModular();
+ document.getElementById("root")!.removeAttribute("data-duration");
+ quiesce();
+ expect(window.__player!.getDuration()).not.toBeCloseTo(12, 3);
+
+ // No DOM mutation and no event: the registry is a plain object. Only the
+ // parked heartbeat's signature re-read can find this.
+ window.__timelines!["main"] = createMockTimeline(12);
+ vi.advanceTimersByTime(PARK_HEARTBEAT_MS);
+ settle();
+ expect(window.__player!.getDuration()).toBeCloseTo(12, 3);
+ });
+
+ it("delivers a timed element mounted after the loop parked", async () => {
+ mount();
+ initSandboxRuntimeModular();
+ quiesce();
+ const manifestBefore = window.__clipManifest?.clips.length ?? 0;
+
+ const late = document.createElement("div");
+ late.id = "late-clip";
+ late.setAttribute("data-start", "1");
+ late.setAttribute("data-duration", "2");
+ document.getElementById("root")!.appendChild(late);
+ await flushObservers();
+
+ settle();
+ expect(window.__clipManifest!.clips.length).toBeGreaterThan(manifestBefore);
+ expect(window.__clipManifest!.clips.some((clip) => clip.id === "late-clip")).toBe(true);
+ });
+
+ it("delivers media metadata that arrives after the loop parked", async () => {
+ mount(`<video id="v" data-start="0" src="a.mp4"></video>`);
+ initSandboxRuntimeModular();
+ quiesce();
+
+ const video = document.getElementById("v") as HTMLVideoElement;
+ Object.defineProperty(video, "duration", { value: 30, configurable: true });
+ // `durationchange` is an event, not a DOM mutation: this is the only route.
+ video.dispatchEvent(new Event("durationchange"));
+ await flushObservers();
+
+ settle();
+ expect(window.__player!.getDuration()).toBeGreaterThanOrEqual(30);
+ });
+
+ it("delivers the start of a Studio manual-edit gesture while parked", async () => {
+ mount(`<div id="c" data-start="0" data-duration="2"></div>`);
+ initSandboxRuntimeModular();
+ quiesce();
+ expect(raf.pending()).toBe(0);
+
+ document.getElementById("c")!.setAttribute(STUDIO_MANUAL_EDIT_GESTURE_ATTR, "token-1");
+ await flushObservers();
+ expect(raf.pending()).toBeGreaterThan(0);
+ });
+
+ it("runs the reconciling seek the frame a manual-edit gesture ends", async () => {
+ mount(`<div id="c" data-start="0" data-duration="2"></div>`);
+ initSandboxRuntimeModular();
+ quiesce();
+
+ const target = document.getElementById("c")!;
+ target.setAttribute(STUDIO_MANUAL_EDIT_GESTURE_ATTR, "token-1");
+ await flushObservers();
+ raf.step();
+ // A gesture owns the paused frame: the loop stays awake and defers the seek.
+ expect(raf.pending()).toBe(1);
+
+ const timeline = window.__timelines!["main"] as RuntimeTimelineLike;
+ const seeks: number[] = [];
+ const originalTotalTime = timeline.totalTime!.bind(timeline);
+ timeline.totalTime = (time?: number, suppress?: boolean) => {
+ if (time !== undefined) seeks.push(time);
+ return originalTotalTime(time, suppress);
+ };
+
+ target.removeAttribute(STUDIO_MANUAL_EDIT_GESTURE_ATTR);
+ await flushObservers();
+ raf.step();
+ expect(seeks.length).toBeGreaterThan(0);
+ });
+
+ it("wakes on an explicit seek from the control surface", () => {
+ mount();
+ initSandboxRuntimeModular();
+ quiesce();
+ expect(raf.pending()).toBe(0);
+
+ window.__player!.seek(1);
+ expect(raf.pending()).toBeGreaterThan(0);
+ settle();
+ expect(window.__player!.getTime()).toBeCloseTo(1, 3);
+ });
+
+ it("never parks while an export render is driving frames", () => {
+ window.__HF_EXPORT_RENDER_SEEK_CONFIG = { mode: "seek" };
+ mount();
+ initSandboxRuntimeModular();
+ quiesce();
+
+ window.__player!.renderSeek(1);
+ // The render path must keep the exact scheduling it had before: a frame is
+ // always in flight, whatever the playhead is doing.
+ for (let i = 0; i < 10; i += 1) {
+ expect(raf.pending()).toBeGreaterThan(0);
+ raf.step();
+ }
+ });
+
+ it("still parks after Studio's own renderSeek fallback, which is not a render", () => {
+ // `playbackAdapter` drives an overhanging-timeline preview through
+ // renderSeek. Latching on that alone would leave the loop unparked for the
+ // whole session — the export config is what separates the two.
+ expect(window.__HF_EXPORT_RENDER_SEEK_CONFIG).toBeUndefined();
+ mount();
+ initSandboxRuntimeModular();
+ quiesce();
+
+ window.__player!.renderSeek(1);
+ quiesce();
+ expect(raf.pending()).toBe(0);
+ expect(window.__player!.getTime()).toBeCloseTo(1, 3);
+ });
+
+ it("stops both the frame loop and the parked timer on teardown", () => {
+ mount();
+ initSandboxRuntimeModular();
+ quiesce();
+
+ window.__hfRuntimeTeardown?.();
+ posted.length = 0;
+ // The count, not just the silence: a heartbeat that is still armed but
+ // returns early on `tornDown` posts nothing either, so counting posts
+ // alone passes with the clearTimeout deleted.
+ expect(vi.getTimerCount()).toBe(0);
+ vi.advanceTimersByTime(PARK_HEARTBEAT_MS * 5);
+ expect(raf.pending()).toBe(0);
+ expect(posted.filter((m) => m["type"] === "state")).toHaveLength(0);
+ });
+
+ it("keeps the manifest on its frame cadence while playing, whatever the DOM does", () => {
+ mount();
+ initSandboxRuntimeModular();
+ quiesce();
+ window.__player!.play();
+ // Two seconds in, so the rebind policy's play hold is not what is doing
+ // the work — this has to hold for the rest of playback too.
+ for (let i = 0; i < 130; i += 1) raf.step();
+
+ const root = document.getElementById("root")!;
+ const before = posted.filter((m) => m["type"] === "timeline").length;
+ for (let frame = 0; frame < 30; frame += 1) {
+ // A composition that appends a node every frame. The manifest is a full
+ // document walk; posting it per frame is the regression this guards.
+ const node = document.createElement("div");
+ node.setAttribute("data-start", String(frame));
+ node.setAttribute("data-duration", "1");
+ root.appendChild(node);
+ raf.step();
+ }
+ const posts = posted.filter((m) => m["type"] === "timeline").length - before;
+ // Main's cadence over 30 frames is one post per 20 frames, so at most two.
+ expect(posts).toBeLessThanOrEqual(2);
+ });
+
+ it("does not park when the manifest post throws with a change still pending", async () => {
+ mount();
+ initSandboxRuntimeModular();
+ quiesce();
+
+ // postTimeline walks author DOM, which can throw. Fail it exactly once.
+ const NODE_SELECTOR =
+ "[data-start], [data-track-index], [data-composition-id], video, audio, img";
+ const realQueryAll = Document.prototype.querySelectorAll;
+ let failuresLeft = 1;
+ vi.spyOn(Document.prototype, "querySelectorAll").mockImplementation(function (
+ this: Document,
+ selector: string,
+ ) {
+ if (selector === NODE_SELECTOR && failuresLeft > 0) {
+ failuresLeft -= 1;
+ throw new Error("author DOM blew up");
+ }
+ return realQueryAll.call(this, selector);
+ } as typeof Document.prototype.querySelectorAll);
+
+ const late = document.createElement("div");
+ late.id = "late-after-throw";
+ late.setAttribute("data-start", "1");
+ late.setAttribute("data-duration", "2");
+ document.getElementById("root")!.appendChild(late);
+ await flushObservers();
+
+ // Run frames until the manifest post is attempted and throws. The post is
+ // rate-limited, so it lands on the frame counter's boundary, not the first
+ // woken frame.
+ let thrown: unknown = null;
+ for (let frame = 0; frame < 60 && thrown == null; frame += 1) {
+ if (raf.pending() === 0) break;
+ try {
+ raf.step();
+ } catch (error) {
+ thrown = error;
+ }
+ }
+ expect(String(thrown)).toContain("author DOM blew up");
+ // The change is still owed, so the loop must not have parked on it.
+ expect(raf.pending()).toBeGreaterThan(0);
+
+ settle();
+ expect(window.__clipManifest!.clips.some((clip) => clip.id === "late-after-throw")).toBe(true);
+ });
+
+ it("delivers an adapter duration that grows while parked, with no DOM mutation and no event", () => {
+ mount();
+ initSandboxRuntimeModular();
+ quiesce();
+ const before = window.__player!.getDuration();
+
+ // A Lottie instance lengthening is a live animation object changing. No
+ // observer and no event can see it; only the parked poll can.
+ window.__hfLottie = [{ goToAndStop: () => {}, totalFrames: 600, frameRate: 30 }] as never;
+ vi.advanceTimersByTime(PARK_HEARTBEAT_MS);
+ settle();
+
+ expect(before).toBeLessThan(20);
+ expect(window.__player!.getDuration()).toBeCloseTo(20, 3);
+ });
+});