Write HTML. Render video. Built for agents.
JavaScript aiai-agentsanimationclaude-codeffmpegframeworkgsaphtmlhtml-to-videomcpmotion-graphicspuppeteerrenderingtypescriptvideo-editor
feat(engine): chrome memory sampler with live onMemorySample capture option
Vance Ingalls53403a589608
diff --git a/packages/engine/src/index.ts b/packages/engine/src/index.tsindex 781d91d86d..6faa6dcb8f 100644--- a/packages/engine/src/index.ts+++ b/packages/engine/src/index.ts@@ -139,6 +139,10 @@ export {type CaptureFailureKind,type CaptureWorkerDiagnostic,} from "./services/captureFailure.js";+export {+ createChromeMemorySampler,+ type ChromeMemoryStats,+} from "./services/chromeMemorySampler.js";// ── Screenshot (BeginFrame) ─────────────────────────────────────────────────────export {diff --git a/packages/engine/src/services/chromeMemorySampler.test.ts b/packages/engine/src/services/chromeMemorySampler.test.tsnew file mode 100644index 0000000000..46b54965f2--- /dev/null+++ b/packages/engine/src/services/chromeMemorySampler.test.ts@@ -0,0 +1,157 @@+import { afterEach, describe, expect, it, vi } from "vitest";+import {+ createChromeMemorySampler,+ mergeSample,+ type ChromeMemoryStats,+ type ChromePids,+} from "./chromeMemorySampler.js";++const empty: ChromeMemoryStats = { samples: 0 };++describe("mergeSample", () => {+ it("tracks browser and renderer peaks separately and sums the last sample", () => {+ const pids: ChromePids = { browser: 1, renderers: [2, 3], gpu: [4] };+ const first = mergeSample(empty, pids, [+ { pid: 1, rssMb: 100 },+ { pid: 2, rssMb: 300 },+ { pid: 3, rssMb: 200 },+ { pid: 4, rssMb: 50 },+ ]);+ expect(first).toEqual({+ browserRssPeakMb: 100,+ rendererRssPeakMb: 300,+ rssLastMb: 650,+ gpuProcessSeenLastSample: true,+ samples: 1,+ });+ const second = mergeSample(first, { browser: 1, renderers: [2], gpu: [] }, [+ { pid: 1, rssMb: 90 },+ { pid: 2, rssMb: 250 },+ ]);+ expect(second).toEqual({+ browserRssPeakMb: 100,+ rendererRssPeakMb: 300,+ rssLastMb: 340,+ gpuProcessSeenLastSample: false,+ samples: 2,+ });+ });++ it("does not count a sample that returned no rows", () => {+ expect(mergeSample(empty, { renderers: [], gpu: [] }, [])).toEqual(empty);+ });+});++describe("createChromeMemorySampler", () => {+ afterEach(() => vi.useRealTimers());++ it("samples on the interval, reports via onSample, and stops cleanly", async () => {+ vi.useFakeTimers();+ const seen: ChromeMemoryStats[] = [];+ const sampler = createChromeMemorySampler({+ getPids: async () => ({ browser: 1, renderers: [2], gpu: [] }),+ sampleRss: async () => [+ { pid: 1, rssMb: 10 },+ { pid: 2, rssMb: 20 },+ ],+ intervalMs: 1000,+ onSample: (s) => seen.push(s),+ });+ sampler.start();+ await vi.advanceTimersByTimeAsync(2500);+ sampler.stop();+ await vi.advanceTimersByTimeAsync(5000);+ expect(seen.length).toBe(2);+ expect(sampler.stats()).toEqual({+ browserRssPeakMb: 10,+ rendererRssPeakMb: 20,+ rssLastMb: 30,+ gpuProcessSeenLastSample: false,+ samples: 2,+ });+ });++ it("never lets a dependency error escape and keeps sampling", async () => {+ vi.useFakeTimers();+ let calls = 0;+ const sampler = createChromeMemorySampler({+ getPids: async () => {+ calls += 1;+ if (calls === 1) throw new Error("cdp gone");+ return { browser: 1, renderers: [], gpu: [] };+ },+ sampleRss: async () => [{ pid: 1, rssMb: 5 }],+ intervalMs: 100,+ });+ sampler.start();+ await vi.advanceTimersByTimeAsync(250);+ sampler.stop();+ expect(sampler.stats().samples).toBe(1);+ });++ it("resolves sampleOnce() even when a dependency throws", async () => {+ // Direct pin on the catch: the interval test above still ends at one+ // sample if the catch is removed (the next tick succeeds), so only this+ // assertion fails when the guard is gone.+ const sampler = createChromeMemorySampler({+ getPids: async () => {+ throw new Error("cdp gone");+ },+ sampleRss: async () => [],+ intervalMs: 100,+ });+ await expect(sampler.sampleOnce()).resolves.toBeUndefined();+ expect(sampler.stats()).toEqual(empty);+ });++ it("skips a tick while the previous sample is still in flight", async () => {+ vi.useFakeTimers();+ let inFlight = 0;+ let maxInFlight = 0;+ const sampler = createChromeMemorySampler({+ getPids: async () => {+ inFlight += 1;+ maxInFlight = Math.max(maxInFlight, inFlight);+ await new Promise((r) => setTimeout(r, 350));+ inFlight -= 1;+ return { browser: 1, renderers: [], gpu: [] };+ },+ sampleRss: async () => [{ pid: 1, rssMb: 1 }],+ intervalMs: 100,+ });+ sampler.start();+ await vi.advanceTimersByTimeAsync(1000);+ sampler.stop();+ expect(maxInFlight).toBe(1);+ });++ it("does not invoke onSample when a sample returned no rows", async () => {+ const onSample = vi.fn();+ const sampler = createChromeMemorySampler({+ getPids: async () => ({ browser: 1, renderers: [], gpu: [] }),+ sampleRss: async () => [],+ intervalMs: 100,+ onSample,+ });+ await sampler.sampleOnce();+ expect(onSample).not.toHaveBeenCalled();+ expect(sampler.stats()).toEqual(empty);+ });++ it("start() twice schedules a single interval; stop() is safe before start and twice", async () => {+ vi.useFakeTimers();+ const sampler = createChromeMemorySampler({+ getPids: async () => ({ browser: 1, renderers: [], gpu: [] }),+ sampleRss: async () => [{ pid: 1, rssMb: 1 }],+ intervalMs: 100,+ });+ sampler.stop();+ sampler.start();+ sampler.start();+ await vi.advanceTimersByTimeAsync(250);+ sampler.stop();+ sampler.stop();+ await vi.advanceTimersByTimeAsync(500);+ expect(sampler.stats().samples).toBe(2);+ });+});diff --git a/packages/engine/src/services/chromeMemorySampler.ts b/packages/engine/src/services/chromeMemorySampler.tsnew file mode 100644index 0000000000..075626aa53--- /dev/null+++ b/packages/engine/src/services/chromeMemorySampler.ts@@ -0,0 +1,119 @@+import type { ProcessRssSample } from "../utils/processRss.js";++/**+ * Chrome process memory observed during one capture session. Peaks are+ * per-process-type maxima across samples; `rssLastMb` is the whole tree at+ * the most recent successful sample. Surfaced on render_error /+ * render_complete so the long-render "Target closed" class (spec §2.5) can be+ * correlated with memory instead of guessed at.+ */+export interface ChromeMemoryStats {+ browserRssPeakMb?: number;+ rendererRssPeakMb?: number;+ rssLastMb?: number;+ gpuProcessSeenLastSample?: boolean;+ samples: number;+}++export interface ChromePids {+ browser?: number;+ renderers: number[];+ gpu: number[];+}++export interface ChromeMemorySamplerDeps {+ getPids: () => Promise<ChromePids>;+ sampleRss: (pids: readonly number[]) => Promise<ProcessRssSample[]>;+ intervalMs: number;+ onSample?: (stats: ChromeMemoryStats) => void;+ setIntervalFn?: typeof setInterval;+ clearIntervalFn?: typeof clearInterval;+}++export interface ChromeMemorySampler {+ start(): void;+ stop(): void;+ stats(): ChromeMemoryStats;+ /** One synchronous-to-the-caller sample; used by tests and by close(). */+ sampleOnce(): Promise<void>;+}++function maxDefined(a: number | undefined, b: number | undefined): number | undefined {+ if (a === undefined) return b;+ if (b === undefined) return a;+ return Math.max(a, b);+}++/** Pure merge of one sample into the running stats. Empty `rss` → unchanged. */+export function mergeSample(+ prev: ChromeMemoryStats,+ pids: ChromePids,+ rss: readonly ProcessRssSample[],+): ChromeMemoryStats {+ if (rss.length === 0) return prev;+ const byPid = new Map(rss.map((s) => [s.pid, s.rssMb]));+ const browserMb = pids.browser === undefined ? undefined : byPid.get(pids.browser);+ const rendererMbs = pids.renderers+ .map((p) => byPid.get(p))+ .filter((v): v is number => v !== undefined);+ const gpuMbs = pids.gpu.map((p) => byPid.get(p)).filter((v): v is number => v !== undefined);+ const rendererMax = rendererMbs.length > 0 ? Math.max(...rendererMbs) : undefined;+ const total = rss.reduce((sum, s) => sum + s.rssMb, 0);+ return {+ browserRssPeakMb: maxDefined(prev.browserRssPeakMb, browserMb),+ rendererRssPeakMb: maxDefined(prev.rendererRssPeakMb, rendererMax),+ rssLastMb: total,+ gpuProcessSeenLastSample: gpuMbs.length > 0,+ samples: prev.samples + 1,+ };+}++export function createChromeMemorySampler(deps: ChromeMemorySamplerDeps): ChromeMemorySampler {+ const setIntervalFn = deps.setIntervalFn ?? setInterval;+ const clearIntervalFn = deps.clearIntervalFn ?? clearInterval;+ let stats: ChromeMemoryStats = { samples: 0 };+ let timer: ReturnType<typeof setInterval> | null = null;+ let inFlight = false;++ const sampleOnce = async (): Promise<void> => {+ if (inFlight) return;+ inFlight = true;+ try {+ const pids = await deps.getPids();+ const all = [pids.browser, ...pids.renderers, ...pids.gpu].filter(+ (p): p is number => typeof p === "number",+ );+ const rss = await deps.sampleRss(all);+ const next = mergeSample(stats, pids, rss);+ if (next !== stats) {+ stats = next;+ deps.onSample?.(stats);+ }+ } catch {+ // Sampling is observability only; a CDP or ps failure must never reach+ // the capture loop. The next tick retries.+ } finally {+ inFlight = false;+ }+ };++ return {+ start() {+ if (timer !== null) return;+ // Node's Timeout has unref(); the engine already relies on it+ // (utils/processTracker.ts). Keeps the interval from holding the+ // process open if a caller forgets stop().+ timer = setIntervalFn(() => {+ void sampleOnce();+ }, deps.intervalMs);+ timer.unref();+ },+ stop() {+ if (timer === null) return;+ clearIntervalFn(timer);+ timer = null;+ },+ stats: () => stats,+ sampleOnce,+ };+}diff --git a/packages/engine/src/types.ts b/packages/engine/src/types.tsindex a150b3d1f4..7c0be1bfd3 100644--- a/packages/engine/src/types.ts+++ b/packages/engine/src/types.ts@@ -5,6 +5,7 @@* as video must expose `window.__hf` implementing the HfProtocol interface.*/import type { Fps } from "@hyperframes/core";+import type { ChromeMemoryStats } from "./services/chromeMemorySampler.js";import type { MotionBlurOptions } from "./services/motionBlur.js";/**@@ -136,6 +137,13 @@ export interface CaptureOptions {compositionDurationSeconds?: number;/** The composition declares `data-requires-webgpu`; skips createCaptureSession's own fetch. */requiresWebGpu?: boolean;+ /**+ * Live Chrome memory samples during capture (browser/renderer RSS peaks,+ * last total, GPU process presence). Invoked from an unref'd interval; must+ * not throw. The producer forwards these to capture observability so a+ * crash mid-render still reports the last known memory state.+ */+ onMemorySample?: (stats: ChromeMemoryStats) => void;/*** Frame rate as an exact rational. Integer fps is `{ num: 30, den: 1 }`;* NTSC is `{ num: 30000, den: 1001 }`. Captures are scheduled by the