@generativereality/browser-automation 0.4.5 → 0.4.7
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 +34 -6
- package/dist/index.js +646 -49
- 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 +115 -6
package/dist/index.js
CHANGED
|
@@ -2,12 +2,12 @@
|
|
|
2
2
|
import { cli, define } from "gunshi";
|
|
3
3
|
import { consola } from "consola";
|
|
4
4
|
import { homedir } from "node:os";
|
|
5
|
-
import { dirname, join, resolve } from "node:path";
|
|
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.7";
|
|
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 {
|
|
@@ -150,6 +171,27 @@ async function withPage(targetId, fn) {
|
|
|
150
171
|
s.close();
|
|
151
172
|
}
|
|
152
173
|
}
|
|
174
|
+
/** Make a page target behave as the foreground tab for trusted CDP input,
|
|
175
|
+
* WITHOUT stealing OS focus from the user's other apps.
|
|
176
|
+
*
|
|
177
|
+
* CDP `Input.*` events (and the user-activation they grant) are dropped by the
|
|
178
|
+
* renderer when the tab's `visibilityState` is `hidden` — which it is whenever
|
|
179
|
+
* the automation Chrome window isn't the frontmost OS window (the normal case:
|
|
180
|
+
* the user is in their terminal). `Page.bringToFront` alone does NOT fix this;
|
|
181
|
+
* the tab still reports `hidden`. `Emulation.setFocusEmulationEnabled` forces
|
|
182
|
+
* the renderer to treat itself as focused+visible regardless of the real window
|
|
183
|
+
* state (this is how Playwright drives backgrounded/headless pages), and
|
|
184
|
+
* `Page.setWebLifecycleState: active` un-throttles a frozen tab. Together they
|
|
185
|
+
* flip `document.hasFocus()`+`visibilityState:visible` on, so a trusted click /
|
|
186
|
+
* drag actually lands and grants user activation — which activation-gated flows
|
|
187
|
+
* (e.g. drop-zone uploaders that only start work inside a user gesture) require.
|
|
188
|
+
*
|
|
189
|
+
* All three are best-effort: older Chrome builds may not expose every command. */
|
|
190
|
+
async function forceForeground(s) {
|
|
191
|
+
await s.send("Page.bringToFront").catch(() => {});
|
|
192
|
+
await s.send("Emulation.setFocusEmulationEnabled", { enabled: true }).catch(() => {});
|
|
193
|
+
await s.send("Page.setWebLifecycleState", { state: "active" }).catch(() => {});
|
|
194
|
+
}
|
|
153
195
|
/** Run `fn` against the browser-level endpoint (Target.* commands), then close. */
|
|
154
196
|
async function withBrowser(fn) {
|
|
155
197
|
const s = await connect(await browserWsUrl());
|
|
@@ -255,6 +297,194 @@ function normalizeUrl(input) {
|
|
|
255
297
|
return `https://${input}`;
|
|
256
298
|
}
|
|
257
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
|
|
258
488
|
//#region src/commands/new.ts
|
|
259
489
|
const newCommand = define({
|
|
260
490
|
name: "new",
|
|
@@ -282,6 +512,15 @@ const newCommand = define({
|
|
|
282
512
|
url,
|
|
283
513
|
createdAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
284
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
|
+
}
|
|
285
524
|
consola.success(`[${name}] opened background tab ${targetId.slice(0, 12)}… → ${url}`);
|
|
286
525
|
}
|
|
287
526
|
});
|
|
@@ -397,8 +636,8 @@ const gotoCommand = define({
|
|
|
397
636
|
}
|
|
398
637
|
const target = normalizeUrl(url);
|
|
399
638
|
const opts = targetOpts(ctx.values);
|
|
400
|
-
const { targetId, created } = await resolveOrCreateTargetId(opts);
|
|
401
|
-
await navigate(targetId, target);
|
|
639
|
+
const { targetId, created } = await withRendererDiagnosis(() => resolveOrCreateTargetId(opts));
|
|
640
|
+
await withRendererDiagnosis(() => navigate(targetId, target));
|
|
402
641
|
if (!opts.match && !opts.target) {
|
|
403
642
|
const name = opts.session || defaultSessionName();
|
|
404
643
|
saveSession({
|
|
@@ -579,7 +818,19 @@ function focusAndSelectExpr(ref) {
|
|
|
579
818
|
if(!el)return {err:'ref not found: '+${r}+' (re-run snapshot)'};
|
|
580
819
|
el.scrollIntoView({block:'center',inline:'center'});
|
|
581
820
|
el.focus();
|
|
582
|
-
|
|
821
|
+
// Select-all in JS so the subsequent Input.insertText REPLACES the field
|
|
822
|
+
// rather than appending. Doing this here (not via a synthetic Cmd+A key
|
|
823
|
+
// chord) keeps the trusted-fill path from ever dispatching a Meta-modified
|
|
824
|
+
// key event — an unhandled one of those leaks to the macOS main menu and
|
|
825
|
+
// pops system UI (e.g. "About This Mac"). Inputs/textareas: .select();
|
|
826
|
+
// contenteditable: the Selection API.
|
|
827
|
+
try{
|
|
828
|
+
if(typeof el.select==='function') el.select();
|
|
829
|
+
else if(el.isContentEditable){
|
|
830
|
+
const range=document.createRange();range.selectNodeContents(el);
|
|
831
|
+
const sel=window.getSelection();sel.removeAllRanges();sel.addRange(range);
|
|
832
|
+
}
|
|
833
|
+
}catch(e){}
|
|
583
834
|
return {ok:true,tag:el.tagName.toLowerCase(),len:el.value!==undefined?String(el.value).length:0};
|
|
584
835
|
})()`;
|
|
585
836
|
}
|
|
@@ -610,6 +861,36 @@ function readValueAndTrackerExpr(ref) {
|
|
|
610
861
|
function findRefExpr(ref) {
|
|
611
862
|
return WALK + `(() => __baFind(${JSON.stringify(ref)}))()`;
|
|
612
863
|
}
|
|
864
|
+
/** JS-dispatched drag-and-drop of injected files onto an element by ref. Builds
|
|
865
|
+
* real File objects from base64 bytes, assembles a DataTransfer, and fires the
|
|
866
|
+
* full dragenter→dragover→drop sequence (each carrying dataTransfer.files) so
|
|
867
|
+
* drop-zone handlers that read `e.dataTransfer.files` fire. The events are
|
|
868
|
+
* synthetic (isTrusted=false) — drop zones that gate on isTrusted need the
|
|
869
|
+
* trusted CDP path (`drop` without --js) instead. `files` is [{name,type,b64}]. */
|
|
870
|
+
function dropExpr(ref, files) {
|
|
871
|
+
const r = JSON.stringify(ref);
|
|
872
|
+
return WALK + `(() => {
|
|
873
|
+
const el=__baFind(${r});
|
|
874
|
+
if(!el)return {err:'ref not found: '+${r}+' (re-run snapshot)'};
|
|
875
|
+
el.scrollIntoView({block:'center',inline:'center'});
|
|
876
|
+
const dt=new DataTransfer();
|
|
877
|
+
for(const spec of ${JSON.stringify(files)}){
|
|
878
|
+
const bin=atob(spec.b64); const u8=new Uint8Array(bin.length);
|
|
879
|
+
for(let i=0;i<bin.length;i++) u8[i]=bin.charCodeAt(i);
|
|
880
|
+
dt.items.add(new File([u8],spec.name,{type:spec.type}));
|
|
881
|
+
}
|
|
882
|
+
const b=el.getBoundingClientRect();
|
|
883
|
+
const cx=b.left+b.width/2, cy=b.top+b.height/2;
|
|
884
|
+
const fire=(type)=>{
|
|
885
|
+
const ev=new DragEvent(type,{bubbles:true,cancelable:true,clientX:cx,clientY:cy});
|
|
886
|
+
try{ Object.defineProperty(ev,'dataTransfer',{value:dt}); }catch(e){}
|
|
887
|
+
el.dispatchEvent(ev);
|
|
888
|
+
return ev.defaultPrevented;
|
|
889
|
+
};
|
|
890
|
+
fire('dragenter'); fire('dragover'); fire('drop');
|
|
891
|
+
return {ok:true,tag:el.tagName.toLowerCase(),count:dt.files.length};
|
|
892
|
+
})()`;
|
|
893
|
+
}
|
|
613
894
|
function readExpr(selector) {
|
|
614
895
|
return WALK + `(() => { const r=${selector ? `__baQuery(${JSON.stringify(selector)})` : `document.body`}; return r ? __baText(r) : ${selector ? `'(no element matches ' + ${JSON.stringify(selector)} + ')'` : `''`}; })()`;
|
|
615
896
|
}
|
|
@@ -643,7 +924,7 @@ const snapshotCommand = define({
|
|
|
643
924
|
});
|
|
644
925
|
//#endregion
|
|
645
926
|
//#region src/commands/click.ts
|
|
646
|
-
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
|
927
|
+
const sleep$1 = (ms) => new Promise((r) => setTimeout(r, ms));
|
|
647
928
|
const clickCommand = define({
|
|
648
929
|
name: "click",
|
|
649
930
|
description: "Click an element by ref (from the latest snapshot)",
|
|
@@ -679,12 +960,12 @@ const clickCommand = define({
|
|
|
679
960
|
}
|
|
680
961
|
return res.result?.value;
|
|
681
962
|
};
|
|
682
|
-
await s
|
|
963
|
+
await forceForeground(s);
|
|
683
964
|
const focusDeadline = Date.now() + 2e3;
|
|
684
965
|
while (Date.now() < focusDeadline) {
|
|
685
966
|
const f = await evalIn(`({f:document.hasFocus(),v:document.visibilityState})`);
|
|
686
967
|
if (f && f.f && f.v === "visible") break;
|
|
687
|
-
await sleep(50);
|
|
968
|
+
await sleep$1(50);
|
|
688
969
|
}
|
|
689
970
|
let prev = null;
|
|
690
971
|
let point = null;
|
|
@@ -710,7 +991,7 @@ const clickCommand = define({
|
|
|
710
991
|
x: a.x,
|
|
711
992
|
y: a.y
|
|
712
993
|
};
|
|
713
|
-
await sleep(60);
|
|
994
|
+
await sleep$1(60);
|
|
714
995
|
}
|
|
715
996
|
if (!point) {
|
|
716
997
|
consola.error(`<${ref}> not actionable for a trusted click: ${lastReason}`);
|
|
@@ -725,7 +1006,7 @@ const clickCommand = define({
|
|
|
725
1006
|
buttons: 0,
|
|
726
1007
|
pointerType: "mouse"
|
|
727
1008
|
});
|
|
728
|
-
await sleep(20);
|
|
1009
|
+
await sleep$1(20);
|
|
729
1010
|
await s.send("Input.dispatchMouseEvent", {
|
|
730
1011
|
type: "mousePressed",
|
|
731
1012
|
x,
|
|
@@ -760,7 +1041,6 @@ const clickCommand = define({
|
|
|
760
1041
|
});
|
|
761
1042
|
//#endregion
|
|
762
1043
|
//#region src/commands/fill.ts
|
|
763
|
-
const SELECT_ALL_MOD = process.platform === "darwin" ? 4 : 2;
|
|
764
1044
|
const fillCommand = define({
|
|
765
1045
|
name: "fill",
|
|
766
1046
|
description: "Type a value into an input/textarea/contenteditable by ref",
|
|
@@ -808,38 +1088,19 @@ const fillCommand = define({
|
|
|
808
1088
|
process.exit(1);
|
|
809
1089
|
}
|
|
810
1090
|
await withPage(targetId, async (s) => {
|
|
811
|
-
await s.send("Input.dispatchKeyEvent", {
|
|
812
|
-
type: "rawKeyDown",
|
|
813
|
-
key: "a",
|
|
814
|
-
code: "KeyA",
|
|
815
|
-
windowsVirtualKeyCode: 65,
|
|
816
|
-
nativeVirtualKeyCode: 65,
|
|
817
|
-
modifiers: SELECT_ALL_MOD,
|
|
818
|
-
commands: ["selectAll"]
|
|
819
|
-
});
|
|
820
|
-
await s.send("Input.dispatchKeyEvent", {
|
|
821
|
-
type: "keyUp",
|
|
822
|
-
key: "a",
|
|
823
|
-
code: "KeyA",
|
|
824
|
-
windowsVirtualKeyCode: 65,
|
|
825
|
-
nativeVirtualKeyCode: 65,
|
|
826
|
-
modifiers: SELECT_ALL_MOD
|
|
827
|
-
});
|
|
828
1091
|
await s.send("Input.insertText", { text: value });
|
|
829
1092
|
if (submit) {
|
|
830
1093
|
await s.send("Input.dispatchKeyEvent", {
|
|
831
1094
|
type: "rawKeyDown",
|
|
832
1095
|
key: "Enter",
|
|
833
1096
|
code: "Enter",
|
|
834
|
-
windowsVirtualKeyCode: 13
|
|
835
|
-
nativeVirtualKeyCode: 13
|
|
1097
|
+
windowsVirtualKeyCode: 13
|
|
836
1098
|
});
|
|
837
1099
|
await s.send("Input.dispatchKeyEvent", {
|
|
838
1100
|
type: "keyUp",
|
|
839
1101
|
key: "Enter",
|
|
840
1102
|
code: "Enter",
|
|
841
|
-
windowsVirtualKeyCode: 13
|
|
842
|
-
nativeVirtualKeyCode: 13
|
|
1103
|
+
windowsVirtualKeyCode: 13
|
|
843
1104
|
});
|
|
844
1105
|
}
|
|
845
1106
|
});
|
|
@@ -1129,7 +1390,7 @@ async function uploadViaChooser(targetId, clickRef, files, timeout = 15e3) {
|
|
|
1129
1390
|
//#endregion
|
|
1130
1391
|
//#region src/commands/setfiles.ts
|
|
1131
1392
|
/** Resolve each path to absolute and verify it's an existing file. */
|
|
1132
|
-
function absFiles$
|
|
1393
|
+
function absFiles$2(paths) {
|
|
1133
1394
|
return paths.map((p) => {
|
|
1134
1395
|
const abs = resolve(p);
|
|
1135
1396
|
if (!existsSync(abs) || !statSync(abs).isFile()) {
|
|
@@ -1164,7 +1425,7 @@ const setfilesCommand = define({
|
|
|
1164
1425
|
consola.error("At least one file path is required");
|
|
1165
1426
|
process.exit(1);
|
|
1166
1427
|
}
|
|
1167
|
-
const files = absFiles$
|
|
1428
|
+
const files = absFiles$2(paths);
|
|
1168
1429
|
const r = await setFilesByRef(await resolveExistingTargetId(targetOpts(ctx.values)), ref, files);
|
|
1169
1430
|
consola.success(`set ${r.files.length} file(s) on ${ref} <${r.tag} type=${r.type}>:`);
|
|
1170
1431
|
for (const f of r.files) process.stdout.write(f + "\n");
|
|
@@ -1173,7 +1434,7 @@ const setfilesCommand = define({
|
|
|
1173
1434
|
//#endregion
|
|
1174
1435
|
//#region src/commands/upload.ts
|
|
1175
1436
|
/** Resolve each path to absolute and verify it's an existing file. */
|
|
1176
|
-
function absFiles(paths) {
|
|
1437
|
+
function absFiles$1(paths) {
|
|
1177
1438
|
return paths.map((p) => {
|
|
1178
1439
|
const abs = resolve(p);
|
|
1179
1440
|
if (!existsSync(abs) || !statSync(abs).isFile()) {
|
|
@@ -1216,7 +1477,7 @@ const uploadCommand = define({
|
|
|
1216
1477
|
consola.error("At least one file path is required");
|
|
1217
1478
|
process.exit(1);
|
|
1218
1479
|
}
|
|
1219
|
-
const files = absFiles(paths);
|
|
1480
|
+
const files = absFiles$1(paths);
|
|
1220
1481
|
const r = await uploadViaChooser(await resolveExistingTargetId(targetOpts(ctx.values)), click, files, ctx.values.timeout ?? 15e3);
|
|
1221
1482
|
if (r.delivered === 0) {
|
|
1222
1483
|
consola.error(`the file chooser opened (backendNodeId ${r.backendNodeId}) but the file never reached the page's change handler — the page likely replaced/destroyed the transient input before it could be set. Re-snapshot and confirm --click points at the real trigger, or try again.`);
|
|
@@ -1230,6 +1491,174 @@ const uploadCommand = define({
|
|
|
1230
1491
|
}
|
|
1231
1492
|
});
|
|
1232
1493
|
//#endregion
|
|
1494
|
+
//#region src/commands/drop.ts
|
|
1495
|
+
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
|
1496
|
+
/** Resolve each path to absolute and verify it's an existing file. */
|
|
1497
|
+
function absFiles(paths) {
|
|
1498
|
+
return paths.map((p) => {
|
|
1499
|
+
const abs = resolve(p);
|
|
1500
|
+
if (!existsSync(abs) || !statSync(abs).isFile()) {
|
|
1501
|
+
consola.error(`no such file: ${abs}`);
|
|
1502
|
+
process.exit(1);
|
|
1503
|
+
}
|
|
1504
|
+
return abs;
|
|
1505
|
+
});
|
|
1506
|
+
}
|
|
1507
|
+
/** Minimal extension→mime map for the --js path (where the page builds the File
|
|
1508
|
+
* from bytes and needs a type). The trusted CDP path doesn't need this — Chrome
|
|
1509
|
+
* reads the real file off disk and sets the type itself. */
|
|
1510
|
+
function guessMime(p) {
|
|
1511
|
+
return {
|
|
1512
|
+
".mp3": "audio/mpeg",
|
|
1513
|
+
".wav": "audio/wav",
|
|
1514
|
+
".ogg": "audio/ogg",
|
|
1515
|
+
".flac": "audio/flac",
|
|
1516
|
+
".m4a": "audio/mp4",
|
|
1517
|
+
".aac": "audio/aac",
|
|
1518
|
+
".mp4": "video/mp4",
|
|
1519
|
+
".mov": "video/quicktime",
|
|
1520
|
+
".webm": "video/webm",
|
|
1521
|
+
".png": "image/png",
|
|
1522
|
+
".jpg": "image/jpeg",
|
|
1523
|
+
".jpeg": "image/jpeg",
|
|
1524
|
+
".gif": "image/gif",
|
|
1525
|
+
".webp": "image/webp",
|
|
1526
|
+
".svg": "image/svg+xml",
|
|
1527
|
+
".pdf": "application/pdf",
|
|
1528
|
+
".zip": "application/zip",
|
|
1529
|
+
".json": "application/json",
|
|
1530
|
+
".csv": "text/csv",
|
|
1531
|
+
".txt": "text/plain"
|
|
1532
|
+
}[extname(p).toLowerCase()] || "application/octet-stream";
|
|
1533
|
+
}
|
|
1534
|
+
const dropCommand = define({
|
|
1535
|
+
name: "drop",
|
|
1536
|
+
description: "Drop local file(s) onto a drop-zone element by ref — for uploaders wired to drag-and-drop (a `drop` listener reading `e.dataTransfer.files`) rather than an <input type=file>. Default fires a genuinely-trusted CDP drag sequence (Input.dispatchDragEvent) carrying the real files from disk: brings the tab to front, waits for it to be focused+visible, waits for the target to be actionable (stable + unoccluded), then dragEnter→dragOver→drop — mirroring `click --trusted`. Use --js for a synthetic (isTrusted=false) DataTransfer drop that does NOT steal focus, for zones that accept synthetic events. For a static <input type=file> use `setfiles`; for a button that opens a file chooser use `upload`.",
|
|
1537
|
+
args: {
|
|
1538
|
+
...targetArgs,
|
|
1539
|
+
on: {
|
|
1540
|
+
type: "positional",
|
|
1541
|
+
description: "Ref of the drop-zone element (run snapshot first), e.g. e7"
|
|
1542
|
+
},
|
|
1543
|
+
files: {
|
|
1544
|
+
type: "positional",
|
|
1545
|
+
description: "One or more file paths (absolute, or resolved from cwd)"
|
|
1546
|
+
},
|
|
1547
|
+
js: {
|
|
1548
|
+
type: "boolean",
|
|
1549
|
+
description: "Dispatch a synthetic (isTrusted=false) DataTransfer drop instead of the trusted CDP path. Does not bring the tab to front (no focus steal). Injects each file's bytes into the page to build the File objects. Use for drop zones that accept synthetic events; falls short on zones that gate on isTrusted."
|
|
1550
|
+
}
|
|
1551
|
+
},
|
|
1552
|
+
async run(ctx) {
|
|
1553
|
+
const ref = ctx.positionals[1];
|
|
1554
|
+
const paths = ctx.positionals.slice(2);
|
|
1555
|
+
if (!ref || !isValidRef(ref)) {
|
|
1556
|
+
consola.error("A ref like \"e7\" is required (run `browser-automation snapshot` first)");
|
|
1557
|
+
process.exit(1);
|
|
1558
|
+
}
|
|
1559
|
+
if (paths.length === 0) {
|
|
1560
|
+
consola.error("At least one file path is required");
|
|
1561
|
+
process.exit(1);
|
|
1562
|
+
}
|
|
1563
|
+
const files = absFiles(paths);
|
|
1564
|
+
const targetId = await resolveExistingTargetId(targetOpts(ctx.values));
|
|
1565
|
+
if (ctx.values.js ?? false) {
|
|
1566
|
+
const r = await evaluate(targetId, dropExpr(ref, files.map((p) => ({
|
|
1567
|
+
name: basename(p),
|
|
1568
|
+
type: guessMime(p),
|
|
1569
|
+
b64: readFileSync(p).toString("base64")
|
|
1570
|
+
}))));
|
|
1571
|
+
if (r.err) {
|
|
1572
|
+
consola.error(r.err);
|
|
1573
|
+
process.exit(1);
|
|
1574
|
+
}
|
|
1575
|
+
consola.success(`dropped ${r.count} file(s) on ${ref} <${r.tag}> (synthetic — re-snapshot/screenshot to confirm the zone accepted them):`);
|
|
1576
|
+
for (const f of files) process.stdout.write(f + "\n");
|
|
1577
|
+
return;
|
|
1578
|
+
}
|
|
1579
|
+
const tag = await withPage(targetId, async (s) => {
|
|
1580
|
+
const evalIn = async (expr) => {
|
|
1581
|
+
const res = await s.send("Runtime.evaluate", {
|
|
1582
|
+
expression: expr,
|
|
1583
|
+
returnByValue: true,
|
|
1584
|
+
awaitPromise: true
|
|
1585
|
+
});
|
|
1586
|
+
if (res.exceptionDetails) {
|
|
1587
|
+
const e = res.exceptionDetails;
|
|
1588
|
+
throw new Error("page JS exception: " + (e.exception?.description || e.text || "unknown"));
|
|
1589
|
+
}
|
|
1590
|
+
return res.result?.value;
|
|
1591
|
+
};
|
|
1592
|
+
await forceForeground(s);
|
|
1593
|
+
const focusDeadline = Date.now() + 2e3;
|
|
1594
|
+
while (Date.now() < focusDeadline) {
|
|
1595
|
+
const f = await evalIn(`({f:document.hasFocus(),v:document.visibilityState})`);
|
|
1596
|
+
if (f && f.f && f.v === "visible") break;
|
|
1597
|
+
await sleep(50);
|
|
1598
|
+
}
|
|
1599
|
+
let prev = null;
|
|
1600
|
+
let point = null;
|
|
1601
|
+
let lastReason = "never became actionable";
|
|
1602
|
+
const actDeadline = Date.now() + 5e3;
|
|
1603
|
+
while (Date.now() < actDeadline) {
|
|
1604
|
+
const a = await evalIn(actionabilityExpr(ref));
|
|
1605
|
+
if (a?.err) {
|
|
1606
|
+
consola.error(a.err);
|
|
1607
|
+
process.exit(1);
|
|
1608
|
+
}
|
|
1609
|
+
const stable = prev !== null && Math.abs(prev.x - a.x) < .5 && Math.abs(prev.y - a.y) < .5;
|
|
1610
|
+
if (a.hit && stable) {
|
|
1611
|
+
point = {
|
|
1612
|
+
x: a.x,
|
|
1613
|
+
y: a.y,
|
|
1614
|
+
tag: a.tag
|
|
1615
|
+
};
|
|
1616
|
+
break;
|
|
1617
|
+
}
|
|
1618
|
+
lastReason = a.hit ? "position not yet stable (still animating)" : "drop-point occluded (hit-test miss)";
|
|
1619
|
+
prev = {
|
|
1620
|
+
x: a.x,
|
|
1621
|
+
y: a.y
|
|
1622
|
+
};
|
|
1623
|
+
await sleep(60);
|
|
1624
|
+
}
|
|
1625
|
+
if (!point) {
|
|
1626
|
+
consola.error(`<${ref}> not actionable for a drop: ${lastReason}`);
|
|
1627
|
+
process.exit(1);
|
|
1628
|
+
}
|
|
1629
|
+
const { x, y } = point;
|
|
1630
|
+
const data = {
|
|
1631
|
+
items: [],
|
|
1632
|
+
files,
|
|
1633
|
+
dragOperationsMask: 1
|
|
1634
|
+
};
|
|
1635
|
+
await s.send("Input.dispatchDragEvent", {
|
|
1636
|
+
type: "dragEnter",
|
|
1637
|
+
x,
|
|
1638
|
+
y,
|
|
1639
|
+
data
|
|
1640
|
+
});
|
|
1641
|
+
await s.send("Input.dispatchDragEvent", {
|
|
1642
|
+
type: "dragOver",
|
|
1643
|
+
x,
|
|
1644
|
+
y,
|
|
1645
|
+
data
|
|
1646
|
+
});
|
|
1647
|
+
await sleep(20);
|
|
1648
|
+
await s.send("Input.dispatchDragEvent", {
|
|
1649
|
+
type: "drop",
|
|
1650
|
+
x,
|
|
1651
|
+
y,
|
|
1652
|
+
data
|
|
1653
|
+
});
|
|
1654
|
+
return point.tag;
|
|
1655
|
+
});
|
|
1656
|
+
consola.success(`dropped ${files.length} file(s) on ${ref} <${tag}> (trusted):`);
|
|
1657
|
+
for (const f of files) process.stdout.write(f + "\n");
|
|
1658
|
+
consola.info("Re-snapshot or screenshot to confirm the zone accepted the drop — the DOM changed.");
|
|
1659
|
+
}
|
|
1660
|
+
});
|
|
1661
|
+
//#endregion
|
|
1233
1662
|
//#region src/core/network.ts
|
|
1234
1663
|
const INTERESTING = new Set([
|
|
1235
1664
|
"XHR",
|
|
@@ -1532,38 +1961,78 @@ function launchScriptPath() {
|
|
|
1532
1961
|
//#region src/commands/launch.ts
|
|
1533
1962
|
const launchCommand = define({
|
|
1534
1963
|
name: "launch",
|
|
1535
|
-
description: "Start (idempotent)
|
|
1536
|
-
args: {
|
|
1537
|
-
|
|
1538
|
-
|
|
1539
|
-
|
|
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
|
+
},
|
|
1540
1975
|
async run(ctx) {
|
|
1541
1976
|
const script = launchScriptPath();
|
|
1542
1977
|
if (!existsSync(script)) {
|
|
1543
1978
|
consola.error(`launch-chrome.sh not found at ${script}. Reinstall the package.`);
|
|
1544
1979
|
process.exit(1);
|
|
1545
1980
|
}
|
|
1546
|
-
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" });
|
|
1547
1987
|
process.exit(r.status ?? 1);
|
|
1548
1988
|
}
|
|
1549
1989
|
});
|
|
1550
1990
|
//#endregion
|
|
1551
1991
|
//#region src/commands/doctor.ts
|
|
1552
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
|
+
}
|
|
1553
2018
|
const doctorCommand = define({
|
|
1554
2019
|
name: "doctor",
|
|
1555
|
-
description: "Diagnose the setup: Node,
|
|
2020
|
+
description: "Diagnose the setup: Node, this user's Chrome, targets, sessions",
|
|
1556
2021
|
args: {},
|
|
1557
2022
|
async run() {
|
|
1558
2023
|
const ok = (m) => consola.log(` ✓ ${m}`);
|
|
1559
2024
|
const bad = (m) => consola.log(` ✗ ${m}`);
|
|
1560
2025
|
if (Number(process.versions.node.split(".")[0]) >= 22) ok(`Node ${process.versions.node} (global WebSocket available)`);
|
|
1561
2026
|
else bad(`Node ${process.versions.node} — need >= 22 for the global WebSocket CDP client`);
|
|
1562
|
-
consola.log(` • CDP host: ${cdpHost()}`);
|
|
2027
|
+
consola.log(` • CDP host: ${cdpHost()} (port ${cdpPort()} — derived from uid ${process.getuid?.() ?? "?"})`);
|
|
1563
2028
|
consola.log(` • Profile: ${PROFILE}`);
|
|
1564
2029
|
let version;
|
|
1565
2030
|
try {
|
|
1566
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
|
+
}
|
|
1567
2036
|
ok(`Chrome reachable: ${version.Browser}`);
|
|
1568
2037
|
} catch {
|
|
1569
2038
|
bad(`No CDP browser on ${cdpHost()} — run: browser-automation launch`);
|
|
@@ -1579,8 +2048,132 @@ const doctorCommand = define({
|
|
|
1579
2048
|
} catch {
|
|
1580
2049
|
bad("Could not enumerate targets");
|
|
1581
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
|
+
}
|
|
1582
2070
|
const sessions = listSessions();
|
|
1583
|
-
|
|
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";
|
|
2135
|
+
const sessions = listSessions();
|
|
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`);
|
|
1584
2177
|
}
|
|
1585
2178
|
});
|
|
1586
2179
|
//#endregion
|
|
@@ -1605,6 +2198,7 @@ const subCommands = new Map([
|
|
|
1605
2198
|
["download", downloadCommand],
|
|
1606
2199
|
["setfiles", setfilesCommand],
|
|
1607
2200
|
["upload", uploadCommand],
|
|
2201
|
+
["drop", dropCommand],
|
|
1608
2202
|
["network", networkCommand],
|
|
1609
2203
|
["screenshot", screenshotCommand],
|
|
1610
2204
|
["shot", screenshotCommand],
|
|
@@ -1613,7 +2207,10 @@ const subCommands = new Map([
|
|
|
1613
2207
|
["close", closeCommand],
|
|
1614
2208
|
["bind", bindCommand],
|
|
1615
2209
|
["launch", launchCommand],
|
|
1616
|
-
["doctor", doctorCommand]
|
|
2210
|
+
["doctor", doctorCommand],
|
|
2211
|
+
["gc", gcCommand],
|
|
2212
|
+
["prune", gcCommand],
|
|
2213
|
+
["port", portCommand]
|
|
1617
2214
|
]);
|
|
1618
2215
|
async function run() {
|
|
1619
2216
|
await cli(process.argv.slice(2), defaultCommand, {
|