Write HTML. Render video. Built for agents.
JavaScript aiai-agentsanimationclaude-codeffmpegframeworkgsaphtmlhtml-to-videomcpmotion-graphicspuppeteerrenderingtypescriptvideo-editor
feat(engine): sample Chrome process memory per capture session
Vance Ingalls428922162d48
diff --git a/packages/engine/src/services/frameCapture-chromeMemory.test.ts b/packages/engine/src/services/frameCapture-chromeMemory.test.tsnew file mode 100644index 0000000000..b564231188--- /dev/null+++ b/packages/engine/src/services/frameCapture-chromeMemory.test.ts@@ -0,0 +1,38 @@+import { describe, expect, it } from "vitest";+import { classifyChromeProcesses } from "./frameCapture.js";++describe("classifyChromeProcesses", () => {+ it("splits CDP SystemInfo.getProcessInfo rows by type and keeps the browser pid", () => {+ const pids = classifyChromeProcesses(100, [+ { type: "browser", id: 100, cpuTime: 0 },+ { type: "renderer", id: 101, cpuTime: 0 },+ { type: "renderer", id: 102, cpuTime: 0 },+ { type: "GPU", id: 103, cpuTime: 0 },+ { type: "utility", id: 104, cpuTime: 0 },+ ]);+ expect(pids).toEqual({ browser: 100, renderers: [101, 102], gpu: [103] });+ });++ it("works without a browser pid", () => {+ expect(classifyChromeProcesses(undefined, [{ type: "renderer", id: 7, cpuTime: 0 }])).toEqual({+ renderers: [7],+ gpu: [],+ });+ });++ it("keeps the browser pid even when CDP reports no children", () => {+ expect(classifyChromeProcesses(100, [])).toEqual({ browser: 100, renderers: [], gpu: [] });+ });++ it("ignores process types that are neither renderer nor GPU", () => {+ // Guard mutation: dropping the `type` checks would fold utility/browser+ // rows into `renderers` and inflate the renderer peak.+ expect(+ classifyChromeProcesses(1, [+ { type: "utility", id: 2, cpuTime: 0 },+ { type: "browser", id: 1, cpuTime: 0 },+ { type: "gpu", id: 3, cpuTime: 0 },+ ]),+ ).toEqual({ browser: 1, renderers: [], gpu: [] });+ });+});diff --git a/packages/engine/src/services/frameCapture.ts b/packages/engine/src/services/frameCapture.tsindex bfcfa9ec41..03678cca8a 100644--- a/packages/engine/src/services/frameCapture.ts+++ b/packages/engine/src/services/frameCapture.ts@@ -84,6 +84,12 @@ import type {} from "../types.js";import { cloneCaptureWarnings } from "./captureWarning.js";import { installMediaRenderIdBridge } from "./mediaRenderIdBridge.js";+import {+ createChromeMemorySampler,+ type ChromeMemorySampler,+ type ChromePids,+} from "./chromeMemorySampler.js";+import { sampleProcessRss } from "../utils/processRss.js";export { isMemoryExhaustionError, isTransientBrowserError } from "./captureFailure.js";export type { CaptureOptions, CaptureResult, CaptureBufferResult, CapturePerfSummary };@@ -116,6 +122,8 @@ export interface CaptureSession {lastFrameAbsoluteIndex?: number;/** Count of frames served from a reused buffer (dedup telemetry). */staticDedupCount?: number;+ /** Live Chrome memory sampler; started in initializeSession, stopped in closeCaptureSession. */+ chromeMemory?: ChromeMemorySampler;/*** Resolved sub-frame motion-blur plan, or undefined when off. Set once by* `resolveSessionMotionBlur` at the end of initialization, where the capture mode has@@ -3858,6 +3866,58 @@ async function captureFrameSurface(function finalizeSessionInit(session: CaptureSession): void {session.motionBlur = resolveSessionMotionBlur(session);session.isInitialized = true;+ startChromeMemorySampler(session);+}++/** Shape of one `SystemInfo.getProcessInfo` row; only the fields we read. */+export interface CdpProcessInfoRow {+ type: string;+ id: number;+ cpuTime: number;+}++/** Group Chrome child pids by role. `browser` comes from puppeteer, not CDP. */+export function classifyChromeProcesses(+ browserPid: number | undefined,+ processInfo: readonly CdpProcessInfoRow[],+): ChromePids {+ const renderers: number[] = [];+ const gpu: number[] = [];+ for (const row of processInfo) {+ if (row.type === "renderer") renderers.push(row.id);+ else if (row.type === "GPU") gpu.push(row.id);+ }+ return browserPid === undefined ? { renderers, gpu } : { browser: browserPid, renderers, gpu };+}++const CHROME_MEMORY_SAMPLE_MS_DEFAULT = 2_000;++function resolveChromeMemorySampleMs(): number {+ const raw = process.env.HF_CHROME_MEMORY_SAMPLE_MS;+ const parsed = raw === undefined ? Number.NaN : Number(raw);+ return Number.isFinite(parsed) && parsed >= 250 ? parsed : CHROME_MEMORY_SAMPLE_MS_DEFAULT;+}++function startChromeMemorySampler(session: CaptureSession): void {+ if (session.chromeMemory) return;+ if (process.env.HF_CHROME_MEMORY_SAMPLER === "false") return;+ const sampler = createChromeMemorySampler({+ intervalMs: resolveChromeMemorySampleMs(),+ onSample: session.options.onMemorySample,+ sampleRss: (pids) => sampleProcessRss(pids),+ getPids: async () => {+ const browserPid = session.browser.process()?.pid;+ const cdp = await session.page.createCDPSession();+ try {+ const info = await cdp.send("SystemInfo.getProcessInfo");+ return classifyChromeProcesses(browserPid, info.processInfo);+ } finally {+ await cdp.detach().catch(() => {});+ }+ },+ });+ session.chromeMemory = sampler;+ sampler.start();}/** Choose how many samples this frame gets when the plan is adaptive: the floor with@@ -4456,6 +4516,12 @@ export async function discardWarmupCapture(}export async function closeCaptureSession(session: CaptureSession): Promise<void> {+ if (session.chromeMemory) {+ session.chromeMemory.stop();+ // One last sample so the summary reflects the session's end state, not a+ // point up to `intervalMs` earlier. Best effort; the page may be gone.+ await session.chromeMemory.sampleOnce();+ }// Realized static-dedup telemetry: how much the cache actually helped this// render (vs the prediction logged at arm time). Both capture paths// (sequential orchestrator + parallel workers) close their session here, so@@ -4753,6 +4819,11 @@ export function getCapturePerfSummary(session: CaptureSession): CapturePerfSummabeginFrameHasDamage: session.beginFrameHasDamageCount,captureMode: session.captureMode,gpuRenderer: session.gpuRenderer,+ chromeBrowserRssPeakMb: session.chromeMemory?.stats().browserRssPeakMb,+ chromeRendererRssPeakMb: session.chromeMemory?.stats().rendererRssPeakMb,+ chromeRssLastMb: session.chromeMemory?.stats().rssLastMb,+ chromeGpuProcessSeenLastSample: session.chromeMemory?.stats().gpuProcessSeenLastSample,+ chromeMemorySamples: session.chromeMemory?.stats().samples,deGateReason: session.deGateReason,deFallbackTrigger: session.deFallbackTrigger,deWorkerEncode: session.workerEncodeEnabled ?? false,diff --git a/packages/engine/src/types.ts b/packages/engine/src/types.tsindex 7c0be1bfd3..e58e7f360f 100644--- a/packages/engine/src/types.ts+++ b/packages/engine/src/types.ts@@ -361,6 +361,14 @@ export interface CapturePerfSummary {* see `classifyGpuRenderer`.*/gpuRenderer?: string;+ // ── Chrome process memory (spec: long-form render capture, Phase −1).+ // Undefined when the sampler was disabled (HF_CHROME_MEMORY_SAMPLER=false)+ // or never produced a successful sample. ──+ chromeBrowserRssPeakMb?: number;+ chromeRendererRssPeakMb?: number;+ chromeRssLastMb?: number;+ chromeGpuProcessSeenLastSample?: boolean;+ chromeMemorySamples?: number;/*** Low-cardinality init-time gate that routed a drawElement-eligible session* to the baseline: `swiftshader` | `css_effect:<fx>` | `at_risk_timeline` |