Skip to content

Write HTML. Render video. Built for agents.

fix(core): hold render-ready on declared compute, not just adapter loaders (#4065)

Miguel Ángele36a53d6b6bd
diff --git a/packages/core/src/compositionReadiness.test.ts b/packages/core/src/compositionReadiness.test.ts
index 6dc1e5ffd6..ca444fa7ec 100644
--- a/packages/core/src/compositionReadiness.test.ts
+++ b/packages/core/src/compositionReadiness.test.ts
@@ -1,6 +1,8 @@
import { describe, expect, it, vi } from "vitest";
import {
+ computeReadinessInput,
mediaReadinessInput,
+ paintAndIdleReadinessInput,
scanPendingCompositionAssets,
settleCompositionReadiness,
} from "./compositionReadiness.js";
@@ -11,6 +13,46 @@ function docWith(bodyHtml: string): Document {
return doc;
}
+// A same-origin composition iframe's document always has a defaultView; the
+// two timing-based inputs need one to call requestAnimationFrame on, so
+// `docWith` (a viewless DOMImplementation document, like the composition
+// tag-scanning tests above use) can't exercise them.
+function docWithFakeWindow(
+ renderReady = false,
+ hasRuntime = true,
+): {
+ doc: Document;
+ win: { __renderReady: boolean; __hf?: Record<string, unknown> };
+ fireFrame: (ts: number) => void;
+ pendingFrameCount: () => number;
+} {
+ let queue = new Map<number, (ts: number) => void>();
+ let nextId = 1;
+ const win = {
+ __renderReady: renderReady,
+ __hf: hasRuntime ? {} : undefined,
+ requestAnimationFrame: (cb: (ts: number) => void) => {
+ const id = nextId++;
+ queue.set(id, cb);
+ return id;
+ },
+ cancelAnimationFrame: (id: number) => {
+ queue.delete(id);
+ },
+ };
+ const fireFrame = (ts: number) => {
+ const callbacks = Array.from(queue.values());
+ queue.clear();
+ callbacks.forEach((cb) => cb(ts));
+ };
+ const doc = { defaultView: win } as unknown as Document;
+ return { doc, win, fireFrame, pendingFrameCount: () => queue.size };
+}
+
+async function flushMicrotasks(): Promise<void> {
+ await new Promise((resolve) => setTimeout(resolve, 0));
+}
+
describe("scanPendingCompositionAssets", () => {
it("reports nothing pending for an empty document", () => {
const scan = scanPendingCompositionAssets(docWith(""));
@@ -25,11 +67,196 @@ describe("scanPendingCompositionAssets", () => {
describe("mediaReadinessInput", () => {
it("returns null when there is nothing to wait on", () => {
- expect(mediaReadinessInput(docWith(""))).toBeNull();
+ expect(mediaReadinessInput(docWith(""), new AbortController().signal)).toBeNull();
+ });
+});
+
+describe("computeReadinessInput", () => {
+ it("returns null when the runtime already published __renderReady", () => {
+ const { doc } = docWithFakeWindow(true);
+ expect(computeReadinessInput(doc, new AbortController().signal)).toBeNull();
+ });
+
+ it("returns null for a document with no view (nothing to poll)", () => {
+ expect(computeReadinessInput(docWith(""), new AbortController().signal)).toBeNull();
+ });
+
+ it("returns null when no runtime ever ran (no window.__hf) instead of polling for __renderReady forever", () => {
+ // A probe-only composition (plain video/native duration, no HyperFrames
+ // runtime injected) never sets window.__hf, so __renderReady would also
+ // never be set — this is the exact shape that used to poll for the full
+ // 8s shared timeout on every single Play.
+ const { doc } = docWithFakeWindow(false, false);
+ expect(computeReadinessInput(doc, new AbortController().signal)).toBeNull();
+ });
+
+ it("resolves once __renderReady flips true", async () => {
+ vi.useFakeTimers();
+ const { doc, win } = docWithFakeWindow(false);
+ let resolved = false;
+ computeReadinessInput(doc, new AbortController().signal)!.then(() => {
+ resolved = true;
+ });
+ await vi.advanceTimersByTimeAsync(50);
+ expect(resolved).toBe(false);
+ win.__renderReady = true;
+ await vi.advanceTimersByTimeAsync(50);
+ expect(resolved).toBe(true);
+ vi.useRealTimers();
+ });
+
+ it("stops polling once aborted, and resolves without __renderReady ever flipping", async () => {
+ vi.useFakeTimers();
+ const { doc } = docWithFakeWindow(false);
+ const controller = new AbortController();
+ let resolved = false;
+ computeReadinessInput(doc, controller.signal)!.then(() => {
+ resolved = true;
+ });
+ await vi.advanceTimersByTimeAsync(50);
+ expect(resolved).toBe(false);
+ const pendingBefore = vi.getTimerCount();
+ controller.abort();
+ await vi.advanceTimersByTimeAsync(0);
+ expect(resolved).toBe(true);
+ // The poll's own timer is cleared on abort, not just left to fire once more.
+ expect(vi.getTimerCount()).toBe(pendingBefore - 1);
+ vi.useRealTimers();
+ });
+});
+
+function startPaintAndIdleTracking(signal: AbortSignal = new AbortController().signal): {
+ fireFrame: (ts: number) => void;
+ isResolved: () => boolean;
+ pendingFrameCount: () => number;
+} {
+ const { doc, fireFrame, pendingFrameCount } = docWithFakeWindow();
+ let resolved = false;
+ paintAndIdleReadinessInput(doc, signal)!.then(() => {
+ resolved = true;
+ });
+ return { fireFrame, isResolved: () => resolved, pendingFrameCount };
+}
+
+describe("paintAndIdleReadinessInput", () => {
+ it("returns null for a document with no view (nothing to observe)", () => {
+ expect(paintAndIdleReadinessInput(docWith(""), new AbortController().signal)).toBeNull();
+ });
+
+ it("waits for first paint, then two consecutive quiet frame gaps", async () => {
+ const { fireFrame, isResolved } = startPaintAndIdleTracking();
+
+ // First paint: two nested frames.
+ fireFrame(0);
+ await flushMicrotasks();
+ fireFrame(16);
+ await flushMicrotasks();
+ expect(isResolved()).toBe(false);
+
+ // First quiet gap (10ms < 50ms threshold) — one is not enough.
+ fireFrame(26);
+ await flushMicrotasks();
+ expect(isResolved()).toBe(false);
+
+ // Second consecutive quiet gap settles it.
+ fireFrame(36);
+ await flushMicrotasks();
+ expect(isResolved()).toBe(true);
+ });
+
+ it("resets the quiet streak on a slow frame gap (the busy stretch itself)", async () => {
+ const { fireFrame, isResolved } = startPaintAndIdleTracking();
+
+ fireFrame(0); // first paint scheduled
+ await flushMicrotasks();
+ fireFrame(16); // first paint presented, lastTs = 16
+ await flushMicrotasks();
+
+ fireFrame(26); // quiet gap 1 (10ms)
+ await flushMicrotasks();
+ fireFrame(626); // a 600ms stall — the busy stretch — resets the streak
+ await flushMicrotasks();
+ expect(isResolved()).toBe(false);
+
+ fireFrame(636); // quiet gap 1 again
+ await flushMicrotasks();
+ expect(isResolved()).toBe(false);
+ fireFrame(646); // quiet gap 2 — now it settles
+ await flushMicrotasks();
+ expect(isResolved()).toBe(true);
+ });
+
+ it("cancels its pending rAF and resolves once aborted mid-wait", async () => {
+ const controller = new AbortController();
+ const { fireFrame, isResolved, pendingFrameCount } = startPaintAndIdleTracking(
+ controller.signal,
+ );
+
+ fireFrame(0); // first paint scheduled
+ await flushMicrotasks();
+ expect(pendingFrameCount()).toBe(1); // second first-paint frame in flight
+
+ controller.abort();
+ await flushMicrotasks();
+ expect(isResolved()).toBe(true);
+ expect(pendingFrameCount()).toBe(0); // the in-flight rAF was cancelled, not left pending
+ });
+
+ it("gives up and resolves after MAX_PAINT_WAIT_MS of steady sub-20fps painting, never reaching a quiet gap", async () => {
+ // A composition rendering a real, steady 15fps (~66ms/frame) never
+ // produces a sub-50ms gap — this is the exact shape that used to hang
+ // paintAndIdleReadinessInput until settleCompositionReadiness's 8s
+ // shared timeout won the race on every single Play.
+ const { fireFrame, isResolved } = startPaintAndIdleTracking();
+ const FRAME_GAP_MS = 66;
+
+ let ts = 0;
+ fireFrame(ts); // first paint scheduled
+ await flushMicrotasks();
+ ts += FRAME_GAP_MS;
+ fireFrame(ts); // first paint presented, lastTs = 66
+ await flushMicrotasks();
+
+ while (ts < 1_500) {
+ expect(isResolved()).toBe(false);
+ ts += FRAME_GAP_MS;
+ fireFrame(ts);
+ await flushMicrotasks();
+ }
+ // The frame that crosses MAX_PAINT_WAIT_MS resolves on its own — no
+ // quiet gap was ever produced, only elapsed steady-paint time.
+ expect(isResolved()).toBe(true);
});
});
describe("settleCompositionReadiness", () => {
+ it("defaults to media, compute and paint-and-idle together", async () => {
+ vi.useFakeTimers();
+ const { win, fireFrame } = docWithFakeWindow(false);
+ const doc = docWith("");
+ Object.defineProperty(doc, "defaultView", { value: win, configurable: true });
+ let settled = false;
+ settleCompositionReadiness(doc, () => {
+ settled = true;
+ });
+ expect(settled).toBe(false); // paint-and-idle alone keeps this pending
+
+ win.__renderReady = true; // compute settles once its poll observes the flag
+ await vi.advanceTimersByTimeAsync(50);
+
+ fireFrame(0);
+ await vi.advanceTimersByTimeAsync(0);
+ fireFrame(16);
+ await vi.advanceTimersByTimeAsync(0);
+ fireFrame(26);
+ await vi.advanceTimersByTimeAsync(0);
+ expect(settled).toBe(false); // one quiet gap isn't enough
+ fireFrame(36);
+ await vi.advanceTimersByTimeAsync(0);
+ expect(settled).toBe(true);
+ vi.useRealTimers();
+ });
+
it("calls back synchronously, before returning, when nothing is pending", () => {
let calledSync = false;
settleCompositionReadiness(docWith(""), () => {
diff --git a/packages/core/src/compositionReadiness.ts b/packages/core/src/compositionReadiness.ts
index 0798689ed4..dc6709bde1 100644
--- a/packages/core/src/compositionReadiness.ts
+++ b/packages/core/src/compositionReadiness.ts
@@ -1,7 +1,12 @@
/** A composition is "ready" once every declared input settles, not just once
* its duration is known. Each input returns null (nothing to wait on) or a
- * promise that resolves once it settles. */
-export type CompositionReadinessInput = (doc: Document) => Promise<void> | null;
+ * promise that resolves once it settles, and must stop its own pending work
+ * (timer, rAF, listener) once `signal` aborts — settleCompositionReadiness
+ * aborts it the moment the race settles, win or timeout. */
+export type CompositionReadinessInput = (
+ doc: Document,
+ signal: AbortSignal,
+) => Promise<void> | null;
export interface PendingCompositionAssets {
pendingMedia: HTMLMediaElement[];
@@ -45,6 +50,7 @@ export function scanPendingCompositionAssets(doc: Document): PendingCompositionA
function collectPendingCompositionAssets(
doc: Document,
{ pendingMedia, pendingImages, fontsLoading }: PendingCompositionAssets,
+ signal: AbortSignal,
): Promise<void> {
const mediaReady = pendingMedia.map(
(el) =>
@@ -52,10 +58,12 @@ function collectPendingCompositionAssets(
const onSettled = () => {
el.removeEventListener("canplay", onSettled);
el.removeEventListener("error", onSettled);
+ signal.removeEventListener("abort", onSettled);
resolve();
};
el.addEventListener("canplay", onSettled);
el.addEventListener("error", onSettled);
+ signal.addEventListener("abort", onSettled, { once: true });
}),
);
const imagesReady = pendingImages.map((img) =>
@@ -67,12 +75,119 @@ function collectPendingCompositionAssets(
/** Declared-media readiness input: waits on the composition's own video,
* audio, image and font-face loads. */
-export function mediaReadinessInput(doc: Document): Promise<void> | null {
+export function mediaReadinessInput(doc: Document, signal: AbortSignal): Promise<void> | null {
const scan = scanPendingCompositionAssets(doc);
if (scan.pendingMedia.length === 0 && scan.pendingImages.length === 0 && !scan.fontsLoading) {
return null;
}
- return collectPendingCompositionAssets(doc, scan);
+ return collectPendingCompositionAssets(doc, scan, signal);
+}
+
+const RENDER_READY_POLL_MS = 50;
+
+// `window.__renderReady` is declared globally in runtime/window.d.ts, but that
+// file lives under src/runtime — excluded from this package's own build
+// program (see tsconfig.json) — so it isn't visible here. Same flag, declared
+// locally instead of depending on a global merge from outside this file's scope.
+interface RuntimeReadinessWindow extends Window {
+ __renderReady?: boolean;
+ // __renderReady is only ever set by init.ts, which always sets __hf
+ // first (`window.__hf = window.__hf || {}`) — a doc with no __hf can
+ // never get __renderReady either, so this alone is enough to gate on
+ // (unlike composition-probe.ts's hasRuntime, this doesn't need __player too).
+ __hf?: unknown;
+}
+
+/** Declared-compute readiness input: waits on `window.__renderReady`. A
+ * probe-only composition (no HyperFrames runtime injected) never sets
+ * it — __hf absent means nothing to wait on, not an 8s poll for a flag
+ * that was never going to flip. */
+export function computeReadinessInput(doc: Document, signal: AbortSignal): Promise<void> | null {
+ const win = doc.defaultView as RuntimeReadinessWindow | null;
+ if (!win) return null;
+ if (win.__renderReady) return null;
+ if (!win.__hf) return null;
+ return new Promise<void>((resolve) => {
+ let timeoutId: ReturnType<typeof setTimeout> | undefined;
+ const finish = () => {
+ if (timeoutId !== undefined) clearTimeout(timeoutId);
+ signal.removeEventListener("abort", finish);
+ resolve();
+ };
+ if (signal.aborted) {
+ finish();
+ return;
+ }
+ signal.addEventListener("abort", finish, { once: true });
+ const poll = () => {
+ if (win.__renderReady) {
+ finish();
+ return;
+ }
+ timeoutId = setTimeout(poll, RENDER_READY_POLL_MS);
+ };
+ poll();
+ });
+}
+
+// Frame-to-frame gap under which the main thread counts as free. Generous
+// relative to a 16.7ms (60fps) frame budget — this detects a busy stretch
+// (a mesh build, a shader compile), not ordinary frame-time variance.
+const IDLE_FRAME_GAP_MS = 50;
+// Two consecutive quiet frames, not one: a single fast gap can follow
+// directly after the busy work finishes mid-frame and says nothing about
+// whether the next frame is also free.
+const IDLE_FRAMES_REQUIRED = 2;
+// Gives up on a doc that keeps producing frames below 20fps. Does NOT bound
+// a doc that stops painting entirely (backgrounded tab, or fewer than 3
+// frames total) — that still rides the full shared 8s timeout, same as
+// before this input existed. ponytail: 1500ms is unmeasured, retune later.
+const MAX_PAINT_WAIT_MS = 1_500;
+
+// Resolves with -1 on abort instead of rejecting: every caller already
+// re-checks `signal.aborted` right after awaiting this, so a sentinel value
+// is enough and keeps the abort path a plain early-return, not a try/catch.
+function nextAnimationFrame(win: Window, signal: AbortSignal): Promise<number> {
+ return new Promise((resolve) => {
+ if (signal.aborted) {
+ resolve(-1);
+ return;
+ }
+ const id = win.requestAnimationFrame((ts) => {
+ signal.removeEventListener("abort", onAbort);
+ resolve(ts);
+ });
+ const onAbort = () => {
+ win.cancelAnimationFrame?.(id);
+ resolve(-1);
+ };
+ signal.addEventListener("abort", onAbort, { once: true });
+ });
+}
+
+/** Composition-agnostic readiness input: waits for a frame to paint, then
+ * two consecutive quiet frame gaps — an early-out once the main thread is
+ * free, not a hold on steady sub-20fps painting. See MAX_PAINT_WAIT_MS for
+ * what this bound does and does not cover. */
+export function paintAndIdleReadinessInput(
+ doc: Document,
+ signal: AbortSignal,
+): Promise<void> | null {
+ const win = doc.defaultView;
+ if (!win) return null;
+ return (async () => {
+ const firstTs = await nextAnimationFrame(win, signal);
+ if (signal.aborted) return;
+ let lastTs = await nextAnimationFrame(win, signal);
+ let quietStreak = 0;
+ while (!signal.aborted && quietStreak < IDLE_FRAMES_REQUIRED) {
+ if (lastTs - firstTs >= MAX_PAINT_WAIT_MS) return;
+ const ts = await nextAnimationFrame(win, signal);
+ if (signal.aborted) return;
+ quietStreak = ts - lastTs < IDLE_FRAME_GAP_MS ? quietStreak + 1 : 0;
+ lastTs = ts;
+ }
+ })();
}
const DEFAULT_TIMEOUT_MS = 8_000;
@@ -84,14 +199,23 @@ export interface CompositionReadinessResult {
/** Invokes `onSettled` once every input settles, or the timeout elapses.
* Calls back synchronously, before returning, when nothing is pending — a
* caller that plays right after this call sees the decision already
- * applied, same as before this gate existed. */
+ * applied, same as before this gate existed. With the default inputs this
+ * only happens for a document with no `defaultView`, since
+ * paintAndIdleReadinessInput always has a frame to wait on otherwise. */
export function settleCompositionReadiness(
doc: Document,
onSettled: (result: CompositionReadinessResult) => void,
opts: { inputs?: CompositionReadinessInput[]; timeoutMs?: number } = {},
): void {
- const inputs = opts.inputs ?? [mediaReadinessInput];
- const pending = inputs.map((input) => input(doc)).filter((p): p is Promise<void> => p !== null);
+ const inputs = opts.inputs ?? [
+ mediaReadinessInput,
+ computeReadinessInput,
+ paintAndIdleReadinessInput,
+ ];
+ const controller = new AbortController();
+ const pending = inputs
+ .map((input) => input(doc, controller.signal))
+ .filter((p): p is Promise<void> => p !== null);
if (pending.length === 0) {
onSettled({ timedOut: false });
return;
@@ -102,8 +226,13 @@ export function settleCompositionReadiness(
const timeout = new Promise<"timed-out">((resolve) => {
timeoutId = setTimeout(() => resolve("timed-out"), timeoutMs);
});
+ // A timeout win leaves the losing inputs' promises pending forever unless
+ // told to stop: this abort is what lets computeReadinessInput clear its
+ // poll timer and paintAndIdleReadinessInput cancel its rAF chain instead
+ // of running for the life of the page.
Promise.race([Promise.all(pending).then(() => "done" as const), timeout]).then((result) => {
clearTimeout(timeoutId);
+ controller.abort();
onSettled({ timedOut: result === "timed-out" });
});
}
diff --git a/packages/core/src/runtime/init.test.ts b/packages/core/src/runtime/init.test.ts
index 5d38ce2980..415fa6ee6b 100644
--- a/packages/core/src/runtime/init.test.ts
+++ b/packages/core/src/runtime/init.test.ts
@@ -196,6 +196,7 @@ describe("initSandboxRuntimeModular", () => {
delete window.__hfTimelinesBuilding;
delete (window as { THREE?: unknown }).THREE;
delete (window as { __hfAutoNoopRegistered?: boolean }).__hfAutoNoopRegistered;
+ delete window.__hf;
delete window.gsap;
vi.restoreAllMocks();
vi.useRealTimers();
@@ -2826,6 +2827,94 @@ describe("initSandboxRuntimeModular", () => {
expect(window.__player?.getDuration()).toBe(10);
});
+ it("waits for window.__hf.buildReady before publishing render readiness", async () => {
+ const root = document.createElement("div");
+ root.setAttribute("data-composition-id", "main");
+ root.setAttribute("data-root", "true");
+ root.setAttribute("data-start", "0");
+ root.setAttribute("data-width", "1920");
+ root.setAttribute("data-height", "1080");
+ document.body.appendChild(root);
+
+ window.__timelines = {
+ main: createMockTimeline(10),
+ };
+
+ // Same registration shape a composition uses: a promise it resolves once
+ // its own heavy setup (mesh build, shader compile) is actually drawable.
+ let resolveBuild: () => void = () => {};
+ const buildPromise = new Promise<void>((resolve) => {
+ resolveBuild = resolve;
+ });
+ window.__hf = window.__hf || {};
+ window.__hf.buildReady = { frost: buildPromise };
+
+ initSandboxRuntimeModular();
+
+ // Player ready, render NOT ready because the declared build is pending.
+ expect(window.__playerReady).toBe(true);
+ expect(window.__renderReady).toBe(false);
+
+ resolveBuild();
+ await Promise.resolve();
+ await Promise.resolve();
+
+ expect(window.__renderReady).toBe(true);
+ });
+
+ it("settles window.__hf.buildReady with two or more registered keys", async () => {
+ const root = document.createElement("div");
+ root.setAttribute("data-composition-id", "main");
+ root.setAttribute("data-root", "true");
+ root.setAttribute("data-start", "0");
+ root.setAttribute("data-width", "1920");
+ root.setAttribute("data-height", "1080");
+ document.body.appendChild(root);
+
+ window.__timelines = { main: createMockTimeline(10) };
+
+ // A multi-key registry rebuilds a fresh Promise.all on every poll; a
+ // settled-tracker that compares that combined promise's identity (rather
+ // than the source promises) never observes "settled" and hangs forever.
+ window.__hf = window.__hf || {};
+ window.__hf.buildReady = { a: Promise.resolve(), b: Promise.resolve() };
+
+ initSandboxRuntimeModular();
+ await Promise.resolve();
+ await Promise.resolve();
+ await Promise.resolve();
+
+ expect(window.__renderReady).toBe(true);
+ });
+
+ it("clears a stale buildReady entry on teardown so the next init isn't blocked by it", async () => {
+ const root = document.createElement("div");
+ root.setAttribute("data-composition-id", "main");
+ root.setAttribute("data-root", "true");
+ root.setAttribute("data-start", "0");
+ root.setAttribute("data-width", "1920");
+ root.setAttribute("data-height", "1080");
+ document.body.appendChild(root);
+
+ window.__timelines = { main: createMockTimeline(10) };
+ window.__hf = window.__hf || {};
+ // Simulates a composition that registered a build hold and was torn down
+ // (piece removed, project swapped) before that promise ever resolved.
+ window.__hf.buildReady = { stale: new Promise<void>(() => {}) };
+
+ initSandboxRuntimeModular();
+ window.__hfRuntimeTeardown?.();
+
+ // A fresh composition loads into the same window without registering
+ // anything under "stale" — the leftover promise must not still be polled.
+ window.__timelines = { main: createMockTimeline(10) };
+ initSandboxRuntimeModular();
+ await Promise.resolve();
+ await Promise.resolve();
+
+ expect(window.__renderReady).toBe(true);
+ });
+
it("sets __renderReady even without a GSAP timeline (CSS/WAAPI compositions)", () => {
const root = document.createElement("div");
root.setAttribute("data-composition-id", "main");
diff --git a/packages/core/src/runtime/init.ts b/packages/core/src/runtime/init.ts
index d5de489bd5..ad6453efad 100644
--- a/packages/core/src/runtime/init.ts
+++ b/packages/core/src/runtime/init.ts
@@ -151,6 +151,50 @@ function resolveExportRenderFps(): ExportRenderFpsResolution {
};
}
+function samePromiseSet(a: PromiseLike<unknown>[], b: PromiseLike<unknown>[] | null): boolean {
+ return b !== null && a.length === b.length && a.every((p, i) => p === b[i]);
+}
+
+// `Promise.all` allocates a fresh promise every call, so comparing ITS
+// identity across repeat polls is never stable — that re-arms a `.then()`
+// on every poll and never lets the caller observe "settled", even once the
+// underlying work is done. Compares the source promises themselves instead.
+function createSettledTracker(
+ collectPromises: () => PromiseLike<unknown>[],
+ onSettled: () => void,
+ onError: (err: unknown) => void,
+): () => boolean {
+ let tracked: PromiseLike<unknown>[] | null = null;
+ let settled = true;
+ return () => {
+ const promises = collectPromises();
+ if (promises.length === 0) {
+ tracked = null;
+ settled = true;
+ return true;
+ }
+ if (samePromiseSet(promises, tracked)) return settled;
+ tracked = promises;
+ settled = false;
+ const combined: PromiseLike<unknown> =
+ promises.length === 1 ? promises[0]! : Promise.all(promises);
+ void Promise.resolve(combined).then(
+ () => {
+ if (tracked !== promises) return;
+ settled = true;
+ onSettled();
+ },
+ (err) => {
+ if (tracked !== promises) return;
+ settled = true;
+ onError(err);
+ onSettled();
+ },
+ );
+ return settled;
+ };
+}
+
export function initSandboxRuntimeModular(): void {
const state = createRuntimeState();
// Runtime-data handlers may replace the timeline object they mutate. Keep the
@@ -2815,67 +2859,50 @@ export function initSandboxRuntimeModular(): void {
let maybePublishRenderReady = () => {
window.__renderReady = false;
};
+
// Internal adapter-readiness tracking. Adapters with outstanding async work
// (Three.js `DefaultLoadingManager`, future fetch/font/image detectors) expose
// a `getReadyPromise()` method; the runtime waits for whatever they return
// before publishing render-ready. This is purely internal — there is no
// authored-code-facing flag (LLMs should not need to know about render
// readiness, the framework handles async asset gating automatically).
- let trackedAdapterReadyPromise: PromiseLike<unknown> | null = null;
- let trackedAdapterReadySettled = true;
-
- const collectAdapterReadyPromises = (): PromiseLike<unknown>[] => {
- const promises: PromiseLike<unknown>[] = [];
- for (const adapter of state.deterministicAdapters) {
- const getter = adapter.getReadyPromise;
- if (typeof getter !== "function") continue;
- try {
- const p = getter();
- if (p) promises.push(p);
- } catch (err) {
- // A throwing readiness gate must not permanently block render; swallow
- // and continue, matching the rest of the runtime's adapter-resilience
- // pattern.
- swallow("runtime.init.adapterReady", err);
+ const isAdapterReadinessSettled = createSettledTracker(
+ () => {
+ const promises: PromiseLike<unknown>[] = [];
+ for (const adapter of state.deterministicAdapters) {
+ const getter = adapter.getReadyPromise;
+ if (typeof getter !== "function") continue;
+ try {
+ const p = getter();
+ if (p) promises.push(p);
+ } catch (err) {
+ // A throwing readiness gate must not permanently block render; swallow
+ // and continue, matching the rest of the runtime's adapter-resilience
+ // pattern.
+ swallow("runtime.init.adapterReady", err);
+ }
}
- }
- return promises;
- };
+ return promises;
+ },
+ () => maybePublishRenderReady(),
+ (err) => swallow("runtime.init.adapterReady", err),
+ );
- const isAdapterReadinessSettled = (): boolean => {
- const promises = collectAdapterReadyPromises();
- if (promises.length === 0) {
- trackedAdapterReadyPromise = null;
- trackedAdapterReadySettled = true;
- return true;
- }
- // Combine multiple adapter promises so we only attach a single resume
- // handler. Identity is stable as long as the inputs are stable (each
- // adapter is expected to return the same promise on repeat calls while
- // its work is in flight).
- const firstPromise = promises[0];
- if (!firstPromise) return true;
- const combined: PromiseLike<unknown> =
- promises.length === 1 ? firstPromise : Promise.all(promises);
- if (combined !== trackedAdapterReadyPromise) {
- trackedAdapterReadyPromise = combined;
- trackedAdapterReadySettled = false;
- void Promise.resolve(combined).then(
- () => {
- if (trackedAdapterReadyPromise !== combined) return;
- trackedAdapterReadySettled = true;
- maybePublishRenderReady();
- },
- (err) => {
- if (trackedAdapterReadyPromise !== combined) return;
- trackedAdapterReadySettled = true;
- swallow("runtime.init.adapterReady", err);
- maybePublishRenderReady();
- },
+ // window.__hf.buildReady[key]: a piece registers a promise for setup no
+ // adapter can observe (mesh building, shader compiles). Waited the same
+ // way as adapter readiness, so render and preview both hold on it.
+ const isBuildReadinessSettled = createSettledTracker(
+ () => {
+ const registry = window.__hf?.buildReady;
+ if (!registry) return [];
+ return Object.values(registry).filter(
+ (p): p is PromiseLike<unknown> =>
+ p != null && typeof (p as PromiseLike<unknown>).then === "function",
);
- }
- return trackedAdapterReadySettled;
- };
+ },
+ () => maybePublishRenderReady(),
+ (err) => swallow("runtime.init.buildReady", err),
+ );
if (!externalCompositionsReady) {
const compositionLoaderParams = {
@@ -3254,6 +3281,10 @@ export function initSandboxRuntimeModular(): void {
window.__renderReady = false;
return;
}
+ if (!isBuildReadinessSettled()) {
+ window.__renderReady = false;
+ return;
+ }
publishRenderReadyAfterTimelineBinding();
};
@@ -4179,6 +4210,10 @@ export function initSandboxRuntimeModular(): void {
}
}
state.deterministicAdapters = [];
+ // A stale, never-resolved buildReady promise from the torn-down composition
+ // would otherwise permanently block render-ready for whatever loads next
+ // into this window, since window.__hf itself is never reset.
+ if (window.__hf?.buildReady) window.__hf.buildReady = {};
for (const cleanup of runtimeCleanupCallbacks.splice(0)) {
try {
cleanup();
diff --git a/packages/core/src/runtime/window.d.ts b/packages/core/src/runtime/window.d.ts
index 80e6d46c73..3de25e17fc 100644
--- a/packages/core/src/runtime/window.d.ts
+++ b/packages/core/src/runtime/window.d.ts
@@ -50,6 +50,10 @@ declare global {
* runtime's paused-side enforcement leaves it alone. Always release. */
leasePausedMedia?: (el: HTMLMediaElement) => void;
releasePausedMedia?: (el: HTMLMediaElement) => void;
+ /** Declared-compute hold for setup no adapter can see (mesh building,
+ * shader compiles). Runtime and player hold until every promise
+ * registered here, under any key unique to your piece, resolves. */
+ buildReady?: Record<string, PromiseLike<unknown>>;
};
__playerReady?: boolean;
__renderReady?: boolean;
diff --git a/packages/engine/src/services/frameCapture.test.ts b/packages/engine/src/services/frameCapture.test.ts
index 05cd4fb52c..d60d70a19b 100644
--- a/packages/engine/src/services/frameCapture.test.ts
+++ b/packages/engine/src/services/frameCapture.test.ts
@@ -1,5 +1,6 @@
import { describe, it, expect } from "vitest";
import {
+ buildZeroDurationDiagnostic,
classifyConsoleScriptFailure,
DrawElementVerificationError,
formatHttpErrorDiagnostic,
@@ -7,6 +8,7 @@ import {
formatNavigationFailureDiagnostic,
formatNavigationStartDiagnostic,
formatRequestFailureDiagnostic,
+ HF_READY_DIAGNOSTIC_EXPR,
getDrawElementVerificationDetails,
isFontResourceError,
isDrawElementVerificationError,
@@ -357,3 +359,101 @@ describe("DrawElementVerificationError details", () => {
expect(getDrawElementVerificationDetails(adversarial)?.kind).toBe("psnr");
});
});
+
+describe("buildZeroDurationDiagnostic", () => {
+ const baseDiag = {
+ renderReady: false,
+ hasHf: true,
+ hasSeek: true,
+ hasPlayer: true,
+ duration: 0,
+ hasTimeline: true,
+ declaredDuration: 6,
+ pendingBuildReadyKeys: [] as string[],
+ rejectedBuildReadyKeys: [] as string[],
+ };
+
+ it("names the stuck buildReady key instead of blaming GSAP/data-duration", () => {
+ const message = buildZeroDurationDiagnostic({
+ ...baseDiag,
+ pendingBuildReadyKeys: ["heavy-mesh"],
+ });
+ expect(message).toContain("window.__hf.buildReady never resolved for: heavy-mesh");
+ });
+
+ it("lists every stuck key when more than one is pending", () => {
+ const message = buildZeroDurationDiagnostic({
+ ...baseDiag,
+ pendingBuildReadyKeys: ["heavy-mesh", "shader-warmup"],
+ });
+ expect(message).toContain(
+ "window.__hf.buildReady never resolved for: heavy-mesh, shader-warmup",
+ );
+ });
+
+ it("omits the buildReady hint entirely when nothing is pending or rejected", () => {
+ const message = buildZeroDurationDiagnostic(baseDiag);
+ expect(message).not.toContain("buildReady");
+ });
+
+ it("names a rejected buildReady key separately from a pending one", () => {
+ const message = buildZeroDurationDiagnostic({
+ ...baseDiag,
+ pendingBuildReadyKeys: ["heavy-mesh"],
+ rejectedBuildReadyKeys: ["shader-warmup"],
+ });
+ expect(message).toContain("window.__hf.buildReady never resolved for: heavy-mesh");
+ expect(message).toContain("window.__hf.buildReady rejected for: shader-warmup");
+ });
+});
+
+describe("HF_READY_DIAGNOSTIC_EXPR (evaluated as real JS, not via a fake fixture)", () => {
+ // The expression is a Puppeteer page.evaluate string, never executed by
+ // any other test. Running it here through `new Function` against a fake
+ // window/document exercises its actual settle/reject logic in-process.
+ async function runDiagnosticExpr(buildReady: Record<string, unknown>): Promise<{
+ pendingBuildReadyKeys: string[];
+ rejectedBuildReadyKeys: string[];
+ }> {
+ const fakeWindow = {
+ __hf: { seek: () => {}, duration: 0, buildReady },
+ __player: {},
+ __renderReady: false,
+ __timelines: {},
+ };
+ const fakeDocument = { querySelector: () => null };
+ const run = new Function("window", "document", `return ${HF_READY_DIAGNOSTIC_EXPR}`) as (
+ win: unknown,
+ doc: unknown,
+ ) => Promise<{
+ pendingBuildReadyKeys: string[];
+ rejectedBuildReadyKeys: string[];
+ }>;
+ return run(fakeWindow, fakeDocument);
+ }
+
+ it("does not reject the whole diagnostic when a buildReady entry rejects", async () => {
+ const result = await runDiagnosticExpr({ heavy: Promise.reject(new Error("boom")) });
+ expect(result.rejectedBuildReadyKeys).toEqual(["heavy"]);
+ expect(result.pendingBuildReadyKeys).toEqual([]);
+ });
+
+ it("reports a settled non-native thenable as resolved, not pending", async () => {
+ const settledThenable = { then: (res: (v: unknown) => void) => res(1) };
+ const result = await runDiagnosticExpr({ heavy: settledThenable });
+ expect(result.pendingBuildReadyKeys).toEqual([]);
+ expect(result.rejectedBuildReadyKeys).toEqual([]);
+ });
+
+ it("reports a genuinely pending promise as pending", async () => {
+ const result = await runDiagnosticExpr({ heavy: new Promise(() => {}) });
+ expect(result.pendingBuildReadyKeys).toEqual(["heavy"]);
+ expect(result.rejectedBuildReadyKeys).toEqual([]);
+ });
+
+ it("returns empty arrays for a composition with no buildReady registrations", async () => {
+ const result = await runDiagnosticExpr({});
+ expect(result.pendingBuildReadyKeys).toEqual([]);
+ expect(result.rejectedBuildReadyKeys).toEqual([]);
+ });
+});
diff --git a/packages/engine/src/services/frameCapture.ts b/packages/engine/src/services/frameCapture.ts
index f367b007ce..ec852cdede 100644
--- a/packages/engine/src/services/frameCapture.ts
+++ b/packages/engine/src/services/frameCapture.ts
@@ -1528,7 +1528,7 @@ export function formatConsoleDiagnostic(
return { text: `${prefix} ${text}`, suppressHostLog: false };
}
-const HF_READY_DIAGNOSTIC_EXPR = `(function() {
+export const HF_READY_DIAGNOSTIC_EXPR = `(async function() {
var hf = window.__hf;
var player = window.__player;
var renderReady = !!window.__renderReady;
@@ -1537,6 +1537,26 @@ const HF_READY_DIAGNOSTIC_EXPR = `(function() {
var hasTimeline = !!(window.__timelines && Object.keys(window.__timelines).length > 0);
var root = document.querySelector("[data-composition-id]");
var declaredDuration = root ? Number(root.getAttribute("data-duration")) : -1;
+ var registry = (window.__hf && window.__hf.buildReady) || {};
+ var keys = Object.keys(registry);
+ // A microtask race mis-sorts a non-native thenable (extra adoption tick)
+ // and rejects the whole expression on a rejected entry. Settling each
+ // key onto its own record and waiting one macrotask avoids both.
+ var settled = {};
+ if (keys.length > 0) {
+ keys.forEach(function(key) {
+ Promise.resolve(registry[key]).then(
+ function() { settled[key] = "resolved"; },
+ function() { settled[key] = "rejected"; },
+ );
+ });
+ await new Promise(function(r) { setTimeout(r, 0); });
+ }
+ // A thenable resolving via its own setTimeout(0) can still misreport as
+ // pending here (macrotask registration order, not resolution order) — a
+ // narrow case that self-corrects on the next ~1s diagnostic tick.
+ var pendingBuildReadyKeys = keys.filter(function(key) { return !settled[key]; });
+ var rejectedBuildReadyKeys = keys.filter(function(key) { return settled[key] === "rejected"; });
return {
renderReady: renderReady,
hasHf: !!hf,
@@ -1545,11 +1565,12 @@ const HF_READY_DIAGNOSTIC_EXPR = `(function() {
duration: duration,
hasTimeline: hasTimeline,
declaredDuration: declaredDuration,
+ pendingBuildReadyKeys: pendingBuildReadyKeys,
+ rejectedBuildReadyKeys: rejectedBuildReadyKeys,
};
})()`;
-// fallow-ignore-next-line complexity
-function buildZeroDurationDiagnostic(diag: {
+export interface HfDiagnostic {
renderReady: boolean;
hasHf: boolean;
hasSeek: boolean;
@@ -1557,8 +1578,26 @@ function buildZeroDurationDiagnostic(diag: {
duration: number;
hasTimeline: boolean;
declaredDuration: number;
-}): string {
+ pendingBuildReadyKeys: string[];
+ rejectedBuildReadyKeys: string[];
+}
+
+// fallow-ignore-next-line complexity
+export function buildZeroDurationDiagnostic(diag: HfDiagnostic): string {
const hints: string[] = [];
+ if (diag.pendingBuildReadyKeys.length > 0) {
+ hints.push(
+ `window.__hf.buildReady never resolved for: ${diag.pendingBuildReadyKeys.join(", ")}. ` +
+ "The runtime holds render-ready until every registered buildReady promise settles — " +
+ "find where the composition registers that key and confirm it actually resolves.",
+ );
+ }
+ if (diag.rejectedBuildReadyKeys.length > 0) {
+ hints.push(
+ `window.__hf.buildReady rejected for: ${diag.rejectedBuildReadyKeys.join(", ")}. ` +
+ "That key's build promise failed rather than hanging — find why it rejects.",
+ );
+ }
if (!diag.hasPlayer) {
hints.push("window.__player was never set — the HyperFrames runtime did not initialize.");
}
@@ -1589,16 +1628,6 @@ function buildZeroDurationDiagnostic(diag: {
);
}
-interface HfDiagnostic {
- renderReady: boolean;
- hasHf: boolean;
- hasSeek: boolean;
- hasPlayer: boolean;
- duration: number;
- hasTimeline: boolean;
- declaredDuration: number;
-}
-
async function evaluateHfDiagnostic(page: Page): Promise<HfDiagnostic> {
return (await page.evaluate(HF_READY_DIAGNOSTIC_EXPR)) as HfDiagnostic;
}
diff --git a/packages/player/src/hyperframes-player.test.ts b/packages/player/src/hyperframes-player.test.ts
index ebd81e6278..a7ce1d643d 100644
--- a/packages/player/src/hyperframes-player.test.ts
+++ b/packages/player/src/hyperframes-player.test.ts
@@ -12,6 +12,15 @@ function stubIframeContentDocument(iframe: HTMLIFrameElement, doc: Document): vo
});
}
+// Bare test docs never run a runtime, so only paintAndIdleReadinessInput
+// is ever pending — drain real rAF frames past its quiet-frame minimum
+// on the given window (the iframe's own, not the test's global one).
+async function awaitPaintAndIdle(win: Window = window): Promise<void> {
+ for (let i = 0; i < 6; i++) {
+ await new Promise<void>((resolve) => win.requestAnimationFrame(() => resolve()));
+ }
+}
+
function createForeignFrameMediaDocument(): {
doc: Document;
video: HTMLMediaElement & { pause: ReturnType<typeof vi.fn> };
@@ -2196,11 +2205,22 @@ describe("HyperframesPlayer runtime ready handshake", () => {
expect(readyEvents).toEqual([{ duration: 4 }]);
});
- it("honors autoplay after cross-origin runtime timeline readiness", () => {
+ it("honors autoplay after cross-origin runtime timeline readiness", async () => {
+ // A bare iframe fires its own async `load` a few ms after append, which
+ // resets pending-play state (see createConnectedPlayer's comment below) —
+ // await it first so it can't land mid-test during the readiness wait.
+ await new Promise<void>((resolve) => {
+ player.iframe.addEventListener("load", () => resolve(), { once: true });
+ });
player.setAttribute("autoplay", "");
postSpy.mockClear();
player._onMessage(timelineMessage(120));
+ // The same-origin doc under test has no pending media, but play() is now
+ // gated on paint-and-idle too — it queues until that settles. The gate
+ // polls the real (unstubbed) iframe document's own window, not the
+ // stubbed contentWindow used for postMessage.
+ await awaitPaintAndIdle(player.iframe.contentDocument!.defaultView!);
expect(player.paused).toBe(false);
expect(findControlCalls("play")).toHaveLength(1);
@@ -2774,6 +2794,7 @@ describe("HyperframesPlayer asset-ready gate", () => {
play(): void;
pause(): void;
seek(timeInSeconds: number): void;
+ shaderLoader: { showAssetsLoading(): void };
};
beforeEach(async () => {
@@ -2813,6 +2834,25 @@ describe("HyperframesPlayer asset-ready gate", () => {
player.remove();
});
+ it("debounces the loading overlay so a fast, nothing-pending wait never shows it", async () => {
+ const player = await createConnectedPlayer();
+ const doc = player.iframe.contentDocument!;
+ const showSpy = vi.spyOn(player.shaderLoader, "showAssetsLoading");
+
+ player._waitForAssetsReady(doc);
+ expect(player.assetsReady).toBe(false);
+
+ // Only paint-and-idle is pending on this blank iframe doc (no runtime,
+ // no media) — it settles well under ASSETS_LOADING_SHOW_DELAY_MS.
+ await awaitPaintAndIdle(doc.defaultView!);
+
+ expect(player.assetsReady).toBe(true);
+ expect(player.hasAttribute("assets-loading")).toBe(false);
+ expect(showSpy).not.toHaveBeenCalled();
+
+ player.remove();
+ });
+
it("defers play() until a pending video settles, then plays and clears the overlay attribute", async () => {
const player = await createConnectedPlayer();
@@ -2824,6 +2864,10 @@ describe("HyperframesPlayer asset-ready gate", () => {
player._waitForAssetsReady(doc);
expect(player.assetsReady).toBe(false);
+ // The loading overlay is debounced (ASSETS_LOADING_SHOW_DELAY_MS) so a
+ // wait that resolves fast never flashes it — advance past the debounce
+ // to exercise the shown state, since this video is still genuinely stuck.
+ await new Promise((resolve) => setTimeout(resolve, 160));
expect(player.hasAttribute("assets-loading")).toBe(true);
player.play();
@@ -2929,6 +2973,10 @@ describe("HyperframesPlayer asset-ready gate", () => {
vi.useFakeTimers();
try {
const { doc } = createStalledVideoDoc();
+ // A document with no browsing context (created via createHTMLDocument,
+ // as this fixture is) reports hidden=true per spec regardless of the
+ // real page — stub it visible so this test isn't about visibility.
+ Object.defineProperty(doc, "hidden", { value: false, configurable: true });
stubIframeContentDocument(player.iframe, doc);
player._waitForAssetsReady(doc);
@@ -2943,6 +2991,35 @@ describe("HyperframesPlayer asset-ready gate", () => {
expect(player._pendingPlay).toBe(false);
expect(warnSpy).toHaveBeenCalledTimes(1);
expect(warnSpy.mock.calls[0]?.[0]).toContain("assets-loading timed out");
+ // computeReady is reported alongside the media/image/font scan, since
+ // compute (window.__renderReady) can also be why the timeout fired.
+ expect(warnSpy.mock.calls[0]?.[1]).toMatchObject({
+ computeReady: false,
+ documentHidden: false,
+ });
+ warnSpy.mockRestore();
+
+ player.remove();
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it("reports documentHidden: true when the composition document is backgrounded", async () => {
+ const player = await createConnectedPlayer();
+ vi.useFakeTimers();
+ try {
+ const { doc } = createStalledVideoDoc();
+ Object.defineProperty(doc, "hidden", { value: true, configurable: true });
+ stubIframeContentDocument(player.iframe, doc);
+
+ player._waitForAssetsReady(doc);
+ const warnSpy = vi.spyOn(console, "warn").mockImplementation(() => undefined);
+
+ await vi.advanceTimersByTimeAsync(8_000);
+
+ expect(warnSpy.mock.calls[0]?.[1]).toMatchObject({ documentHidden: true });
+ warnSpy.mockRestore();
player.remove();
} finally {
@@ -3034,6 +3111,9 @@ describe("HyperframesPlayer asset-ready gate", () => {
adapter: { kind: "runtime", getDuration: () => 5 },
compositionSize: null,
});
+ // The blank iframe doc has no pending media, but play() also queues on
+ // the paint-and-idle default now — it fires once that settles.
+ await awaitPaintAndIdle(player.iframe.contentDocument!.defaultView!);
expect(playSpy).toHaveBeenCalledTimes(1);
diff --git a/packages/player/src/hyperframes-player.ts b/packages/player/src/hyperframes-player.ts
index 868b88b9e0..567524b1e4 100644
--- a/packages/player/src/hyperframes-player.ts
+++ b/packages/player/src/hyperframes-player.ts
@@ -36,11 +36,15 @@ const MIN_PLAYBACK_RATE = 0.1;
const MAX_PLAYBACK_RATE = 5;
const SANDBOX_ORIGIN_ATTR = "sandbox-origin";
const RUNTIME_DATA_DELIVERY_TIMEOUT_MS = 10_000;
-// Bounds how long the player waits for a same-origin composition's media,
-// images and fonts before playing anyway — a stuck asset must not block
-// playback forever.
+// Bounds how long the player waits on a same-origin composition's readiness
+// inputs (media, compute, paint-and-idle) before playing anyway — a stuck
+// asset or a composition that never goes quiet must not block playback forever.
const ASSETS_READY_TIMEOUT_MS = 8_000;
const ASSETS_LOADING_ATTR = "assets-loading";
+// paint-and-idle now always has a frame to wait on, so the overlay would
+// flash on every single Play without this debounce. ponytail: 150ms is
+// unmeasured, retune once there's production data on paint-and-idle timing.
+const ASSETS_LOADING_SHOW_DELAY_MS = 150;
export type ColorGradingTarget =
| string
@@ -107,6 +111,7 @@ class HyperframesPlayer extends HTMLElement {
private _assetsReady = false;
private _pendingPlay = false;
private _assetsGeneration = 0;
+ private _assetsLoadingShowTimer: ReturnType<typeof setTimeout> | null = null;
private _currentTime = 0;
private _duration = 0;
private _paused = true;
@@ -519,8 +524,8 @@ class HyperframesPlayer extends HTMLElement {
return this._ready;
}
- /** True once the composition's media, images and fonts have loaded (or the
- * 8s wait timed out) — mirrors the `assetsready` event. Always true for
+ /** True once every readiness input (media, compute, paint-and-idle) has
+ * settled or the wait timed out. Mirrors `assetsready`. Always true for
* cross-origin compositions, which the player has no DOM access to wait on. */
get assetsReady() {
return this._assetsReady;
@@ -1013,9 +1018,12 @@ class HyperframesPlayer extends HTMLElement {
if (this.hasAttribute("autoplay") || this._pendingPlay) this.play();
}
- /** Gates play() on composition readiness (media/images/fonts), bounded by
- * ASSETS_READY_TIMEOUT_MS; settles synchronously when nothing is pending. */
+ /** Gates play() on composition readiness (media, compute, paint-and-idle),
+ * bounded by ASSETS_READY_TIMEOUT_MS. The overlay is debounced by
+ * ASSETS_LOADING_SHOW_DELAY_MS rather than shown the instant a wait
+ * starts, since one is now pending on nearly every Play. */
private _waitForAssetsReady(doc: Document | null): void {
+ this._clearAssetsLoadingShowTimer();
this._assetsReady = false;
// Invalidates any earlier wait still in flight (a composition swap, or
// disconnect, mid-wait) — its eventual settle checks this and no-ops
@@ -1034,19 +1042,23 @@ class HyperframesPlayer extends HTMLElement {
},
{ timeoutMs: ASSETS_READY_TIMEOUT_MS },
);
- // settleCompositionReadiness calls back synchronously when nothing was
- // pending, so _assetsReady is already true here in the common case — the
- // loading overlay only shows for the genuinely-waiting case.
if (!this._assetsReady) {
- this.setAttribute(ASSETS_LOADING_ATTR, "");
- this.shaderLoader.showAssetsLoading();
+ this._assetsLoadingShowTimer = setTimeout(() => {
+ this._assetsLoadingShowTimer = null;
+ if (generation !== this._assetsGeneration || this._assetsReady) return;
+ this.setAttribute(ASSETS_LOADING_ATTR, "");
+ this.shaderLoader.showAssetsLoading();
+ }, ASSETS_LOADING_SHOW_DELAY_MS);
}
}
- /** Timeout diagnostic. Re-scans (rather than reusing the original scan)
- * since some assets may have resolved in the 8s since. */
+ /** Timeout diagnostic. Re-scans since some assets may have resolved by
+ * now. Compute can cause the timeout, so it's reported too. A hidden
+ * document can starve paint-and-idle of frames for the full 8s — that's
+ * reported directly rather than inferred, since it can't be bounded. */
private _warnStuckAssets(doc: Document): void {
const { pendingMedia, pendingImages, fontsLoading } = scanPendingCompositionAssets(doc);
+ const win = doc.defaultView as (Window & { __renderReady?: boolean }) | null;
console.warn(
`[hyperframes-player] assets-loading timed out after ${ASSETS_READY_TIMEOUT_MS}ms — playing anyway`,
{
@@ -1057,12 +1069,15 @@ class HyperframesPlayer extends HTMLElement {
(img) => img.currentSrc || img.getAttribute("src") || "<img>",
),
fontsLoading,
+ computeReady: win?.__renderReady === true,
+ documentHidden: doc.hidden === true,
},
);
}
private _settleAssetsReady(generation: number): void {
if (generation !== this._assetsGeneration || this._assetsReady) return;
+ this._clearAssetsLoadingShowTimer();
this._assetsReady = true;
this.removeAttribute(ASSETS_LOADING_ATTR);
this.shaderLoader.hide();
@@ -1073,6 +1088,7 @@ class HyperframesPlayer extends HTMLElement {
/** Abandons any in-flight asset wait — every `_ready = false` site calls
* this first, so a stale wait's settle can't apply to what comes next. */
private _invalidateAssetsWait(): void {
+ this._clearAssetsLoadingShowTimer();
this._assetsReady = false;
this._pendingPlay = false;
this._assetsGeneration++;
@@ -1080,6 +1096,12 @@ class HyperframesPlayer extends HTMLElement {
this.shaderLoader.hide();
}
+ private _clearAssetsLoadingShowTimer(): void {
+ if (this._assetsLoadingShowTimer === null) return;
+ clearTimeout(this._assetsLoadingShowTimer);
+ this._assetsLoadingShowTimer = null;
+ }
+
private _rescale() {
const applied = scaleIframeToFit(
this,
diff --git a/packages/studio/src/player/store/readinessSlice.ts b/packages/studio/src/player/store/readinessSlice.ts
index ddaba6c129..2943d1b23b 100644
--- a/packages/studio/src/player/store/readinessSlice.ts
+++ b/packages/studio/src/player/store/readinessSlice.ts
@@ -1,7 +1,8 @@
/** Gates `timelineReady` on the composition's declared readiness inputs
- * (media, for now) instead of just a known duration. The generation counter
- * is module-scope, not store state: it guards an in-flight settlement, not
- * something a component reads, so bumping it shouldn't trigger a render. */
+ * (media, compute, and the paint-and-idle default) instead of just a known
+ * duration. The generation counter is module-scope, not store state: it
+ * guards an in-flight settlement, not something a component reads, so
+ * bumping it shouldn't trigger a render. */
import type { StoreApi } from "zustand";
import { settleCompositionReadiness } from "@hyperframes/core/composition-readiness";
diff --git a/skills-manifest.json b/skills-manifest.json
index 5746300095..f3a2533a0e 100644
--- a/skills-manifest.json
+++ b/skills-manifest.json
@@ -22,7 +22,7 @@
"files": 26
},
"hyperframes-animation": {
- "hash": "3947516ec450f3aa",
+ "hash": "4225f299e6ff9a0e",
"files": 121
},
"hyperframes-audio": {
diff --git a/skills/hyperframes-animation/adapters/three.md b/skills/hyperframes-animation/adapters/three.md
index e6c3b1c553..4c532b46b5 100644
--- a/skills/hyperframes-animation/adapters/three.md
+++ b/skills/hyperframes-animation/adapters/three.md
@@ -87,6 +87,20 @@ For anything under `three/addons/`, use an importmap so bare specifiers resolve.
Pin the `three` version in both entries to the same value. Mixing versions across the map and bare imports causes silent breakage.
+## Heavy Setup (Large Meshes, Shader Compiles)
+
+The runtime already waits for textures/models queued through Three's `DefaultLoadingManager` before publishing render-ready. It has no visibility into CPU-bound work you do yourself after assets load — building a large procedural mesh, compiling shaders, warming a pipeline. That work can leave the canvas blank for seconds after the runtime and player already say "ready".
+
+If your setup does this kind of work, register a promise on `window.__hf.buildReady` (declared-compute hold: runtime waits, player shows its loading state instead of a blank frame):
+
+```js
+window.__hf = window.__hf || {};
+window.__hf.buildReady = window.__hf.buildReady || {};
+window.__hf.buildReady["<your-piece-name>"] = buildScene(); // resolves once the scene is actually drawable
+```
+
+Register it synchronously, in the same script block that starts the build — same timing as `DefaultLoadingManager`, so the runtime's first readiness check already sees it. Only do this for setup an adapter cannot see; render-critical seeking still comes from `hf-seek`, not this hold. The key must be unique within the composition — a second registration under the same key silently replaces the first, dropping its hold.
+
## AnimationMixer Pattern
For GLTF or authored clip animation, seek the mixer directly: