mcp-browser-dev-tools 0.3.0 → 0.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +16 -3
- package/package.json +2 -1
- package/src/browser-adapter.mjs +8 -0
- package/src/cdp-client.mjs +296 -1
- package/src/config.mjs +1 -0
- package/src/firefox-bidi-client.mjs +10 -0
- package/src/tool-sets.mjs +1 -1
- package/src/tools/performance-tools.mjs +67 -0
- package/src/video-output.mjs +401 -0
package/README.md
CHANGED
|
@@ -36,7 +36,7 @@ Then ask the agent for browser work, for example "open example.com and check the
|
|
|
36
36
|
|
|
37
37
|

|
|
38
38
|
|
|
39
|
-
Your agent gets
|
|
39
|
+
Your agent gets 45 browser tools over MCP: open or attach to tabs, click, type, drag, upload files, and navigate, read the console and network, block or mock requests, take screenshots, and save and restore sessions. At the center is `run_steps`: the agent sends a whole task, with branches and waits in it, and the server carries it out in the browser and replies once. `run_tabs` does the same in several tabs at the same time.
|
|
40
40
|
|
|
41
41
|
## Why This One
|
|
42
42
|
|
|
@@ -128,6 +128,19 @@ A research step usually means opening several pages and reading each one. `read_
|
|
|
128
128
|
|
|
129
129
|
The result lists every tab in the order given, each with its steps' results: here, each page's main text, cut to `maxChars`. Each tab opens a new tab, loads its URL, and runs its steps at the same time as the others, so the call takes about as long as the slowest page; the tabs close afterwards. Steps are the same as in `run_steps`, including `if` and `repeat`, and a tab that fails or runs past its `timeoutMs` does not stop the others. `browserFamily` picks the browser for the new tabs when the server runs in its default `auto` mode. The details are in [Tools](docs/tools.md#several-tabs-at-once).
|
|
130
130
|
|
|
131
|
+
## Record A Demo
|
|
132
|
+
|
|
133
|
+
`record_video` records what a Chromium tab shows while the agent drives it, as an MP4. For a 1920x1080 recording, set the viewport first, then start, act, and stop:
|
|
134
|
+
|
|
135
|
+
```json
|
|
136
|
+
{ "name": "set_viewport", "arguments": { "sessionId": "s1", "width": 1920, "height": 1080 } }
|
|
137
|
+
{ "name": "record_video", "arguments": { "sessionId": "s1", "action": "start" } }
|
|
138
|
+
{ "name": "click", "arguments": { "sessionId": "s1", "selector": "text=Open dashboard" } }
|
|
139
|
+
{ "name": "record_video", "arguments": { "sessionId": "s1", "action": "stop", "path": "/home/me/demo.mp4" } }
|
|
140
|
+
```
|
|
141
|
+
|
|
142
|
+
`stop` returns the file's `path`, `durationMs`, `frames`, `width`, and `height`. Chrome streams a frame on each repaint, and `stop` encodes them with ffmpeg (found on `PATH`, or named by `MCP_BROWSER_FFMPEG`) at a constant frame rate, each frame lasting as long as it was on screen. Without ffmpeg, `stop` keeps the frames and returns the command that encodes them. `record_video` is in the `performance` group, reached through `more_tools` or as a `run_steps` step. The details, including `fps`, `quality`, `maxWidth` and `maxHeight`, and `maxDurationMs`, are in [Tools](docs/tools.md#performance).
|
|
143
|
+
|
|
131
144
|
## Measured
|
|
132
145
|
|
|
133
146
|
Median of 3 runs on the current build, from the benchmark in [PERFORMANCE.md](PERFORMANCE.md). "One action per call" disallows `run_steps` and `run_tabs`.
|
|
@@ -143,14 +156,14 @@ Every form run started with `get_snapshot` and acted by ref, without being told
|
|
|
143
156
|
|
|
144
157
|
## Tools
|
|
145
158
|
|
|
146
|
-
|
|
159
|
+
45 tools, described in [docs/tools.md](docs/tools.md). The server lists the core set by default, since every model turn pays for each tool listed, and `more_tools` lists, describes, and calls the rest; `MCP_BROWSER_TOOLS=all`, or a list of groups such as `network,state`, lists them too ([Tool Sets](docs/tools.md#tool-sets)).
|
|
147
160
|
|
|
148
161
|
- **Browser and tabs:** `browser_status`, `ensure_browser`, `launch_browser`, `list_tabs`, `new_tab`, `close_tab`, `attach_tab`, `detach_tab`, `list_sessions`
|
|
149
162
|
- **Act:** `navigate`, `reload`, `click`, `hover`, `drag`, `type`, `select`, `press_key`, `upload_file`, `scroll`, `set_viewport`
|
|
150
163
|
- **Wait and batch:** `wait_for`, `run_steps`, `run_tabs`
|
|
151
164
|
- **Inspect:** `get_page_state`, `get_snapshot`, `get_document`, `inspect_element`, `read_text`, `take_screenshot`, `evaluate_js`
|
|
152
165
|
- **Console and network:** `get_console_messages`, `get_network_requests`, `get_events`, `get_har`, `set_network`
|
|
153
|
-
- **Performance:** `get_performance`, `record_trace`
|
|
166
|
+
- **Performance:** `get_performance`, `record_trace`, `record_video`
|
|
154
167
|
- **Session state:** `get_cookies`, `get_storage`, `capture_session_snapshot`, `restore_session_snapshot`, `compare_page_state`, `compare_selector`, `capture_debug_report`
|
|
155
168
|
|
|
156
169
|
## Configuration
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "mcp-browser-dev-tools",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.4.0",
|
|
4
4
|
"description": "Browser MCP server for AI agents: batch actions, waits, and checks into one call on Chrome, Edge, or Firefox (CDP and WebDriver BiDi)",
|
|
5
5
|
"author": "Hinaser <rindo.hinase@gmail.com>",
|
|
6
6
|
"license": "MIT",
|
|
@@ -56,6 +56,7 @@
|
|
|
56
56
|
"src/tool-schemas.mjs",
|
|
57
57
|
"src/tool-sets.mjs",
|
|
58
58
|
"src/upload-files.mjs",
|
|
59
|
+
"src/video-output.mjs",
|
|
59
60
|
"src/network-control.mjs",
|
|
60
61
|
"src/tools/action-tools.mjs",
|
|
61
62
|
"src/tools/browser-tools.mjs",
|
package/src/browser-adapter.mjs
CHANGED
|
@@ -288,6 +288,14 @@ export class MultiBrowserAdapter {
|
|
|
288
288
|
return this.delegateSession(sessionId, "stopTrace");
|
|
289
289
|
}
|
|
290
290
|
|
|
291
|
+
startVideo(sessionId, options) {
|
|
292
|
+
return this.delegateSession(sessionId, "startVideo", [options]);
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
stopVideo(sessionId) {
|
|
296
|
+
return this.delegateSession(sessionId, "stopVideo");
|
|
297
|
+
}
|
|
298
|
+
|
|
291
299
|
type(sessionId, selector, text, options) {
|
|
292
300
|
return this.delegateSession(sessionId, "type", [selector, text, options]);
|
|
293
301
|
}
|
package/src/cdp-client.mjs
CHANGED
|
@@ -1,3 +1,7 @@
|
|
|
1
|
+
import { mkdtemp, rm, writeFile } from "node:fs/promises";
|
|
2
|
+
import { tmpdir } from "node:os";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
|
|
1
5
|
import {
|
|
2
6
|
exportHarLikeSummary,
|
|
3
7
|
filterConsoleMessages,
|
|
@@ -14,6 +18,7 @@ import {
|
|
|
14
18
|
} from "./page-context.mjs";
|
|
15
19
|
import { buildCdpKeyEvents } from "./keyboard.mjs";
|
|
16
20
|
import { sendCheckedInput } from "./input-delivery.mjs";
|
|
21
|
+
import { imageSize, SCREENSHOT_FILE_MODE } from "./screenshot-output.mjs";
|
|
17
22
|
import {
|
|
18
23
|
applyNetworkOptions,
|
|
19
24
|
describeNetworkState,
|
|
@@ -60,6 +65,14 @@ const TRACE_CATEGORIES = [
|
|
|
60
65
|
"loading",
|
|
61
66
|
];
|
|
62
67
|
const TRACE_COMPLETE_MS = 60_000;
|
|
68
|
+
// A video capture stops by itself after maxDurationMs, 10 minutes unless
|
|
69
|
+
// asked, 30 at most, so a forgotten recording does not fill the disk. A
|
|
70
|
+
// stretch with no frame longer than VIDEO_GAP_WARN_S is reported, since a
|
|
71
|
+
// hidden or minimised tab sends none.
|
|
72
|
+
export const VIDEO_DEFAULT_DURATION_MS = 10 * 60_000;
|
|
73
|
+
export const VIDEO_MAX_DURATION_MS = 30 * 60_000;
|
|
74
|
+
const VIDEO_GAP_WARN_S = 5;
|
|
75
|
+
const ORPHANED_VIDEO_LIMIT = 8;
|
|
63
76
|
// How long a click may take to open a file chooser.
|
|
64
77
|
const FILE_CHOOSER_MS = 2000;
|
|
65
78
|
const DRAG_SESSION_MS = 30_000;
|
|
@@ -433,6 +446,31 @@ function pageExceptionMessage(details) {
|
|
|
433
446
|
return details.text || "Page action failed";
|
|
434
447
|
}
|
|
435
448
|
|
|
449
|
+
// A stretch with no frame plays as one still frame. Longer than a few
|
|
450
|
+
// seconds, that is worth saying: the page did not repaint, or the tab was
|
|
451
|
+
// hidden or minimised, which stops Chrome's frames.
|
|
452
|
+
function videoGapWarnings(state) {
|
|
453
|
+
const seconds = (value) => Math.round((value - state.startedAt) * 10) / 10;
|
|
454
|
+
const gaps = [];
|
|
455
|
+
const times = state.frames.map((frame) => frame.timestamp);
|
|
456
|
+
times.push(state.stoppedAt ?? Date.now() / 1000);
|
|
457
|
+
for (let index = 1; index < times.length; index += 1) {
|
|
458
|
+
const gap = times[index] - times[index - 1];
|
|
459
|
+
if (gap > VIDEO_GAP_WARN_S) {
|
|
460
|
+
gaps.push({ gap, from: times[index - 1], to: times[index] });
|
|
461
|
+
}
|
|
462
|
+
}
|
|
463
|
+
if (gaps.length === 0) {
|
|
464
|
+
return [];
|
|
465
|
+
}
|
|
466
|
+
const longest = gaps.reduce((a, b) => (b.gap > a.gap ? b : a));
|
|
467
|
+
const others =
|
|
468
|
+
gaps.length > 1 ? ` and in ${gaps.length - 1} other stretch(es)` : "";
|
|
469
|
+
return [
|
|
470
|
+
`No frame arrived for ${Math.round(longest.gap * 10) / 10} s (from ${seconds(longest.from)} s to ${seconds(longest.to)} s into the recording)${others}: the page did not repaint, or the tab was hidden or minimised, so the video holds one frame there`,
|
|
471
|
+
];
|
|
472
|
+
}
|
|
473
|
+
|
|
436
474
|
export class CdpSession {
|
|
437
475
|
constructor(target, options = {}) {
|
|
438
476
|
this.id = crypto.randomUUID();
|
|
@@ -451,6 +489,7 @@ export class CdpSession {
|
|
|
451
489
|
this.lastNavigationAt = null;
|
|
452
490
|
this.lastReloadAt = null;
|
|
453
491
|
this.viewportOverride = null;
|
|
492
|
+
this.video = null;
|
|
454
493
|
// Frames: child sessions of cross-site iframes (attached in flatten
|
|
455
494
|
// mode, by session id), the default execution context of each frame,
|
|
456
495
|
// keyed by session and frame id, and the frame keys refs use.
|
|
@@ -465,6 +504,7 @@ export class CdpSession {
|
|
|
465
504
|
}
|
|
466
505
|
|
|
467
506
|
this.closed = true;
|
|
507
|
+
void this.endVideoCapture(this.video, "closed");
|
|
468
508
|
this.rejectPending(new Error("CDP session closed"));
|
|
469
509
|
this.rejectEventWaiters(new Error("CDP session closed"));
|
|
470
510
|
this.onClosed?.(this);
|
|
@@ -813,6 +853,13 @@ export class CdpSession {
|
|
|
813
853
|
}
|
|
814
854
|
|
|
815
855
|
bufferEvent(method, params) {
|
|
856
|
+
// Frames carry image data and arrive many times a second, so they are
|
|
857
|
+
// written to the recording, never buffered or logged.
|
|
858
|
+
if (method === "Page.screencastFrame") {
|
|
859
|
+
this.handleScreencastFrame(params);
|
|
860
|
+
return;
|
|
861
|
+
}
|
|
862
|
+
|
|
816
863
|
const capturedAt = new Date().toISOString();
|
|
817
864
|
if (
|
|
818
865
|
method === "Page.frameNavigated" &&
|
|
@@ -1872,6 +1919,201 @@ export class CdpSession {
|
|
|
1872
1919
|
return { data: Buffer.concat(chunks), durationMs: Date.now() - startedAt };
|
|
1873
1920
|
}
|
|
1874
1921
|
|
|
1922
|
+
// Records what the tab shows: Chrome streams a JPEG of each repaint, and
|
|
1923
|
+
// each is written to a private temp directory as it arrives, with its
|
|
1924
|
+
// time, for the stop action to encode. The first frame is a screenshot,
|
|
1925
|
+
// so a page that never repaints still has one. Frames are scaled by Chrome
|
|
1926
|
+
// to fit maxWidth and maxHeight, by default the viewport in device pixels.
|
|
1927
|
+
async startVideo(options = {}) {
|
|
1928
|
+
if (this.video) {
|
|
1929
|
+
throw new Error("A video is already recording; stop it first");
|
|
1930
|
+
}
|
|
1931
|
+
const fps = options.fps ?? 30;
|
|
1932
|
+
const quality = options.quality ?? 80;
|
|
1933
|
+
const maxDurationMs = Math.min(
|
|
1934
|
+
options.maxDurationMs ?? VIDEO_DEFAULT_DURATION_MS,
|
|
1935
|
+
VIDEO_MAX_DURATION_MS,
|
|
1936
|
+
);
|
|
1937
|
+
// Reserved before the first await, so a second start meanwhile fails
|
|
1938
|
+
// instead of making a second recording.
|
|
1939
|
+
const state = {
|
|
1940
|
+
starting: true,
|
|
1941
|
+
dir: null,
|
|
1942
|
+
fps,
|
|
1943
|
+
width: null,
|
|
1944
|
+
height: null,
|
|
1945
|
+
maxDurationMs,
|
|
1946
|
+
startedAt: Date.now() / 1000,
|
|
1947
|
+
stoppedAt: null,
|
|
1948
|
+
capturing: false,
|
|
1949
|
+
written: 0,
|
|
1950
|
+
frames: [],
|
|
1951
|
+
warnings: [],
|
|
1952
|
+
writeErrors: 0,
|
|
1953
|
+
queue: Promise.resolve(),
|
|
1954
|
+
timer: null,
|
|
1955
|
+
};
|
|
1956
|
+
this.video = state;
|
|
1957
|
+
try {
|
|
1958
|
+
const shot = await this.send("Page.captureScreenshot", {
|
|
1959
|
+
format: "jpeg",
|
|
1960
|
+
quality,
|
|
1961
|
+
});
|
|
1962
|
+
const first = Buffer.from(shot.data, "base64");
|
|
1963
|
+
const viewport = imageSize(first);
|
|
1964
|
+
if (!viewport) {
|
|
1965
|
+
throw new Error("Could not read the size of the first frame");
|
|
1966
|
+
}
|
|
1967
|
+
const scale = Math.min(
|
|
1968
|
+
1,
|
|
1969
|
+
(options.maxWidth ?? Infinity) / viewport.width,
|
|
1970
|
+
(options.maxHeight ?? Infinity) / viewport.height,
|
|
1971
|
+
);
|
|
1972
|
+
state.width = Math.max(1, Math.round(viewport.width * scale));
|
|
1973
|
+
state.height = Math.max(1, Math.round(viewport.height * scale));
|
|
1974
|
+
state.dir = await mkdtemp(
|
|
1975
|
+
path.join(tmpdir(), "mcp-browser-dev-tools-video-"),
|
|
1976
|
+
);
|
|
1977
|
+
state.capturing = true;
|
|
1978
|
+
this.writeVideoFrame(state, first, state.startedAt);
|
|
1979
|
+
await this.send("Page.startScreencast", {
|
|
1980
|
+
format: "jpeg",
|
|
1981
|
+
quality,
|
|
1982
|
+
maxWidth: state.width,
|
|
1983
|
+
maxHeight: state.height,
|
|
1984
|
+
everyNthFrame: 1,
|
|
1985
|
+
});
|
|
1986
|
+
} catch (error) {
|
|
1987
|
+
state.capturing = false;
|
|
1988
|
+
if (this.video === state) {
|
|
1989
|
+
this.video = null;
|
|
1990
|
+
}
|
|
1991
|
+
await state.queue;
|
|
1992
|
+
if (state.dir) {
|
|
1993
|
+
await rm(state.dir, { recursive: true, force: true });
|
|
1994
|
+
}
|
|
1995
|
+
throw error;
|
|
1996
|
+
}
|
|
1997
|
+
state.starting = false;
|
|
1998
|
+
state.timer = setTimeout(() => {
|
|
1999
|
+
void this.endVideoCapture(state, "maxDurationMs");
|
|
2000
|
+
}, maxDurationMs);
|
|
2001
|
+
state.timer.unref?.();
|
|
2002
|
+
return {
|
|
2003
|
+
browserFamily: cdpBrowserFamily(this.config),
|
|
2004
|
+
recording: true,
|
|
2005
|
+
dir: state.dir,
|
|
2006
|
+
startedAt: state.startedAt,
|
|
2007
|
+
width: state.width,
|
|
2008
|
+
height: state.height,
|
|
2009
|
+
fps,
|
|
2010
|
+
};
|
|
2011
|
+
}
|
|
2012
|
+
|
|
2013
|
+
// Every frame is acknowledged, or Chrome stops sending them: a recorded
|
|
2014
|
+
// frame once it is on disk, so a slow disk slows Chrome's frames rather
|
|
2015
|
+
// than filling memory with queued ones; any other frame at once.
|
|
2016
|
+
handleScreencastFrame(params) {
|
|
2017
|
+
const ack = () => {
|
|
2018
|
+
try {
|
|
2019
|
+
this.send("Page.screencastFrameAck", {
|
|
2020
|
+
sessionId: params.sessionId,
|
|
2021
|
+
}).catch(() => {});
|
|
2022
|
+
} catch {
|
|
2023
|
+
// Not connected any more; there is nothing to acknowledge to.
|
|
2024
|
+
}
|
|
2025
|
+
};
|
|
2026
|
+
const state = this.video;
|
|
2027
|
+
if (!state?.capturing) {
|
|
2028
|
+
ack();
|
|
2029
|
+
return;
|
|
2030
|
+
}
|
|
2031
|
+
this.writeVideoFrame(
|
|
2032
|
+
state,
|
|
2033
|
+
Buffer.from(params.data, "base64"),
|
|
2034
|
+
params.metadata?.timestamp ?? Date.now() / 1000,
|
|
2035
|
+
).then(ack, ack);
|
|
2036
|
+
}
|
|
2037
|
+
|
|
2038
|
+
// Writes are chained so frames keep their order and stop can wait for
|
|
2039
|
+
// the last one. A frame whose write fails is left out of the video.
|
|
2040
|
+
writeVideoFrame(state, data, timestamp) {
|
|
2041
|
+
const file = `${String(state.written).padStart(6, "0")}.jpg`;
|
|
2042
|
+
state.written += 1;
|
|
2043
|
+
state.queue = state.queue
|
|
2044
|
+
.then(async () => {
|
|
2045
|
+
await writeFile(path.join(state.dir, file), data, {
|
|
2046
|
+
flag: "wx",
|
|
2047
|
+
mode: SCREENSHOT_FILE_MODE,
|
|
2048
|
+
});
|
|
2049
|
+
state.frames.push({ file, timestamp });
|
|
2050
|
+
})
|
|
2051
|
+
.catch((error) => {
|
|
2052
|
+
state.writeErrors += 1;
|
|
2053
|
+
state.writeError = error.message;
|
|
2054
|
+
});
|
|
2055
|
+
return state.queue;
|
|
2056
|
+
}
|
|
2057
|
+
|
|
2058
|
+
// Stops taking frames (on stop, at maxDurationMs, or when the session
|
|
2059
|
+
// ends) but keeps them for stop to encode.
|
|
2060
|
+
async endVideoCapture(state, reason) {
|
|
2061
|
+
if (!state?.capturing) {
|
|
2062
|
+
return;
|
|
2063
|
+
}
|
|
2064
|
+
state.capturing = false;
|
|
2065
|
+
clearTimeout(state.timer);
|
|
2066
|
+
state.stoppedAt = Date.now() / 1000;
|
|
2067
|
+
if (reason === "maxDurationMs") {
|
|
2068
|
+
state.warnings.push(
|
|
2069
|
+
`Capture stopped at maxDurationMs (${state.maxDurationMs} ms); the frames up to then are kept, and stop encodes them`,
|
|
2070
|
+
);
|
|
2071
|
+
}
|
|
2072
|
+
if (!this.closed) {
|
|
2073
|
+
try {
|
|
2074
|
+
await this.send("Page.stopScreencast");
|
|
2075
|
+
} catch (error) {
|
|
2076
|
+
state.warnings.push(`Page.stopScreencast failed: ${error.message}`);
|
|
2077
|
+
}
|
|
2078
|
+
}
|
|
2079
|
+
}
|
|
2080
|
+
|
|
2081
|
+
// Ends the capture and hands over the frames, in order with their times,
|
|
2082
|
+
// for encoding. A closed session (the tab closed or was detached) still
|
|
2083
|
+
// hands over what it captured.
|
|
2084
|
+
async stopVideo() {
|
|
2085
|
+
const state = this.video;
|
|
2086
|
+
if (!state) {
|
|
2087
|
+
throw new Error("No video is recording; start one first");
|
|
2088
|
+
}
|
|
2089
|
+
if (state.starting) {
|
|
2090
|
+
throw new Error(
|
|
2091
|
+
"The video is still starting; stop it once start returns",
|
|
2092
|
+
);
|
|
2093
|
+
}
|
|
2094
|
+
// Taken at once, so a second stop while this one finishes has nothing
|
|
2095
|
+
// to stop and the frames are encoded once.
|
|
2096
|
+
this.video = null;
|
|
2097
|
+
await this.endVideoCapture(state, "stop");
|
|
2098
|
+
await state.queue;
|
|
2099
|
+
const warnings = [...state.warnings, ...videoGapWarnings(state)];
|
|
2100
|
+
if (state.writeErrors > 0) {
|
|
2101
|
+
warnings.push(
|
|
2102
|
+
`${state.writeErrors} frame(s) could not be written (${state.writeError})`,
|
|
2103
|
+
);
|
|
2104
|
+
}
|
|
2105
|
+
return {
|
|
2106
|
+
dir: state.dir,
|
|
2107
|
+
frames: state.frames,
|
|
2108
|
+
startedAt: state.startedAt,
|
|
2109
|
+
stoppedAt: state.stoppedAt,
|
|
2110
|
+
fps: state.fps,
|
|
2111
|
+
width: state.width,
|
|
2112
|
+
height: state.height,
|
|
2113
|
+
warnings,
|
|
2114
|
+
};
|
|
2115
|
+
}
|
|
2116
|
+
|
|
1875
2117
|
async select(selector, options = {}) {
|
|
1876
2118
|
return this.runPageAction(
|
|
1877
2119
|
{
|
|
@@ -2124,6 +2366,7 @@ export class CdpSession {
|
|
|
2124
2366
|
return;
|
|
2125
2367
|
}
|
|
2126
2368
|
|
|
2369
|
+
await this.endVideoCapture(this.video, "detach");
|
|
2127
2370
|
this.websocket.close();
|
|
2128
2371
|
}
|
|
2129
2372
|
}
|
|
@@ -2132,6 +2375,9 @@ export class CdpSessionManager {
|
|
|
2132
2375
|
constructor(config) {
|
|
2133
2376
|
this.config = config;
|
|
2134
2377
|
this.sessions = new Map();
|
|
2378
|
+
// Sessions that ended while recording a video, kept by id so that stop
|
|
2379
|
+
// still encodes their frames, which are on disk.
|
|
2380
|
+
this.orphanedVideos = new Map();
|
|
2135
2381
|
this.resolvedBaseUrl = null;
|
|
2136
2382
|
this.lastAttemptedBaseUrl = null;
|
|
2137
2383
|
this.lastKnownBaseUrl = null;
|
|
@@ -2423,6 +2669,7 @@ export class CdpSessionManager {
|
|
|
2423
2669
|
eventBufferSize: this.config.eventBufferSize,
|
|
2424
2670
|
onClosed: (closedSession) => {
|
|
2425
2671
|
this.sessions.delete(closedSession.id);
|
|
2672
|
+
this.orphanVideo(closedSession);
|
|
2426
2673
|
},
|
|
2427
2674
|
});
|
|
2428
2675
|
await session.connect();
|
|
@@ -2443,12 +2690,44 @@ export class CdpSessionManager {
|
|
|
2443
2690
|
const session = this.getSession(sessionId);
|
|
2444
2691
|
await session.close();
|
|
2445
2692
|
this.sessions.delete(sessionId);
|
|
2693
|
+
const video = this.orphanVideo(session);
|
|
2446
2694
|
return {
|
|
2447
2695
|
detached: true,
|
|
2448
2696
|
sessionId,
|
|
2697
|
+
...(video ? { video } : {}),
|
|
2698
|
+
};
|
|
2699
|
+
}
|
|
2700
|
+
|
|
2701
|
+
// A session that ends while recording keeps its frames: record_video
|
|
2702
|
+
// stop with the same sessionId encodes them, and the result of the
|
|
2703
|
+
// detach or close says where they are.
|
|
2704
|
+
// Up to ORPHANED_VIDEO_LIMIT such recordings are kept; past that, the
|
|
2705
|
+
// oldest one's frames are deleted, so ended sessions cannot fill the disk.
|
|
2706
|
+
orphanVideo(session) {
|
|
2707
|
+
if (!session.video?.dir) {
|
|
2708
|
+
return null;
|
|
2709
|
+
}
|
|
2710
|
+
this.orphanedVideos.set(session.id, session);
|
|
2711
|
+
for (const [id, oldest] of this.orphanedVideos) {
|
|
2712
|
+
if (this.orphanedVideos.size <= ORPHANED_VIDEO_LIMIT) {
|
|
2713
|
+
break;
|
|
2714
|
+
}
|
|
2715
|
+
this.orphanedVideos.delete(id);
|
|
2716
|
+
void this.discardOrphanedVideo(oldest);
|
|
2717
|
+
}
|
|
2718
|
+
return {
|
|
2719
|
+
framesDir: session.video.dir,
|
|
2720
|
+
note: `The recording's frames are kept; record_video stop with this sessionId encodes them (the frames of the ${ORPHANED_VIDEO_LIMIT} most recently ended recordings are kept)`,
|
|
2449
2721
|
};
|
|
2450
2722
|
}
|
|
2451
2723
|
|
|
2724
|
+
async discardOrphanedVideo(session) {
|
|
2725
|
+
const state = session.video;
|
|
2726
|
+
session.video = null;
|
|
2727
|
+
await state.queue;
|
|
2728
|
+
await rm(state.dir, { recursive: true, force: true });
|
|
2729
|
+
}
|
|
2730
|
+
|
|
2452
2731
|
async closeTarget(targetId) {
|
|
2453
2732
|
const result = await this.sendBrowserCommand("Target.closeTarget", {
|
|
2454
2733
|
targetId,
|
|
@@ -2462,7 +2741,8 @@ export class CdpSessionManager {
|
|
|
2462
2741
|
.map((session) => {
|
|
2463
2742
|
session.markClosed?.();
|
|
2464
2743
|
this.sessions.delete(session.id);
|
|
2465
|
-
|
|
2744
|
+
const video = this.orphanVideo(session);
|
|
2745
|
+
return { sessionId: session.id, ...(video ? { video } : {}) };
|
|
2466
2746
|
});
|
|
2467
2747
|
|
|
2468
2748
|
return {
|
|
@@ -2535,6 +2815,21 @@ export class CdpSessionManager {
|
|
|
2535
2815
|
return this.getSession(sessionId).stopTrace();
|
|
2536
2816
|
}
|
|
2537
2817
|
|
|
2818
|
+
async startVideo(sessionId, options) {
|
|
2819
|
+
return this.getSession(sessionId).startVideo(options);
|
|
2820
|
+
}
|
|
2821
|
+
|
|
2822
|
+
async stopVideo(sessionId) {
|
|
2823
|
+
const session =
|
|
2824
|
+
this.sessions.get(sessionId) ?? this.orphanedVideos.get(sessionId);
|
|
2825
|
+
if (!session) {
|
|
2826
|
+
throw new Error(`No active session found for ${sessionId}`);
|
|
2827
|
+
}
|
|
2828
|
+
const capture = await session.stopVideo();
|
|
2829
|
+
this.orphanedVideos.delete(sessionId);
|
|
2830
|
+
return capture;
|
|
2831
|
+
}
|
|
2832
|
+
|
|
2538
2833
|
async type(sessionId, selector, text, options) {
|
|
2539
2834
|
return this.getSession(sessionId).type(selector, text, options);
|
|
2540
2835
|
}
|
package/src/config.mjs
CHANGED
|
@@ -140,6 +140,7 @@ export function loadConfig(env = process.env) {
|
|
|
140
140
|
.map((dir) => dir.trim())
|
|
141
141
|
.filter(Boolean),
|
|
142
142
|
timingLogFile: env.MCP_BROWSER_TIMING_LOG?.trim() || null,
|
|
143
|
+
ffmpegPath: env.MCP_BROWSER_FFMPEG?.trim() || null,
|
|
143
144
|
protocolVersion:
|
|
144
145
|
env.MCP_PROTOCOL_VERSION?.trim() || DEFAULT_PROTOCOL_VERSION,
|
|
145
146
|
};
|
|
@@ -1627,6 +1627,16 @@ export class FirefoxBidiSessionManager {
|
|
|
1627
1627
|
return this.startTrace();
|
|
1628
1628
|
}
|
|
1629
1629
|
|
|
1630
|
+
async startVideo() {
|
|
1631
|
+
throw new Error(
|
|
1632
|
+
"record_video is Chromium only; WebDriver BiDi has no screencast",
|
|
1633
|
+
);
|
|
1634
|
+
}
|
|
1635
|
+
|
|
1636
|
+
async stopVideo() {
|
|
1637
|
+
return this.startVideo();
|
|
1638
|
+
}
|
|
1639
|
+
|
|
1630
1640
|
async uploadFiles(sessionId, selector, files) {
|
|
1631
1641
|
const session = this.getSession(sessionId);
|
|
1632
1642
|
const token = crypto.randomUUID();
|
package/src/tool-sets.mjs
CHANGED
|
@@ -41,7 +41,7 @@ export const TOOL_GROUPS = {
|
|
|
41
41
|
],
|
|
42
42
|
compare: ["compare_page_state", "compare_selector"],
|
|
43
43
|
browser: ["browser_status", "launch_browser", "list_sessions", "detach_tab"],
|
|
44
|
-
performance: ["get_performance", "record_trace"],
|
|
44
|
+
performance: ["get_performance", "record_trace", "record_video"],
|
|
45
45
|
};
|
|
46
46
|
|
|
47
47
|
// The tool names MCP_BROWSER_TOOLS enables, or null for all. The core set
|
|
@@ -7,6 +7,7 @@ import {
|
|
|
7
7
|
writeScreenshotFile,
|
|
8
8
|
} from "../screenshot-output.mjs";
|
|
9
9
|
import { sessionSchema } from "../tool-schemas.mjs";
|
|
10
|
+
import { checkVideoPath, encodeVideo } from "../video-output.mjs";
|
|
10
11
|
|
|
11
12
|
// A trace can show signed-in pages, so it is written like a screenshot:
|
|
12
13
|
// private to the user, never through a symlink, and not over an existing
|
|
@@ -112,5 +113,71 @@ export function performanceTools(server) {
|
|
|
112
113
|
},
|
|
113
114
|
},
|
|
114
115
|
],
|
|
116
|
+
[
|
|
117
|
+
"record_video",
|
|
118
|
+
{
|
|
119
|
+
definition: {
|
|
120
|
+
name: "record_video",
|
|
121
|
+
description:
|
|
122
|
+
"Record what a Chromium tab shows to an MP4: start, act, then stop encodes the frames with ffmpeg (on PATH or MCP_BROWSER_FFMPEG; without it, stop returns the frames and the command). For 1920x1080, set_viewport first.",
|
|
123
|
+
inputSchema: sessionSchema(
|
|
124
|
+
{
|
|
125
|
+
action: { type: "string", enum: ["start", "stop"] },
|
|
126
|
+
fps: {
|
|
127
|
+
type: "integer",
|
|
128
|
+
minimum: 1,
|
|
129
|
+
maximum: 60,
|
|
130
|
+
description: "With start: output frame rate; default 30.",
|
|
131
|
+
},
|
|
132
|
+
quality: {
|
|
133
|
+
type: "integer",
|
|
134
|
+
minimum: 1,
|
|
135
|
+
maximum: 100,
|
|
136
|
+
description: "With start: JPEG quality; default 80.",
|
|
137
|
+
},
|
|
138
|
+
maxWidth: {
|
|
139
|
+
type: "integer",
|
|
140
|
+
minimum: 1,
|
|
141
|
+
description:
|
|
142
|
+
"With start: frames are scaled to fit; default the viewport.",
|
|
143
|
+
},
|
|
144
|
+
maxHeight: { type: "integer", minimum: 1 },
|
|
145
|
+
maxDurationMs: {
|
|
146
|
+
type: "integer",
|
|
147
|
+
minimum: 1000,
|
|
148
|
+
maximum: 1_800_000,
|
|
149
|
+
description:
|
|
150
|
+
"With start: capture stops by itself after this; default 600000.",
|
|
151
|
+
},
|
|
152
|
+
path: {
|
|
153
|
+
type: "string",
|
|
154
|
+
description:
|
|
155
|
+
"With stop: absolute .mp4 path; default a temp file.",
|
|
156
|
+
},
|
|
157
|
+
overwrite: { type: "boolean" },
|
|
158
|
+
},
|
|
159
|
+
["action"],
|
|
160
|
+
),
|
|
161
|
+
},
|
|
162
|
+
handler: async (args) => {
|
|
163
|
+
if (args.action === "start") {
|
|
164
|
+
const { dir, recording } = await server.browserAdapter.startVideo(
|
|
165
|
+
args.sessionId,
|
|
166
|
+
{
|
|
167
|
+
fps: args.fps,
|
|
168
|
+
quality: args.quality,
|
|
169
|
+
maxWidth: args.maxWidth,
|
|
170
|
+
maxHeight: args.maxHeight,
|
|
171
|
+
maxDurationMs: args.maxDurationMs,
|
|
172
|
+
},
|
|
173
|
+
);
|
|
174
|
+
return { recording, dir };
|
|
175
|
+
}
|
|
176
|
+
await checkVideoPath(args);
|
|
177
|
+
const capture = await server.browserAdapter.stopVideo(args.sessionId);
|
|
178
|
+
return encodeVideo(capture, args, server.config);
|
|
179
|
+
},
|
|
180
|
+
},
|
|
181
|
+
],
|
|
115
182
|
];
|
|
116
183
|
}
|
|
@@ -0,0 +1,401 @@
|
|
|
1
|
+
import { spawn } from "node:child_process";
|
|
2
|
+
import { randomUUID } from "node:crypto";
|
|
3
|
+
import {
|
|
4
|
+
access,
|
|
5
|
+
chmod,
|
|
6
|
+
constants,
|
|
7
|
+
link,
|
|
8
|
+
lstat,
|
|
9
|
+
mkdir,
|
|
10
|
+
mkdtemp,
|
|
11
|
+
open,
|
|
12
|
+
realpath,
|
|
13
|
+
rename,
|
|
14
|
+
rm,
|
|
15
|
+
unlink,
|
|
16
|
+
writeFile,
|
|
17
|
+
} from "node:fs/promises";
|
|
18
|
+
import { createReadStream } from "node:fs";
|
|
19
|
+
import { tmpdir } from "node:os";
|
|
20
|
+
import path from "node:path";
|
|
21
|
+
import { pipeline } from "node:stream/promises";
|
|
22
|
+
|
|
23
|
+
import { SCREENSHOT_FILE_MODE } from "./screenshot-output.mjs";
|
|
24
|
+
|
|
25
|
+
// How long an encode may run before it is given up and the frames kept.
|
|
26
|
+
const ENCODE_TIMEOUT_MS = 10 * 60_000;
|
|
27
|
+
const STDERR_KEEP = 4096;
|
|
28
|
+
|
|
29
|
+
// Each frame lasts until the next one, and the last until the capture
|
|
30
|
+
// stopped, so a page that repaints rarely plays at its real pace. A frame
|
|
31
|
+
// that is not later than the one before it (a duplicate timestamp, or one
|
|
32
|
+
// delivered out of order) is left out, so every duration is positive. The
|
|
33
|
+
// last frame is listed again half a frame before the end: ffmpeg ends a
|
|
34
|
+
// stream one estimated interval after its last frame, and drops a frame at
|
|
35
|
+
// or past -t, so the copy holds the picture while -t sets the length.
|
|
36
|
+
export function frameDurations(frames, stoppedAt, fps) {
|
|
37
|
+
const kept = [];
|
|
38
|
+
for (const frame of frames) {
|
|
39
|
+
if (kept.length === 0 || frame.timestamp > kept.at(-1).timestamp) {
|
|
40
|
+
kept.push(frame);
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
return kept.map((frame, index) => {
|
|
44
|
+
const next = kept[index + 1];
|
|
45
|
+
const until = next ? next.timestamp : stoppedAt - 0.5 / fps;
|
|
46
|
+
return {
|
|
47
|
+
file: frame.file,
|
|
48
|
+
duration: Math.max(
|
|
49
|
+
0.001,
|
|
50
|
+
Math.round((until - frame.timestamp) * 1000) / 1000,
|
|
51
|
+
),
|
|
52
|
+
};
|
|
53
|
+
});
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
// The concat demuxer's script. File names are relative to the script, so
|
|
57
|
+
// no path needs quoting. Each JPEG is read with a 1 ms timebase (the
|
|
58
|
+
// default, 1/25 s, would round every frame time to 40 ms), which needs
|
|
59
|
+
// -safe 0; the script and the frames are in the recording's own directory.
|
|
60
|
+
export function concatList(entries) {
|
|
61
|
+
const lines = ["ffconcat version 1.0"];
|
|
62
|
+
for (const entry of entries) {
|
|
63
|
+
lines.push(
|
|
64
|
+
`file ${entry.file}`,
|
|
65
|
+
"option framerate 1000",
|
|
66
|
+
`duration ${entry.duration.toFixed(3)}`,
|
|
67
|
+
);
|
|
68
|
+
}
|
|
69
|
+
if (entries.length > 0) {
|
|
70
|
+
lines.push(`file ${entries.at(-1).file}`, "option framerate 1000");
|
|
71
|
+
}
|
|
72
|
+
return `${lines.join("\n")}\n`;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
export function evenSize(size) {
|
|
76
|
+
return {
|
|
77
|
+
width: Math.max(2, Math.floor(size.width / 2) * 2),
|
|
78
|
+
height: Math.max(2, Math.floor(size.height / 2) * 2),
|
|
79
|
+
};
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
// H.264 at a constant frame rate for exactly the capture's length, scaled
|
|
83
|
+
// to the recording's even size and to limited-range yuv420p (JPEG frames
|
|
84
|
+
// are full range) so players and browsers open it, with the index first.
|
|
85
|
+
export function ffmpegArgs({
|
|
86
|
+
listPath,
|
|
87
|
+
fps,
|
|
88
|
+
width,
|
|
89
|
+
height,
|
|
90
|
+
durationS,
|
|
91
|
+
outputPath,
|
|
92
|
+
}) {
|
|
93
|
+
return [
|
|
94
|
+
"-hide_banner",
|
|
95
|
+
"-loglevel",
|
|
96
|
+
"error",
|
|
97
|
+
"-nostdin",
|
|
98
|
+
"-y",
|
|
99
|
+
"-safe",
|
|
100
|
+
"0",
|
|
101
|
+
"-f",
|
|
102
|
+
"concat",
|
|
103
|
+
"-i",
|
|
104
|
+
listPath,
|
|
105
|
+
"-fps_mode",
|
|
106
|
+
"cfr",
|
|
107
|
+
"-r",
|
|
108
|
+
String(fps),
|
|
109
|
+
"-vf",
|
|
110
|
+
`scale=${width}:${height}:in_range=full:out_range=limited,setsar=1,format=yuv420p`,
|
|
111
|
+
"-t",
|
|
112
|
+
durationS.toFixed(3),
|
|
113
|
+
"-c:v",
|
|
114
|
+
"libx264",
|
|
115
|
+
"-preset",
|
|
116
|
+
"veryfast",
|
|
117
|
+
"-crf",
|
|
118
|
+
"23",
|
|
119
|
+
"-pix_fmt",
|
|
120
|
+
"yuv420p",
|
|
121
|
+
"-movflags",
|
|
122
|
+
"+faststart",
|
|
123
|
+
outputPath,
|
|
124
|
+
];
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
function shellQuote(value) {
|
|
128
|
+
return /^[\w./:=+@%,-]+$/.test(value)
|
|
129
|
+
? value
|
|
130
|
+
: `'${value.replaceAll("'", `'\\''`)}'`;
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
export function formatCommand(command, args) {
|
|
134
|
+
return [command, ...args].map(shellQuote).join(" ");
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
async function isExecutable(file) {
|
|
138
|
+
return access(file, constants.X_OK).then(
|
|
139
|
+
() => true,
|
|
140
|
+
() => false,
|
|
141
|
+
);
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
// MCP_BROWSER_FFMPEG, else the first ffmpeg on PATH, else null.
|
|
145
|
+
export async function findFfmpeg(config = {}, env = process.env) {
|
|
146
|
+
if (config.ffmpegPath) {
|
|
147
|
+
return (await isExecutable(config.ffmpegPath)) ? config.ffmpegPath : null;
|
|
148
|
+
}
|
|
149
|
+
const names =
|
|
150
|
+
process.platform === "win32" ? ["ffmpeg.exe", "ffmpeg"] : ["ffmpeg"];
|
|
151
|
+
for (const dir of (env.PATH ?? "").split(path.delimiter).filter(Boolean)) {
|
|
152
|
+
for (const name of names) {
|
|
153
|
+
const candidate = path.join(dir, name);
|
|
154
|
+
if (await isExecutable(candidate)) {
|
|
155
|
+
return candidate;
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
return null;
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
const encoders = new Set();
|
|
163
|
+
let exitHookInstalled = false;
|
|
164
|
+
|
|
165
|
+
// An encoder still running when the server exits is killed with it.
|
|
166
|
+
function trackEncoder(child) {
|
|
167
|
+
encoders.add(child);
|
|
168
|
+
child.once("exit", () => encoders.delete(child));
|
|
169
|
+
if (!exitHookInstalled) {
|
|
170
|
+
exitHookInstalled = true;
|
|
171
|
+
process.once("exit", () => {
|
|
172
|
+
for (const encoder of encoders) {
|
|
173
|
+
encoder.kill("SIGKILL");
|
|
174
|
+
}
|
|
175
|
+
});
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
export function runFfmpeg(command, args, { spawnFn = spawn } = {}) {
|
|
180
|
+
return new Promise((resolve) => {
|
|
181
|
+
let stderr = "";
|
|
182
|
+
let child;
|
|
183
|
+
try {
|
|
184
|
+
child = spawnFn(command, args, { stdio: ["ignore", "ignore", "pipe"] });
|
|
185
|
+
} catch (error) {
|
|
186
|
+
resolve({ ok: false, error: error.message });
|
|
187
|
+
return;
|
|
188
|
+
}
|
|
189
|
+
trackEncoder(child);
|
|
190
|
+
const timer = setTimeout(() => {
|
|
191
|
+
child.kill("SIGKILL");
|
|
192
|
+
stderr += `\nffmpeg was stopped after ${ENCODE_TIMEOUT_MS / 60_000} minutes`;
|
|
193
|
+
}, ENCODE_TIMEOUT_MS);
|
|
194
|
+
child.stderr?.on("data", (chunk) => {
|
|
195
|
+
stderr = (stderr + chunk.toString()).slice(-STDERR_KEEP);
|
|
196
|
+
});
|
|
197
|
+
child.once("error", (error) => {
|
|
198
|
+
clearTimeout(timer);
|
|
199
|
+
resolve({ ok: false, error: error.message });
|
|
200
|
+
});
|
|
201
|
+
child.once("exit", (code, signal) => {
|
|
202
|
+
clearTimeout(timer);
|
|
203
|
+
if (code === 0) {
|
|
204
|
+
resolve({ ok: true });
|
|
205
|
+
} else {
|
|
206
|
+
resolve({
|
|
207
|
+
ok: false,
|
|
208
|
+
error: `ffmpeg exited with ${signal ?? code}${stderr.trim() ? `: ${stderr.trim()}` : ""}`,
|
|
209
|
+
});
|
|
210
|
+
}
|
|
211
|
+
});
|
|
212
|
+
});
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
// Checked before the capture stops, so a bad path does not cost the frames.
|
|
216
|
+
export async function checkVideoPath(args) {
|
|
217
|
+
if (args.path === undefined) {
|
|
218
|
+
return;
|
|
219
|
+
}
|
|
220
|
+
if (!path.isAbsolute(args.path) || !args.path.endsWith(".mp4")) {
|
|
221
|
+
throw new Error("record_video path must be absolute and end in .mp4");
|
|
222
|
+
}
|
|
223
|
+
if (!args.overwrite) {
|
|
224
|
+
const exists = await lstat(args.path).then(
|
|
225
|
+
() => true,
|
|
226
|
+
() => false,
|
|
227
|
+
);
|
|
228
|
+
if (exists) {
|
|
229
|
+
throw new Error(
|
|
230
|
+
`${args.path} already exists; pass overwrite: true to replace it`,
|
|
231
|
+
);
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
// Moves the encoded file, private already, into place like a screenshot:
|
|
237
|
+
// never over an existing file unless asked, and never through a symlink
|
|
238
|
+
// (link and rename replace a link at the path rather than following it).
|
|
239
|
+
// Across volumes the file is copied into one opened exclusively instead.
|
|
240
|
+
async function placeVideo(encoded, filePath, overwrite) {
|
|
241
|
+
await mkdir(path.dirname(filePath), { recursive: true });
|
|
242
|
+
try {
|
|
243
|
+
if (overwrite) {
|
|
244
|
+
await rename(encoded, filePath);
|
|
245
|
+
} else {
|
|
246
|
+
await link(encoded, filePath);
|
|
247
|
+
await unlink(encoded);
|
|
248
|
+
}
|
|
249
|
+
return;
|
|
250
|
+
} catch (error) {
|
|
251
|
+
if (error.code === "EEXIST") {
|
|
252
|
+
throw new Error(
|
|
253
|
+
`${filePath} already exists; pass overwrite: true to replace it`,
|
|
254
|
+
{ cause: error },
|
|
255
|
+
);
|
|
256
|
+
}
|
|
257
|
+
// Another volume, or a filesystem without hard links: copy instead.
|
|
258
|
+
if (!["EXDEV", "EPERM", "ENOTSUP", "EOPNOTSUPP"].includes(error.code)) {
|
|
259
|
+
throw error;
|
|
260
|
+
}
|
|
261
|
+
}
|
|
262
|
+
const target = overwrite ? `${filePath}.${randomUUID()}.tmp` : filePath;
|
|
263
|
+
let handle;
|
|
264
|
+
try {
|
|
265
|
+
handle = await open(target, "wx", SCREENSHOT_FILE_MODE);
|
|
266
|
+
} catch (error) {
|
|
267
|
+
if (error.code === "EEXIST") {
|
|
268
|
+
throw new Error(
|
|
269
|
+
`${filePath} already exists; pass overwrite: true to replace it`,
|
|
270
|
+
{ cause: error },
|
|
271
|
+
);
|
|
272
|
+
}
|
|
273
|
+
throw error;
|
|
274
|
+
}
|
|
275
|
+
try {
|
|
276
|
+
await pipeline(createReadStream(encoded), handle.createWriteStream());
|
|
277
|
+
if (overwrite) {
|
|
278
|
+
await rename(target, filePath);
|
|
279
|
+
}
|
|
280
|
+
} catch (error) {
|
|
281
|
+
await rm(target, { force: true });
|
|
282
|
+
throw error;
|
|
283
|
+
}
|
|
284
|
+
await unlink(encoded);
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
// Both sides are resolved through symlinks (the destination by its nearest
|
|
288
|
+
// existing ancestor), so an alias such as /private/var for /var is caught.
|
|
289
|
+
async function isInside(dir, filePath) {
|
|
290
|
+
const realDir = await realpath(dir);
|
|
291
|
+
let ancestor = path.resolve(filePath);
|
|
292
|
+
let rest = "";
|
|
293
|
+
while (true) {
|
|
294
|
+
try {
|
|
295
|
+
ancestor = await realpath(ancestor);
|
|
296
|
+
break;
|
|
297
|
+
} catch {
|
|
298
|
+
rest = path.join(path.basename(ancestor), rest);
|
|
299
|
+
const parent = path.dirname(ancestor);
|
|
300
|
+
if (parent === ancestor) {
|
|
301
|
+
break;
|
|
302
|
+
}
|
|
303
|
+
ancestor = parent;
|
|
304
|
+
}
|
|
305
|
+
}
|
|
306
|
+
const relative = path.relative(realDir, path.join(ancestor, rest));
|
|
307
|
+
return (
|
|
308
|
+
relative === "" ||
|
|
309
|
+
(!relative.startsWith("..") && !path.isAbsolute(relative))
|
|
310
|
+
);
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
async function tempVideoPath() {
|
|
314
|
+
const dir = await mkdtemp(path.join(tmpdir(), "mcp-browser-dev-tools-"));
|
|
315
|
+
return path.join(dir, "video.mp4");
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
// Encodes a capture ({ dir, frames, startedAt, stoppedAt, fps, width,
|
|
319
|
+
// height, warnings }) to MP4. Without ffmpeg, or when it fails, the frames
|
|
320
|
+
// stay in their directory and the result says so and gives the command.
|
|
321
|
+
export async function encodeVideo(capture, args, config, { spawnFn } = {}) {
|
|
322
|
+
const entries = frameDurations(
|
|
323
|
+
capture.frames,
|
|
324
|
+
capture.stoppedAt,
|
|
325
|
+
capture.fps,
|
|
326
|
+
);
|
|
327
|
+
const { width, height } = evenSize(capture);
|
|
328
|
+
const listPath = path.join(capture.dir, "frames.ffconcat");
|
|
329
|
+
await writeFile(listPath, concatList(entries), {
|
|
330
|
+
mode: SCREENSHOT_FILE_MODE,
|
|
331
|
+
});
|
|
332
|
+
const encoded = path.join(capture.dir, "video.mp4");
|
|
333
|
+
const durationS = Math.max(0, capture.stoppedAt - capture.startedAt);
|
|
334
|
+
const ffmpegArguments = ffmpegArgs({
|
|
335
|
+
listPath,
|
|
336
|
+
fps: capture.fps,
|
|
337
|
+
width,
|
|
338
|
+
height,
|
|
339
|
+
durationS,
|
|
340
|
+
outputPath: encoded,
|
|
341
|
+
});
|
|
342
|
+
const summary = {
|
|
343
|
+
durationMs: Math.round(durationS * 1000),
|
|
344
|
+
frames: entries.length,
|
|
345
|
+
width,
|
|
346
|
+
height,
|
|
347
|
+
...(capture.warnings?.length ? { warnings: capture.warnings } : {}),
|
|
348
|
+
};
|
|
349
|
+
const kept = (error) => ({
|
|
350
|
+
...summary,
|
|
351
|
+
framesDir: capture.dir,
|
|
352
|
+
ffmpegCommand: formatCommand(
|
|
353
|
+
config.ffmpegPath || "ffmpeg",
|
|
354
|
+
ffmpegArguments,
|
|
355
|
+
),
|
|
356
|
+
error,
|
|
357
|
+
});
|
|
358
|
+
|
|
359
|
+
const ffmpeg = await findFfmpeg(config);
|
|
360
|
+
if (!ffmpeg) {
|
|
361
|
+
return kept(
|
|
362
|
+
config.ffmpegPath
|
|
363
|
+
? `${config.ffmpegPath} (MCP_BROWSER_FFMPEG) is not an executable; the frames are kept in framesDir and ffmpegCommand encodes them`
|
|
364
|
+
: "ffmpeg was not found on PATH (set MCP_BROWSER_FFMPEG to its path); the frames are kept in framesDir and ffmpegCommand encodes them",
|
|
365
|
+
);
|
|
366
|
+
}
|
|
367
|
+
const run = await runFfmpeg(ffmpeg, ffmpegArguments, { spawnFn });
|
|
368
|
+
if (!run.ok) {
|
|
369
|
+
await rm(encoded, { force: true });
|
|
370
|
+
return kept(
|
|
371
|
+
`${run.error}; the frames are kept in framesDir and ffmpegCommand encodes them`,
|
|
372
|
+
);
|
|
373
|
+
}
|
|
374
|
+
await chmod(encoded, SCREENSHOT_FILE_MODE);
|
|
375
|
+
|
|
376
|
+
let placed;
|
|
377
|
+
let error;
|
|
378
|
+
if (args.path === undefined) {
|
|
379
|
+
placed = await tempVideoPath();
|
|
380
|
+
await placeVideo(encoded, placed, false);
|
|
381
|
+
} else {
|
|
382
|
+
try {
|
|
383
|
+
// The frame directory is deleted below, so a video placed in it
|
|
384
|
+
// would go with it.
|
|
385
|
+
if (await isInside(capture.dir, args.path)) {
|
|
386
|
+
throw new Error(
|
|
387
|
+
"the path is inside the frame directory, which is deleted after encoding",
|
|
388
|
+
);
|
|
389
|
+
}
|
|
390
|
+
await placeVideo(encoded, args.path, args.overwrite);
|
|
391
|
+
placed = args.path;
|
|
392
|
+
} catch (placeError) {
|
|
393
|
+
// The video is not lost: it goes to a temp file instead.
|
|
394
|
+
placed = await tempVideoPath();
|
|
395
|
+
await placeVideo(encoded, placed, false);
|
|
396
|
+
error = `Could not write ${args.path} (${placeError.message}); the video was saved to a temp file instead`;
|
|
397
|
+
}
|
|
398
|
+
}
|
|
399
|
+
await rm(capture.dir, { recursive: true, force: true });
|
|
400
|
+
return { path: placed, ...summary, ...(error ? { error } : {}) };
|
|
401
|
+
}
|