dsh-browser-cdp 0.0.1 → 0.17.1
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/LICENSE +27 -0
- package/README.md +279 -9
- package/THIRD_PARTY_NOTICES.md +62 -0
- package/bin/cdp-cast-worker.mjs +6960 -0
- package/bin/cdp-chrome-wrapper.sh +53 -0
- package/bin/cdp-render-worker.mjs +610 -0
- package/bin/record-normalize.d.mts +32 -0
- package/bin/record-normalize.mjs +156 -0
- package/cordis.patch.yml +17 -0
- package/dsh-plugin.json +148 -0
- package/lib/client.js +3235 -0
- package/lib/index.js +8865 -0
- package/lib/launcher-CQyI8-By.js +3 -0
- package/lib/launcher-DBaxfIsF.js +269 -0
- package/package.json +90 -14
- package/runtime/PATCHES.md +30 -0
- package/runtime/ego-browser/dist/out/index.js +7206 -0
- package/runtime/ego-browser/screenshot-clip.d.mts +22 -0
- package/runtime/ego-browser/screenshot-clip.mjs +45 -0
- package/runtime/ego-linux/bin/ego-browser.mjs +399 -0
- package/runtime/ego-linux/src/agent-identity.mjs +65 -0
- package/runtime/ego-linux/src/chrome.mjs +867 -0
- package/runtime/ego-linux/src/cursor.mjs +1292 -0
- package/runtime/ego-linux/src/desktop.mjs +73 -0
- package/runtime/ego-linux/src/paths.mjs +35 -0
- package/runtime/ego-linux/src/session.mjs +37 -0
- package/runtime/ego-linux/src/shim.mjs +145 -0
- package/runtime/ego-linux/src/snapshot.mjs +424 -0
- package/runtime/ego-linux/src/spaces-server.mjs +355 -0
- package/runtime/ego-linux/src/spaces-ui.mjs +456 -0
- package/runtime/ego-linux/src/tabs.mjs +109 -0
- package/runtime/ego-linux/src/task-spaces.mjs +671 -0
- package/runtime/ego-linux/src/transport.mjs +321 -0
- package/runtime/ego-linux/src/window-fit.mjs +107 -0
- package/runtime/skills/ego-browser/SKILL.md +209 -0
- package/runtime/skills/ego-browser/agents/openai.yaml +7 -0
- package/runtime/skills/ego-browser/assets/composer-icon.png +0 -0
- package/runtime/skills/ego-browser/assets/logo.png +0 -0
- package/runtime/skills/ego-browser/learnings/google/browser-tools/autocomplete.js +11 -0
- package/runtime/skills/ego-browser/learnings/google/manifest.json +40 -0
- package/runtime/skills/ego-browser/learnings/google/notes/overview.md +23 -0
- package/runtime/skills/ego-browser/learnings/google/tools/search-extract.js +35 -0
- package/runtime/skills/ego-browser/learnings/x-com/browser-tools/extract-post.js +9 -0
- package/runtime/skills/ego-browser/learnings/x-com/manifest.json +51 -0
- package/runtime/skills/ego-browser/learnings/x-com/notes/overview.md +18 -0
- package/runtime/skills/ego-browser/learnings/x-com/notes/timeline.md +19 -0
- package/runtime/skills/ego-browser/learnings/x-com/tools/search-users.js +33 -0
- package/runtime/skills/ego-browser/learnings/x-com/tools/timeline.js +32 -0
- package/runtime/skills/ego-browser/references/install.md +131 -0
- package/runtime/skills/ego-browser/references/task-spaces.md +122 -0
- package/runtime/skills/ego-browser/references/video.md +17 -0
- package/runtime/skills/ego-browser/scripts/install.sh +309 -0
- package/index.js +0 -11
|
@@ -0,0 +1,867 @@
|
|
|
1
|
+
import { spawn } from "node:child_process";
|
|
2
|
+
import { access, mkdir, readdir, readFile, readlink, writeFile, rm } from "node:fs/promises";
|
|
3
|
+
import { constants } from "node:fs";
|
|
4
|
+
import { isAbsolute, join } from "node:path";
|
|
5
|
+
|
|
6
|
+
import { BROWSER_STATE_FILE, PROFILE_DIR, STATE_DIR } from "./paths.mjs";
|
|
7
|
+
|
|
8
|
+
const BINARY_CANDIDATES = [
|
|
9
|
+
process.env.EGO_LINUX_CHROME,
|
|
10
|
+
"google-chrome",
|
|
11
|
+
"google-chrome-stable",
|
|
12
|
+
"chromium",
|
|
13
|
+
"chromium-browser",
|
|
14
|
+
"brave-browser",
|
|
15
|
+
"microsoft-edge",
|
|
16
|
+
].filter(Boolean);
|
|
17
|
+
|
|
18
|
+
// Chrome writes the negotiated port here once the DevTools endpoint is live.
|
|
19
|
+
const PORT_FILE = "DevToolsActivePort";
|
|
20
|
+
|
|
21
|
+
// Shared by the launch args and the orphan reaper that reads them back out of
|
|
22
|
+
// /proc — if the two spellings drifted, the reaper would match nothing.
|
|
23
|
+
const PROFILE_FLAG = "--user-data-dir=";
|
|
24
|
+
|
|
25
|
+
/** Window class shared with the desktop entry's StartupWMClass. */
|
|
26
|
+
export const WM_CLASS = "ego-lite-linux";
|
|
27
|
+
|
|
28
|
+
/** Shown in Chrome's profile chip so the agent window is identifiable. */
|
|
29
|
+
const PROFILE_LABEL = "ego lite — agent";
|
|
30
|
+
|
|
31
|
+
const LAUNCH_FLAGS = [
|
|
32
|
+
"--no-first-run",
|
|
33
|
+
"--no-default-browser-check",
|
|
34
|
+
"--disable-background-timer-throttling",
|
|
35
|
+
"--disable-backgrounding-occluded-windows",
|
|
36
|
+
"--disable-renderer-backgrounding",
|
|
37
|
+
// Node's WebSocket sends no Origin; without this Chrome rejects the upgrade.
|
|
38
|
+
"--remote-allow-origins=*",
|
|
39
|
+
// Big enough that a page laid out for a desktop viewport fits. The default
|
|
40
|
+
// headless window is ~800x600, which pushes lower page content out of view;
|
|
41
|
+
// input dispatched at those coordinates hit-tests to nothing and
|
|
42
|
+
// Input.dispatchMouseEvent can hang waiting for a frame that never comes.
|
|
43
|
+
"--window-size=1280,900",
|
|
44
|
+
// Without this the desktop's HiDPI scaling (1.5x here) shrinks the CSS
|
|
45
|
+
// viewport — a 1280px window lays out as 853px — so page content the agent
|
|
46
|
+
// expects on screen falls below the fold.
|
|
47
|
+
"--force-device-scale-factor=1",
|
|
48
|
+
// "Chrome didn't shut down correctly — Restore pages?". Two things keep it
|
|
49
|
+
// away, covering different halves: the graceful Browser.close in stopBrowser()
|
|
50
|
+
// stops the profile *earning* the mark, and clearStaleCrashMark() clears a
|
|
51
|
+
// mark it already carries, which a clean exit alone never does. This flag is
|
|
52
|
+
// the backstop for what neither covers — a browser killed by something outside
|
|
53
|
+
// this launcher, between one launch's clear and the next.
|
|
54
|
+
"--hide-crash-restore-bubble",
|
|
55
|
+
// Give the agent browser its own window class. Without it the window carries
|
|
56
|
+
// Chrome's, so the desktop groups it under the ordinary Chrome icon: it never
|
|
57
|
+
// appears as its own running app and the launcher icon cannot raise it.
|
|
58
|
+
// Paired with StartupWMClass in the desktop entry.
|
|
59
|
+
`--class=${WM_CLASS}`,
|
|
60
|
+
// The browser must come up holding NO tab. ego_space_open (and every other
|
|
61
|
+
// structured ego_* tool) routes through useSpace(...) + ensureRealTab(),
|
|
62
|
+
// which creates the first tab inside its own browser context — Chrome
|
|
63
|
+
// isolates each context to its own window, so that tab is the single window
|
|
64
|
+
// the user sees. If launch also opened a tab (the old "about:blank"
|
|
65
|
+
// positional arg), it would land in the default context and force a second
|
|
66
|
+
// window. The "no active tab to attach session" failure that used to make
|
|
67
|
+
// --no-startup-window unsafe only fired when a tool called page.* directly
|
|
68
|
+
// without first going through useSpace+ensureRealTab; the structured tools
|
|
69
|
+
// all do, so it no longer applies.
|
|
70
|
+
"--no-startup-window",
|
|
71
|
+
];
|
|
72
|
+
|
|
73
|
+
// ── user-defined extra Chrome args (mirrors lib/config.js) ──────────────────
|
|
74
|
+
// The runtime must not import from lib/, so the blocklist + tokenizer are
|
|
75
|
+
// duplicated here. Keep in sync with lib/config.js (EGO_CLI_BLOCKED is not
|
|
76
|
+
// needed here — only the Chrome side runs in this process). See
|
|
77
|
+
// runtime/PATCHES.md and docs/plans/2026-08-20-custom-cli-args-design.md.
|
|
78
|
+
const CHROME_BLOCKED = new Set([
|
|
79
|
+
"--user-data-dir",
|
|
80
|
+
"--remote-debugging-port",
|
|
81
|
+
"--remote-allow-origins",
|
|
82
|
+
"--headless",
|
|
83
|
+
"--no-startup-window",
|
|
84
|
+
"--proxy-server",
|
|
85
|
+
"--proxy-bypass-list",
|
|
86
|
+
]);
|
|
87
|
+
|
|
88
|
+
function tokenizeArgs(input) {
|
|
89
|
+
if (typeof input !== "string") return [];
|
|
90
|
+
const out = [];
|
|
91
|
+
let cur = "";
|
|
92
|
+
let i = 0;
|
|
93
|
+
let quote = null;
|
|
94
|
+
while (i < input.length) {
|
|
95
|
+
const c = input[i];
|
|
96
|
+
if (quote) {
|
|
97
|
+
if (c === "\\") {
|
|
98
|
+
const next = input[i + 1];
|
|
99
|
+
if (next !== undefined) { cur += next; i += 2; continue; }
|
|
100
|
+
} else if (c === quote) { quote = null; i += 1; continue; }
|
|
101
|
+
cur += c; i += 1; continue;
|
|
102
|
+
}
|
|
103
|
+
if (c === '"' || c === "'") { quote = c; i += 1; continue; }
|
|
104
|
+
if (c === "\\") {
|
|
105
|
+
const next = input[i + 1];
|
|
106
|
+
if (next !== undefined) { cur += next; i += 2; continue; }
|
|
107
|
+
i += 1; continue;
|
|
108
|
+
}
|
|
109
|
+
if (c === " " || c === "\t" || c === "\n" || c === "\r") {
|
|
110
|
+
if (cur !== "") { out.push(cur); cur = ""; }
|
|
111
|
+
i += 1; continue;
|
|
112
|
+
}
|
|
113
|
+
cur += c; i += 1;
|
|
114
|
+
}
|
|
115
|
+
if (cur !== "") out.push(cur);
|
|
116
|
+
return out;
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
function filterChromeArgs(raw) {
|
|
120
|
+
const tokens = tokenizeArgs(raw);
|
|
121
|
+
const kept = [];
|
|
122
|
+
for (let i = 0; i < tokens.length; i++) {
|
|
123
|
+
const tok = tokens[i];
|
|
124
|
+
const key = tok.includes("=") ? tok.slice(0, tok.indexOf("=")) : tok;
|
|
125
|
+
if (CHROME_BLOCKED.has(key)) {
|
|
126
|
+
if (!tok.includes("=") && i + 1 < tokens.length && !tokens[i + 1].startsWith("-")) i += 1;
|
|
127
|
+
continue;
|
|
128
|
+
}
|
|
129
|
+
kept.push(tok);
|
|
130
|
+
}
|
|
131
|
+
return kept;
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/**
|
|
135
|
+
* Is this directory *provably* absent?
|
|
136
|
+
*
|
|
137
|
+
* exists() answers "could I stat it", collapsing every failure into false —
|
|
138
|
+
* fine for picking a browser binary, dangerous for deciding whether to kill a
|
|
139
|
+
* process. A transient ESTALE on NFS, an EIO, or a FUSE timeout would read as
|
|
140
|
+
* "profile deleted" and take a live browser down with it. Only ENOENT is
|
|
141
|
+
* evidence of absence; every other error means "assume it is there".
|
|
142
|
+
*/
|
|
143
|
+
async function definitelyGone(path) {
|
|
144
|
+
try {
|
|
145
|
+
await access(path, constants.F_OK);
|
|
146
|
+
return false;
|
|
147
|
+
} catch (error) {
|
|
148
|
+
return error?.code === "ENOENT";
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
async function exists(path) {
|
|
153
|
+
try {
|
|
154
|
+
await access(path, constants.F_OK);
|
|
155
|
+
return true;
|
|
156
|
+
} catch {
|
|
157
|
+
return false;
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
async function resolveBinary() {
|
|
162
|
+
for (const candidate of BINARY_CANDIDATES) {
|
|
163
|
+
if (isAbsolute(candidate)) {
|
|
164
|
+
if (await exists(candidate)) return candidate;
|
|
165
|
+
continue;
|
|
166
|
+
}
|
|
167
|
+
const found = await which(candidate);
|
|
168
|
+
if (found) return found;
|
|
169
|
+
}
|
|
170
|
+
throw new Error(
|
|
171
|
+
`no Chrome/Chromium binary found (tried: ${BINARY_CANDIDATES.join(", ")}). ` +
|
|
172
|
+
`Set EGO_LINUX_CHROME to an absolute path.`,
|
|
173
|
+
);
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
function which(name) {
|
|
177
|
+
return new Promise((resolve) => {
|
|
178
|
+
// Windows has no `which`; `where` is its equivalent and prints one path
|
|
179
|
+
// per line (may return several — take the first).
|
|
180
|
+
const cmd = process.platform === "win32" ? "where" : "which";
|
|
181
|
+
const child = spawn(cmd, [name], { stdio: ["ignore", "pipe", "ignore"] });
|
|
182
|
+
let out = "";
|
|
183
|
+
child.stdout.on("data", (chunk) => {
|
|
184
|
+
out += chunk;
|
|
185
|
+
});
|
|
186
|
+
child.on("error", () => resolve(null));
|
|
187
|
+
child.on("close", (code) => {
|
|
188
|
+
if (code !== 0) return resolve(null);
|
|
189
|
+
const first = out.trim().split(/\r?\n/)[0];
|
|
190
|
+
resolve(first || null);
|
|
191
|
+
});
|
|
192
|
+
});
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
/** Ask a running DevTools endpoint for its browser-level WebSocket URL. */
|
|
196
|
+
async function probe(port) {
|
|
197
|
+
try {
|
|
198
|
+
const response = await fetch(`http://127.0.0.1:${port}/json/version`, {
|
|
199
|
+
signal: AbortSignal.timeout(1500),
|
|
200
|
+
});
|
|
201
|
+
if (!response.ok) return null;
|
|
202
|
+
const info = await response.json();
|
|
203
|
+
return info.webSocketDebuggerUrl || null;
|
|
204
|
+
} catch {
|
|
205
|
+
return null;
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
async function readBrowserState() {
|
|
210
|
+
try {
|
|
211
|
+
return JSON.parse(await readFile(BROWSER_STATE_FILE, "utf8"));
|
|
212
|
+
} catch {
|
|
213
|
+
return null;
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
async function writeBrowserState(state) {
|
|
218
|
+
await mkdir(STATE_DIR, { recursive: true });
|
|
219
|
+
await writeFile(BROWSER_STATE_FILE, JSON.stringify(state, null, 2));
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
/**
|
|
223
|
+
* Poll for a DevTools endpoint that answers.
|
|
224
|
+
*
|
|
225
|
+
* The port file appears a beat after the process starts, and Chrome does not
|
|
226
|
+
* necessarily write it once: a launch that loses the ProcessSingleton race is
|
|
227
|
+
* restarted internally, and the process that survives publishes a different
|
|
228
|
+
* port. Probing whatever the file said first therefore names a port that never
|
|
229
|
+
* listens — so re-read it on every attempt and keep probing until one answers.
|
|
230
|
+
*/
|
|
231
|
+
export async function waitForEndpoint(profileDir, { timeoutMs = 20000 } = {}) {
|
|
232
|
+
const path = join(profileDir, PORT_FILE);
|
|
233
|
+
const deadline = Date.now() + timeoutMs;
|
|
234
|
+
let lastPort = null;
|
|
235
|
+
while (Date.now() < deadline) {
|
|
236
|
+
let port = null;
|
|
237
|
+
try {
|
|
238
|
+
const [line] = (await readFile(path, "utf8")).split("\n");
|
|
239
|
+
port = Number(line.trim()) || null;
|
|
240
|
+
} catch {
|
|
241
|
+
// not written yet
|
|
242
|
+
}
|
|
243
|
+
if (port) {
|
|
244
|
+
lastPort = port;
|
|
245
|
+
const wsUrl = await probe(port);
|
|
246
|
+
if (wsUrl) return { port, wsUrl };
|
|
247
|
+
}
|
|
248
|
+
await new Promise((resolve) => setTimeout(resolve, 100));
|
|
249
|
+
}
|
|
250
|
+
throw new Error(
|
|
251
|
+
lastPort
|
|
252
|
+
? `Chrome came up on port ${lastPort} but exposed no WebSocket URL within ${timeoutMs}ms`
|
|
253
|
+
: `Chrome did not expose a DevTools port within ${timeoutMs}ms`,
|
|
254
|
+
);
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
/**
|
|
258
|
+
* Reset page zoom in the agent profile.
|
|
259
|
+
*
|
|
260
|
+
* --import-chrome-profile copies real Chrome preferences, which include the
|
|
261
|
+
* user's zoom level. A 150% zoom lays a 1280px window out as 853 CSS px, so
|
|
262
|
+
* content the page expects on screen falls below the fold — element coordinates
|
|
263
|
+
* then hit-test to nothing and pointer input silently does nothing. This profile
|
|
264
|
+
* exists only to drive agents, so zoom is pinned to 100%.
|
|
265
|
+
*/
|
|
266
|
+
async function neutralizeZoom(profileDir) {
|
|
267
|
+
const path = join(profileDir, "Default", "Preferences");
|
|
268
|
+
try {
|
|
269
|
+
const prefs = JSON.parse(await readFile(path, "utf8"));
|
|
270
|
+
let changed = false;
|
|
271
|
+
for (const scope of ["partition", "profile"]) {
|
|
272
|
+
for (const key of ["default_zoom_level", "per_host_zoom_levels"]) {
|
|
273
|
+
if (prefs[scope]?.[key] && Object.keys(prefs[scope][key]).length > 0) {
|
|
274
|
+
prefs[scope][key] = {};
|
|
275
|
+
changed = true;
|
|
276
|
+
}
|
|
277
|
+
}
|
|
278
|
+
}
|
|
279
|
+
// --import-chrome-profile clones the user's real profile, so the agent
|
|
280
|
+
// browser ends up looking exactly like their everyday Chrome — same
|
|
281
|
+
// bookmarks, same theme, no way to tell which window an agent is driving.
|
|
282
|
+
// Naming the profile puts a label in Chrome's own toolbar chip.
|
|
283
|
+
if (prefs.profile?.name !== PROFILE_LABEL) {
|
|
284
|
+
prefs.profile = { ...prefs.profile, name: PROFILE_LABEL };
|
|
285
|
+
changed = true;
|
|
286
|
+
}
|
|
287
|
+
if (changed) await writeFile(path, JSON.stringify(prefs));
|
|
288
|
+
return changed;
|
|
289
|
+
} catch {
|
|
290
|
+
// A fresh profile has no Preferences file yet; nothing to reset.
|
|
291
|
+
return false;
|
|
292
|
+
}
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
/**
|
|
296
|
+
* Clear a stale crash mark before launching.
|
|
297
|
+
*
|
|
298
|
+
* Chrome stamps `profile.exit_type` "Crashed" while it runs and rewrites it to
|
|
299
|
+
* "Normal" on a graceful exit — but only if it did not *start* out marked. Once
|
|
300
|
+
* a profile carries the mark, Chrome keeps it until someone answers the
|
|
301
|
+
* "Restore pages?" prompt, and in an agent browser nobody ever does. So a single
|
|
302
|
+
* ungraceful kill marks a profile permanently: every later launch opens with the
|
|
303
|
+
* prompt, and even a clean Browser.close leaves the mark exactly where it was.
|
|
304
|
+
*
|
|
305
|
+
* Established by bisecting a marked profile's Preferences against a fresh one,
|
|
306
|
+
* top-level keys first and then within `profile`, down to this single key: seed
|
|
307
|
+
* "Crashed" and the next clean stop still reads "Crashed"; seed anything else
|
|
308
|
+
* and it reads "Normal".
|
|
309
|
+
*
|
|
310
|
+
* The mark exists to protect a human's tabs. This profile has none worth
|
|
311
|
+
* restoring — the agent opens what it needs — so clearing it costs nothing.
|
|
312
|
+
*/
|
|
313
|
+
export async function clearStaleCrashMark(profileDir) {
|
|
314
|
+
const path = join(profileDir, "Default", "Preferences");
|
|
315
|
+
try {
|
|
316
|
+
const prefs = JSON.parse(await readFile(path, "utf8"));
|
|
317
|
+
if (!prefs.profile || prefs.profile.exit_type === "Normal") return false;
|
|
318
|
+
prefs.profile = { ...prefs.profile, exit_type: "Normal" };
|
|
319
|
+
await writeFile(path, JSON.stringify(prefs));
|
|
320
|
+
return true;
|
|
321
|
+
} catch {
|
|
322
|
+
// A fresh profile has no Preferences file yet; nothing to clear.
|
|
323
|
+
return false;
|
|
324
|
+
}
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
/** Whether a pid is a browser running against our own profile directory. */
|
|
328
|
+
async function ownsOurProfile(pid, profileDir) {
|
|
329
|
+
try {
|
|
330
|
+
const cmdline = await readFile(`/proc/${pid}/cmdline`, "utf8");
|
|
331
|
+
return cmdline.includes(profileDir);
|
|
332
|
+
} catch {
|
|
333
|
+
return false;
|
|
334
|
+
}
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
/**
|
|
338
|
+
* Terminate ego browsers whose profile directory no longer exists.
|
|
339
|
+
*
|
|
340
|
+
* A harness that points EGO_LINUX_PROFILE (or XDG_DATA_HOME) at a scratch tree
|
|
341
|
+
* gets a browser of its own, and browsers are spawned detached so they outlive
|
|
342
|
+
* whatever started them. A harness that deletes its scratch tree without
|
|
343
|
+
* stopping its browser first leaves that browser running against a profile
|
|
344
|
+
* nobody can reach: ensureBrowser() tracks one browser per state file, so the
|
|
345
|
+
* orphan is invisible to it and simply accumulates — hundreds of MB per stale
|
|
346
|
+
* run, for as long as the machine stays up.
|
|
347
|
+
*
|
|
348
|
+
* A missing profile directory is the unambiguous signal. Chrome cannot function
|
|
349
|
+
* without it, so such a browser is already dead weight rather than someone's
|
|
350
|
+
* live session. Our own profile is created before this runs, which keeps the
|
|
351
|
+
* browser we are about to launch — and any other live one — out of scope.
|
|
352
|
+
*
|
|
353
|
+
* @returns {Promise<number>} How many orphans were signalled.
|
|
354
|
+
*/
|
|
355
|
+
export async function reapOrphanedBrowsers() {
|
|
356
|
+
let entries;
|
|
357
|
+
try {
|
|
358
|
+
entries = await readdir("/proc");
|
|
359
|
+
} catch {
|
|
360
|
+
return 0; // no procfs to walk; nothing to reap
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
let reaped = 0;
|
|
364
|
+
await Promise.all(
|
|
365
|
+
entries
|
|
366
|
+
.filter((entry) => /^\d+$/.test(entry))
|
|
367
|
+
.map(async (pid) => {
|
|
368
|
+
let argv;
|
|
369
|
+
try {
|
|
370
|
+
argv = (await readFile(`/proc/${pid}/cmdline`, "utf8")).split("\0");
|
|
371
|
+
} catch {
|
|
372
|
+
return; // exited under us, or another user's process
|
|
373
|
+
}
|
|
374
|
+
// Renderers and helpers inherit --user-data-dir but carry --type=;
|
|
375
|
+
// signalling the browser process takes its children with it anyway.
|
|
376
|
+
if (!argv.includes(`--class=${WM_CLASS}`)) return;
|
|
377
|
+
if (argv.some((arg) => arg.startsWith("--type="))) return;
|
|
378
|
+
|
|
379
|
+
const flag = argv.find((arg) => arg.startsWith(PROFILE_FLAG));
|
|
380
|
+
if (!flag) return;
|
|
381
|
+
const profileDir = flag.slice(PROFILE_FLAG.length);
|
|
382
|
+
if (profileDir === PROFILE_DIR) return;
|
|
383
|
+
if (!(await definitelyGone(profileDir))) return;
|
|
384
|
+
|
|
385
|
+
try {
|
|
386
|
+
process.kill(Number(pid), "SIGTERM");
|
|
387
|
+
reaped += 1;
|
|
388
|
+
} catch {
|
|
389
|
+
// already gone, or not ours to signal
|
|
390
|
+
}
|
|
391
|
+
}),
|
|
392
|
+
);
|
|
393
|
+
return reaped;
|
|
394
|
+
}
|
|
395
|
+
|
|
396
|
+
/**
|
|
397
|
+
* Clear the profile lock before launching.
|
|
398
|
+
*
|
|
399
|
+
* Chrome's SingletonLock is a symlink named `<host>-<pid>`; a browser that dies
|
|
400
|
+
* without a clean shutdown leaves it behind, and the next launch refuses to
|
|
401
|
+
* start ("Failed to create a ProcessSingleton ... Aborting now").
|
|
402
|
+
*
|
|
403
|
+
* launch() only runs after ensureBrowser() has confirmed no DevTools endpoint
|
|
404
|
+
* answers, so a lock owner that is still alive is an unreachable orphan of ours
|
|
405
|
+
* — a browser we can no longer drive. Since this profile is single-purpose,
|
|
406
|
+
* that orphan is terminated rather than left to block every future run.
|
|
407
|
+
*/
|
|
408
|
+
async function clearProfileLock(profileDir) {
|
|
409
|
+
const lock = join(profileDir, "SingletonLock");
|
|
410
|
+
let target;
|
|
411
|
+
try {
|
|
412
|
+
target = await readlink(lock);
|
|
413
|
+
} catch {
|
|
414
|
+
return false; // no lock at all
|
|
415
|
+
}
|
|
416
|
+
|
|
417
|
+
const pid = Number(target.slice(target.lastIndexOf("-") + 1));
|
|
418
|
+
if (Number.isFinite(pid) && pid > 0 && (await ownsOurProfile(pid, profileDir))) {
|
|
419
|
+
try {
|
|
420
|
+
process.kill(pid, "SIGTERM");
|
|
421
|
+
// Give it a moment to release the lock on its own.
|
|
422
|
+
await new Promise((resolve) => setTimeout(resolve, 500));
|
|
423
|
+
} catch {
|
|
424
|
+
// already gone
|
|
425
|
+
}
|
|
426
|
+
}
|
|
427
|
+
|
|
428
|
+
await Promise.all(
|
|
429
|
+
["SingletonLock", "SingletonSocket", "SingletonCookie"].map((name) =>
|
|
430
|
+
rm(join(profileDir, name), { force: true }),
|
|
431
|
+
),
|
|
432
|
+
);
|
|
433
|
+
return true;
|
|
434
|
+
}
|
|
435
|
+
|
|
436
|
+
// ── X display (Xvfb) handling ───────────────────────────────────────────────
|
|
437
|
+
// A visible (non-headless) browser draws into an X server, and on a machine
|
|
438
|
+
// with no display — a container, CI runner, headless server — $DISPLAY is
|
|
439
|
+
// unset, so Chrome aborts with "Missing X server or $DISPLAY". Rather than
|
|
440
|
+
// fail, the absence is detected through the environment (the $DISPLAY
|
|
441
|
+
// variable plus the socket it names) and a virtual framebuffer (Xvfb) is
|
|
442
|
+
// started automatically. A user-provided display is always preferred and is
|
|
443
|
+
// never touched.
|
|
444
|
+
|
|
445
|
+
const X11_UNIX_DIR = "/tmp/.X11-unix";
|
|
446
|
+
|
|
447
|
+
/**
|
|
448
|
+
* Does this $DISPLAY value name a usable X server right now?
|
|
449
|
+
*
|
|
450
|
+
* The env var is the primary signal, but a set-but-stale value (a dead
|
|
451
|
+
* session, a wiped /tmp) would read as "X is here" when it is not — so a
|
|
452
|
+
* local display must also have its socket file present. A display with a
|
|
453
|
+
* host part names a *remote* X server whose socket is not local; trust it
|
|
454
|
+
* as-is instead of shadowing it with a local Xvfb.
|
|
455
|
+
*/
|
|
456
|
+
async function displayUsable(display) {
|
|
457
|
+
if (typeof display !== "string" || display === "") return false;
|
|
458
|
+
const [host, numPart] = display.split(":");
|
|
459
|
+
const num = Number((numPart ?? "").split(".")[0]);
|
|
460
|
+
if (!Number.isInteger(num)) return false;
|
|
461
|
+
if (host) return true;
|
|
462
|
+
return exists(join(X11_UNIX_DIR, `X${num}`));
|
|
463
|
+
}
|
|
464
|
+
|
|
465
|
+
/**
|
|
466
|
+
* Find an Xvfb an earlier launch already started, so it can be reused.
|
|
467
|
+
*
|
|
468
|
+
* Every CLI run is a fresh process with a fresh environment, so a display
|
|
469
|
+
* this machine started earlier is invisible through $DISPLAY here. Without
|
|
470
|
+
* this check a crash-and-relaunch cycle would spawn a fresh Xvfb on every
|
|
471
|
+
* attempt, one display number per cycle, until the numbers ran out.
|
|
472
|
+
*
|
|
473
|
+
* @returns {Promise<string | null>} the display name (":N") when a live Xvfb
|
|
474
|
+
* with a matching X socket exists, else null.
|
|
475
|
+
*/
|
|
476
|
+
async function findLiveXvfbDisplay() {
|
|
477
|
+
let sockets;
|
|
478
|
+
try {
|
|
479
|
+
sockets = await readdir(X11_UNIX_DIR);
|
|
480
|
+
} catch {
|
|
481
|
+
return null; // no X runtime dir at all
|
|
482
|
+
}
|
|
483
|
+
const liveDisplays = new Set();
|
|
484
|
+
try {
|
|
485
|
+
const entries = await readdir("/proc");
|
|
486
|
+
await Promise.all(
|
|
487
|
+
entries
|
|
488
|
+
.filter((entry) => /^\d+$/.test(entry))
|
|
489
|
+
.map(async (pid) => {
|
|
490
|
+
try {
|
|
491
|
+
const argv = (await readFile(`/proc/${pid}/cmdline`, "utf8")).split("\0");
|
|
492
|
+
const idx = argv.findIndex((arg) => arg === "Xvfb" || arg.endsWith("/Xvfb"));
|
|
493
|
+
const match = idx >= 0 ? argv[idx + 1]?.match(/^:(\d+)$/) : null;
|
|
494
|
+
if (match) liveDisplays.add(match[1]);
|
|
495
|
+
} catch {
|
|
496
|
+
// exited under us, or another user's process
|
|
497
|
+
}
|
|
498
|
+
}),
|
|
499
|
+
);
|
|
500
|
+
} catch {
|
|
501
|
+
return null; // no procfs to walk (non-Linux) — nothing to reuse
|
|
502
|
+
}
|
|
503
|
+
for (const socket of sockets) {
|
|
504
|
+
const match = socket.match(/^X(\d+)$/);
|
|
505
|
+
if (match && liveDisplays.has(match[1])) return `:${match[1]}`;
|
|
506
|
+
}
|
|
507
|
+
return null;
|
|
508
|
+
}
|
|
509
|
+
|
|
510
|
+
/** Pick a display number whose socket does not exist yet. */
|
|
511
|
+
async function pickFreeDisplayNumber() {
|
|
512
|
+
const taken = new Set();
|
|
513
|
+
try {
|
|
514
|
+
const sockets = await readdir(X11_UNIX_DIR);
|
|
515
|
+
for (const socket of sockets) {
|
|
516
|
+
const match = socket.match(/^X(\d+)$/);
|
|
517
|
+
if (match) taken.add(Number(match[1]));
|
|
518
|
+
}
|
|
519
|
+
} catch {
|
|
520
|
+
// no X runtime dir yet — nothing taken
|
|
521
|
+
}
|
|
522
|
+
for (const num of [99, 98, 97, 96, 95]) if (!taken.has(num)) return num;
|
|
523
|
+
for (let num = 1; num < 128; num++) if (!taken.has(num)) return num;
|
|
524
|
+
throw new Error("no free X display number available");
|
|
525
|
+
}
|
|
526
|
+
|
|
527
|
+
/**
|
|
528
|
+
* Start Xvfb on the given display number and wait for its X socket to come
|
|
529
|
+
* up.
|
|
530
|
+
*
|
|
531
|
+
* @returns {Promise<{ display: string, pid: number }>}
|
|
532
|
+
*/
|
|
533
|
+
async function spawnXvfb(num) {
|
|
534
|
+
const xvfb = await which("Xvfb");
|
|
535
|
+
if (!xvfb) {
|
|
536
|
+
throw new Error(
|
|
537
|
+
"no X display (DISPLAY is not set) and no Xvfb binary on PATH. " +
|
|
538
|
+
"Install xvfb (e.g. `apt-get install -y xvfb`) or run the browser " +
|
|
539
|
+
"headless instead (EGO_LINUX_HEADLESS=1).",
|
|
540
|
+
);
|
|
541
|
+
}
|
|
542
|
+
const display = `:${num}`;
|
|
543
|
+
const child = spawn(
|
|
544
|
+
xvfb,
|
|
545
|
+
[display, "-screen", "0", "1280x900x24", "-nolisten", "tcp", "-ac"],
|
|
546
|
+
{ detached: true, stdio: "ignore" },
|
|
547
|
+
);
|
|
548
|
+
child.unref();
|
|
549
|
+
const socket = join(X11_UNIX_DIR, `X${num}`);
|
|
550
|
+
const deadline = Date.now() + 10000;
|
|
551
|
+
while (Date.now() < deadline) {
|
|
552
|
+
if (await exists(socket)) return { display, pid: child.pid };
|
|
553
|
+
if (child.exitCode !== null) break; // Xvfb died before its socket appeared
|
|
554
|
+
await new Promise((resolve) => setTimeout(resolve, 100));
|
|
555
|
+
}
|
|
556
|
+
throw new Error(`Xvfb ${display} did not create its X socket within 10000ms`);
|
|
557
|
+
}
|
|
558
|
+
|
|
559
|
+
/**
|
|
560
|
+
* Make sure a visible browser has an X display to draw into.
|
|
561
|
+
*
|
|
562
|
+
* Preference order: (1) a $DISPLAY that already names a live socket — the
|
|
563
|
+
* user's real session, never touched; (2) an Xvfb an earlier launch started
|
|
564
|
+
* on this machine (see findLiveXvfbDisplay); (3) a fresh Xvfb on a free
|
|
565
|
+
* display number. Headless launches skip this entirely.
|
|
566
|
+
*
|
|
567
|
+
* A *remote* display (host part in $DISPLAY) can be trusted as "usable" but
|
|
568
|
+
* not verified from inside a container — the browser launch itself is the
|
|
569
|
+
* real test. Callers that already know the environment display failed pass
|
|
570
|
+
* `ignoreEnvDisplay` so this function moves straight to Xvfb instead of
|
|
571
|
+
* handing the same broken display back.
|
|
572
|
+
*
|
|
573
|
+
* @param {{ ignoreEnvDisplay?: boolean }} [options]
|
|
574
|
+
* @returns {Promise<{ display: string, pid: number | null, launched: boolean }>}
|
|
575
|
+
* `launched` is true only when this call started the X server itself; the
|
|
576
|
+
* caller records that in the browser state so stopBrowser knows which
|
|
577
|
+
* displays are ours to terminate.
|
|
578
|
+
*/
|
|
579
|
+
export async function ensureXDisplay({ ignoreEnvDisplay = false } = {}) {
|
|
580
|
+
// Windows has a desktop session and no X server: Chrome opens a real window
|
|
581
|
+
// directly (the v0.4.0 Windows adaptation). Returning a pseudo display keeps
|
|
582
|
+
// the headed path alive without ever touching Xvfb (issue: post-merge cold
|
|
583
|
+
// start failed with "no X display ... no Xvfb binary on PATH").
|
|
584
|
+
if (process.platform === "win32") {
|
|
585
|
+
return { display: process.env.DISPLAY || "win32-desktop", pid: null, launched: false };
|
|
586
|
+
}
|
|
587
|
+
if (!ignoreEnvDisplay && (await displayUsable(process.env.DISPLAY))) {
|
|
588
|
+
return { display: process.env.DISPLAY, pid: null, launched: false };
|
|
589
|
+
}
|
|
590
|
+
const reused = await findLiveXvfbDisplay();
|
|
591
|
+
if (reused) return { display: reused, pid: null, launched: false };
|
|
592
|
+
const { display, pid } = await spawnXvfb(await pickFreeDisplayNumber());
|
|
593
|
+
return { display, pid, launched: true };
|
|
594
|
+
}
|
|
595
|
+
|
|
596
|
+
/**
|
|
597
|
+
* Spawn the browser and wait for its DevTools endpoint.
|
|
598
|
+
*
|
|
599
|
+
* @param {string[] | null} args - full Chrome argv (null for headless is
|
|
600
|
+
* not used; headless simply passes its own flag list).
|
|
601
|
+
* @param {{ display: string, launched: boolean } | null} plan - which display
|
|
602
|
+
* the browser should draw into; null means "inherit the environment".
|
|
603
|
+
* @returns {Promise<{ port: number, wsUrl: string, pid: number } | null>}
|
|
604
|
+
* null when no endpoint answered within the timeout; the attempt's process
|
|
605
|
+
* is guaranteed to be dead on return, so a caller may retry immediately.
|
|
606
|
+
*/
|
|
607
|
+
async function spawnAndAwait(binary, args, plan, lastError) {
|
|
608
|
+
const child = spawn(binary, args, {
|
|
609
|
+
detached: true,
|
|
610
|
+
stdio: "ignore",
|
|
611
|
+
// Xvfb lives on a display number this process just chose, so the browser
|
|
612
|
+
// must be told where to draw explicitly — the caller's environment may
|
|
613
|
+
// still carry no DISPLAY at all.
|
|
614
|
+
env: plan ? { ...process.env, DISPLAY: plan.display } : process.env,
|
|
615
|
+
});
|
|
616
|
+
child.unref();
|
|
617
|
+
try {
|
|
618
|
+
const { port, wsUrl } = await waitForEndpoint(PROFILE_DIR);
|
|
619
|
+
return { port, wsUrl, pid: child.pid };
|
|
620
|
+
} catch (error) {
|
|
621
|
+
lastError.error = error;
|
|
622
|
+
// The endpoint never came up. Before the caller retries, make sure this
|
|
623
|
+
// attempt's process is really gone: a half-dead Chrome would keep holding
|
|
624
|
+
// the profile lock and block the next spawn.
|
|
625
|
+
if (child.exitCode === null) {
|
|
626
|
+
try {
|
|
627
|
+
process.kill(child.pid, "SIGTERM");
|
|
628
|
+
} catch {
|
|
629
|
+
// already gone
|
|
630
|
+
}
|
|
631
|
+
if (!(await waitForProcessExit(child.pid, 3000))) {
|
|
632
|
+
try {
|
|
633
|
+
process.kill(child.pid, "SIGKILL");
|
|
634
|
+
} catch {
|
|
635
|
+
// already gone
|
|
636
|
+
}
|
|
637
|
+
}
|
|
638
|
+
}
|
|
639
|
+
return null;
|
|
640
|
+
}
|
|
641
|
+
}
|
|
642
|
+
|
|
643
|
+
async function launch({ headless }) {
|
|
644
|
+
const binary = await resolveBinary();
|
|
645
|
+
await mkdir(PROFILE_DIR, { recursive: true });
|
|
646
|
+
// Ours now exists, so it cannot be mistaken for an orphan below.
|
|
647
|
+
await reapOrphanedBrowsers();
|
|
648
|
+
|
|
649
|
+
const args = [
|
|
650
|
+
...LAUNCH_FLAGS,
|
|
651
|
+
`${PROFILE_FLAG}${PROFILE_DIR}`,
|
|
652
|
+
"--remote-debugging-port=0",
|
|
653
|
+
...(headless ? [
|
|
654
|
+
"--headless=new",
|
|
655
|
+
// Headless fingerprint stripping (issue #2): the `-headless` UA and
|
|
656
|
+
// navigator.webdriver flag both mark us as automation to high-risk
|
|
657
|
+
// sites (Douyin/Doubao reject agent sessions otherwise). Only inject on
|
|
658
|
+
// the headless path so a headed window keeps its real UA. The UA version
|
|
659
|
+
// tracks the bundled Chromium major (152 in this runtime snapshot); if a
|
|
660
|
+
// future update bumps the vendored Chromium, bump it here too.
|
|
661
|
+
"--disable-blink-features=AutomationControlled",
|
|
662
|
+
"--user-agent=Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/152.0.0.0 Safari/537.36",
|
|
663
|
+
] : []),
|
|
664
|
+
// Optional HTTP proxy for the agent browser, e.g. EGO_LINUX_PROXY=http://host:7890
|
|
665
|
+
// (WSL2 -> Windows Clash). Explicit flags are used instead of relying on
|
|
666
|
+
// http_proxy env propagation: the CLI's own fetch/CDP traffic must never go
|
|
667
|
+
// through the proxy, and loopback/private ranges are always bypassed so CDP
|
|
668
|
+
// and local test pages keep working.
|
|
669
|
+
...(process.env.EGO_LINUX_PROXY
|
|
670
|
+
? [
|
|
671
|
+
`--proxy-server=${process.env.EGO_LINUX_PROXY}`,
|
|
672
|
+
"--proxy-bypass-list=<-loopback>;127.0.0.1;localhost;[::1];172.16.0.0/12;10.0.0.0/8;*.local",
|
|
673
|
+
]
|
|
674
|
+
: []),
|
|
675
|
+
// User-configured extra Chrome args, bridged from the plugin's `chromeArgs`
|
|
676
|
+
// settings field via resolveEgoEnv(). Filtered against CHROME_BLOCKED
|
|
677
|
+
// (mirrored here — the runtime must not import from lib/) so a saved value
|
|
678
|
+
// cannot break CDP control / profile isolation / proxy bypass.
|
|
679
|
+
...filterChromeArgs(process.env.EGO_LINUX_EXTRA_ARGS ?? ""),
|
|
680
|
+
];
|
|
681
|
+
|
|
682
|
+
// Display strategy for a visible browser:
|
|
683
|
+
//
|
|
684
|
+
// 1. The environment's display goes first — the user's session wins. A
|
|
685
|
+
// remote display (host:screen) cannot be verified from inside a
|
|
686
|
+
// container, so the launch itself is the test.
|
|
687
|
+
// 2. If that attempt fails to bring the browser up — unreachable remote X,
|
|
688
|
+
// dead socket, whatever the cause — fall back to a virtual framebuffer
|
|
689
|
+
// and retry immediately.
|
|
690
|
+
// 3. If there is no usable display at all, go straight to Xvfb.
|
|
691
|
+
//
|
|
692
|
+
// Headless needs no display at all.
|
|
693
|
+
const initial = headless ? null : await ensureXDisplay();
|
|
694
|
+
|
|
695
|
+
// Pre-spawn cleanup lives inside the attempt because a retry must redo it:
|
|
696
|
+
// a failed attempt can leave a profile lock and a stale port file behind.
|
|
697
|
+
const lastError = { error: null };
|
|
698
|
+
const attempt = async (plan) => {
|
|
699
|
+
await neutralizeZoom(PROFILE_DIR);
|
|
700
|
+
await clearStaleCrashMark(PROFILE_DIR);
|
|
701
|
+
await clearProfileLock(PROFILE_DIR);
|
|
702
|
+
// A stale port file would be read as this launch's port.
|
|
703
|
+
await rm(join(PROFILE_DIR, PORT_FILE), { force: true });
|
|
704
|
+
return spawnAndAwait(binary, args, plan, lastError);
|
|
705
|
+
};
|
|
706
|
+
|
|
707
|
+
let plan = initial;
|
|
708
|
+
let result = await attempt(plan);
|
|
709
|
+
let xvfb = plan?.launched ? plan : null;
|
|
710
|
+
|
|
711
|
+
if (!result && plan && !plan.launched) {
|
|
712
|
+
// The environment display did not bring the browser up. Retry right away
|
|
713
|
+
// on a virtual framebuffer — never hand the same broken display back.
|
|
714
|
+
process.stderr.write(
|
|
715
|
+
`ego: browser did not come up on display ${plan.display}; falling back to Xvfb\n`,
|
|
716
|
+
);
|
|
717
|
+
plan = await ensureXDisplay({ ignoreEnvDisplay: true });
|
|
718
|
+
xvfb = plan.launched ? plan : null;
|
|
719
|
+
result = await attempt(plan);
|
|
720
|
+
}
|
|
721
|
+
if (!result) {
|
|
722
|
+
throw new Error(
|
|
723
|
+
plan
|
|
724
|
+
? `browser failed to come up on display ${plan.display}: ${lastError.error?.message}`
|
|
725
|
+
: (lastError.error?.message ?? "browser failed to come up"),
|
|
726
|
+
);
|
|
727
|
+
}
|
|
728
|
+
|
|
729
|
+
await writeBrowserState({
|
|
730
|
+
port: result.port,
|
|
731
|
+
wsUrl: result.wsUrl,
|
|
732
|
+
pid: result.pid,
|
|
733
|
+
binary,
|
|
734
|
+
headless,
|
|
735
|
+
profileDir: PROFILE_DIR,
|
|
736
|
+
// Only recorded when *we* started the X server: stopBrowser terminates
|
|
737
|
+
// what is ours and leaves any user display alone.
|
|
738
|
+
...(xvfb ? { xvfb: { pid: xvfb.pid, display: xvfb.display } } : {}),
|
|
739
|
+
});
|
|
740
|
+
return { port: result.port, wsUrl: result.wsUrl, launched: true };
|
|
741
|
+
}
|
|
742
|
+
|
|
743
|
+
/**
|
|
744
|
+
* Return a live browser-level CDP endpoint, reusing the browser this machine
|
|
745
|
+
* already has open when possible. Each heredoc runs in its own short-lived Node
|
|
746
|
+
* process, so the browser — not this process — is what has to persist.
|
|
747
|
+
*/
|
|
748
|
+
export async function ensureBrowser({ headless = false } = {}) {
|
|
749
|
+
if (process.env.EGO_LINUX_CDP_URL) {
|
|
750
|
+
return { wsUrl: process.env.EGO_LINUX_CDP_URL, launched: false };
|
|
751
|
+
}
|
|
752
|
+
|
|
753
|
+
const state = await readBrowserState();
|
|
754
|
+
if (state?.port) {
|
|
755
|
+
const wsUrl = await probe(state.port);
|
|
756
|
+
if (wsUrl) return { port: state.port, wsUrl, launched: false };
|
|
757
|
+
}
|
|
758
|
+
return launch({ headless });
|
|
759
|
+
}
|
|
760
|
+
|
|
761
|
+
/**
|
|
762
|
+
* Ask the browser to close itself, over CDP.
|
|
763
|
+
*
|
|
764
|
+
* SIGTERM is recorded by Chrome as a crash: the profile keeps `exit_type:
|
|
765
|
+
* "Crashed"`, and every later launch greets the user with "Chrome didn't shut
|
|
766
|
+
* down correctly — Restore pages?". Browser.close is the graceful path, so the
|
|
767
|
+
* profile records a clean exit and there is nothing left to restore.
|
|
768
|
+
*/
|
|
769
|
+
async function closeBrowserGracefully(port, timeoutMs = 5000) {
|
|
770
|
+
const wsUrl = await probe(port);
|
|
771
|
+
if (!wsUrl) return false;
|
|
772
|
+
|
|
773
|
+
return new Promise((resolve) => {
|
|
774
|
+
let socket = null;
|
|
775
|
+
let sent = false;
|
|
776
|
+
let settled = false;
|
|
777
|
+
const finish = (ok) => {
|
|
778
|
+
if (settled) return;
|
|
779
|
+
settled = true;
|
|
780
|
+
clearTimeout(timer);
|
|
781
|
+
try {
|
|
782
|
+
socket?.close();
|
|
783
|
+
} catch {
|
|
784
|
+
// already closing
|
|
785
|
+
}
|
|
786
|
+
resolve(ok);
|
|
787
|
+
};
|
|
788
|
+
const timer = setTimeout(() => finish(false), timeoutMs);
|
|
789
|
+
|
|
790
|
+
try {
|
|
791
|
+
socket = new WebSocket(wsUrl);
|
|
792
|
+
} catch {
|
|
793
|
+
finish(false);
|
|
794
|
+
return;
|
|
795
|
+
}
|
|
796
|
+
socket.onopen = () => {
|
|
797
|
+
sent = true;
|
|
798
|
+
socket.send(JSON.stringify({ id: 1, method: "Browser.close" }));
|
|
799
|
+
};
|
|
800
|
+
// Chrome answers and then drops the socket as it goes away; whichever lands
|
|
801
|
+
// first means the request was taken. A close *before* the request went out
|
|
802
|
+
// is a failed connection, not a shutdown.
|
|
803
|
+
socket.onmessage = () => finish(true);
|
|
804
|
+
socket.onclose = () => finish(sent);
|
|
805
|
+
socket.onerror = () => finish(false);
|
|
806
|
+
});
|
|
807
|
+
}
|
|
808
|
+
|
|
809
|
+
/** Wait for a pid to disappear — a browser still exiting still holds the profile lock. */
|
|
810
|
+
async function waitForProcessExit(pid, timeoutMs = 5000) {
|
|
811
|
+
const deadline = Date.now() + timeoutMs;
|
|
812
|
+
while (Date.now() < deadline) {
|
|
813
|
+
try {
|
|
814
|
+
process.kill(pid, 0);
|
|
815
|
+
} catch {
|
|
816
|
+
return true;
|
|
817
|
+
}
|
|
818
|
+
await new Promise((resolve) => setTimeout(resolve, 100));
|
|
819
|
+
}
|
|
820
|
+
return false;
|
|
821
|
+
}
|
|
822
|
+
|
|
823
|
+
/** Terminate the backing browser and forget it. */
|
|
824
|
+
export async function stopBrowser() {
|
|
825
|
+
const state = await readBrowserState();
|
|
826
|
+
let stopped = false;
|
|
827
|
+
|
|
828
|
+
if (state?.port) stopped = await closeBrowserGracefully(state.port);
|
|
829
|
+
// Answering the request is not the same as acting on it. A browser that
|
|
830
|
+
// stayed up has to be signalled anyway — otherwise --stop removes the state
|
|
831
|
+
// file that is the only handle on it and leaves it running, unreachable.
|
|
832
|
+
if (stopped && state?.pid && !(await waitForProcessExit(state.pid))) stopped = false;
|
|
833
|
+
|
|
834
|
+
// The blunt instrument, only when the browser did not take the polite request.
|
|
835
|
+
if (!stopped && state?.pid) {
|
|
836
|
+
try {
|
|
837
|
+
process.kill(state.pid, "SIGTERM");
|
|
838
|
+
stopped = true;
|
|
839
|
+
} catch {
|
|
840
|
+
// already gone
|
|
841
|
+
}
|
|
842
|
+
}
|
|
843
|
+
|
|
844
|
+
// An X server we started for a display-less machine is dead weight once the
|
|
845
|
+
// browser is gone; a user display (reused, not launched by us) stays up.
|
|
846
|
+
if (state?.xvfb?.pid) {
|
|
847
|
+
try {
|
|
848
|
+
process.kill(state.xvfb.pid, "SIGTERM");
|
|
849
|
+
} catch {
|
|
850
|
+
// already gone
|
|
851
|
+
}
|
|
852
|
+
}
|
|
853
|
+
|
|
854
|
+
await rm(BROWSER_STATE_FILE, { force: true });
|
|
855
|
+
// A SIGTERMed Chrome does not always release its profile lock, which would
|
|
856
|
+
// block the next launch. After a graceful close there is nothing left to
|
|
857
|
+
// clear, and this is a no-op.
|
|
858
|
+
await clearProfileLock(PROFILE_DIR);
|
|
859
|
+
return stopped;
|
|
860
|
+
}
|
|
861
|
+
|
|
862
|
+
export async function browserStatus() {
|
|
863
|
+
const state = await readBrowserState();
|
|
864
|
+
if (!state?.port) return { running: false };
|
|
865
|
+
const wsUrl = await probe(state.port);
|
|
866
|
+
return wsUrl ? { running: true, ...state, wsUrl } : { running: false, ...state };
|
|
867
|
+
}
|