Skip to content

Write HTML. Render video. Built for agents.

fix: respect user timeouts on low-memory systems (#1221)

Miguel Ángel20894ab9a3e2
diff --git a/.fallowrc.jsonc b/.fallowrc.jsonc
index 0b7c4db1d3..54f9fb3337 100644
--- a/.fallowrc.jsonc
+++ b/.fallowrc.jsonc
@@ -96,6 +96,20 @@
"file": "packages/cli/src/commands/render.ts",
"exports": ["resolveBrowserGpuForCli", "renderLocal"],
},
+ // captureCost.ts: constants and helpers consumed by the runCaptureCalibration
+ // orchestration function and tests, but the entry-point graph doesn't
+ // reach them because the orchestrator's caller resolves them dynamically.
+ {
+ "file": "packages/producer/src/services/render/captureCost.ts",
+ "exports": [
+ "CAPTURE_CALIBRATION_TARGET_MS",
+ "MAX_MEASURED_CAPTURE_COST_MULTIPLIER",
+ "CAPTURE_CALIBRATION_PROTOCOL_TIMEOUT_MS",
+ "measureCaptureCostFromSession",
+ "logCaptureCalibrationResult",
+ "createFailedCaptureCalibrationEstimate",
+ ],
+ },
],
"ignoreDependencies": [
// Runtime/dynamic deps not visible to static analysis: tsup `external`,
diff --git a/packages/cli/src/commands/render.ts b/packages/cli/src/commands/render.ts
index 3dea86b72f..74434dca96 100644
--- a/packages/cli/src/commands/render.ts
+++ b/packages/cli/src/commands/render.ts
@@ -249,6 +249,20 @@ export default defineCommand({
"readiness poll has its own 45s budget). " +
"Env fallback: PRODUCER_PAGE_NAVIGATION_TIMEOUT_MS (MILLISECONDS).",
},
+ "protocol-timeout": {
+ type: "string",
+ description:
+ "CDP protocol timeout in ms. Increase on slow/low-memory machines " +
+ "where Chrome operations time out. Default: 300000 (5 min). " +
+ "Env: PRODUCER_PUPPETEER_PROTOCOL_TIMEOUT_MS.",
+ },
+ "player-ready-timeout": {
+ type: "string",
+ description:
+ "Timeout in ms for the composition player to become ready. " +
+ "Increase for complex compositions on slow hardware. Default: 45000 (45 s). " +
+ "Env: PRODUCER_PLAYER_READY_TIMEOUT_MS.",
+ },
},
// `run` is the citty handler for `hyperframes render` — sequential flag
// validation + render dispatch. Inherited CRITICAL on main (CRAP 1290);
@@ -326,6 +340,32 @@ export default defineCommand({
workers = parsed;
}
+ // ── Validate timeout overrides ─────────────────────────────────────
+ let protocolTimeout: number | undefined;
+ if (args["protocol-timeout"] != null) {
+ const parsed = parseInt(args["protocol-timeout"], 10);
+ if (isNaN(parsed) || parsed < 1000) {
+ errorBox(
+ "Invalid protocol-timeout",
+ `Got "${args["protocol-timeout"]}". Must be a number >= 1000 (ms).`,
+ );
+ process.exit(1);
+ }
+ protocolTimeout = parsed;
+ }
+ let playerReadyTimeout: number | undefined;
+ if (args["player-ready-timeout"] != null) {
+ const parsed = parseInt(args["player-ready-timeout"], 10);
+ if (isNaN(parsed) || parsed < 1000) {
+ errorBox(
+ "Invalid player-ready-timeout",
+ `Got "${args["player-ready-timeout"]}". Must be a number >= 1000 (ms).`,
+ );
+ process.exit(1);
+ }
+ playerReadyTimeout = parsed;
+ }
+
// ── Wire opt-in: page-side compositing ───────────────────────────────
if (args["page-side-compositing"] === false) {
process.env.HF_PAGE_SIDE_COMPOSITING = "false";
@@ -347,6 +387,7 @@ export default defineCommand({
// ── Resolve output path ───────────────────────────────────────────────
const rendersDir = resolve("renders");
const ext = FORMAT_EXT[format] ?? ".mp4";
+ // fallow-ignore-next-line code-duplication
const now = new Date();
const datePart = now.toISOString().slice(0, 10);
const timePart = now.toTimeString().slice(0, 8).replace(/:/g, "-");
@@ -528,6 +569,8 @@ export default defineCommand({
outputResolution,
pageSideCompositing: args["page-side-compositing"] !== false,
pageNavigationTimeoutMs,
+ protocolTimeout,
+ playerReadyTimeout,
exitAfterComplete: true,
});
} else {
@@ -547,6 +590,8 @@ export default defineCommand({
entryFile,
outputResolution,
pageNavigationTimeoutMs,
+ protocolTimeout,
+ playerReadyTimeout,
exitAfterComplete: true,
});
}
@@ -583,6 +628,10 @@ interface RenderOptions {
* producer's EngineConfig override.
*/
pageNavigationTimeoutMs?: number;
+ /** CDP protocol timeout override (ms). */
+ protocolTimeout?: number;
+ /** Player-ready timeout override (ms). */
+ playerReadyTimeout?: number;
}
/**
@@ -848,6 +897,7 @@ async function renderDocker(
if (options.exitAfterComplete) scheduleRenderProcessExit();
}
+// fallow-ignore-next-line complexity
export async function renderLocal(
projectDir: string,
outputPath: string,
@@ -885,6 +935,8 @@ export async function renderLocal(
...(options.pageNavigationTimeoutMs != null
? { pageNavigationTimeout: options.pageNavigationTimeoutMs }
: {}),
+ ...(options.protocolTimeout != null && { protocolTimeout: options.protocolTimeout }),
+ ...(options.playerReadyTimeout != null && { playerReadyTimeout: options.playerReadyTimeout }),
}),
hdrMode: options.hdrMode,
crf: options.crf,
diff --git a/packages/core/scripts/test-hyperframe-runtime-seek.ts b/packages/core/scripts/test-hyperframe-runtime-seek.ts
index e8bcafdda0..8ae32b877f 100644
--- a/packages/core/scripts/test-hyperframe-runtime-seek.ts
+++ b/packages/core/scripts/test-hyperframe-runtime-seek.ts
@@ -93,12 +93,18 @@ function testGsapAdapterPreservesTotalTime(): void {
const { calls, timeline } = createTimeline(true);
const adapter = createGsapAdapter({ getTimeline: () => timeline });
- adapter.seek({ time: 2.033333333333333 });
+ const seekTime = 2.033333333333333;
+ adapter.seek({ time: seekTime });
assert.deepEqual(
calls,
- [{ method: "pause" }, { method: "totalTime", time: 2.033333333333333, suppressEvents: false }],
- "GSAP adapter should not downgrade deterministic seeks back to seek()",
+ [
+ { method: "pause" },
+ // Nudge to force GSAP 3.x dirty state before the real seek
+ { method: "totalTime", time: seekTime + 0.001, suppressEvents: true },
+ { method: "totalTime", time: seekTime, suppressEvents: false },
+ ],
+ "GSAP adapter should nudge then seek via totalTime() (not downgrade to seek())",
);
}
diff --git a/packages/core/src/parsers/gsapParser.stress.test.ts b/packages/core/src/parsers/gsapParser.stress.test.ts
index faaea81937..191521df64 100644
--- a/packages/core/src/parsers/gsapParser.stress.test.ts
+++ b/packages/core/src/parsers/gsapParser.stress.test.ts
@@ -869,16 +869,18 @@ describe("Additional edge cases", () => {
expect(result.animations[1].targetSelector).toBe("#el2");
});
- it("skips a variable target that is not bound to a DOM lookup", () => {
+ it("marks a variable target that is not bound to a DOM lookup as __unresolved__", () => {
const script = `
const tl = gsap.timeline({ paused: true });
tl.to(mysteryTarget, { opacity: 1, duration: 0.5 }, 0);
tl.to("#el2", { x: 100, duration: 0.5 }, 0);
`;
const result = parseGsapScript(script);
- // mysteryTarget has no resolvable selector binding — only the literal survives.
- expect(result.animations).toHaveLength(1);
- expect(result.animations[0].targetSelector).toBe("#el2");
+ // mysteryTarget has no resolvable selector binding — kept with __unresolved__ marker.
+ expect(result.animations).toHaveLength(2);
+ expect(result.animations[0].targetSelector).toBe("__unresolved__");
+ expect(result.animations[0].hasUnresolvedSelector).toBe(true);
+ expect(result.animations[1].targetSelector).toBe("#el2");
});
it("boolean values in vars are not included in properties", () => {
diff --git a/packages/core/src/parsers/gsapParser.test.ts b/packages/core/src/parsers/gsapParser.test.ts
index df9e7ff5d3..d4e0e7cd27 100644
--- a/packages/core/src/parsers/gsapParser.test.ts
+++ b/packages/core/src/parsers/gsapParser.test.ts
@@ -920,14 +920,16 @@ describe("variable-target resolution (querySelector pattern)", () => {
expect(result.animations[2].extras?.stagger).toBe("__raw:0.1");
});
- it("leaves unresolvable variable targets out of the animation list", () => {
+ it("marks unresolvable variable targets with __unresolved__ and hasUnresolvedSelector", () => {
const script = `
const tl = gsap.timeline({ paused: true });
tl.to(someUnknownThing, { opacity: 1, duration: 0.5 }, 0);
tl.to(".real", { opacity: 1, duration: 0.5 }, 1);
`;
const result = parseGsapScript(script);
- expect(result.animations.map((a) => a.targetSelector)).toEqual([".real"]);
+ expect(result.animations.map((a) => a.targetSelector)).toEqual(["__unresolved__", ".real"]);
+ expect(result.animations[0].hasUnresolvedSelector).toBe(true);
+ expect(result.animations[1].hasUnresolvedSelector).toBeUndefined();
});
});
diff --git a/packages/core/src/studio-api/routes/render.ts b/packages/core/src/studio-api/routes/render.ts
index ac3253f449..18caaafa5e 100644
--- a/packages/core/src/studio-api/routes/render.ts
+++ b/packages/core/src/studio-api/routes/render.ts
@@ -86,6 +86,7 @@ export function registerRenderRoutes(api: Hono, adapter: StudioApiAdapter): void
composition = body.composition;
}
+ // fallow-ignore-next-line code-duplication
const now = new Date();
const datePart = now.toISOString().slice(0, 10);
const timePart = now.toTimeString().slice(0, 8).replace(/:/g, "-");
diff --git a/packages/engine/src/config.ts b/packages/engine/src/config.ts
index 8669d9dc05..04a9455432 100644
--- a/packages/engine/src/config.ts
+++ b/packages/engine/src/config.ts
@@ -228,14 +228,14 @@ function getSystemTotalMb(): number {
function memoryAdaptiveCacheLimit(): number {
const total = getSystemTotalMb();
if (total < 4096) return 32;
- if (total < 8192) return 64;
+ if (total <= 8192) return 64;
return DEFAULT_CONFIG.frameDataUriCacheLimit;
}
function memoryAdaptiveCacheBytesMb(): number {
const total = getSystemTotalMb();
if (total < 4096) return 128;
- if (total < 8192) return 256;
+ if (total <= 8192) return 256;
return DEFAULT_CONFIG.frameDataUriCacheBytesLimitMb;
}
diff --git a/packages/engine/src/services/browserManager.ts b/packages/engine/src/services/browserManager.ts
index 2f4ebac0d6..9ddec17201 100644
--- a/packages/engine/src/services/browserManager.ts
+++ b/packages/engine/src/services/browserManager.ts
@@ -331,6 +331,7 @@ export async function acquireBrowser(
return launchPromise;
}
+// fallow-ignore-next-line complexity
async function launchBrowser(
chromeArgs: string[],
config?: Partial<
@@ -509,13 +510,13 @@ function getGpuMemBudgetMb(): number {
const total = getTotalMemMb();
if (total < 4096) return 512;
- if (total < 8192) return 1024;
+ if (total <= 8192) return 1024;
return Math.min(Math.floor(total / 2), 16384);
}
function getLowMemoryFlags(): string[] {
const total = getTotalMemMb();
- if (total >= 8192) return [];
+ if (total > 8192) return [];
const heapMb = total < 4096 ? 256 : 512;
return [`--js-flags=--max-old-space-size=${heapMb}`];
}
diff --git a/packages/producer/src/services/render/captureCost.ts b/packages/producer/src/services/render/captureCost.ts
index c4f3b2cb92..03d12381f9 100644
--- a/packages/producer/src/services/render/captureCost.ts
+++ b/packages/producer/src/services/render/captureCost.ts
@@ -161,7 +161,7 @@ export function resolveRenderWorkerCount(
export function createCaptureCalibrationConfig(cfg: EngineConfig): EngineConfig {
return {
...cfg,
- protocolTimeout: Math.min(cfg.protocolTimeout, CAPTURE_CALIBRATION_PROTOCOL_TIMEOUT_MS),
+ protocolTimeout: Math.max(cfg.protocolTimeout, CAPTURE_CALIBRATION_PROTOCOL_TIMEOUT_MS),
};
}
@@ -282,6 +282,7 @@ export interface CaptureCalibrationOutcome {
* the fallback fires (BeginFrame is no longer the active capture mode,
* so the probe session is no longer reusable).
*/
+// fallow-ignore-next-line complexity
export async function runCaptureCalibration(input: {
cfg: EngineConfig;
fileServer: FileServerHandle;
diff --git a/packages/producer/src/services/render/stages/compileStage.test.ts b/packages/producer/src/services/render/stages/compileStage.test.ts
index 4d4062049c..ed376370ed 100644
--- a/packages/producer/src/services/render/stages/compileStage.test.ts
+++ b/packages/producer/src/services/render/stages/compileStage.test.ts
@@ -37,6 +37,7 @@ function createCfg(overrides: Partial<EngineConfig> = {}): EngineConfig {
chromeArgs: [],
chromePath: undefined,
captureCostMultiplier: 1,
+ // fallow-ignore-next-line code-duplication
format: "jpeg",
jpegQuality: 80,
concurrency: "auto",
diff --git a/packages/producer/src/services/renderOrchestrator.test.ts b/packages/producer/src/services/renderOrchestrator.test.ts
index e18f213616..528b5b9c2e 100644
--- a/packages/producer/src/services/renderOrchestrator.test.ts
+++ b/packages/producer/src/services/renderOrchestrator.test.ts
@@ -212,6 +212,7 @@ describe("materializeExtractedFramesForCompiledDir", () => {
expect(extracted.framePaths.get(0)).toBe(framePath);
});
+ // fallow-ignore-next-line code-duplication
it("remaps Windows cache frames under compiledDir using only the frame basename", () => {
const compiledDir = win32.resolve("C:\\compiled");
const outputDir = win32.resolve("D:\\cache\\abc123");
@@ -219,6 +220,7 @@ describe("materializeExtractedFramesForCompiledDir", () => {
const extracted = createExtractedFrames(outputDir, framePath);
const symlinks: Array<{ target: string; path: string }> = [];
+ // fallow-ignore-next-line code-duplication
materializeExtractedFramesForCompiledDir([extracted], compiledDir, {
pathModule: win32,
fileSystem: {
@@ -240,6 +242,7 @@ describe("materializeExtractedFramesForCompiledDir", () => {
expect(symlinks).toEqual([{ target: outputDir, path: linkPath }]);
});
+ // fallow-ignore-next-line code-duplication
it("recursively copies frames into compiledDir when materializeSymlinks is true", () => {
// Distributed plan() must produce a self-contained planDir — symlinks
// don't survive S3 / GCS round-trips. With materializeSymlinks=true the
@@ -250,6 +253,7 @@ describe("materializeExtractedFramesForCompiledDir", () => {
const extracted = createExtractedFrames(outputDir, framePath);
const copies: Array<{ src: string; dest: string; recursive: boolean }> = [];
+ // fallow-ignore-next-line code-duplication
materializeExtractedFramesForCompiledDir([extracted], compiledDir, {
pathModule: win32,
fileSystem: {
@@ -385,6 +389,7 @@ function createCompiledComposition(
};
}
+// fallow-ignore-next-line code-duplication
function createConfig(): EngineConfig {
return {
fps: 30,
@@ -421,6 +426,7 @@ function createConfig(): EngineConfig {
}
describe("applyRenderModeHints", () => {
+ // fallow-ignore-next-line code-duplication
it("forces screenshot mode when compatibility hints recommend it", () => {
const compiled = createCompiledComposition(["iframe", "requestAnimationFrame"]);
const log = {
@@ -451,6 +457,7 @@ describe("applyRenderModeHints", () => {
expect(log.warn).not.toHaveBeenCalled();
});
+ // fallow-ignore-next-line code-duplication
it("returns false when neither caller nor hint forces", () => {
const compiled = createCompiledComposition([]);
const log = {
@@ -561,6 +568,7 @@ describe("resolveRenderWorkerCount", () => {
expect(workers).toBe(1);
});
+ // fallow-ignore-next-line code-duplication
it("forces single worker when html-in-canvas is detected", () => {
const log = {
error: vi.fn(),
@@ -587,6 +595,7 @@ describe("resolveRenderWorkerCount", () => {
expect(log.warn).toHaveBeenCalledOnce();
});
+ // fallow-ignore-next-line code-duplication
it("overrides explicit --workers when html-in-canvas is detected", () => {
const log = {
error: vi.fn(),
@@ -728,19 +737,21 @@ describe("selectCaptureCalibrationFrames", () => {
});
describe("capture calibration safeguards", () => {
- it("uses a bounded protocol timeout for calibration probes", () => {
+ it("respects user protocol timeout when higher than calibration default", () => {
const cfg = createConfig();
const calibrationCfg = createCaptureCalibrationConfig(cfg);
- expect(calibrationCfg.protocolTimeout).toBe(30000);
+ // User's 300s timeout is higher than the 30s calibration default — use the user's value
+ expect(calibrationCfg.protocolTimeout).toBe(300000);
expect(cfg.protocolTimeout).toBe(300000);
});
- it("preserves smaller explicit protocol timeouts for calibration probes", () => {
+ it("uses calibration floor when user timeout is lower", () => {
const cfg = createConfig();
cfg.protocolTimeout = 5000;
- expect(createCaptureCalibrationConfig(cfg).protocolTimeout).toBe(5000);
+ // 5s is below the 30s calibration floor — use the floor
+ expect(createCaptureCalibrationConfig(cfg).protocolTimeout).toBe(30000);
});
it("falls back to screenshot mode after beginFrame calibration failures", () => {
diff --git a/packages/studio/src/components/TimelineToolbar.tsx b/packages/studio/src/components/TimelineToolbar.tsx
index 5b6d5581b7..a478c53208 100644
--- a/packages/studio/src/components/TimelineToolbar.tsx
+++ b/packages/studio/src/components/TimelineToolbar.tsx
@@ -86,7 +86,7 @@ interface DomEditSessionSlice {
handleGsapRemoveKeyframe: (animId: string, pct: number) => void;
handleGsapAddKeyframe: (animId: string, pct: number, prop: string, val: number | string) => void;
handleGsapConvertToKeyframes: (animId: string) => void;
- handleGsapMaterializeKeyframes: (animId: string) => Promise<void>;
+ handleGsapMaterializeKeyframes?: (animId: string) => Promise<void>;
handleGsapAddAnimation: (method: "to" | "from" | "set" | "fromTo") => void;
previewIframeRef?: React.RefObject<HTMLIFrameElement | null>;
}
@@ -125,7 +125,7 @@ function useKeyframeToggle(session?: DomEditSessionSlice) {
? async () => {
const t = usePlayerStore.getState().currentTime;
if (kfAnim?.keyframes) {
- if (kfAnim.hasUnresolvedKeyframes) {
+ if (kfAnim.hasUnresolvedKeyframes && session.handleGsapMaterializeKeyframes) {
await session.handleGsapMaterializeKeyframes(kfAnim.id);
}
const elStart = Number.parseFloat(sel.dataAttributes?.start ?? "0") || 0;
diff --git a/packages/studio/src/player/components/Timeline.test.ts b/packages/studio/src/player/components/Timeline.test.ts
index 6b9390e63d..3d6e995f1b 100644
--- a/packages/studio/src/player/components/Timeline.test.ts
+++ b/packages/studio/src/player/components/Timeline.test.ts
@@ -230,7 +230,8 @@ describe("getTimelinePlayheadLeft", () => {
describe("getTimelineCanvasHeight", () => {
it("includes bottom scroll buffer below the last track", () => {
- expect(getTimelineCanvasHeight(3)).toBeGreaterThan(24 + 3 * 72);
+ // RULER_H (24) + trackCount * TRACK_H (48) + scroll buffer
+ expect(getTimelineCanvasHeight(3)).toBeGreaterThan(24 + 3 * 48);
});
it("still keeps ruler space when there are no tracks", () => {