Chrome DevTools for coding agents
feat: implement ffmpeg-free screencast tools enabled by default (#3123)
Alex Rudenko8953ea5159e3
diff --git a/docs/configuration.md b/docs/configuration.mdindex 3a1a9119..5c4e096e 100644--- a/docs/configuration.md+++ b/docs/configuration.md@@ -182,16 +182,16 @@ The Chrome DevTools MCP server supports the following configuration option:- **Default:** `false`- **`--experimentalScreencast`/ `--experimental-screencast`**- Exposes experimental screencast tools (requires ffmpeg). Install ffmpeg https://www.ffmpeg.org/download.html and ensure it is available in the MCP server PATH.+ Use the legacy ffmpeg-based screencast implementation instead of the built-in Chrome recorder. Install ffmpeg https://www.ffmpeg.org/download.html and ensure it is available in the MCP server PATH. This option is deprecated and will be removed in favour of dependency-free screencast commands that are available by default.- **Type:** boolean- **Default:** `false`- **`--experimentalFfmpegPath`/ `--experimental-ffmpeg-path`**- Path to ffmpeg executable for screencast recording.+ Path to ffmpeg executable for legacy screencast recording (requires --experimentalScreencast).- **Type:** string-- **`--experimentalScreencastFps`/ `--experimental-screencast-fps`**- Frames per second to use for screencast recording. Lower values can reduce memory pressure on pages that produce frames faster than ffmpeg can encode them.+- **`--screencastFps`/ `--screencast-fps`, `--experimentalScreencastFps`**+ Frames per second to use for screencast recording. Lower values reduce file size and encoding load.- **Type:** number- **`--performanceCrux`/ `--performance-crux`**diff --git a/docs/tool-reference.md b/docs/tool-reference.mdindex 86a47caf..3c36d1af 100644--- a/docs/tool-reference.md+++ b/docs/tool-reference.md@@ -36,10 +36,10 @@- [`get_css_styles`](#get_css_styles)- [`lighthouse_audit`](#lighthouse_audit)- [`list_console_messages`](#list_console_messages)- - [`take_screenshot`](#take_screenshot)- - [`take_snapshot`](#take_snapshot)- [`screencast_start`](#screencast_start)- [`screencast_stop`](#screencast_stop)+ - [`take_screenshot`](#take_screenshot)+ - [`take_snapshot`](#take_snapshot)- **[Memory](#memory)** (14 tools)- [`take_heapsnapshot`](#take_heapsnapshot)- [`analyze_heapsnapshot_contexts`](#analyze_heapsnapshot_contexts)@@ -454,53 +454,53 @@ Results are paginated (10 rules per page by default); use pageIdx to page throug----### `take_screenshot`+### `screencast_start`-**Description:** Take a screenshot of the page or element.+**Description:** Starts recording a screencast (video) of the target page.**Parameters:**- **pageId** (number) **(required)**: Targets a specific page by ID.-- **filePath** (string) _(optional)_: The absolute path, or a path relative to the current working directory, to save the screenshot to instead of attaching it to the response.-- **format** (enum: "png", "jpeg", "webp") _(optional)_: Type of format to save the screenshot as. Default is "png"-- **fullPage** (boolean) _(optional)_: If set to true takes a screenshot of the full page instead of the currently visible viewport. Incompatible with uid.-- **quality** (number) _(optional)_: Compression quality for JPEG and WebP formats (0-100). Higher values mean better quality but larger file sizes. Ignored for PNG format.-- **uid** (string) _(optional)_: The uid of an element on the page from the page content snapshot. If omitted, takes a page screenshot.+- **filePath** (string) _(optional)_: Output file path (.mp4). Uses mkdtemp to generate a unique path if not provided.----### `take_snapshot`+### `screencast_stop`-**Description:** Take a text snapshot of the target page based on the a11y tree. The snapshot lists page elements along with a unique-identifier (uid). Always use the latest snapshot. Prefer taking a snapshot over taking a screenshot. The snapshot indicates the element selected-in the DevTools Elements panel (if any).+**Description:** Stops the active screencast recording on the target page.**Parameters:**- **pageId** (number) **(required)**: Targets a specific page by ID.-- **filePath** (string) _(optional)_: The absolute path, or a path relative to the current working directory, to save the snapshot to instead of attaching it to the response.-- **verbose** (boolean) _(optional)_: Whether to include all possible information available in the full a11y tree. Default is false.----### `screencast_start`+### `take_screenshot`-**Description:** Starts recording a screencast (video) of the target page in specified format. (requires flag: --experimentalScreencast=true)+**Description:** Take a screenshot of the page or element.**Parameters:**- **pageId** (number) **(required)**: Targets a specific page by ID.-- **filePath** (string) _(optional)_: Output file path (.webm,.mp4 are supported). Uses mkdtemp to generate a unique path if not provided.+- **filePath** (string) _(optional)_: The absolute path, or a path relative to the current working directory, to save the screenshot to instead of attaching it to the response.+- **format** (enum: "png", "jpeg", "webp") _(optional)_: Type of format to save the screenshot as. Default is "png"+- **fullPage** (boolean) _(optional)_: If set to true takes a screenshot of the full page instead of the currently visible viewport. Incompatible with uid.+- **quality** (number) _(optional)_: Compression quality for JPEG and WebP formats (0-100). Higher values mean better quality but larger file sizes. Ignored for PNG format.+- **uid** (string) _(optional)_: The uid of an element on the page from the page content snapshot. If omitted, takes a page screenshot.----### `screencast_stop`+### `take_snapshot`-**Description:** Stops the active screencast recording on the target page. (requires flag: --experimentalScreencast=true)+**Description:** Take a text snapshot of the target page based on the a11y tree. The snapshot lists page elements along with a unique+identifier (uid). Always use the latest snapshot. Prefer taking a snapshot over taking a screenshot. The snapshot indicates the element selected+in the DevTools Elements panel (if any).**Parameters:**- **pageId** (number) **(required)**: Targets a specific page by ID.+- **filePath** (string) _(optional)_: The absolute path, or a path relative to the current working directory, to save the snapshot to instead of attaching it to the response.+- **verbose** (boolean) _(optional)_: Whether to include all possible information available in the full a11y tree. Default is false.---diff --git a/skills/chrome-devtools-cli/SKILL.md b/skills/chrome-devtools-cli/SKILL.mdindex 7e50f198..b1e8ae12 100644--- a/skills/chrome-devtools-cli/SKILL.md+++ b/skills/chrome-devtools-cli/SKILL.md@@ -152,6 +152,8 @@ chrome-devtools take_screenshot 1 --fullPage true --format "jpeg" --quality 80 #chrome-devtools take_screenshot 1 --uid "id" --filePath "s.png" # Take a screenshot of an elementchrome-devtools take_snapshot 1 # Take a text snapshot of the page from the a11y treechrome-devtools take_snapshot 1 --verbose true --filePath "s.txt" # Take a verbose snapshot and save to file+chrome-devtools screencast_start 1 --filePath "screen.mp4" # Starts an mp4 screencast recording on page 1+chrome-devtools screencast_stop 1 # Stops the active screencast on page 1```## Extensions@@ -179,8 +181,6 @@ Experimental tools are disabled by default. Enable them with the corresponding f```bashchrome-devtools click_at 1 100 200 # Clicks at the provided coordinates on page 1 (requires --experimentalVision=true)-chrome-devtools screencast_start 1 --filePath "screen.mp4" # Starts a screencast recording on page 1 (requires --experimentalScreencast=true and ffmpeg)-chrome-devtools screencast_stop 1 # Stops the active screencast on page 1chrome-devtools list_webmcp_tools 1 # List all WebMCP tools on page 1 (requires --categoryExperimentalWebmcp=true)chrome-devtools execute_webmcp_tool 1 "tool_name" --input '{"arg":"val"}' # Execute a WebMCP tool on page 1 (requires --categoryExperimentalWebmcp=true)chrome-devtools list_3p_developer_tools 1 # List third-party developer tools on page 1 (requires --categoryExperimentalThirdParty=true)diff --git a/src/McpContext.ts b/src/McpContext.tsindex d63c6240..942bc0d5 100644--- a/src/McpContext.ts+++ b/src/McpContext.ts@@ -34,7 +34,6 @@ import {type Page,type Protocol,type PWAState,- type ScreenRecorder,type Target,type UninstallPWAOptions,type Extension,@@ -108,8 +107,6 @@ export class McpContext implements Context {#serviceWorkerConsoleCollector: ServiceWorkerConsoleCollector;#isRunningTrace = false;- #screenRecorderData: {recorder: ScreenRecorder; filePath: string} | null =- null;#reconnectNotice = false;@@ -404,16 +401,6 @@ export class McpContext implements Context {return this.#isRunningTrace;}- getScreenRecorder(): {recorder: ScreenRecorder; filePath: string} | null {- return this.#screenRecorderData;- }-- setScreenRecorder(- data: {recorder: ScreenRecorder; filePath: string} | null,- ): void {- this.#screenRecorderData = data;- }-isCruxEnabled(): boolean {return this.#options.performanceCrux;}diff --git a/src/McpPage.ts b/src/McpPage.tsindex 9d87159e..8dd6ed05 100644--- a/src/McpPage.ts+++ b/src/McpPage.ts@@ -37,6 +37,7 @@ import type {DevToolsData,MatchedStyles,Response,+ ScreenRecorderData,} from './tools/ToolDefinition.js';import type {EmulationSettings,@@ -170,6 +171,9 @@ export class McpPage implements ContextPage {#dialog?: Dialog;#dialogHandler: (dialog: Dialog) => void;+ // Screencast+ #screenRecorder: ScreenRecorderData | null = null;+eventBasedThirdPartyTools: ToolGroups = [];#networkCollector?: NetworkCollector;@@ -371,6 +375,14 @@ export class McpPage implements ContextPage {this.#dialog = undefined;}+ getScreenRecorder(): ScreenRecorderData | null {+ return this.#screenRecorder;+ }++ setScreenRecorder(data: ScreenRecorderData | null): void {+ this.#screenRecorder = data;+ }+throwIfDialogOpen(): void {if (this.#dialog && !this.#dialog.handled) {throw new Error(diff --git a/src/config/cli-options.ts b/src/config/cli-options.tsindex e023ef4e..c63ef58e 100644--- a/src/config/cli-options.ts+++ b/src/config/cli-options.ts@@ -1555,8 +1555,7 @@ export const commands: Commands = {},},screencast_start: {- description:- 'Starts recording a screencast (video) of the target page in specified format. (requires flag: --experimentalScreencast=true)',+ description: 'Starts recording a screencast (video) of the target page.',category: 'Debugging',args: {pageId: {@@ -1569,14 +1568,13 @@ export const commands: Commands = {name: 'filePath',type: 'string',description:- 'Output file path (.webm,.mp4 are supported). Uses mkdtemp to generate a unique path if not provided.',+ 'Output file path (.mp4). Uses mkdtemp to generate a unique path if not provided.',required: false,},},},screencast_stop: {- description:- 'Stops the active screencast recording on the target page. (requires flag: --experimentalScreencast=true)',+ description: 'Stops the active screencast recording on the target page.',category: 'Debugging',args: {pageId: {diff --git a/src/config/mcp-options.ts b/src/config/mcp-options.tsindex a62acc80..6ca24ddc 100644--- a/src/config/mcp-options.ts+++ b/src/config/mcp-options.ts@@ -109,18 +109,20 @@ export const mcpOptions = {type: 'boolean',default: false,describe:- 'Exposes experimental screencast tools (requires ffmpeg). Install ffmpeg https://www.ffmpeg.org/download.html and ensure it is available in the MCP server PATH.',+ 'Use the legacy ffmpeg-based screencast implementation instead of the built-in Chrome recorder. Install ffmpeg https://www.ffmpeg.org/download.html and ensure it is available in the MCP server PATH. This option is deprecated and will be removed in favour of dependency-free screencast commands that are available by default.',reloadable: true,},experimentalFfmpegPath: {type: 'string',- describe: 'Path to ffmpeg executable for screencast recording.',+ describe:+ 'Path to ffmpeg executable for legacy screencast recording (requires --experimentalScreencast).',reloadable: true,},- experimentalScreencastFps: {+ screencastFps: {type: 'number',+ alias: 'experimentalScreencastFps',describe:- 'Frames per second to use for screencast recording. Lower values can reduce memory pressure on pages that produce frames faster than ffmpeg can encode them.',+ 'Frames per second to use for screencast recording. Lower values reduce file size and encoding load.',reloadable: true,coerce: (value: number | undefined) => {if (value === undefined) {@@ -128,7 +130,7 @@ export const mcpOptions = {}if (!Number.isInteger(value) || value <= 0) {throw new Error(- `Invalid experimentalScreencastFps ${value}. Expected a positive integer.`,+ `Invalid screencastFps ${value}. Expected a positive integer.`,);}return value;@@ -375,7 +377,6 @@ export const IMPLICATIONS: Array<> = [['wsHeaders', 'wsEndpoint'],['experimentalFfmpegPath', 'experimentalScreencast'],- ['experimentalScreencastFps', 'experimentalScreencast'],];export function withoutDefaults(diff --git a/src/telemetry/flag_usage_metrics.json b/src/telemetry/flag_usage_metrics.jsonindex 948b7d94..d13eb04b 100644--- a/src/telemetry/flag_usage_metrics.json+++ b/src/telemetry/flag_usage_metrics.json@@ -400,7 +400,8 @@},{"name": "experimental_screencast_fps_present",- "flagType": "boolean"+ "flagType": "boolean",+ "isDeprecated": true},{"name": "filesystem_root_present",@@ -465,5 +466,9 @@{"name": "file_navigations","flagType": "boolean"+ },+ {+ "name": "screencast_fps_present",+ "flagType": "boolean"}]diff --git a/src/third_party/index.ts b/src/third_party/index.tsindex b0a4f002..8b4d3282 100644--- a/src/third_party/index.ts+++ b/src/third_party/index.ts@@ -71,6 +71,7 @@ export {PipeTransport} from 'puppeteer-core/internal/node/PipeTransport.js';export {CdpBrowser} from 'puppeteer-core/internal/cdp/Browser.js';export {CdpFrame} from 'puppeteer-core/internal/cdp/Frame.js';export {CdpPage} from 'puppeteer-core/internal/cdp/Page.js';+export {CdpScreenRecording} from 'puppeteer-core/internal/cdp/ScreenRecording.js';export {CdpExtension} from 'puppeteer-core/internal/cdp/Extension.js';export type {CdpWebWorker} from 'puppeteer-core/internal/cdp/WebWorker.js';export type {Realm} from 'puppeteer-core/internal/api/Realm.js';diff --git a/src/tools/ToolDefinition.ts b/src/tools/ToolDefinition.tsindex 233173a0..aab19596 100644--- a/src/tools/ToolDefinition.ts+++ b/src/tools/ToolDefinition.ts@@ -30,6 +30,7 @@ import type {LaunchPWAOptions,PWAState,ScreenRecorder,+ ScreenRecording,UninstallPWAOptions,Viewport,DevTools,@@ -297,6 +298,11 @@ export type SupportedExtensions =/*** Only add methods used by tools/*.*/+export interface ScreenRecorderData {+ recorder: ScreenRecorder | ScreenRecording;+ filePath: string;+}+export type Context = Readonly<{installPWA(options: InstallPWAOptions): Promise<string>;uninstallPWA(options: UninstallPWAOptions): Promise<void>;@@ -329,10 +335,6 @@ export type Context = Readonly<{): Promise<{filename: string}>;loadResource(path: string): Promise<string>;- getScreenRecorder(): {recorder: ScreenRecorder; filePath: string} | null;- setScreenRecorder(- data: {recorder: ScreenRecorder; filePath: string} | null,- ): void;installExtension(path: string): Promise<string>;uninstallExtension(id: string): Promise<void>;triggerExtensionAction(id: string): Promise<void>;@@ -437,6 +439,8 @@ export type ContextPage = Readonly<{getDialog(): Dialog | undefined;clearDialog(): void;throwIfDialogOpen(): void;+ getScreenRecorder(): ScreenRecorderData | null;+ setScreenRecorder(data: ScreenRecorderData | null): void;waitForEventsAfterAction(action: (signal: AbortSignal) => Promise<unknown>,options?: {diff --git a/src/tools/screencast.ts b/src/tools/screencast.tsindex cba48b48..5db386ca 100644--- a/src/tools/screencast.ts+++ b/src/tools/screencast.ts@@ -10,7 +10,11 @@ import path from 'node:path';import type {ParsedArguments} from '../config/ConfigParser.js';import {zod} from '../third_party/index.js';-import type {ScreenRecorder, VideoFormat} from '../third_party/index.js';+import type {+ ScreenRecorder,+ ScreenRecording,+ VideoFormat,+} from '../third_party/index.js';import {ToolCategory} from './categories.js';import {definePageTool} from './ToolDefinition.js';@@ -24,20 +28,45 @@ type SupportedVideoExtension = '.webm' | '.mp4';const supportedExtensions: SupportedVideoExtension[] = ['.webm', '.mp4'];+/**+ * Resolves the output extension for the legacy ffmpeg-based recorder.+ *+ * Matches the extension case-insensitively so e.g. `.WEBM` is recognized as+ * WebM. An explicitly requested but unsupported extension is rejected rather+ * than being silently rewritten to `.mp4` (which would change both the format+ * and the output path from what was requested). A missing extension falls+ * back to `.mp4`. The matched extension is normalized to lower case.+ */+function getLegacyExtension(filePath: string): SupportedVideoExtension {+ const requestedExtension = path.extname(filePath);+ const matchedExtension = supportedExtensions.find(+ supportedExtension =>+ supportedExtension === requestedExtension.toLowerCase(),+ );+ if (!matchedExtension && requestedExtension !== '') {+ throw new Error(+ `Unsupported screencast file extension "${requestedExtension}". ` ++ `Supported formats: ${supportedExtensions.join(', ')} (case-insensitive).`,+ );+ }+ return matchedExtension ?? '.mp4';+}+export const startScreencast = definePageTool((args: ParsedArguments) => ({name: 'screencast_start',- description: `Starts recording a screencast (video) of the target page in specified format.`,+ description: `Starts recording a screencast (video) of the target page.`,annotations: {category: ToolCategory.DEBUGGING,readOnlyHint: false,- conditions: ['experimentalScreencast'],},schema: {filePath: zod.string().optional().describe(- `Output file path (${supportedExtensions.join(',')} are supported). Uses mkdtemp to generate a unique path if not provided.`,+ args?.experimentalScreencast+ ? `Output file path (${supportedExtensions.join(',')} are supported). Uses mkdtemp to generate a unique path if not provided.`+ : 'Output file path (.mp4). Uses mkdtemp to generate a unique path if not provided.',),},blockedByDialog: false,@@ -45,7 +74,8 @@ export const startScreencast = definePageTool((args: ParsedArguments) => ({filePath: true,},handler: async (request, response, context) => {- if (context.getScreenRecorder() !== null) {+ const page = request.page;+ if (page.getScreenRecorder() !== null) {response.appendResponseLine('Error: a screencast recording is already in progress. Use screencast_stop to stop it before starting a new one.',);@@ -55,43 +85,28 @@ export const startScreencast = definePageTool((args: ParsedArguments) => ({const requestedFilePath = request.params.filePath;const filePath = requestedFilePath ?? (await generateTempFilePath());- // Match the extension case-insensitively so e.g. `.WEBM` is recognized as- // WebM. An explicitly requested but unsupported extension is rejected- // rather than being silently rewritten to `.mp4` (which would change both- // the format and the output path from what was requested). A missing- // extension falls back to `.mp4`. The matched extension is normalized to- // lower case.- const requestedExtension = path.extname(filePath);- const matchedExtension = supportedExtensions.find(- supportedExtension =>- supportedExtension === requestedExtension.toLowerCase(),- );- if (!matchedExtension && requestedExtension !== '') {- throw new Error(- `Unsupported screencast file extension "${requestedExtension}". ` +- `Supported formats: ${supportedExtensions.join(', ')} (case-insensitive).`,- );- }- const enforcedExtension: SupportedVideoExtension =- matchedExtension ?? '.mp4';- const format: VideoFormat = (matchedExtension?.substring(1) ??- 'mp4') as VideoFormat;-- const resolvedPath = await context.ensureExtension(- filePath,- enforcedExtension,- );+ // The built-in Chrome recorder (page.record) always produces mp4. The+ // legacy ffmpeg recorder (page.screencast) also supports WebM.+ const useLegacy = Boolean(args?.experimentalScreencast);+ const extension = useLegacy ? getLegacyExtension(filePath) : '.mp4';+ const resolvedPath = await context.ensureExtension(filePath, extension);- const page = request.page;-- let recorder: ScreenRecorder;+ let recorder: ScreenRecorder | ScreenRecording;try {- recorder = await page.pptrPage.screencast({- path: resolvedPath,- format,- ffmpegPath: args?.experimentalFfmpegPath,- fps: args?.experimentalScreencastFps,- });+ if (useLegacy) {+ const format: VideoFormat = extension === '.webm' ? 'webm' : 'mp4';+ recorder = await page.pptrPage.screencast({+ path: resolvedPath,+ format,+ ffmpegPath: args?.experimentalFfmpegPath,+ fps: args?.screencastFps,+ });+ } else {+ recorder = await page.pptrPage.record({+ path: resolvedPath,+ fps: args?.screencastFps,+ });+ }} catch (err) {// If we generated a temporary directory for this recording, remove it so// a failed start (e.g. ffmpeg missing) does not leak an empty directory.@@ -112,10 +127,15 @@ export const startScreencast = definePageTool((args: ParsedArguments) => ({'Install ffmpeg (https://ffmpeg.org/) and ensure it is available in your PATH.',);}+ if (message.includes('Page.startScreenRecording')) {+ throw new Error(+ 'The connected Chrome does not support screen recording. Update Chrome to a newer version.',+ );+ }throw err;}- context.setScreenRecorder({recorder, filePath: resolvedPath});+ page.setScreenRecorder({recorder, filePath: resolvedPath});response.appendResponseLine(`Screencast recording started. The recording will be saved to ${resolvedPath}. Use ${stopScreencast(args).name} to stop recording.`,@@ -129,13 +149,13 @@ export const stopScreencast = definePageTool(() => ({annotations: {category: ToolCategory.DEBUGGING,readOnlyHint: false,- conditions: ['experimentalScreencast'],},schema: {},blockedByDialog: false,verifyFilesSchema: {},- handler: async (_request, response, context) => {- const data = context.getScreenRecorder();+ handler: async (request, response) => {+ const page = request.page;+ const data = page.getScreenRecorder();if (!data) {response.appendResponseLine('Error: no active screencast recording to stop.',@@ -148,7 +168,7 @@ export const stopScreencast = definePageTool(() => ({`The screencast recording has been stopped and saved to ${data.filePath}.`,);} finally {- context.setScreenRecorder(null);+ page.setScreenRecorder(null);}},}));diff --git a/tests/cli.test.ts b/tests/cli.test.tsindex 1e112142..a5b09392 100644--- a/tests/cli.test.ts+++ b/tests/cli.test.ts@@ -372,7 +372,7 @@ describe('cli args parsing', () => {});it('rejects invalid screencast fps values', async () => {- const coerce = mcpOptions.experimentalScreencastFps.coerce;+ const coerce = mcpOptions.screencastFps.coerce;assert.ok(coerce);assert.strictEqual(coerce(undefined), undefined);@@ -381,11 +381,29 @@ describe('cli args parsing', () => {for (const value of [0, -1, 10.5, Number.NaN]) {assert.throws(() => coerce(value),- /Invalid experimentalScreencastFps .* Expected a positive integer\./,+ /Invalid screencastFps .* Expected a positive integer\./,);}});+ it('parses screencast fps without requiring experimental screencast', async () => {+ const args = parseConfig(['--screencast-fps=5']);+ assert.deepStrictEqual(args, {+ ...defaultArgs,+ channel: 'stable',+ screencastFps: 5,+ });+ });++ it('accepts --experimental-screencast-fps as an alias for --screencast-fps', async () => {+ const args = parseConfig(['--experimental-screencast-fps=5']);+ assert.deepStrictEqual(args, {+ ...defaultArgs,+ channel: 'stable',+ screencastFps: 5,+ });+ });+it('parses usage statistics flag', async () => {// Test default (should be true).const defaultArgs = parseConfig(['main.js'], {});diff --git a/tests/tools/screencast.test.ts b/tests/tools/screencast.test.tsindex 43fa1e7c..9578ff50 100644--- a/tests/tools/screencast.test.ts+++ b/tests/tools/screencast.test.ts@@ -13,20 +13,26 @@ import {afterEach, describe, it} from 'node:test';import sinon from 'sinon';import {ConfigParser} from '../../src/config/ConfigParser.js';-import {ScreenRecorder} from '../../src/third_party/index.js';+import {+ CdpScreenRecording,+ ScreenRecorder,+} from '../../src/third_party/index.js';import {startScreencast, stopScreencast} from '../../src/tools/screencast.js';import {createHandlerMocks} from '../mocks.js';+import {createTempDir, html, withMcpContext} from '../utils.js';-function createMockScreenRecorder(): sinon.SinonStubbedInstance<ScreenRecorder> {- return sinon.createStubInstance(ScreenRecorder);+function parseArgs(...argv: string[]) {+ return new ConfigParser('test', ['node', 'test', ...argv]).parse();}function createScreencastMocks() {const {page, context, response, args} = createHandlerMocks();- const mockRecorder = createMockScreenRecorder();+ const mockRecording = sinon.createStubInstance(CdpScreenRecording);+ const mockRecorder = sinon.createStubInstance(ScreenRecorder);+ page.pptrPage.record.resolves(mockRecording);page.pptrPage.screencast.resolves(mockRecorder);- context.getScreenRecorder.returns(null);- return {page, context, response, mockRecorder, args};+ page.getScreenRecorder.returns(null);+ return {page, context, response, mockRecording, mockRecorder, args};}describe('screencast', () => {@@ -35,8 +41,8 @@ describe('screencast', () => {});describe('screencast_start', () => {- it('starts a screencast recording with filePath', async () => {- const {page, context, response, mockRecorder, args} =+ it('starts an mp4 recording with filePath', async () => {+ const {page, context, response, mockRecording, args} =createScreencastMocks();const filePath: `${string}.mp4` = `${path.join(@@ -46,10 +52,7 @@ describe('screencast', () => {context.ensureExtension.resolves(filePath);await startScreencast(args).handler(- {- params: {filePath},- page,- },+ {params: {filePath}, page},response,context,);@@ -59,14 +62,13 @@ describe('screencast', () => {filePath,'.mp4',);- sinon.assert.calledOnceWithExactly(page.pptrPage.screencast, {+ sinon.assert.calledOnceWithExactly(page.pptrPage.record, {path: filePath,- format: 'mp4',- ffmpegPath: undefined,fps: undefined,});- sinon.assert.calledOnceWithExactly(context.setScreenRecorder, {- recorder: mockRecorder,+ sinon.assert.notCalled(page.pptrPage.screencast);+ sinon.assert.calledOnceWithExactly(page.setScreenRecorder, {+ recorder: mockRecording,filePath,});sinon.assert.calledOnceWithExactly(@@ -75,66 +77,8 @@ describe('screencast', () => {);});- it('records WebM for an uppercase extension (case-insensitive)', async () => {- const {page, context, response, mockRecorder, args} =- createScreencastMocks();-- const requestedPath = `${path.join(os.tmpdir(), 'test-recording')}.WEBM`;- const expectedPath: `${string}.webm` = `${path.join(- os.tmpdir(),- 'test-recording',- )}.webm`;- context.ensureExtension.resolves(expectedPath);-- await startScreencast(args).handler(- {- params: {filePath: requestedPath},- page,- },- response,- context,- );-- sinon.assert.calledOnceWithExactly(- context.ensureExtension,- requestedPath,- '.webm',- );- sinon.assert.calledOnceWithExactly(page.pptrPage.screencast, {- path: expectedPath,- format: 'webm',- ffmpegPath: undefined,- fps: undefined,- });- sinon.assert.calledOnceWithExactly(context.setScreenRecorder, {- recorder: mockRecorder,- filePath: expectedPath,- });- });-- it('rejects an unsupported extension instead of silently using mp4', async () => {- const {page, context, response, args} = createScreencastMocks();- const filePath = `${path.join(os.tmpdir(), 'recording')}.avi`;-- await assert.rejects(- startScreencast(args).handler(- {- params: {filePath},- page,- },- response,- context,- ),- /Unsupported screencast file extension/,- );-- sinon.assert.notCalled(context.ensureExtension);- sinon.assert.notCalled(page.pptrPage.screencast);- sinon.assert.notCalled(context.setScreenRecorder);- });-- it('starts a screencast recording with temp file when no filePath', async () => {- const {page, context, response, mockRecorder, args} =+ it('starts a recording with temp file when no filePath', async () => {+ const {page, context, response, mockRecording, args} =createScreencastMocks();const expectedPath: `${string}.mp4` = `${path.join(os.tmpdir(),@@ -151,23 +95,21 @@ describe('screencast', () => {sinon.assert.calledOnce(context.ensureExtension);assert.ok(context.ensureExtension.firstCall.args[0].endsWith('.mp4'));assert.strictEqual(context.ensureExtension.firstCall.args[1], '.mp4');- sinon.assert.calledOnceWithExactly(page.pptrPage.screencast, {+ sinon.assert.calledOnceWithExactly(page.pptrPage.record, {path: expectedPath,- format: 'mp4',- ffmpegPath: undefined,fps: undefined,});- sinon.assert.calledOnceWithExactly(context.setScreenRecorder, {- recorder: mockRecorder,+ sinon.assert.calledOnceWithExactly(page.setScreenRecorder, {+ recorder: mockRecording,filePath: expectedPath,});});it('errors if a recording is already active', async () => {- const {page, context, response, mockRecorder, args} =+ const {page, context, response, mockRecording, args} =createScreencastMocks();- context.getScreenRecorder.returns({- recorder: mockRecorder,+ page.getScreenRecorder.returns({+ recorder: mockRecording,filePath: `${path.join(os.tmpdir(), 'existing')}.mp4`,});@@ -178,122 +120,278 @@ describe('screencast', () => {);sinon.assert.notCalled(context.ensureExtension);- sinon.assert.notCalled(page.pptrPage.screencast);- sinon.assert.notCalled(context.setScreenRecorder);+ sinon.assert.notCalled(page.pptrPage.record);+ sinon.assert.notCalled(page.setScreenRecorder);sinon.assert.calledOnceWithExactly(response.appendResponseLine,'Error: a screencast recording is already in progress. Use screencast_stop to stop it before starting a new one.',);});- it('provides a clear error when ffmpeg is not found', async () => {- const {page, context, response, args} = createScreencastMocks();+ it('passes screencast fps from --screencast-fps to puppeteer', async () => {+ const {page, context, response} = createScreencastMocks();const filePath: `${string}.mp4` = `${path.join(os.tmpdir(), 'test')}.mp4`;context.ensureExtension.resolves(filePath);- page.pptrPage.screencast.rejects(new Error('spawn ffmpeg ENOENT'));- await assert.rejects(- startScreencast(args).handler(- {- params: {filePath},- page,- },- response,- context,- ),- /ffmpeg is required for screencast recording/,+ await startScreencast(parseArgs('--screencast-fps=10')).handler(+ {params: {filePath}, page},+ response,+ context,);- sinon.assert.calledOnceWithExactly(- context.ensureExtension,- filePath,- '.mp4',- );- sinon.assert.notCalled(context.setScreenRecorder);+ sinon.assert.calledOnceWithExactly(page.pptrPage.record, {+ path: filePath,+ fps: 10,+ });});- it('cleans up the generated temp directory if recording fails to start', async () => {+ it('passes screencast fps from --experimental-screencast-fps to puppeteer', async () => {+ const {page, context, response} = createScreencastMocks();+ const filePath: `${string}.mp4` = `${path.join(os.tmpdir(), 'test')}.mp4`;+ context.ensureExtension.resolves(filePath);++ await startScreencast(+ parseArgs('--experimental-screencast-fps=10'),+ ).handler({params: {filePath}, page}, response, context);++ sinon.assert.calledOnceWithExactly(page.pptrPage.record, {+ path: filePath,+ fps: 10,+ });+ });++ it('provides a clear error when Chrome does not support recording', async () => {const {page, context, response, args} = createScreencastMocks();context.ensureExtension.callsFake(async filePath => `${filePath}.mp4`);- page.pptrPage.screencast.rejects(new Error('spawn ffmpeg ENOENT'));+ page.pptrPage.record.rejects(+ new Error(+ "Protocol error (Page.startScreenRecording): 'Page.startScreenRecording' wasn't found",+ ),+ );await assert.rejects(startScreencast(args).handler({params: {}, page}, response, context),- /ffmpeg is required for screencast recording/,+ /The connected Chrome does not support screen recording/,);- const tempPath = page.pptrPage.screencast.firstCall.args[0]?.path;+ const tempPath = page.pptrPage.record.firstCall.args[0]?.path;assert.ok(tempPath);await assert.rejects(fs.access(path.dirname(tempPath)));- sinon.assert.notCalled(context.setScreenRecorder);+ sinon.assert.notCalled(page.setScreenRecorder);});- it('passes ffmpegPath from args to puppeteer', async () => {- const {page, context, response, mockRecorder} = createScreencastMocks();- const filePath: `${string}.mp4` = `${path.join(os.tmpdir(), 'test')}.mp4`;- context.ensureExtension.resolves(filePath);+ describe('with --experimental-screencast', () => {+ const legacyArgs = parseArgs('--experimental-screencast');- const experimentalFfmpegPath = '/custom/path/to/ffmpeg';- const args = new ConfigParser('test', [- 'node',- 'test',- '--experimental-screencast',- `--experimental-ffmpeg-path=${experimentalFfmpegPath}`,- ]).parse();- await startScreencast(args).handler(- {params: {filePath}, page},- response,- context,- );+ it('starts a screencast recording with filePath', async () => {+ const {page, context, response, mockRecorder} = createScreencastMocks();- sinon.assert.calledOnceWithExactly(- context.ensureExtension,- filePath,- '.mp4',- );- sinon.assert.calledOnceWithExactly(page.pptrPage.screencast, {- path: filePath,- format: 'mp4',- ffmpegPath: experimentalFfmpegPath,- fps: undefined,+ const filePath: `${string}.mp4` = `${path.join(+ os.tmpdir(),+ 'test-recording',+ )}.mp4`;+ context.ensureExtension.resolves(filePath);++ await startScreencast(legacyArgs).handler(+ {params: {filePath}, page},+ response,+ context,+ );++ sinon.assert.calledOnceWithExactly(+ context.ensureExtension,+ filePath,+ '.mp4',+ );+ sinon.assert.calledOnceWithExactly(page.pptrPage.screencast, {+ path: filePath,+ format: 'mp4',+ ffmpegPath: undefined,+ fps: undefined,+ });+ sinon.assert.notCalled(page.pptrPage.record);+ sinon.assert.calledOnceWithExactly(page.setScreenRecorder, {+ recorder: mockRecorder,+ filePath,+ });+ sinon.assert.calledOnceWithExactly(+ response.appendResponseLine,+ `Screencast recording started. The recording will be saved to ${filePath}. Use screencast_stop to stop recording.`,+ );});- sinon.assert.calledOnceWithExactly(context.setScreenRecorder, {- recorder: mockRecorder,- filePath,++ it('records WebM for an uppercase extension (case-insensitive)', async () => {+ const {page, context, response, mockRecorder} = createScreencastMocks();++ const requestedPath = `${path.join(os.tmpdir(), 'test-recording')}.WEBM`;+ const expectedPath: `${string}.webm` = `${path.join(+ os.tmpdir(),+ 'test-recording',+ )}.webm`;+ context.ensureExtension.resolves(expectedPath);++ await startScreencast(legacyArgs).handler(+ {params: {filePath: requestedPath}, page},+ response,+ context,+ );++ sinon.assert.calledOnceWithExactly(+ context.ensureExtension,+ requestedPath,+ '.webm',+ );+ sinon.assert.calledOnceWithExactly(page.pptrPage.screencast, {+ path: expectedPath,+ format: 'webm',+ ffmpegPath: undefined,+ fps: undefined,+ });+ sinon.assert.calledOnceWithExactly(page.setScreenRecorder, {+ recorder: mockRecorder,+ filePath: expectedPath,+ });});- });- it('passes screencast fps from args to puppeteer', async () => {- const {page, context, response, mockRecorder} = createScreencastMocks();- const filePath: `${string}.mp4` = `${path.join(os.tmpdir(), 'test')}.mp4`;- context.ensureExtension.resolves(filePath);+ it('rejects an unsupported extension instead of silently using mp4', async () => {+ const {page, context, response} = createScreencastMocks();+ const filePath = `${path.join(os.tmpdir(), 'recording')}.avi`;++ await assert.rejects(+ startScreencast(legacyArgs).handler(+ {params: {filePath}, page},+ response,+ context,+ ),+ /Unsupported screencast file extension/,+ );++ sinon.assert.notCalled(context.ensureExtension);+ sinon.assert.notCalled(page.pptrPage.screencast);+ sinon.assert.notCalled(page.setScreenRecorder);+ });- const args = new ConfigParser('test', [- 'node',- 'test',- '--experimental-screencast',- '--experimental-screencast-fps=10',- ]).parse();- await startScreencast(args).handler(- {params: {filePath}, page},- response,- context,- );+ it('starts a screencast recording with temp file when no filePath', async () => {+ const {page, context, response, mockRecorder} = createScreencastMocks();+ const expectedPath: `${string}.mp4` = `${path.join(+ os.tmpdir(),+ 'temp-screencast',+ )}.mp4`;+ context.ensureExtension.resolves(expectedPath);- sinon.assert.calledOnceWithExactly(- context.ensureExtension,- filePath,- '.mp4',- );- sinon.assert.calledOnceWithExactly(page.pptrPage.screencast, {- path: filePath,- format: 'mp4',- ffmpegPath: undefined,- fps: 10,+ await startScreencast(legacyArgs).handler(+ {params: {}, page},+ response,+ context,+ );++ sinon.assert.calledOnce(context.ensureExtension);+ assert.ok(context.ensureExtension.firstCall.args[0].endsWith('.mp4'));+ assert.strictEqual(context.ensureExtension.firstCall.args[1], '.mp4');+ sinon.assert.calledOnceWithExactly(page.pptrPage.screencast, {+ path: expectedPath,+ format: 'mp4',+ ffmpegPath: undefined,+ fps: undefined,+ });+ sinon.assert.calledOnceWithExactly(page.setScreenRecorder, {+ recorder: mockRecorder,+ filePath: expectedPath,+ });});- sinon.assert.calledOnceWithExactly(context.setScreenRecorder, {- recorder: mockRecorder,- filePath,++ it('provides a clear error when ffmpeg is not found', async () => {+ const {page, context, response} = createScreencastMocks();+ const filePath: `${string}.mp4` = `${path.join(os.tmpdir(), 'test')}.mp4`;+ context.ensureExtension.resolves(filePath);+ page.pptrPage.screencast.rejects(new Error('spawn ffmpeg ENOENT'));++ await assert.rejects(+ startScreencast(legacyArgs).handler(+ {params: {filePath}, page},+ response,+ context,+ ),+ /ffmpeg is required for screencast recording/,+ );++ sinon.assert.calledOnceWithExactly(+ context.ensureExtension,+ filePath,+ '.mp4',+ );+ sinon.assert.notCalled(page.setScreenRecorder);+ });++ it('cleans up the generated temp directory if recording fails to start', async () => {+ const {page, context, response} = createScreencastMocks();+ context.ensureExtension.callsFake(async filePath => `${filePath}.mp4`);+ page.pptrPage.screencast.rejects(new Error('spawn ffmpeg ENOENT'));++ await assert.rejects(+ startScreencast(legacyArgs).handler(+ {params: {}, page},+ response,+ context,+ ),+ /ffmpeg is required for screencast recording/,+ );++ const tempPath = page.pptrPage.screencast.firstCall.args[0]?.path;+ assert.ok(tempPath);+ await assert.rejects(fs.access(path.dirname(tempPath)));+ sinon.assert.notCalled(page.setScreenRecorder);+ });++ it('passes ffmpegPath from args to puppeteer', async () => {+ const {page, context, response, mockRecorder} = createScreencastMocks();+ const filePath: `${string}.mp4` = `${path.join(os.tmpdir(), 'test')}.mp4`;+ context.ensureExtension.resolves(filePath);++ const experimentalFfmpegPath = '/custom/path/to/ffmpeg';+ const args = parseArgs(+ '--experimental-screencast',+ `--experimental-ffmpeg-path=${experimentalFfmpegPath}`,+ );+ await startScreencast(args).handler(+ {params: {filePath}, page},+ response,+ context,+ );++ sinon.assert.calledOnceWithExactly(page.pptrPage.screencast, {+ path: filePath,+ format: 'mp4',+ ffmpegPath: experimentalFfmpegPath,+ fps: undefined,+ });+ sinon.assert.calledOnceWithExactly(page.setScreenRecorder, {+ recorder: mockRecorder,+ filePath,+ });+ });++ it('passes screencast fps from args to puppeteer', async () => {+ const {page, context, response} = createScreencastMocks();+ const filePath: `${string}.mp4` = `${path.join(os.tmpdir(), 'test')}.mp4`;+ context.ensureExtension.resolves(filePath);++ const args = parseArgs(+ '--experimental-screencast',+ '--screencast-fps=10',+ );+ await startScreencast(args).handler(+ {params: {filePath}, page},+ response,+ context,+ );++ sinon.assert.calledOnceWithExactly(page.pptrPage.screencast, {+ path: filePath,+ format: 'mp4',+ ffmpegPath: undefined,+ fps: 10,+ });});});});@@ -302,7 +400,7 @@ describe('screencast', () => {it('returns an error message if no recording is active', async () => {const {page, context, response, args} = createScreencastMocks();await stopScreencast(args).handler({params: {}, page}, response, context);- sinon.assert.notCalled(context.setScreenRecorder);+ sinon.assert.notCalled(page.setScreenRecorder);sinon.assert.calledOnceWithExactly(response.appendResponseLine,'Error: no active screencast recording to stop.',@@ -310,18 +408,18 @@ describe('screencast', () => {});it('stops an active recording and reports the file path', async () => {- const {page, context, response, mockRecorder, args} =+ const {page, context, response, mockRecording, args} =createScreencastMocks();const filePath = `${path.join(os.tmpdir(), 'test-recording')}.mp4`;- context.getScreenRecorder.returns({- recorder: mockRecorder,+ page.getScreenRecorder.returns({+ recorder: mockRecording,filePath,});await stopScreencast(args).handler({params: {}, page}, response, context);- sinon.assert.calledOnce(mockRecorder.stop);- sinon.assert.calledOnceWithExactly(context.setScreenRecorder, null);+ sinon.assert.calledOnce(mockRecording.stop);+ sinon.assert.calledOnceWithExactly(page.setScreenRecorder, null);sinon.assert.calledOnceWithExactly(response.appendResponseLine,`The screencast recording has been stopped and saved to ${filePath}.`,@@ -329,22 +427,71 @@ describe('screencast', () => {});it('clears the recorder even if stop() throws', async () => {- const {page, context, response, mockRecorder, args} =+ const {page, context, response, mockRecording, args} =createScreencastMocks();- mockRecorder.stop.rejects(new Error('ffmpeg process error'));+ mockRecording.stop.rejects(new Error('recording error'));const filePath = `${path.join(os.tmpdir(), 'test')}.mp4`;- context.getScreenRecorder.returns({- recorder: mockRecorder,+ page.getScreenRecorder.returns({+ recorder: mockRecording,filePath,});await assert.rejects(stopScreencast(args).handler({params: {}, page}, response, context),- /ffmpeg process error/,+ /recording error/,+ );++ sinon.assert.calledOnce(mockRecording.stop);+ sinon.assert.calledOnceWithExactly(page.setScreenRecorder, null);+ });+ });++ it('records two pages concurrently (e2e)', async () => {+ using tmpDir = createTempDir();+ await withMcpContext(async (response, context, args) => {+ const page1 = context.getSelectedMcpPage();+ const page2 = await context.newPage();+ await page1.pptrPage.setContent(html`<h1>Page 1</h1>`);+ await page2.pptrPage.setContent(html`<h1>Page 2</h1>`);++ const filePath1 = path.join(tmpDir.path, 'page1.mp4');+ const filePath2 = path.join(tmpDir.path, 'page2.mp4');++ await startScreencast(args).handler(+ {params: {filePath: filePath1}, page: page1},+ response,+ context,+ );+ await startScreencast(args).handler(+ {params: {filePath: filePath2}, page: page2},+ response,+ context,+ );++ await page1.pptrPage.evaluate(() => {+ document.body.style.background = 'red';+ });+ await page2.pptrPage.evaluate(() => {+ document.body.style.background = 'blue';+ });++ await stopScreencast(args).handler(+ {params: {}, page: page1},+ response,+ context,+ );+ await stopScreencast(args).handler(+ {params: {}, page: page2},+ response,+ context,);- sinon.assert.calledOnce(mockRecorder.stop);- sinon.assert.calledOnceWithExactly(context.setScreenRecorder, null);+ for (const filePath of [filePath1, filePath2]) {+ const content = await fs.readFile(filePath);+ assert.ok(content.length > 0, `${filePath} should not be empty`);+ // MP4 files start with a size-prefixed `ftyp` box.+ assert.strictEqual(content.subarray(4, 8).toString(), 'ftyp');+ }});});});