🎥 Make videos programmatically with React
Skills: Add WebMCP-controlled React Scan recordings
Jonny Burger33ef2f38fd44
diff --git a/.agents/skills/react-scan/SKILL.md b/.agents/skills/react-scan/SKILL.mdindex 237fd34f79..b1cbd1ebf6 100644--- a/.agents/skills/react-scan/SKILL.md+++ b/.agents/skills/react-scan/SKILL.md@@ -16,9 +16,18 @@ Start from the repository root:bun run react-scan:capture -- --label <short-kebab-case-description>```-Wait for Studio to finish building and settle. Perform one named interaction-three times, then stop the command with Ctrl+C. Keep captures short so startup,-HMR, and unrelated interactions do not dominate the data.+Wait for Studio to finish building, open the printed Studio URL with the browser,+and let the page settle. The React Scan WebMCP tools are only registered in this+development capture mode.++Call `start_react_scan_recording`, then use browser-use to perform one named+interaction three times. Call `stop_react_scan_recording` immediately+afterwards. Keep the recording short so startup, HMR, and unrelated interactions+do not dominate the data. Call `get_react_scan_recording` to return the raw+events and the same agent-oriented summary used by the on-disk collector.++After retrieving the recording, stop the capture command with Ctrl+C. This+finalizes the on-disk copy for deeper inspection and comparison.The command writes an ignored directory under `out/react-scan/` containing:@@ -34,9 +43,10 @@ not record with the React DevTools Timeline Profiler at the same time.## Analyze the evidence-Read `metadata.json` and `summary.json` first. Confirm the capture contains-commit events and inspect `profilingHooksStatuses`; do not interpret a missing-profiling channel as an idle application.+Read the `summary` returned by `get_react_scan_recording` first. For the persisted+capture, read `metadata.json` and `summary.json` before the raw events. Confirm+the capture contains commit events and inspect `profilingHooksStatuses`; do not+interpret a missing profiling channel as an idle application.Prioritize components with high total self duration, repeated expensiverenders, or a clear user-visible slow commit. Inclusive duration contains childdiff --git a/packages/.monorepo/react-scan/client.ts b/packages/.monorepo/react-scan/client.tsindex d5aef7be13..95231d2e6a 100644--- a/packages/.monorepo/react-scan/client.ts+++ b/packages/.monorepo/react-scan/client.ts@@ -1,5 +1,6 @@import type {LiteEvent} from 'react-scan/lite';import {instrument} from 'react-scan/lite';+import {summarizeReactScanEvents} from './summarize';const endpoint = process.env.REMOTION_REACT_SCAN_ENDPOINT;const sessionId = process.env.REMOTION_REACT_SCAN_SESSION_ID;@@ -9,9 +10,17 @@ if (!endpoint || !sessionId) {}const pendingEvents: LiteEvent[] = [];+const recordingContextEvents = new Map<string, LiteEvent>();+let recordedEvents: LiteEvent[] = [];+let recordingStartedAt: string | null = null;+let recordingStartedAtInMilliseconds: number | null = null;+let recordingEndedAt: string | null = null;+let recordingDurationInMilliseconds: number | null = null;+let isRecording = false;let flushTimer: ReturnType<typeof setTimeout> | null = null;let batchSequence = 0;let warnedAboutConnectionFailure = false;+let flushChain = Promise.resolve();const flush = () => {if (flushTimer !== null) {@@ -20,58 +29,209 @@ const flush = () => {}if (pendingEvents.length === 0) {- return;+ return flushChain;}const events = pendingEvents.splice(0, pendingEvents.length);const sequence = batchSequence;batchSequence++;- fetch(endpoint, {- body: JSON.stringify({- client:- sequence === 0- ? {- devicePixelRatio: window.devicePixelRatio,- height: window.innerHeight,- href: window.location.href,- userAgent: navigator.userAgent,- width: window.innerWidth,- }- : undefined,- events,- sequence,- sessionId,- }),- headers: {'Content-Type': 'application/json'},- method: 'POST',- }).catch(() => {- if (!warnedAboutConnectionFailure) {- warnedAboutConnectionFailure = true;- // eslint-disable-next-line no-console- console.warn('Could not stream React Scan events to the collector.');+ flushChain = flushChain.then(async () => {+ try {+ await fetch(endpoint, {+ body: JSON.stringify({+ client:+ sequence === 0+ ? {+ devicePixelRatio: window.devicePixelRatio,+ height: window.innerHeight,+ href: window.location.href,+ userAgent: navigator.userAgent,+ width: window.innerWidth,+ }+ : undefined,+ events,+ sequence,+ sessionId,+ }),+ headers: {'Content-Type': 'application/json'},+ method: 'POST',+ });+ } catch {+ if (!warnedAboutConnectionFailure) {+ warnedAboutConnectionFailure = true;+ console.warn('Could not stream React Scan events to the collector.');+ }}});++ return flushChain;+};++const getRecordingStatus = () => ({+ durationInMilliseconds: recordingDurationInMilliseconds,+ endedAt: recordingEndedAt,+ eventCount: recordedEvents.length,+ recording: isRecording,+ startedAt: recordingStartedAt,+});++type WebMcpTool = {+ readonly name: string;+ readonly title: string;+ readonly description: string;+ readonly inputSchema: Record<string, unknown>;+ readonly annotations: {readonly readOnlyHint: boolean};+ readonly execute: (input: Record<string, unknown>) => Promise<unknown>;+};++type WebMcpModelContext = {+ registerTool: (+ tool: WebMcpTool,+ options: {readonly signal: AbortSignal},+ ) => Promise<void>;+};++const {modelContext} = document as Document & {+ readonly modelContext?: WebMcpModelContext;};+if (typeof modelContext?.registerTool === 'function') {+ const controller = new AbortController();+ const emptyInputSchema = {+ type: 'object',+ properties: {},+ additionalProperties: false,+ };++ Promise.all([+ modelContext.registerTool(+ {+ name: 'start_react_scan_recording',+ title: 'Start React Scan recording',+ description:+ 'Start a focused React Scan Lite recording in this development Studio. This clears the previous in-memory recording. Keep recordings short and perform only the interaction being measured.',+ inputSchema: emptyInputSchema,+ annotations: {readOnlyHint: false},+ execute: async () => {+ if (isRecording) {+ throw new Error('React Scan is already recording.');+ }++ if (flushTimer !== null) {+ clearTimeout(flushTimer);+ flushTimer = null;+ }++ pendingEvents.splice(0, pendingEvents.length);+ recordedEvents = [...recordingContextEvents.values()];+ pendingEvents.push(...recordedEvents);+ recordingStartedAt = new Date().toISOString();+ recordingStartedAtInMilliseconds = performance.now();+ recordingEndedAt = null;+ recordingDurationInMilliseconds = null;+ isRecording = true;++ return getRecordingStatus();+ },+ },+ {signal: controller.signal},+ ),+ modelContext.registerTool(+ {+ name: 'stop_react_scan_recording',+ title: 'Stop React Scan recording',+ description:+ 'Stop the active React Scan Lite recording and freeze it for retrieval. Call get_react_scan_recording afterwards to return its events and summary.',+ inputSchema: emptyInputSchema,+ annotations: {readOnlyHint: false},+ execute: async () => {+ if (!isRecording || recordingStartedAtInMilliseconds === null) {+ throw new Error('React Scan is not recording.');+ }++ recordingDurationInMilliseconds = Number(+ (performance.now() - recordingStartedAtInMilliseconds).toFixed(3),+ );+ recordingEndedAt = new Date().toISOString();+ isRecording = false;+ await flush();++ return getRecordingStatus();+ },+ },+ {signal: controller.signal},+ ),+ modelContext.registerTool(+ {+ name: 'get_react_scan_recording',+ title: 'Get React Scan recording',+ description:+ 'Return the current React Scan Lite recording, including raw events and a summary ranked by commit and component cost. Stop the recording first so the result is stable.',+ inputSchema: emptyInputSchema,+ annotations: {readOnlyHint: true},+ execute: async () => {+ if (recordingStartedAt === null) {+ throw new Error('No React Scan recording has been started.');+ }+ if (isRecording) {+ throw new Error('Stop React Scan before returning the recording.');+ }++ const receivedAt = new Date().toISOString();+ return {+ ...getRecordingStatus(),+ events: recordedEvents,+ summary: summarizeReactScanEvents(+ recordedEvents.map((event, eventIndex) => ({+ event,+ eventIndex,+ receivedAt,+ sequence: 0,+ sessionId,+ })),+ ),+ };+ },+ },+ {signal: controller.signal},+ ),+ ]).catch(() => undefined);+}+instrument({includeFiberIdentity: true,includeFiberSource: true,maxFibersPerCommit: 5000,minFiberActualDurationMs: 0,onEvent: (event) => {+ if (+ event.kind === 'renderer-injected' ||+ event.kind === 'profiling-hooks-status'+ ) {+ recordingContextEvents.set(+ `${event.kind}:${event.rendererId ?? 'unknown'}`,+ event,+ );+ }++ if (!isRecording) {+ return;+ }++ recordedEvents.push(event);pendingEvents.push(event);if (pendingEvents.length >= 20) {- flush();+ void flush();return;}if (flushTimer === null) {- flushTimer = setTimeout(flush, 100);+ flushTimer = setTimeout(() => void flush(), 100);}},recordChangeDescriptions: true,});-window.addEventListener('pagehide', flush);+window.addEventListener('pagehide', () => void flush());diff --git a/packages/example/e2e/studio-lifecycle-webmcp.test.mts b/packages/example/e2e/studio-lifecycle-webmcp.test.mtsindex fabd156577..d1938eabaf 100644--- a/packages/example/e2e/studio-lifecycle-webmcp.test.mts+++ b/packages/example/e2e/studio-lifecycle-webmcp.test.mts@@ -1,9 +1,10 @@import {spawn} from 'node:child_process';import {createServer} from 'node:net';+import path from 'node:path';import {expect, test} from '@playwright/test';import {e2eEntryPoint, exampleDir, remotionBin} from './constants.mts';-test('WebMCP restarts Studio and gracefully shuts it down through the public APIs', async ({+test('WebMCP records React Scan and controls the Studio lifecycle', async ({page,}) => {test.setTimeout(120_000);@@ -25,7 +26,20 @@ test('WebMCP restarts Studio and gracefully shuts it down through the public API'--no-open','--force-new',],- {cwd: exampleDir, stdio: 'pipe'},+ {+ cwd: exampleDir,+ env: {+ ...process.env,+ REMOTION_REACT_SCAN_ENDPOINT:+ 'http://127.0.0.1:9/react-scan-e2e-not-used',+ REMOTION_REACT_SCAN_ENTRY_POINT: path.resolve(+ exampleDir,+ '../.monorepo/react-scan/client.ts',+ ),+ REMOTION_REACT_SCAN_SESSION_ID: 'react-scan-e2e',+ },+ stdio: 'pipe',+ },);let logs = '';studio.stdout.on('data', (data: Buffer) => {@@ -60,7 +74,10 @@ test('WebMCP restarts Studio and gracefully shuts it down through the public API});});await page.goto(studioUrl);- const runTool = async (name: string) => {+ const runTool = async (+ name: string,+ input: Record<string, unknown> = {},+ ) => {await expect.poll(() =>page.evaluate((toolName) => {@@ -72,25 +89,58 @@ test('WebMCP restarts Studio and gracefully shuts it down through the public API}, name),).toBe(true);- return page.evaluate(async (toolName) => {- const tool = (- window as typeof window & {- __remotion_webmcp_tools: Map<- string,- {- annotations: {readOnlyHint: boolean};- execute: (input: Record<string, unknown>) => Promise<unknown>;- }- >;- }- ).__remotion_webmcp_tools.get(toolName);- if (!tool) throw new Error('Tool not registered');- return {- readOnly: tool.annotations.readOnlyHint,- result: await tool.execute({}),- };- }, name);+ return page.evaluate(+ async ({input, name: toolName}) => {+ const tool = (+ window as typeof window & {+ __remotion_webmcp_tools: Map<+ string,+ {+ annotations: {readOnlyHint: boolean};+ execute: (input: Record<string, unknown>) => Promise<unknown>;+ }+ >;+ }+ ).__remotion_webmcp_tools.get(toolName);+ if (!tool) throw new Error('Tool not registered');+ return {+ readOnly: tool.annotations.readOnlyHint,+ result: await tool.execute(input),+ };+ },+ {input, name},+ );};+ expect(await runTool('start_react_scan_recording')).toMatchObject({+ readOnly: false,+ result: {recording: true},+ });+ await runTool('select_composition', {+ compositionName: 'AnimatedBarChart',+ });+ await runTool('select_composition', {+ compositionName: 'schema-test',+ });+ await page.waitForTimeout(100);+ const stoppedRecording = await runTool('stop_react_scan_recording');+ expect(stoppedRecording).toMatchObject({+ readOnly: false,+ result: {recording: false},+ });+ expect(+ (stoppedRecording.result as {eventCount: number}).eventCount,+ ).toBeGreaterThan(0);+ const recording = await runTool('get_react_scan_recording');+ expect(recording.readOnly).toBe(true);+ expect(+ (recording.result as {summary: {commitCount: number}}).summary+ .commitCount,+ ).toBeGreaterThan(0);+ expect(+ (recording.result as {events: Array<{kind: string}>}).events.some(+ (event) => event.kind === 'commit',+ ),+ ).toBe(true);expect(await runTool('restart_studio')).toEqual({readOnly: false,result: {},