@generativereality/browser-automation 0.4.6 → 0.4.8
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/.claude-plugin/plugin.json +1 -1
- package/README.md +16 -6
- package/dist/index.js +401 -16
- package/package.json +3 -3
- package/scripts/check-one-port.sh +70 -0
- package/scripts/launch-chrome.sh +122 -7
- package/skills/browser/SKILL.md +133 -11
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "browser-automation",
|
|
3
3
|
"description": "Daemonless, per-tab-isolated browser automation for Claude Code via the `browser-automation` CLI. Drives one shared headed Chrome (persistent profile + extensions) over per-target CDP — many parallel sessions, no focus stealing, nothing long-lived to crash.",
|
|
4
|
-
"version": "0.4.
|
|
4
|
+
"version": "0.4.8",
|
|
5
5
|
"author": {
|
|
6
6
|
"name": "generativereality"
|
|
7
7
|
},
|
package/README.md
CHANGED
|
@@ -35,8 +35,8 @@ long-lived process**:
|
|
|
35
35
|
|
|
36
36
|
```bash
|
|
37
37
|
npm install -g @generativereality/browser-automation
|
|
38
|
-
browser-automation launch # start
|
|
39
|
-
browser-automation doctor # verify
|
|
38
|
+
browser-automation launch # start this user's Chrome (idempotent)
|
|
39
|
+
browser-automation doctor # verify (incl. renderer capacity)
|
|
40
40
|
```
|
|
41
41
|
|
|
42
42
|
Claude Code skill (so the agent knows how to use it):
|
|
@@ -92,8 +92,9 @@ browser-automation bind -s bank -m nordnet # …or adopt it into a session
|
|
|
92
92
|
|
|
93
93
|
| Command | What it does |
|
|
94
94
|
|---|---|
|
|
95
|
-
| `launch [--status]` | Start
|
|
96
|
-
| `doctor` | Diagnose Node, Chrome, targets, sessions |
|
|
95
|
+
| `launch [--status]` | Start this user's headed Chrome (idempotent) |
|
|
96
|
+
| `doctor` | Diagnose Node, Chrome, targets, sessions — and **renderer capacity** (a browser that can no longer launch renderers passes every other check) |
|
|
97
|
+
| `gc` | Prune stale session bookmarks and dead tabs (`--dry` to preview, `--orphans` to also close unclaimed live tabs) |
|
|
97
98
|
| `list` | List sessions and every open tab (id, title, url) |
|
|
98
99
|
| `new -s <s> [url]` | Open a background tab for a session |
|
|
99
100
|
| `goto (-s\|-m\|-t) <url>` | Navigate (session tab created if needed) |
|
|
@@ -158,11 +159,20 @@ same one-action-per-snapshot rule as Playwright refs.
|
|
|
158
159
|
snapshot-interactive. After dropping, confirm with `read`/`screenshot` and pull
|
|
159
160
|
the result (often a `download --url` endpoint).
|
|
160
161
|
- `launch` resolves Chrome on macOS/Linux; elsewhere start Chrome manually with
|
|
161
|
-
`--remote-debugging-port
|
|
162
|
+
`--remote-debugging-port=<your port> --user-data-dir="<profile>"` — `browser-automation doctor` prints the port.
|
|
162
163
|
|
|
163
164
|
## Environment
|
|
164
165
|
|
|
165
|
-
- `
|
|
166
|
+
- `BROWSER_AUTOMATION_PORT` — the debugging port. **Defaults to one per user**,
|
|
167
|
+
not one per machine: `127.0.0.1` is machine-wide and CDP has no
|
|
168
|
+
authentication, so a single shared port means the first account to launch owns
|
|
169
|
+
it and every other account's automation silently drives *that* account's
|
|
170
|
+
browser — same-looking page loads, in somebody else's signed-in session.
|
|
171
|
+
**Run `browser-automation port` for yours** — the number is derived from your
|
|
172
|
+
uid, and this file deliberately does not restate the formula: prose that
|
|
173
|
+
repeats a rule is a copy of it, and goes stale the same way code does.
|
|
174
|
+
`doctor` prints it too, and warns if another user holds it.
|
|
175
|
+
- `BROWSER_AUTOMATION_CDP` — full CDP host, overriding the port entirely.
|
|
166
176
|
- `BROWSER_AUTOMATION_PROFILE` — Chrome profile dir for `launch`.
|
|
167
177
|
- `BAC_SESSION` — default session name for page commands.
|
|
168
178
|
|
package/dist/index.js
CHANGED
|
@@ -4,10 +4,10 @@ import { consola } from "consola";
|
|
|
4
4
|
import { homedir } from "node:os";
|
|
5
5
|
import { basename, dirname, extname, join, resolve } from "node:path";
|
|
6
6
|
import { existsSync, mkdirSync, readFileSync, readdirSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
|
|
7
|
-
import { spawnSync } from "node:child_process";
|
|
7
|
+
import { execFileSync, spawnSync } from "node:child_process";
|
|
8
8
|
import { fileURLToPath } from "node:url";
|
|
9
9
|
//#region package.json
|
|
10
|
-
var version = "0.4.
|
|
10
|
+
var version = "0.4.8";
|
|
11
11
|
var description = "Daemonless, per-tab-isolated browser automation CLI for Claude Code. Drives one shared headed Chrome (persistent profile + extensions) over per-target CDP — many parallel sessions, no focus stealing, nothing long-lived to crash.";
|
|
12
12
|
//#endregion
|
|
13
13
|
//#region src/core/session.ts
|
|
@@ -36,9 +36,30 @@ function listSessions() {
|
|
|
36
36
|
}
|
|
37
37
|
//#endregion
|
|
38
38
|
//#region src/core/cdp.ts
|
|
39
|
-
const
|
|
39
|
+
const BASE_PORT = 9223;
|
|
40
|
+
const FIRST_HUMAN_UID = process.platform === "darwin" ? 501 : 1e3;
|
|
41
|
+
/**
|
|
42
|
+
* The CDP port for THIS user.
|
|
43
|
+
*
|
|
44
|
+
* `BROWSER_AUTOMATION_PORT` overrides it, for the cases a formula cannot know
|
|
45
|
+
* about: a shared CI box, a container, or somebody who simply wants two.
|
|
46
|
+
*
|
|
47
|
+
* **This is the only place the number is decided.** It was copied into
|
|
48
|
+
* `scripts/launch-chrome.sh` within an hour of being written, each copy with a
|
|
49
|
+
* comment promising to keep it in step — which is the tell, not the plan. The
|
|
50
|
+
* script asks `browser-automation port` instead, and the `port` command exists
|
|
51
|
+
* for exactly that.
|
|
52
|
+
*/
|
|
53
|
+
function cdpPort() {
|
|
54
|
+
const explicit = Number(process.env.BROWSER_AUTOMATION_PORT);
|
|
55
|
+
if (Number.isInteger(explicit) && explicit > 0 && explicit < 65536) return explicit;
|
|
56
|
+
const uid = typeof process.getuid === "function" ? process.getuid() : FIRST_HUMAN_UID;
|
|
57
|
+
const offset = uid - FIRST_HUMAN_UID;
|
|
58
|
+
if (offset < 0 || offset > 499) return 9723 + uid % 500;
|
|
59
|
+
return BASE_PORT + offset;
|
|
60
|
+
}
|
|
40
61
|
function cdpHost() {
|
|
41
|
-
return process.env.BROWSER_AUTOMATION_CDP ||
|
|
62
|
+
return process.env.BROWSER_AUTOMATION_CDP || `http://localhost:${cdpPort()}`;
|
|
42
63
|
}
|
|
43
64
|
/** A target has gone away (tab closed, or Chrome restarted -> new targetIds). */
|
|
44
65
|
var TargetGoneError = class extends Error {
|
|
@@ -276,6 +297,194 @@ function normalizeUrl(input) {
|
|
|
276
297
|
return `https://${input}`;
|
|
277
298
|
}
|
|
278
299
|
//#endregion
|
|
300
|
+
//#region src/core/renderer-health.ts
|
|
301
|
+
/**
|
|
302
|
+
* Create a throwaway tab, make its renderer prove it is alive, close it.
|
|
303
|
+
*
|
|
304
|
+
* Deliberately uses `about:blank` and `Runtime.evaluate`, not a navigation:
|
|
305
|
+
* we are asking "can a new renderer exist and execute", which is the narrowest
|
|
306
|
+
* question that separates a wedged browser from a slow network or a hostile
|
|
307
|
+
* site. Nothing here touches the caller's tabs.
|
|
308
|
+
*/
|
|
309
|
+
async function probeRenderer({ timeout = 5e3 } = {}) {
|
|
310
|
+
const started = Date.now();
|
|
311
|
+
let pageTargets = 0;
|
|
312
|
+
try {
|
|
313
|
+
pageTargets = (await listPageTargets()).length;
|
|
314
|
+
} catch {}
|
|
315
|
+
let targetId;
|
|
316
|
+
try {
|
|
317
|
+
targetId = await createTab("about:blank");
|
|
318
|
+
} catch (e) {
|
|
319
|
+
return {
|
|
320
|
+
ok: false,
|
|
321
|
+
ms: Date.now() - started,
|
|
322
|
+
pageTargets,
|
|
323
|
+
reason: `could not create a target at all: ${e?.message ?? e}`
|
|
324
|
+
};
|
|
325
|
+
}
|
|
326
|
+
try {
|
|
327
|
+
const reason = await renderersAnswer(targetId, timeout);
|
|
328
|
+
return {
|
|
329
|
+
ok: reason === null,
|
|
330
|
+
ms: Date.now() - started,
|
|
331
|
+
pageTargets,
|
|
332
|
+
reason: reason ?? void 0
|
|
333
|
+
};
|
|
334
|
+
} finally {
|
|
335
|
+
if (targetId) await closeTab(targetId).catch(() => {});
|
|
336
|
+
}
|
|
337
|
+
}
|
|
338
|
+
/**
|
|
339
|
+
* Ask an EXISTING target's renderer to prove it is alive.
|
|
340
|
+
*
|
|
341
|
+
* Returns null when it answers correctly, or a human-readable reason when it
|
|
342
|
+
* does not. Used both by the throwaway probe and by `new`, which has just
|
|
343
|
+
* created a tab and should check that one rather than manufacture a second.
|
|
344
|
+
*/
|
|
345
|
+
async function renderersAnswer(targetId, timeout = 5e3) {
|
|
346
|
+
try {
|
|
347
|
+
const ws = await targetWsUrl(targetId);
|
|
348
|
+
if (!ws) return "the target vanished immediately";
|
|
349
|
+
const s = await connect(ws, { timeout });
|
|
350
|
+
try {
|
|
351
|
+
const value = (await s.send("Runtime.evaluate", {
|
|
352
|
+
expression: "1+1",
|
|
353
|
+
returnByValue: true
|
|
354
|
+
}, timeout))?.result?.value;
|
|
355
|
+
return value === 2 ? null : `the renderer answered with ${JSON.stringify(value)} instead of 2`;
|
|
356
|
+
} finally {
|
|
357
|
+
s.close();
|
|
358
|
+
}
|
|
359
|
+
} catch (e) {
|
|
360
|
+
const msg = String(e?.message ?? e);
|
|
361
|
+
return /timed out|timeout/i.test(msg) ? "the target exists, but no renderer ever answered it" : msg;
|
|
362
|
+
}
|
|
363
|
+
}
|
|
364
|
+
/**
|
|
365
|
+
* The port we are actually talking to.
|
|
366
|
+
*
|
|
367
|
+
* NOT always `cdpPort()`: `BROWSER_AUTOMATION_CDP` points the CLI at an
|
|
368
|
+
* arbitrary host:port, and everything here that shells out to `pgrep` or
|
|
369
|
+
* `launchctl` has to ask about THAT browser. Using the uid-derived port
|
|
370
|
+
* instead finds the user's default Chrome and cheerfully reports its health
|
|
371
|
+
* as if it were the one being driven — caught while testing this module
|
|
372
|
+
* against a second Chrome, where a perfectly healthy browser was accused of
|
|
373
|
+
* having lost the bootstrap name that in fact belonged to a different pid.
|
|
374
|
+
*/
|
|
375
|
+
function targetPort() {
|
|
376
|
+
const explicit = process.env.BROWSER_AUTOMATION_CDP;
|
|
377
|
+
if (explicit) {
|
|
378
|
+
const p = Number(new URL(explicit).port);
|
|
379
|
+
if (Number.isInteger(p) && p > 0) return p;
|
|
380
|
+
}
|
|
381
|
+
return cdpPort();
|
|
382
|
+
}
|
|
383
|
+
/** The pid of the browser process serving the port we are driving, if visible. */
|
|
384
|
+
function browserPid() {
|
|
385
|
+
try {
|
|
386
|
+
const out = execFileSync("pgrep", [
|
|
387
|
+
"-u",
|
|
388
|
+
String(process.getuid?.() ?? -1),
|
|
389
|
+
"-f",
|
|
390
|
+
"--",
|
|
391
|
+
`--remote-debugging-port=${targetPort()}`
|
|
392
|
+
], { encoding: "utf8" });
|
|
393
|
+
for (const pid of out.split("\n").map((s) => s.trim()).filter(Boolean)) try {
|
|
394
|
+
if (!execFileSync("ps", [
|
|
395
|
+
"-o",
|
|
396
|
+
"command=",
|
|
397
|
+
"-p",
|
|
398
|
+
pid
|
|
399
|
+
], { encoding: "utf8" }).includes("--type=")) return Number(pid);
|
|
400
|
+
} catch {}
|
|
401
|
+
} catch {}
|
|
402
|
+
return null;
|
|
403
|
+
}
|
|
404
|
+
/**
|
|
405
|
+
* macOS only: is the browser's Mach port rendezvous service still registered?
|
|
406
|
+
*
|
|
407
|
+
* This is the ROOT CAUSE signal, not a symptom — when it is missing, every
|
|
408
|
+
* child process Chrome launches kills itself on startup. Returns null when we
|
|
409
|
+
* cannot tell (not macOS, `launchctl` unavailable, pid unknown), which is
|
|
410
|
+
* different from `false` and must not be reported as a fault.
|
|
411
|
+
*/
|
|
412
|
+
function rendezvousRegistered(pid) {
|
|
413
|
+
if (process.platform !== "darwin" || !pid) return null;
|
|
414
|
+
try {
|
|
415
|
+
return execFileSync("launchctl", ["print", `gui/${process.getuid?.() ?? 501}`], {
|
|
416
|
+
encoding: "utf8",
|
|
417
|
+
maxBuffer: 64 * 1024 * 1024,
|
|
418
|
+
stdio: [
|
|
419
|
+
"ignore",
|
|
420
|
+
"pipe",
|
|
421
|
+
"ignore"
|
|
422
|
+
]
|
|
423
|
+
}).includes(`MachPortRendezvousServer.${pid}`);
|
|
424
|
+
} catch {
|
|
425
|
+
return null;
|
|
426
|
+
}
|
|
427
|
+
}
|
|
428
|
+
/** Where `launch` writes Chrome's stdout/stderr — Chrome logs the real reason there. */
|
|
429
|
+
function chromeLogPath() {
|
|
430
|
+
const tmp = process.env.TMPDIR?.replace(/\/$/, "") || "/tmp";
|
|
431
|
+
return process.env.BROWSER_AUTOMATION_LOG || `${tmp}/chrome-${targetPort()}.log`;
|
|
432
|
+
}
|
|
433
|
+
/**
|
|
434
|
+
* A ready-to-print explanation of a renderer failure, with the recovery.
|
|
435
|
+
*
|
|
436
|
+
* Written to be read by somebody who has just been told a site blocks them, so
|
|
437
|
+
* it says what is and is not true before it says what to do.
|
|
438
|
+
*/
|
|
439
|
+
function explainRendererFailure(h) {
|
|
440
|
+
const pid = browserPid();
|
|
441
|
+
const rendezvous = rendezvousRegistered(pid);
|
|
442
|
+
const lines = [
|
|
443
|
+
`Chrome cannot give a new tab a working renderer.`,
|
|
444
|
+
``,
|
|
445
|
+
` probe: created a target, ${h.reason ?? "no renderer answered"} (${h.ms}ms)`,
|
|
446
|
+
` page targets: ${h.pageTargets} (context only — this is NOT the cause; a healthy`,
|
|
447
|
+
` Chrome has been driven to 421 tabs with every renderer alive)`
|
|
448
|
+
];
|
|
449
|
+
if (rendezvous === false) lines.push(` root cause: the browser process (pid ${pid}) has lost its Mach bootstrap`, ` service "com.google.Chrome.MachPortRendezvousServer.${pid}".`, ` Chrome registers that name once, at startup; every child`, ` process looks it up to receive its shared memory. With the`, ` name gone, every renderer Chrome launches immediately exits.`, ` This is permanent for this browser process.`);
|
|
450
|
+
else if (rendezvous === true) lines.push(` note: the Mach rendezvous service for pid ${pid} IS still registered,`, ` so this is a different renderer failure from the one seen on`, ` 2026-08-22. Chrome's own log will say why:`, ` tail -50 ${chromeLogPath()}`);
|
|
451
|
+
lines.push(``, `This is a browser-level failure. It is NOT the site blocking automation, and`, `retrying, changing the URL, or adding a user agent will not help. Two tells:`, `same-origin navigations in tabs that already work keep working (they reuse a`, `renderer that already exists), and cross-origin ones fail with ERR_ABORTED`, `(site isolation needs a new renderer, which is the thing Chrome can't do).`, ``, `Recovery: restart Chrome. Nothing else clears it — closing tabs does not,`, `and plain \`launch\` will not either (it is idempotent and sees a live browser).`, ``, ` browser-automation launch --restart # closes ALL tabs, then relaunches`, ``, `If other sessions are driving this Chrome, agree on the restart first — their`, `open tabs go with it. \`browser-automation list\` shows who holds what.`);
|
|
452
|
+
return lines.join("\n");
|
|
453
|
+
}
|
|
454
|
+
/**
|
|
455
|
+
* Does this error look like it could be the renderer wedge rather than the site?
|
|
456
|
+
*
|
|
457
|
+
* Kept deliberately narrow. These three are the ONLY shapes the failure takes
|
|
458
|
+
* through the CLI, and each of them has an innocent explanation too — so a hit
|
|
459
|
+
* here buys a probe, never a conclusion.
|
|
460
|
+
*/
|
|
461
|
+
function mayBeRendererFailure(err) {
|
|
462
|
+
const m = String(err?.message ?? err);
|
|
463
|
+
return /Page\.enable timed out/i.test(m) || /net::ERR_ABORTED/i.test(m) || /Runtime\.evaluate timed out/i.test(m) || /Render process gone/i.test(m) || /CDP connect timeout/i.test(m);
|
|
464
|
+
}
|
|
465
|
+
/**
|
|
466
|
+
* Run `fn`; if it fails in a way the renderer wedge could explain, spend one
|
|
467
|
+
* probe finding out, and re-throw with the diagnosis attached.
|
|
468
|
+
*
|
|
469
|
+
* The probe only ever runs on the error path, so the happy path pays nothing.
|
|
470
|
+
* If the probe comes back healthy the original error is re-thrown untouched —
|
|
471
|
+
* the point is to stop misattributing a browser fault to a site, not to blame
|
|
472
|
+
* the browser for every timeout.
|
|
473
|
+
*/
|
|
474
|
+
async function withRendererDiagnosis(fn) {
|
|
475
|
+
try {
|
|
476
|
+
return await fn();
|
|
477
|
+
} catch (e) {
|
|
478
|
+
if (!mayBeRendererFailure(e)) throw e;
|
|
479
|
+
const h = await probeRenderer().catch(() => null);
|
|
480
|
+
if (!h || h.ok) throw e;
|
|
481
|
+
const err = /* @__PURE__ */ new Error(`${String(e?.message ?? e)}\n\n${explainRendererFailure(h)}`);
|
|
482
|
+
err.cause = e;
|
|
483
|
+
err.rendererHealth = h;
|
|
484
|
+
throw err;
|
|
485
|
+
}
|
|
486
|
+
}
|
|
487
|
+
//#endregion
|
|
279
488
|
//#region src/commands/new.ts
|
|
280
489
|
const newCommand = define({
|
|
281
490
|
name: "new",
|
|
@@ -303,6 +512,15 @@ const newCommand = define({
|
|
|
303
512
|
url,
|
|
304
513
|
createdAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
305
514
|
});
|
|
515
|
+
const dead = await renderersAnswer(targetId).catch(() => null);
|
|
516
|
+
if (dead) {
|
|
517
|
+
const health = await probeRenderer().catch(() => null);
|
|
518
|
+
if (health && !health.ok) {
|
|
519
|
+
consola.error(`[${name}] tab ${targetId.slice(0, 12)}… was created but has no working renderer.\n\n${explainRendererFailure(health)}`);
|
|
520
|
+
process.exit(1);
|
|
521
|
+
}
|
|
522
|
+
consola.warn(`[${name}] tab ${targetId.slice(0, 12)}… did not answer yet (${dead}). Chrome can still create renderers, so this is likely transient — retry the next command.`);
|
|
523
|
+
}
|
|
306
524
|
consola.success(`[${name}] opened background tab ${targetId.slice(0, 12)}… → ${url}`);
|
|
307
525
|
}
|
|
308
526
|
});
|
|
@@ -418,8 +636,8 @@ const gotoCommand = define({
|
|
|
418
636
|
}
|
|
419
637
|
const target = normalizeUrl(url);
|
|
420
638
|
const opts = targetOpts(ctx.values);
|
|
421
|
-
const { targetId, created } = await resolveOrCreateTargetId(opts);
|
|
422
|
-
await navigate(targetId, target);
|
|
639
|
+
const { targetId, created } = await withRendererDiagnosis(() => resolveOrCreateTargetId(opts));
|
|
640
|
+
await withRendererDiagnosis(() => navigate(targetId, target));
|
|
423
641
|
if (!opts.match && !opts.target) {
|
|
424
642
|
const name = opts.session || defaultSessionName();
|
|
425
643
|
saveSession({
|
|
@@ -1743,38 +1961,78 @@ function launchScriptPath() {
|
|
|
1743
1961
|
//#region src/commands/launch.ts
|
|
1744
1962
|
const launchCommand = define({
|
|
1745
1963
|
name: "launch",
|
|
1746
|
-
description: "Start (idempotent)
|
|
1747
|
-
args: {
|
|
1748
|
-
|
|
1749
|
-
|
|
1750
|
-
|
|
1964
|
+
description: "Start (idempotent) this user's headed Chrome with the persistent profile",
|
|
1965
|
+
args: {
|
|
1966
|
+
status: {
|
|
1967
|
+
type: "boolean",
|
|
1968
|
+
description: "Only report whether the CDP browser is up (exit 0/1)"
|
|
1969
|
+
},
|
|
1970
|
+
restart: {
|
|
1971
|
+
type: "boolean",
|
|
1972
|
+
description: "Quit this user's running Chrome first, then launch. CLOSES ALL ITS TABS — the only recovery for a browser that can no longer launch renderers (see `doctor`)."
|
|
1973
|
+
}
|
|
1974
|
+
},
|
|
1751
1975
|
async run(ctx) {
|
|
1752
1976
|
const script = launchScriptPath();
|
|
1753
1977
|
if (!existsSync(script)) {
|
|
1754
1978
|
consola.error(`launch-chrome.sh not found at ${script}. Reinstall the package.`);
|
|
1755
1979
|
process.exit(1);
|
|
1756
1980
|
}
|
|
1757
|
-
const r = spawnSync("bash", [script, ...
|
|
1981
|
+
const r = spawnSync("bash", [script, ...[
|
|
1982
|
+
"--port",
|
|
1983
|
+
String(cdpPort()),
|
|
1984
|
+
...ctx.values.status ? ["--status"] : [],
|
|
1985
|
+
...ctx.values.restart ? ["--restart"] : []
|
|
1986
|
+
]], { stdio: "inherit" });
|
|
1758
1987
|
process.exit(r.status ?? 1);
|
|
1759
1988
|
}
|
|
1760
1989
|
});
|
|
1761
1990
|
//#endregion
|
|
1762
1991
|
//#region src/commands/doctor.ts
|
|
1763
1992
|
const PROFILE = process.env.BROWSER_AUTOMATION_PROFILE || `${homedir()}/Library/Application Support/Google/Chrome/browser-automation`;
|
|
1993
|
+
/**
|
|
1994
|
+
* Does a Chrome THIS user started serve our CDP port?
|
|
1995
|
+
*
|
|
1996
|
+
* **The question is "is it mine", not "whose is it"**, and that is the whole
|
|
1997
|
+
* trick. `lsof` tells a non-root user nothing about another user's socket — it
|
|
1998
|
+
* prints an empty result and exits 0, which is indistinguishable from a free
|
|
1999
|
+
* port. Measured 2026-08-08 on a two-account Mac: as the second user,
|
|
2000
|
+
* `lsof -nP -iTCP:9223 -sTCP:LISTEN` returned nothing while the first user's
|
|
2001
|
+
* Chrome was plainly listening and answering every request. You can always see
|
|
2002
|
+
* your own processes, so ask about those.
|
|
2003
|
+
*/
|
|
2004
|
+
function portIsOurs() {
|
|
2005
|
+
try {
|
|
2006
|
+
execFileSync("pgrep", [
|
|
2007
|
+
"-u",
|
|
2008
|
+
String(process.getuid?.() ?? -1),
|
|
2009
|
+
"-f",
|
|
2010
|
+
"--",
|
|
2011
|
+
`--remote-debugging-port=${cdpPort()}`
|
|
2012
|
+
], { stdio: "ignore" });
|
|
2013
|
+
return true;
|
|
2014
|
+
} catch {
|
|
2015
|
+
return false;
|
|
2016
|
+
}
|
|
2017
|
+
}
|
|
1764
2018
|
const doctorCommand = define({
|
|
1765
2019
|
name: "doctor",
|
|
1766
|
-
description: "Diagnose the setup: Node,
|
|
2020
|
+
description: "Diagnose the setup: Node, this user's Chrome, targets, sessions",
|
|
1767
2021
|
args: {},
|
|
1768
2022
|
async run() {
|
|
1769
2023
|
const ok = (m) => consola.log(` ✓ ${m}`);
|
|
1770
2024
|
const bad = (m) => consola.log(` ✗ ${m}`);
|
|
1771
2025
|
if (Number(process.versions.node.split(".")[0]) >= 22) ok(`Node ${process.versions.node} (global WebSocket available)`);
|
|
1772
2026
|
else bad(`Node ${process.versions.node} — need >= 22 for the global WebSocket CDP client`);
|
|
1773
|
-
consola.log(` • CDP host: ${cdpHost()}`);
|
|
2027
|
+
consola.log(` • CDP host: ${cdpHost()} (port ${cdpPort()} — derived from uid ${process.getuid?.() ?? "?"})`);
|
|
1774
2028
|
consola.log(` • Profile: ${PROFILE}`);
|
|
1775
2029
|
let version;
|
|
1776
2030
|
try {
|
|
1777
2031
|
version = await (await fetch(`${cdpHost()}/json/version`)).json();
|
|
2032
|
+
if (!portIsOurs()) {
|
|
2033
|
+
bad(`something on port ${cdpPort()} is serving CDP (${version.Browser}) but this account did not start it — it is another user's Chrome, and anything you drive would happen in their browser. Quit Chrome in that account, or set BROWSER_AUTOMATION_PORT to a free port.`);
|
|
2034
|
+
return;
|
|
2035
|
+
}
|
|
1778
2036
|
ok(`Chrome reachable: ${version.Browser}`);
|
|
1779
2037
|
} catch {
|
|
1780
2038
|
bad(`No CDP browser on ${cdpHost()} — run: browser-automation launch`);
|
|
@@ -1790,8 +2048,132 @@ const doctorCommand = define({
|
|
|
1790
2048
|
} catch {
|
|
1791
2049
|
bad("Could not enumerate targets");
|
|
1792
2050
|
}
|
|
2051
|
+
const health = await probeRenderer().catch((e) => ({
|
|
2052
|
+
ok: false,
|
|
2053
|
+
ms: 0,
|
|
2054
|
+
pageTargets: 0,
|
|
2055
|
+
reason: String(e?.message ?? e)
|
|
2056
|
+
}));
|
|
2057
|
+
if (health.ok) {
|
|
2058
|
+
ok(`Renderer capacity: a new tab got a live renderer in ${health.ms}ms`);
|
|
2059
|
+
const pid = browserPid();
|
|
2060
|
+
if (rendezvousRegistered(pid) === false) {
|
|
2061
|
+
consola.log(` ⚠ but the Mach rendezvous service for pid ${pid} is NOT registered —`);
|
|
2062
|
+
consola.log(` new renderers are expected to start failing. Restart Chrome soon:`);
|
|
2063
|
+
consola.log(` browser-automation launch --restart`);
|
|
2064
|
+
}
|
|
2065
|
+
} else {
|
|
2066
|
+
bad(`Renderer capacity: FAILED`);
|
|
2067
|
+
for (const line of explainRendererFailure(health).split("\n")) consola.log(` ${line}`);
|
|
2068
|
+
consola.log(` Chrome's own log: ${chromeLogPath()}`);
|
|
2069
|
+
}
|
|
2070
|
+
const sessions = listSessions();
|
|
2071
|
+
let live = 0;
|
|
2072
|
+
try {
|
|
2073
|
+
const liveIds = new Set((await listTargets()).map((t) => t.id));
|
|
2074
|
+
live = sessions.filter((s) => liveIds.has(s.targetId)).length;
|
|
2075
|
+
} catch {}
|
|
2076
|
+
const stale = sessions.length - live;
|
|
2077
|
+
consola.log(` • ${sessions.length} known session(s): ${live} live, ${stale} stale`);
|
|
2078
|
+
if (sessions.length) {
|
|
2079
|
+
const names = sessions.map((s) => s.name);
|
|
2080
|
+
const shown = names.slice(0, 12).join(", ");
|
|
2081
|
+
consola.log(` ${shown}${names.length > 12 ? `, … (+${names.length - 12} more — \`browser-automation list\`)` : ""}`);
|
|
2082
|
+
}
|
|
2083
|
+
if (stale > 20) consola.log(` ${stale} stale bookmarks point at tabs that no longer exist — \`browser-automation gc --dry\` to review.`);
|
|
2084
|
+
}
|
|
2085
|
+
});
|
|
2086
|
+
//#endregion
|
|
2087
|
+
//#region src/commands/gc.ts
|
|
2088
|
+
/**
|
|
2089
|
+
* Tidy up what accumulates when many sessions share one Chrome for weeks.
|
|
2090
|
+
*
|
|
2091
|
+
* Two different kinds of junk, and only one of them is a browser tab:
|
|
2092
|
+
*
|
|
2093
|
+
* - **Stale session bookmarks** — a `~/.browser-automation/sessions/*.json`
|
|
2094
|
+
* pointing at a targetId that no longer exists (its tab was closed, or
|
|
2095
|
+
* Chrome restarted and reissued every id). Purely local; deleting one
|
|
2096
|
+
* cannot affect anybody's browsing.
|
|
2097
|
+
* - **Dead tabs** — page targets whose renderer does not answer. On a wedged
|
|
2098
|
+
* Chrome these breed: every `new` that failed left a blank-titled corpse
|
|
2099
|
+
* behind. They are unusable by definition — nothing can read, click or
|
|
2100
|
+
* navigate them — so closing them takes nothing away.
|
|
2101
|
+
*
|
|
2102
|
+
* What it will NOT do without being asked twice is close a *working* tab it
|
|
2103
|
+
* merely cannot attribute to a session. Tabs are addressed by `-m` as often as
|
|
2104
|
+
* by `-s`, and the user opens tabs by hand in this same window, so "no session
|
|
2105
|
+
* claims it" is not evidence that nobody wants it. That lives behind
|
|
2106
|
+
* `--orphans`, and even then it lists everything first.
|
|
2107
|
+
*
|
|
2108
|
+
* **`gc` is not a fix for a Chrome that cannot launch renderers.** It is worth
|
|
2109
|
+
* being blunt about, because reaching for it is the obvious move once you have
|
|
2110
|
+
* been told there are 66 tabs open: the wedge has nothing to do with tab count
|
|
2111
|
+
* (a healthy Chrome runs fine at 421), so closing tabs changes nothing about
|
|
2112
|
+
* it. `doctor` says so, and so does the summary here when the probe fails.
|
|
2113
|
+
*/
|
|
2114
|
+
const gcCommand = define({
|
|
2115
|
+
name: "gc",
|
|
2116
|
+
description: "Clean up stale session bookmarks and dead tabs. Use --dry first; --orphans also closes working tabs no session claims.",
|
|
2117
|
+
args: {
|
|
2118
|
+
dry: {
|
|
2119
|
+
type: "boolean",
|
|
2120
|
+
description: "Show what would be removed, change nothing"
|
|
2121
|
+
},
|
|
2122
|
+
orphans: {
|
|
2123
|
+
type: "boolean",
|
|
2124
|
+
description: "ALSO close live tabs that no session claims (includes tabs opened by hand — review the --dry output first)"
|
|
2125
|
+
},
|
|
2126
|
+
sessions: {
|
|
2127
|
+
type: "boolean",
|
|
2128
|
+
description: "Only prune stale session files; touch no tabs"
|
|
2129
|
+
}
|
|
2130
|
+
},
|
|
2131
|
+
async run(ctx) {
|
|
2132
|
+
const dry = !!ctx.values.dry;
|
|
2133
|
+
const act = dry ? "would remove" : "removed";
|
|
2134
|
+
const actTab = dry ? "would close" : "closed";
|
|
1793
2135
|
const sessions = listSessions();
|
|
1794
|
-
|
|
2136
|
+
const pages = await listPageTargets();
|
|
2137
|
+
const liveIds = new Set(pages.map((t) => t.id));
|
|
2138
|
+
const stale = sessions.filter((s) => !liveIds.has(s.targetId));
|
|
2139
|
+
for (const s of stale) {
|
|
2140
|
+
if (!dry) deleteSession(s.name);
|
|
2141
|
+
consola.log(` session ${act} ${s.name} (tab gone: ${s.targetId.slice(0, 12)}…)`);
|
|
2142
|
+
}
|
|
2143
|
+
if (ctx.values.sessions) {
|
|
2144
|
+
consola.success(`${stale.length} stale session bookmark(s) ${act}. No tabs touched.`);
|
|
2145
|
+
return;
|
|
2146
|
+
}
|
|
2147
|
+
const claimed = new Map(sessions.filter((s) => liveIds.has(s.targetId)).map((s) => [s.targetId, s.name]));
|
|
2148
|
+
const probes = await Promise.all(pages.map(async (t) => ({
|
|
2149
|
+
t,
|
|
2150
|
+
dead: await renderersAnswer(t.id, 4e3).catch(() => "probe failed")
|
|
2151
|
+
})));
|
|
2152
|
+
const dead = probes.filter((p) => p.dead);
|
|
2153
|
+
for (const { t, dead: why } of dead) {
|
|
2154
|
+
const owner = claimed.get(t.id);
|
|
2155
|
+
if (!dry) await closeTab(t.id).catch(() => {});
|
|
2156
|
+
consola.log(` dead tab ${actTab} ${t.id.slice(0, 12)}… ${owner ? `(${owner}) ` : ""}${(t.url ?? "").slice(0, 60) || "(no url)"} — ${why}`);
|
|
2157
|
+
}
|
|
2158
|
+
const orphans = probes.filter((p) => !p.dead && !claimed.has(p.t.id));
|
|
2159
|
+
if (ctx.values.orphans) for (const { t } of orphans) {
|
|
2160
|
+
if (!dry) await closeTab(t.id).catch(() => {});
|
|
2161
|
+
consola.log(` orphan ${actTab} ${t.id.slice(0, 12)}… ${(t.title ?? "").slice(0, 28).padEnd(28)} ${(t.url ?? "").slice(0, 50)}`);
|
|
2162
|
+
}
|
|
2163
|
+
consola.log("");
|
|
2164
|
+
consola.success(`${stale.length} stale bookmark(s) and ${dead.length} dead tab(s) ${dry ? "would be removed" : "removed"}` + (ctx.values.orphans ? `, ${orphans.length} orphan tab(s) ${actTab}` : "") + ".");
|
|
2165
|
+
if (!ctx.values.orphans && orphans.length) consola.log(` ${orphans.length} live tab(s) no session claims were left alone — \`gc --orphans --dry\` to review them.`);
|
|
2166
|
+
if (dead.length && dead.length === pages.length && pages.length > 0) consola.warn("Every open tab was dead. That is the shape of a Chrome that can no longer launch renderers, which closing tabs does not fix — run `browser-automation doctor` for the diagnosis.");
|
|
2167
|
+
}
|
|
2168
|
+
});
|
|
2169
|
+
//#endregion
|
|
2170
|
+
//#region src/commands/port.ts
|
|
2171
|
+
const portCommand = define({
|
|
2172
|
+
name: "port",
|
|
2173
|
+
description: "Print the CDP port this user's Chrome uses (one number, for scripts)",
|
|
2174
|
+
args: {},
|
|
2175
|
+
async run() {
|
|
2176
|
+
process.stdout.write(`${cdpPort()}\n`);
|
|
1795
2177
|
}
|
|
1796
2178
|
});
|
|
1797
2179
|
//#endregion
|
|
@@ -1825,7 +2207,10 @@ const subCommands = new Map([
|
|
|
1825
2207
|
["close", closeCommand],
|
|
1826
2208
|
["bind", bindCommand],
|
|
1827
2209
|
["launch", launchCommand],
|
|
1828
|
-
["doctor", doctorCommand]
|
|
2210
|
+
["doctor", doctorCommand],
|
|
2211
|
+
["gc", gcCommand],
|
|
2212
|
+
["prune", gcCommand],
|
|
2213
|
+
["port", portCommand]
|
|
1829
2214
|
]);
|
|
1830
2215
|
async function run() {
|
|
1831
2216
|
await cli(process.argv.slice(2), defaultCommand, {
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@generativereality/browser-automation",
|
|
3
|
-
"version": "0.4.
|
|
4
|
-
"description": "Daemonless, per-tab-isolated browser automation CLI for Claude Code. Drives one shared headed Chrome (persistent profile + extensions) over per-target CDP
|
|
3
|
+
"version": "0.4.8",
|
|
4
|
+
"description": "Daemonless, per-tab-isolated browser automation CLI for Claude Code. Drives one shared headed Chrome (persistent profile + extensions) over per-target CDP \u2014 many parallel sessions, no focus stealing, nothing long-lived to crash.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"bin": {
|
|
7
7
|
"browser-automation": "dist/index.js"
|
|
@@ -16,7 +16,7 @@
|
|
|
16
16
|
"dev": "bun run ./src/index.ts",
|
|
17
17
|
"build": "tsdown",
|
|
18
18
|
"typecheck": "tsc --noEmit",
|
|
19
|
-
"check": "npm run typecheck && npm run build",
|
|
19
|
+
"check": "npm run typecheck && bash scripts/check-one-port.sh && npm run build",
|
|
20
20
|
"release": "bumpp && npm publish",
|
|
21
21
|
"sync-plugin": "bash scripts/sync-plugin.sh",
|
|
22
22
|
"prepack": "npm run build"
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
#!/usr/bin/env bash
|
|
2
|
+
#
|
|
3
|
+
# One place decides the CDP port. This fails the build if a second one appears.
|
|
4
|
+
#
|
|
5
|
+
# The formula (base + uid offset) has now been copied out of `cdpPort()` twice:
|
|
6
|
+
# into the launch script within an hour of being written, and into a downstream
|
|
7
|
+
# app the same day. Both copies carried a comment promising to keep them in
|
|
8
|
+
# step, which is the tell rather than the plan — and the second time, the
|
|
9
|
+
# comment outlived the fix that removed the duplication and sat there inviting a
|
|
10
|
+
# third copy in good faith.
|
|
11
|
+
#
|
|
12
|
+
# A comment cannot enforce this. A grep can, and it costs nothing: there is no
|
|
13
|
+
# test runner in this package and this needs none.
|
|
14
|
+
#
|
|
15
|
+
# What is allowed to name the number:
|
|
16
|
+
# - src/core/cdp.ts the definition
|
|
17
|
+
# - src/commands/doctor.ts a historical note about the bug, in a comment
|
|
18
|
+
# Everything else asks: `browser-automation port`, or `--port` from the CLI.
|
|
19
|
+
set -euo pipefail
|
|
20
|
+
|
|
21
|
+
cd "$(dirname "${BASH_SOURCE[0]}")/.."
|
|
22
|
+
|
|
23
|
+
fail=0
|
|
24
|
+
|
|
25
|
+
# The base port, anywhere it could be executed.
|
|
26
|
+
while IFS= read -r hit; do
|
|
27
|
+
echo "✗ $hit" >&2
|
|
28
|
+
fail=1
|
|
29
|
+
done < <(
|
|
30
|
+
grep -rn --include='*.ts' --include='*.sh' -- '9223' src scripts 2>/dev/null \
|
|
31
|
+
| grep -v '^src/core/cdp.ts:' \
|
|
32
|
+
| grep -v '^src/commands/doctor.ts:.*\*' \
|
|
33
|
+
| grep -v '^scripts/check-one-port.sh:' \
|
|
34
|
+
| grep -vE '^[^:]+:[0-9]+:[[:space:]]*(//|#)' || true
|
|
35
|
+
)
|
|
36
|
+
|
|
37
|
+
# Shell ARITHMETIC on the uid — the shape a re-derivation takes when somebody
|
|
38
|
+
# does not want to shell out to node.
|
|
39
|
+
#
|
|
40
|
+
# Deliberately narrow: `$(( … ))` or `expr`, not "a line mentioning id -u".
|
|
41
|
+
# The first version matched `pgrep -u "$(id -u)" -f -- "--remote-debugging-port=…"`
|
|
42
|
+
# — the ownership probe, which uses the port it was GIVEN — and a checker whose
|
|
43
|
+
# first run cries wolf is how the one real finding gets skimmed past.
|
|
44
|
+
while IFS= read -r hit; do
|
|
45
|
+
echo "✗ $hit" >&2
|
|
46
|
+
fail=1
|
|
47
|
+
done < <(
|
|
48
|
+
grep -rnE --include='*.sh' '\$\(\([^)]*id -u|expr[^|]*id -u' scripts 2>/dev/null \
|
|
49
|
+
| grep -v '^scripts/check-one-port.sh:' || true
|
|
50
|
+
)
|
|
51
|
+
|
|
52
|
+
if [ "$fail" -ne 0 ]; then
|
|
53
|
+
cat >&2 <<'MSG'
|
|
54
|
+
|
|
55
|
+
The CDP port is decided in exactly one place: cdpPort() in src/core/cdp.ts.
|
|
56
|
+
Ask for it instead of recomputing it:
|
|
57
|
+
|
|
58
|
+
TypeScript import { cdpPort } from '../core/cdp.js'
|
|
59
|
+
shell browser-automation port
|
|
60
|
+
a subprocess pass --port, as `launch` does
|
|
61
|
+
|
|
62
|
+
Why this is enforced rather than requested: 127.0.0.1 is machine-wide and the
|
|
63
|
+
DevTools protocol has no authentication, so two answers to "which port" means
|
|
64
|
+
one account silently driving another account's browser — which on a real task
|
|
65
|
+
is somebody's signed-in bank session. Found 2026-08-08; not a hypothetical.
|
|
66
|
+
MSG
|
|
67
|
+
exit 1
|
|
68
|
+
fi
|
|
69
|
+
|
|
70
|
+
echo "✓ one place decides the port"
|
package/scripts/launch-chrome.sh
CHANGED
|
@@ -2,25 +2,89 @@
|
|
|
2
2
|
# Launch the canonical long-running headed Chrome that the browser-automation CLI drives via per-target CDP.
|
|
3
3
|
#
|
|
4
4
|
# Usage:
|
|
5
|
-
# ./scripts/launch-chrome.sh
|
|
6
|
-
# ./scripts/launch-chrome.sh --status
|
|
5
|
+
# ./scripts/launch-chrome.sh # launch if not already running
|
|
6
|
+
# ./scripts/launch-chrome.sh --status # exit 0 if a CDP browser is listening, else 1
|
|
7
|
+
# ./scripts/launch-chrome.sh --port 9224 # explicit port (the CLI always passes this)
|
|
8
|
+
# ./scripts/launch-chrome.sh --restart # quit a running Chrome first, then launch
|
|
9
|
+
#
|
|
10
|
+
# Why --restart exists:
|
|
11
|
+
# A browser process can permanently lose the ability to launch renderers (see
|
|
12
|
+
# src/core/renderer-health.ts for the mechanism). Every existing tab keeps
|
|
13
|
+
# working, so the browser looks fine, but no new tab or cross-origin
|
|
14
|
+
# navigation ever will again. Restarting is the ONLY recovery — and plain
|
|
15
|
+
# `launch` cannot do it, because it is idempotent by design and correctly
|
|
16
|
+
# reports "already running". Without an explicit flag the only way out was to
|
|
17
|
+
# go and kill Chrome by hand, which is how a diagnosis ends up unactionable.
|
|
7
18
|
#
|
|
8
19
|
# Why this script exists:
|
|
9
20
|
# The `browser-automation` skill prefers to drive a real, persistent Chrome
|
|
10
21
|
# profile (so logins survive reboots) over a Playwright-managed one. The
|
|
11
|
-
# convention is: one Chrome listening on --remote-debugging-port
|
|
12
|
-
# a dedicated user-data-dir. The browser-automation CLI then drives it over
|
|
13
|
-
# to start
|
|
22
|
+
# convention is: one Chrome per user listening on --remote-debugging-port with
|
|
23
|
+
# a dedicated user-data-dir. The browser-automation CLI then drives it over
|
|
24
|
+
# per-target CDP. This script is the single source of truth for how to start
|
|
25
|
+
# that Chrome.
|
|
26
|
+
#
|
|
27
|
+
# ONE CHROME PER USER, NOT PER MACHINE:
|
|
28
|
+
# 127.0.0.1 is machine-wide and CDP has no authentication, so a single
|
|
29
|
+
# hardcoded port means the first macOS account to launch owns it and every
|
|
30
|
+
# other account's automation silently drives that account's browser. The port
|
|
31
|
+
# is therefore derived from the uid, by `cdpPort()` in src/core/cdp.ts — the
|
|
32
|
+
# one place that decides it. This script is told, or asks.
|
|
14
33
|
set -euo pipefail
|
|
15
34
|
|
|
16
|
-
|
|
35
|
+
# --- port ------------------------------------------------------------------
|
|
36
|
+
# **Asked for, never recomputed.** `cdpPort()` in src/core/cdp.ts is the only
|
|
37
|
+
# place the port is decided; the CLI passes it here with --port, and a person
|
|
38
|
+
# running this script by hand gets the same number by asking the CLI that ships
|
|
39
|
+
# beside it. A second copy of the formula is a second answer waiting to happen.
|
|
40
|
+
ask_cli_for_port() {
|
|
41
|
+
local dist="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)/dist/index.js"
|
|
42
|
+
if [ -f "$dist" ] && command -v node >/dev/null 2>&1; then
|
|
43
|
+
node "$dist" port 2>/dev/null && return 0
|
|
44
|
+
fi
|
|
45
|
+
command -v browser-automation >/dev/null 2>&1 && browser-automation port 2>/dev/null
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
PORT=""
|
|
49
|
+
RESTART=0
|
|
50
|
+
ARGS=()
|
|
51
|
+
while [ $# -gt 0 ]; do
|
|
52
|
+
case "$1" in
|
|
53
|
+
--port) PORT="${2:-}"; shift 2 ;;
|
|
54
|
+
--restart) RESTART=1; shift ;;
|
|
55
|
+
*) ARGS+=("$1"); shift ;;
|
|
56
|
+
esac
|
|
57
|
+
done
|
|
58
|
+
set -- "${ARGS[@]+"${ARGS[@]}"}"
|
|
59
|
+
PORT="${PORT:-$(ask_cli_for_port || true)}"
|
|
60
|
+
if [ -z "${PORT}" ]; then
|
|
61
|
+
echo "Error: could not work out which port to use — pass --port, or set" >&2
|
|
62
|
+
echo " BROWSER_AUTOMATION_PORT. (This script asks the CLI beside it;" >&2
|
|
63
|
+
echo " see cdpPort() in src/core/cdp.ts, the only place it is decided.)" >&2
|
|
64
|
+
exit 1
|
|
65
|
+
fi
|
|
66
|
+
|
|
17
67
|
PROFILE="${BROWSER_AUTOMATION_PROFILE:-$HOME/Library/Application Support/Google/Chrome/browser-automation}"
|
|
18
|
-
|
|
68
|
+
# Under the caller's OWN temp dir: /tmp is shared and sticky, so with a
|
|
69
|
+
# machine-global name the second user cannot write the first user's log.
|
|
70
|
+
LOG="${BROWSER_AUTOMATION_LOG:-${TMPDIR:-/tmp}/chrome-${PORT}.log}"
|
|
19
71
|
|
|
20
72
|
is_up() {
|
|
21
73
|
curl -fs -o /dev/null "http://localhost:${PORT}/json/version"
|
|
22
74
|
}
|
|
23
75
|
|
|
76
|
+
# Is the browser answering on this port OURS?
|
|
77
|
+
#
|
|
78
|
+
# Note the question is "is it mine", not "whose is it". `lsof` tells a
|
|
79
|
+
# non-root user NOTHING about another user's socket — it prints an empty
|
|
80
|
+
# result and exits 0, which reads exactly like a free port. Measured
|
|
81
|
+
# 2026-08-08: as the second account, `lsof -iTCP:9223 -sTCP:LISTEN` returned
|
|
82
|
+
# nothing while the first account's Chrome was plainly listening. You can
|
|
83
|
+
# always see your OWN processes, so ask that instead.
|
|
84
|
+
port_is_ours() {
|
|
85
|
+
pgrep -u "$(id -u)" -f -- "--remote-debugging-port=${PORT}" >/dev/null 2>&1
|
|
86
|
+
}
|
|
87
|
+
|
|
24
88
|
if [ "${1:-}" = "--status" ]; then
|
|
25
89
|
if is_up; then
|
|
26
90
|
echo "Chrome CDP on :${PORT} is up"
|
|
@@ -30,9 +94,50 @@ if [ "${1:-}" = "--status" ]; then
|
|
|
30
94
|
exit 1
|
|
31
95
|
fi
|
|
32
96
|
|
|
97
|
+
# Something is answering on our port and it is not ours. Refuse loudly rather
|
|
98
|
+
# than drive it: "already running" here used to mean "another macOS account's
|
|
99
|
+
# browser, and you will never be told".
|
|
100
|
+
if is_up && ! port_is_ours; then
|
|
101
|
+
echo "Error: something else on this Mac is already serving CDP on port ${PORT}," >&2
|
|
102
|
+
echo " and it is not a Chrome this account started. Driving it would act in" >&2
|
|
103
|
+
echo " ANOTHER user's browser — quit Chrome in that account, or set" >&2
|
|
104
|
+
echo " BROWSER_AUTOMATION_PORT to a free port for this one." >&2
|
|
105
|
+
exit 1
|
|
106
|
+
fi
|
|
107
|
+
|
|
108
|
+
# Restart: quit the Chrome we own, wait for the port to go quiet, fall through
|
|
109
|
+
# to the normal launch. Deliberately SIGTERM, not SIGKILL — Chrome flushes its
|
|
110
|
+
# profile (cookies, extension state, session) on a clean quit, and that profile
|
|
111
|
+
# is the whole reason this browser is long-lived. Only escalate if it will not
|
|
112
|
+
# go, and say so when it happens.
|
|
113
|
+
if [ "$RESTART" = "1" ] && is_up; then
|
|
114
|
+
if ! port_is_ours; then
|
|
115
|
+
echo "Error: refusing to restart a Chrome this account did not start." >&2
|
|
116
|
+
exit 1
|
|
117
|
+
fi
|
|
118
|
+
TABS="$(curl -fs "http://localhost:${PORT}/json/list" 2>/dev/null | grep -c '"type": "page"' || true)"
|
|
119
|
+
echo "Restarting Chrome on :${PORT} — closing ${TABS:-?} open tab(s)."
|
|
120
|
+
pkill -u "$(id -u)" -f -- "--remote-debugging-port=${PORT}" 2>/dev/null || true
|
|
121
|
+
for _ in $(seq 1 40); do
|
|
122
|
+
is_up || break
|
|
123
|
+
sleep 0.25
|
|
124
|
+
done
|
|
125
|
+
if is_up; then
|
|
126
|
+
echo "Chrome did not quit on SIGTERM after 10s; sending SIGKILL." >&2
|
|
127
|
+
pkill -9 -u "$(id -u)" -f -- "--remote-debugging-port=${PORT}" 2>/dev/null || true
|
|
128
|
+
sleep 2
|
|
129
|
+
fi
|
|
130
|
+
# Chrome unregisters its bootstrap names and releases the port on the way out;
|
|
131
|
+
# relaunching before that finishes produces a second browser that cannot serve
|
|
132
|
+
# CDP. A short settle beats a confusing race.
|
|
133
|
+
sleep 1
|
|
134
|
+
fi
|
|
135
|
+
|
|
33
136
|
if is_up; then
|
|
34
137
|
echo "Already running on :${PORT} — nothing to do."
|
|
35
138
|
echo "Drive it with: browser-automation goto -s <session> <url>"
|
|
139
|
+
echo "(To force a fresh browser process — the only fix for a Chrome that can no"
|
|
140
|
+
echo " longer launch renderers — use: browser-automation launch --restart)"
|
|
36
141
|
exit 0
|
|
37
142
|
fi
|
|
38
143
|
|
|
@@ -57,6 +162,16 @@ fi
|
|
|
57
162
|
|
|
58
163
|
mkdir -p "$(dirname "$PROFILE")"
|
|
59
164
|
|
|
165
|
+
# Keep one generation of the previous log. Chrome's stdout is the only place
|
|
166
|
+
# the reason for a renderer failure is ever written, and truncating it on
|
|
167
|
+
# relaunch destroys the evidence at exactly the moment somebody restarted
|
|
168
|
+
# BECAUSE of that failure. (Done during this fix, to this author's own
|
|
169
|
+
# evidence.) One generation, not a rotation scheme: the interesting log is
|
|
170
|
+
# always the one from the browser that just misbehaved.
|
|
171
|
+
if [ -s "$LOG" ]; then
|
|
172
|
+
mv -f "$LOG" "${LOG}.prev" 2>/dev/null || true
|
|
173
|
+
fi
|
|
174
|
+
|
|
60
175
|
nohup "$CHROME" \
|
|
61
176
|
--remote-debugging-port="$PORT" \
|
|
62
177
|
--user-data-dir="$PROFILE" \
|
package/skills/browser/SKILL.md
CHANGED
|
@@ -14,7 +14,8 @@ file under `~/.browser-automation/sessions/`.
|
|
|
14
14
|
|
|
15
15
|
## The model — read this first
|
|
16
16
|
|
|
17
|
-
- **One shared headed Chrome** on
|
|
17
|
+
- **One shared headed Chrome per USER** on a uid-derived
|
|
18
|
+
`--remote-debugging-port` (`9223` for the first account on the machine) with a
|
|
18
19
|
persistent profile (`browser-automation`). Cookies, logins, and **browser
|
|
19
20
|
extensions (password managers, etc.) all persist** across runs and across
|
|
20
21
|
Claude Code restarts. The user can watch and complete interactive auth in the
|
|
@@ -55,7 +56,7 @@ file under `~/.browser-automation/sessions/`.
|
|
|
55
56
|
|
|
56
57
|
```bash
|
|
57
58
|
npm install -g @generativereality/browser-automation
|
|
58
|
-
browser-automation launch # start
|
|
59
|
+
browser-automation launch # start this user's Chrome (idempotent)
|
|
59
60
|
browser-automation doctor # verify Node, Chrome, targets, sessions
|
|
60
61
|
```
|
|
61
62
|
|
|
@@ -71,7 +72,7 @@ Page commands take a tab selector — `-s <session>` (default `$BAC_SESSION`, el
|
|
|
71
72
|
| Need | Command |
|
|
72
73
|
|---|---|
|
|
73
74
|
| Start/refresh the Chrome | `browser-automation launch` |
|
|
74
|
-
| Diagnose setup | `browser-automation doctor` |
|
|
75
|
+
| Diagnose setup (incl. renderer capacity) | `browser-automation doctor` |
|
|
75
76
|
| List sessions + every open tab (id, title, url) | `browser-automation list` |
|
|
76
77
|
| Open a background tab | `browser-automation new -s work [url]` |
|
|
77
78
|
| Navigate (session tab created if needed) | `browser-automation goto -s work https://example.com` |
|
|
@@ -88,6 +89,8 @@ Page commands take a tab selector — `-s <session>` (default `$BAC_SESSION`, el
|
|
|
88
89
|
| Drop file(s) onto a drag-and-drop zone | `browser-automation drop -m app e7 ~/Desktop/clip.mp4` (add `--js` for a synthetic drop) |
|
|
89
90
|
| Inspect network (find the API, headers, bodies) | `browser-automation network -m bank --reload --filter api --headers --body` |
|
|
90
91
|
| Screenshot a tab | `browser-automation screenshot -m op.fi --full -o shot.png` |
|
|
92
|
+
| Prune stale session bookmarks + dead tabs | `browser-automation gc --dry` (then without `--dry`) |
|
|
93
|
+
| Restart Chrome (only fix for the renderer wedge — closes ALL tabs) | `browser-automation launch --restart` |
|
|
91
94
|
| Forget a session (tab stays open) | `browser-automation close -s work` |
|
|
92
95
|
| Forget **and** close the browser tab | `browser-automation close -s work --tab` |
|
|
93
96
|
|
|
@@ -133,12 +136,47 @@ There's no `state-save`/`state-load` to manage — the profile *is* the auth sto
|
|
|
133
136
|
|
|
134
137
|
- **Refs go stale after any DOM change**, not just navigation. Snapshot → use
|
|
135
138
|
those refs for one action → re-snapshot. "ref not found" means re-snapshot.
|
|
136
|
-
- **`isTrusted` / synthetic events.** Clicks and fills are JS-dispatched
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
139
|
+
- **`isTrusted` / synthetic events.** Clicks and fills are JS-dispatched by
|
|
140
|
+
default, so widgets that demand trusted events ignore them. **For clicks, pass
|
|
141
|
+
`--trusted`** — it dispatches a real CDP `Input.dispatchMouseEvent`, brings the
|
|
142
|
+
tab to front, waits for it to be focused+visible (CDP input no-ops on a
|
|
143
|
+
backgrounded tab) and waits for the element to be actionable (stable position +
|
|
144
|
+
unoccluded hit-test) before pressing. For fills, pass `--native` to drive
|
|
145
|
+
character insertion through CDP `Input.insertText`, which fires real
|
|
146
|
+
`beforeinput`/`input` events.
|
|
147
|
+
**Reach for `--trusted` the moment a click "succeeds" but nothing happens** —
|
|
148
|
+
the CLI prints `✔ clicked e7` on a dispatched event regardless of whether the
|
|
149
|
+
widget reacted, so a silent no-op is the signature, not an error. Canonical
|
|
150
|
+
cases: LinkedIn artdeco dropdown items, Radix dropdowns/popovers, cmdk
|
|
151
|
+
comboboxes, and **framework-state form widgets whose inputs are `readonly` with
|
|
152
|
+
no `name`** (Viking Line's booking selectors — the visible fields are display
|
|
153
|
+
shells; the real state lives in the framework, so `fill` and DOM value-setting
|
|
154
|
+
do nothing at all).
|
|
155
|
+
**Do NOT hand-roll a raw-CDP trusted click.** Burned 2026-08-22: wrote a
|
|
156
|
+
bespoke `Input.dispatchMouseEvent` helper for exactly this, and it clicked
|
|
157
|
+
stale coordinates (the panel had animated in) — `--trusted` already solves that
|
|
158
|
+
with the actionability wait. Check `browser-automation click --help` before
|
|
159
|
+
building anything.
|
|
160
|
+
**A form can swallow a dispatched click and submit itself the wrong way.**
|
|
161
|
+
npmjs.com's package-settings forms are the case (2026-08-22): a default click
|
|
162
|
+
on the submit button did not reach the framework's handler, so the browser fell
|
|
163
|
+
through to a plain native POST and the tab was replaced by a raw
|
|
164
|
+
`{"message":"Not Found"}` — no error from the CLI, and nothing saved. It looks
|
|
165
|
+
like the server rejected your data; it did not. `--trusted` submitted the same
|
|
166
|
+
form correctly. On any settings page, verify by reloading and re-reading the
|
|
167
|
+
saved state rather than trusting a click that "worked".
|
|
168
|
+
- **WebAuthn / security keys need a genuinely focused, visible tab, and you
|
|
169
|
+
cannot supply the touch.** `navigator.credentials.get()` refuses outright when
|
|
170
|
+
`document.hasFocus()` is false or `visibilityState` is `hidden` — which is the
|
|
171
|
+
normal state while you work in the terminal, since `--trusted` only fronts the
|
|
172
|
+
tab for the instant of the click. The prompt then never opens and the page just
|
|
173
|
+
sits there, so a 2FA step can look like it is waiting for the user when the
|
|
174
|
+
browser has already declined to ask. Measured 2026-08-22 on npm's
|
|
175
|
+
`Use security key` challenge: the form POST returned **200** and the challenge
|
|
176
|
+
was live, but it could only be satisfied once the user brought that Chrome
|
|
177
|
+
window to the front themselves. Check with
|
|
178
|
+
`eval '({f:document.hasFocus(),v:document.visibilityState})'` before concluding
|
|
179
|
+
anything, and hand hardware-2FA steps to the user with the window frontmost.
|
|
142
180
|
- **Controlled-form state stickiness.** Form libraries that subscribe to React's
|
|
143
181
|
internal value-setter (React Hook Form, Final Form, Formik with a `Controller`,
|
|
144
182
|
Blocket/finn.no's `recommerce` editor) sometimes ignore the synthetic `input`
|
|
@@ -229,11 +267,92 @@ There's no `state-save`/`state-load` to manage — the profile *is* the auth sto
|
|
|
229
267
|
isn't snapshot-interactive. After the drop, `read`/`screenshot`/`network` to
|
|
230
268
|
confirm processing started, then grab the result (often a download endpoint you
|
|
231
269
|
can pull with `download --url`).
|
|
270
|
+
- **"The site is blocking us" — when it is really Chrome that cannot make renderers.**
|
|
271
|
+
A browser process can permanently lose the ability to launch **renderer processes** while
|
|
272
|
+
looking perfectly healthy. Every tab that already exists keeps working, so nothing seems wrong
|
|
273
|
+
until you open a tab or navigate somewhere new, and then the errors read as the remote site's
|
|
274
|
+
doing. Diagnosed 2026-08-22; it cost an hour of blaming ferry-operator bot protection.
|
|
275
|
+
|
|
276
|
+
How it shows up:
|
|
277
|
+
- `browser-automation new` + `goto` → `CDP Page.enable timed out after 30000ms`, **even for
|
|
278
|
+
`example.com`**.
|
|
279
|
+
- **Cross-origin** navigation of an existing, working tab → `navigate failed: net::ERR_ABORTED`.
|
|
280
|
+
Site isolation puts a new origin in a new renderer — the exact thing Chrome can no longer do.
|
|
281
|
+
- **Same-origin** navigation on that same tab keeps working perfectly (Skyscanner → Skyscanner
|
|
282
|
+
with new query params was fine throughout). That asymmetry is what makes it masquerade as
|
|
283
|
+
"only site X blocks us": the tab you were already using still behaves.
|
|
284
|
+
- A target created at the browser level (`PUT /json/new?<url>`) appears in `/json/list` with the
|
|
285
|
+
right URL but an **empty title forever**; every `Runtime.evaluate` against it times out.
|
|
286
|
+
`Page.captureScreenshot` returns `Internal error`. The target shell exists; the renderer does not.
|
|
287
|
+
|
|
288
|
+
**The mechanism** (macOS, from Chrome's own log at `$TMPDIR/chrome-<port>.log` — `launch --restart`
|
|
289
|
+
keeps the previous browser's log as `chrome-<port>.log.prev`, which is the one you want after a
|
|
290
|
+
restart):
|
|
291
|
+
```
|
|
292
|
+
ERROR:base/apple/mach_port_rendezvous_mac.cc:256]
|
|
293
|
+
bootstrap_look_up com.google.Chrome.MachPortRendezvousServer.<pid>: (ipc/send) invalid destination port
|
|
294
|
+
ERROR:base/memory/shared_memory_switch.cc:261]
|
|
295
|
+
No rendezvous client, terminating process (parent died?)
|
|
296
|
+
```
|
|
297
|
+
A Chrome child process gets its shared-memory handles by looking up a Mach bootstrap service the
|
|
298
|
+
browser registers **once, at startup**, named `com.google.Chrome.MachPortRendezvousServer.<browser-pid>`.
|
|
299
|
+
That registration had vanished from the user's launchd namespace — confirmed absent via
|
|
300
|
+
`launchctl print gui/$UID | grep MachPortRendezvousServer.<pid>`, while two healthy Chromes on the
|
|
301
|
+
same machine were both listed. From then on **every renderer Chrome launches kills itself within
|
|
302
|
+
milliseconds**, which is why none ever appears in `ps` and why the browser only reports
|
|
303
|
+
`Render process gone.` **What made the name vanish is not established.** Two things
|
|
304
|
+
correlated and neither is proven: the binary on disk had moved to 151.0.7922.170 while the live
|
|
305
|
+
browser was still running .138, and `GoogleUpdater` was FATAL-ing on its own `bootstrap_check_in`
|
|
306
|
+
with error 141. But the first renderer failure (18:53) *preceded* the first updater FATAL (19:42)
|
|
307
|
+
by ~50 minutes, so the update churn is at best a fellow symptom of a sick launchd bootstrap
|
|
308
|
+
namespace, not the cause. Treat the trigger as unknown; the diagnosis and the recovery do not
|
|
309
|
+
depend on it.
|
|
310
|
+
|
|
311
|
+
**It is NOT about how many tabs are open.** That was the first theory and it is wrong: a freshly
|
|
312
|
+
launched Chrome on the same machine was driven to **421 page targets / 435 live renderer
|
|
313
|
+
processes, every one responsive**, and a 256-fd `ulimit` made no difference either (205 renderers,
|
|
314
|
+
all fine). The broken browser had 66 tabs. The count was a coincidence — so do not treat a big
|
|
315
|
+
tab count as evidence of this, and do not expect closing tabs to fix it.
|
|
316
|
+
|
|
317
|
+
**Diagnose it:**
|
|
318
|
+
```bash
|
|
319
|
+
browser-automation doctor # measures renderer capacity, not just reachability
|
|
320
|
+
```
|
|
321
|
+
`doctor` now creates a throwaway tab, makes its renderer evaluate `1+1`, and closes it — the one
|
|
322
|
+
round-trip that separates a wedged browser from a slow network or a hostile site. On failure it
|
|
323
|
+
names the root cause (including the missing bootstrap service and the pid) and points at Chrome's
|
|
324
|
+
log. On a healthy browser it reports e.g. `✓ Renderer capacity: a new tab got a live renderer in
|
|
325
|
+
73ms`. `goto` and `new` run the same probe automatically **on the error path only**, so a bare
|
|
326
|
+
`Page.enable timed out` now arrives with the diagnosis attached instead of sending you to the
|
|
327
|
+
site's bot-protection docs.
|
|
328
|
+
|
|
329
|
+
**Recovery — only a Chrome restart clears it.** The bootstrap name is registered at startup and
|
|
330
|
+
never re-registered, so nothing short of a new browser process helps. Closing tabs does not, and
|
|
331
|
+
plain `launch` will not either (idempotent by design — it sees a live browser and exits happy):
|
|
332
|
+
```bash
|
|
333
|
+
browser-automation launch --restart # SIGTERM (profile flushes cleanly), wait, relaunch
|
|
334
|
+
```
|
|
335
|
+
It reports how many tabs it is about to close. **Those tabs belong to every parallel Claude Code
|
|
336
|
+
session sharing this Chrome — ask Fred first, never restart unilaterally.**
|
|
337
|
+
|
|
338
|
+
**Housekeeping is a different problem** — `browser-automation gc` prunes stale session bookmarks
|
|
339
|
+
(they are never cleaned up otherwise; this machine had accumulated 234, only 5 of them live) and
|
|
340
|
+
closes tabs whose renderer does not answer. Use `--dry` first. It is genuinely useful, but it is
|
|
341
|
+
**not** a fix for the wedge above, and it never closes a working tab unless you pass `--orphans`
|
|
342
|
+
— tabs get addressed by `-m` and opened by hand, so "no session claims it" is not evidence that
|
|
343
|
+
nobody wants it.
|
|
344
|
+
|
|
345
|
+
**The false lead to resist:** a bare `curl` to a suspicious site may genuinely return a bot wall
|
|
346
|
+
(vikingline.fi serves an Imperva "Pardon Our Interruption" page, HTTP 200), which feels like
|
|
347
|
+
confirmation. It confirms nothing about the browser path — the persistent, cookie-bearing profile
|
|
348
|
+
is a completely different client. Check the browser first: if `doctor` says renderer capacity is
|
|
349
|
+
fine and a boring cross-origin URL loads, *then* start suspecting the site.
|
|
350
|
+
|
|
232
351
|
- **Page still loading.** `goto` waits for the load event, but SPAs render after.
|
|
233
352
|
If a `read`/`snapshot` looks empty, re-run after a moment, or snapshot again
|
|
234
353
|
once a known element should be present.
|
|
235
354
|
- **`launch` is macOS/Linux only** (resolves the Chrome binary per-OS). On other
|
|
236
|
-
setups, start Chrome manually with `--remote-debugging-port
|
|
355
|
+
setups, start Chrome manually with `--remote-debugging-port=<doctor's port>
|
|
237
356
|
--user-data-dir="<profile>"`.
|
|
238
357
|
|
|
239
358
|
## Network insights — find the API behind a page
|
|
@@ -297,7 +416,10 @@ working around it forever**:
|
|
|
297
416
|
|
|
298
417
|
## Troubleshooting
|
|
299
418
|
|
|
300
|
-
- **`No CDP browser on http://localhost
|
|
419
|
+
- **`No CDP browser on http://localhost:<port>`** → `browser-automation launch`.
|
|
420
|
+
If it says the port is held by ANOTHER user, that is not your Chrome and
|
|
421
|
+
driving it would act in their session — quit Chrome in that account, or set
|
|
422
|
+
`BROWSER_AUTOMATION_PORT`.
|
|
301
423
|
- **`command not found: browser-automation`** → `npm install -g @generativereality/browser-automation`.
|
|
302
424
|
- **Chrome was restarted** → nothing to do; the next `goto` recreates the
|
|
303
425
|
session's tab automatically (sessions self-heal; `list` shows `stale`).
|