@generativereality/browser-automation 0.4.10 → 0.4.12

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.
@@ -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.10",
4
+ "version": "0.4.12",
5
5
  "author": {
6
6
  "name": "generativereality"
7
7
  },
package/dist/index.js CHANGED
@@ -4,12 +4,12 @@ import { cli, define } from "gunshi";
4
4
  import { consola } from "consola";
5
5
  import { homedir } from "node:os";
6
6
  import { basename, dirname, extname, join, resolve } from "node:path";
7
- import { existsSync, mkdirSync, readFileSync, readdirSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
7
+ import { appendFileSync, existsSync, mkdirSync, readFileSync, readdirSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
8
8
  import { execFileSync, spawnSync } from "node:child_process";
9
9
  import { fileURLToPath } from "node:url";
10
10
  //#region package.json
11
11
  var name = "@generativereality/browser-automation";
12
- var version = "0.4.10";
12
+ var version = "0.4.12";
13
13
  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.";
14
14
  var package_default = {
15
15
  name,
@@ -29,7 +29,7 @@ var package_default = {
29
29
  "typecheck": "tsc --noEmit",
30
30
  "check": "npm run typecheck && bash scripts/check-one-port.sh && npm run build && npm test",
31
31
  "test": "node --test \"test/**/*.test.mjs\"",
32
- "release": "bumpp && npm publish",
32
+ "release": "echo 'Releases publish from CI, not here. Bump package.json + .claude-plugin/plugin.json, commit onto master, then: git tag vX.Y.Z && git push origin vX.Y.Z — then approve the gated job in GitHub Actions. `npm publish` from a laptop 404s (granular token). See .github/workflows/release.yml.' >&2; exit 1",
33
33
  "sync-plugin": "bash scripts/sync-plugin.sh",
34
34
  "prepack": "npm run build"
35
35
  },
@@ -361,21 +361,51 @@ async function forceForeground(s) {
361
361
  await s.send("Page.setWebLifecycleState", { state: "active" }).catch(() => {});
362
362
  }
363
363
  /** Run `fn` against the browser-level endpoint (Target.* commands), then close. */
364
- async function withBrowser(fn) {
365
- const s = await connect(await browserWsUrl());
364
+ async function withBrowser(fn, timeout) {
365
+ const s = await connect(await browserWsUrl(), timeout === void 0 ? void 0 : { timeout });
366
366
  try {
367
367
  return await fn(s);
368
368
  } finally {
369
369
  s.close();
370
370
  }
371
371
  }
372
- /** Create a new tab in the BACKGROUND (never steals focus) -> returns targetId. */
373
- async function createTab(url = "about:blank") {
372
+ /**
373
+ * Create a new tab in the BACKGROUND (never steals focus) -> returns targetId.
374
+ *
375
+ * `timeout` exists for the health probe. On a browser that has lost the ability
376
+ * to make renderers, `Target.createTarget` itself can hang rather than fail, so
377
+ * a caller that means to spend ~100ms deciding whether the browser works would
378
+ * otherwise sit on the default 30s — measured 2026-09-07, when this put a 30s
379
+ * stall in front of every `launch` on a wedged Chrome. Ordinary callers pass
380
+ * nothing and keep the generous default, which is right for them: a real tab
381
+ * opening slowly should still open.
382
+ */
383
+ async function createTab(url = "about:blank", { timeout } = {}) {
374
384
  return withBrowser(async (s) => {
375
385
  return (await s.send("Target.createTarget", {
376
386
  url,
377
387
  background: true
378
- })).targetId;
388
+ }, timeout)).targetId;
389
+ }, timeout);
390
+ }
391
+ /**
392
+ * Bring a target to the front of its window.
393
+ *
394
+ * **This raises the Chrome window over whatever the operator is using** —
395
+ * measured on macOS 2026-09-11, with the terminal deliberately frontmost:
396
+ * Target.activateTarget, GET /json/activate/<id>, Page.bringToFront and
397
+ * createTarget(background:false) all moved the frontmost app from the terminal
398
+ * to Google Chrome. There is no quiet variant.
399
+ *
400
+ * It is here because a backgrounded target's renderer can take 12+ seconds to
401
+ * answer while an activated one answers in ~19ms (see core/renderer-wake.ts),
402
+ * and a brief flicker beats refusing to work. Nothing calls it casually:
403
+ * `ensureRenderer` spends it only after a grace period has expired, and hands
404
+ * the window straight back.
405
+ */
406
+ async function activateTab(targetId) {
407
+ return withBrowser(async (s) => {
408
+ await s.send("Target.activateTarget", { targetId });
379
409
  });
380
410
  }
381
411
  async function closeTab(targetId) {
@@ -465,39 +495,303 @@ function normalizeUrl(input) {
465
495
  return `https://${input}`;
466
496
  }
467
497
  //#endregion
498
+ //#region src/core/renderer-wake.ts
499
+ /** How long a new tab gets to produce a renderer on its own before we wake it. */
500
+ const DEFAULT_GRACE = 2e3;
501
+ /** How long the woken tab then gets. Generous: waking is the expensive step. */
502
+ const DEFAULT_BUDGET = 1e4;
503
+ function envInt(name, fallback) {
504
+ const v = Number(process.env[name]);
505
+ return Number.isFinite(v) && v > 0 ? Math.floor(v) : fallback;
506
+ }
507
+ /**
508
+ * Ask ONE existing target's renderer to evaluate `1+1`.
509
+ *
510
+ * Deliberately not a navigation: the question is "can this renderer execute",
511
+ * which is the narrowest thing that separates a busy browser from a broken one
512
+ * without involving the network or the site.
513
+ */
514
+ async function askRenderer(targetId, timeout = 5e3) {
515
+ const started = Date.now();
516
+ const ms = () => Date.now() - started;
517
+ let ws;
518
+ try {
519
+ ws = await targetWsUrl(targetId);
520
+ } catch (e) {
521
+ return {
522
+ outcome: "error",
523
+ ms: ms(),
524
+ reason: String(e?.message ?? e)
525
+ };
526
+ }
527
+ if (!ws) return {
528
+ outcome: "gone",
529
+ ms: ms(),
530
+ reason: "the target vanished before we could attach to it"
531
+ };
532
+ let session;
533
+ try {
534
+ session = await connect(ws, { timeout });
535
+ } catch (e) {
536
+ const msg = String(e?.message ?? e);
537
+ return /timed out|timeout|WebSocket error/i.test(msg) ? {
538
+ outcome: "unattachable",
539
+ ms: ms(),
540
+ reason: `the target is listed, but its CDP connection would not open within ${timeout}ms (${msg})`
541
+ } : {
542
+ outcome: "error",
543
+ ms: ms(),
544
+ reason: msg
545
+ };
546
+ }
547
+ try {
548
+ const value = (await session.send("Runtime.evaluate", {
549
+ expression: "1+1",
550
+ returnByValue: true
551
+ }, timeout))?.result?.value;
552
+ if (value === 2) return {
553
+ outcome: "ok",
554
+ ms: ms()
555
+ };
556
+ return {
557
+ outcome: "wrong-answer",
558
+ ms: ms(),
559
+ reason: `the renderer answered with ${JSON.stringify(value)} instead of 2`
560
+ };
561
+ } catch (e) {
562
+ const msg = String(e?.message ?? e);
563
+ return /timed out|timeout/i.test(msg) ? {
564
+ outcome: "silent",
565
+ ms: ms(),
566
+ reason: `attached to the target, but its renderer did not answer within ${timeout}ms`
567
+ } : {
568
+ outcome: "error",
569
+ ms: ms(),
570
+ reason: msg
571
+ };
572
+ } finally {
573
+ session.close();
574
+ }
575
+ }
576
+ /**
577
+ * The macOS app currently in front, as a bundle path we can hand focus back to.
578
+ *
579
+ * `lsappinfo`, not AppleScript: `tell application "System Events" to get name
580
+ * of first application process whose frontmost is true` needs Accessibility
581
+ * permission, and a permission dialog appearing in the middle of an automated
582
+ * command is worse than the focus steal it is trying to undo. `lsappinfo` needs
583
+ * nothing and is present on every macOS.
584
+ */
585
+ function frontmostApp() {
586
+ if (process.platform !== "darwin") return null;
587
+ try {
588
+ const asn = execFileSync("lsappinfo", ["front"], {
589
+ encoding: "utf8",
590
+ stdio: [
591
+ "ignore",
592
+ "pipe",
593
+ "ignore"
594
+ ]
595
+ }).trim();
596
+ if (!asn) return null;
597
+ const info = execFileSync("lsappinfo", [
598
+ "info",
599
+ "-only",
600
+ "bundlepath",
601
+ asn
602
+ ], {
603
+ encoding: "utf8",
604
+ stdio: [
605
+ "ignore",
606
+ "pipe",
607
+ "ignore"
608
+ ]
609
+ });
610
+ return /"LSBundlePath"="([^"]+)"/.exec(info)?.[1] ?? null;
611
+ } catch {
612
+ return null;
613
+ }
614
+ }
615
+ /** Put the operator's app back in front. Best effort, and never fatal. */
616
+ function raiseApp(bundlePath) {
617
+ if (!bundlePath || process.platform !== "darwin") return;
618
+ if (/Google Chrome\.app|Chromium\.app/.test(bundlePath)) return;
619
+ try {
620
+ execFileSync("open", ["-a", bundlePath], { stdio: "ignore" });
621
+ } catch {}
622
+ }
623
+ /**
624
+ * Which tab the operator is looking at, so it can be put back afterwards.
625
+ *
626
+ * Chrome lists page targets most-recently-active first. That is an observation,
627
+ * not a documented guarantee — it held in every trial here, and when it is
628
+ * wrong the cost is that the window comes back to a different tab of the
629
+ * automation browser, not a failure.
630
+ */
631
+ async function activePageId() {
632
+ try {
633
+ return (await listPageTargets())[0]?.id;
634
+ } catch {
635
+ return;
636
+ }
637
+ }
638
+ /**
639
+ * Make sure `targetId` has a renderer that answers — cheaply if possible.
640
+ *
641
+ * Grace period first (the common case: no focus is taken at all), then one
642
+ * wake, then the verdict. `allowWake: false` (or BROWSER_AUTOMATION_NO_WAKE=1)
643
+ * keeps the window untouched for callers who would rather fail than flicker.
644
+ */
645
+ async function ensureRenderer(targetId, { grace, budget, allowWake = !process.env.BROWSER_AUTOMATION_NO_WAKE } = {}) {
646
+ const graceMs = grace ?? envInt("BROWSER_AUTOMATION_RENDERER_GRACE", DEFAULT_GRACE);
647
+ const budgetMs = budget ?? envInt("BROWSER_AUTOMATION_RENDERER_BUDGET", DEFAULT_BUDGET);
648
+ const started = Date.now();
649
+ const first = await askRenderer(targetId, graceMs);
650
+ if (first.outcome === "ok") return {
651
+ ...first,
652
+ ok: true,
653
+ woke: false,
654
+ ms: Date.now() - started
655
+ };
656
+ if (!allowWake || first.outcome !== "silent" && first.outcome !== "unattachable") return {
657
+ ...first,
658
+ ok: false,
659
+ woke: false,
660
+ ms: Date.now() - started
661
+ };
662
+ const previousApp = frontmostApp();
663
+ const previousTab = await activePageId();
664
+ try {
665
+ await activateTab(targetId);
666
+ } catch (e) {
667
+ return {
668
+ ...first,
669
+ ok: false,
670
+ woke: false,
671
+ ms: Date.now() - started,
672
+ reason: `${first.reason}; and it could not be activated either (${e?.message ?? e})`
673
+ };
674
+ }
675
+ const second = await askRenderer(targetId, budgetMs);
676
+ if (previousTab && previousTab !== targetId) await activateTab(previousTab).catch(() => {});
677
+ raiseApp(previousApp);
678
+ return {
679
+ ...second,
680
+ ok: second.outcome === "ok",
681
+ woke: true,
682
+ ms: Date.now() - started
683
+ };
684
+ }
685
+ //#endregion
468
686
  //#region src/core/renderer-health.ts
687
+ /** First attempt's budget. Later attempts double it. */
688
+ const DEFAULT_TIMEOUT = 5e3;
689
+ /** How many times we ask before we are willing to call a browser broken. */
690
+ const DEFAULT_ATTEMPTS = 3;
691
+ /** Breathing room between attempts — a browser mid-GC deserves a second look. */
692
+ const RETRY_PAUSE = 400;
693
+ /**
694
+ * The verdict, from the probe and the corroborations — and from nothing else.
695
+ *
696
+ * Pure, and separate from the probing, because this is the decision that was
697
+ * wrong: every failure used to become 'wedged' by default. Now 'wedged'
698
+ * requires `rendezvous === false`, which is the only thing that has ever
699
+ * actually meant it.
700
+ */
701
+ function rendererVerdict(outcome, e) {
702
+ if (outcome === "ok") return "healthy";
703
+ if (e?.rendezvous === false) return "wedged";
704
+ if (e?.rendezvous === true && (e.renderers ?? 0) > 0) return "busy";
705
+ return "unknown";
706
+ }
469
707
  /**
470
708
  * Create a throwaway tab, make its renderer prove it is alive, close it.
471
709
  *
472
- * Deliberately uses `about:blank` and `Runtime.evaluate`, not a navigation:
473
- * we are asking "can a new renderer exist and execute", which is the narrowest
474
- * question that separates a wedged browser from a slow network or a hostile
475
- * site. Nothing here touches the caller's tabs.
710
+ * Three things changed after 2026-09-11, and each of them is load-bearing:
711
+ *
712
+ * 1. It goes through `ensureRenderer`, so the probe opens its tab the way the
713
+ * tool opens tabs AND gets the same wake treatment. A probe that is harsher
714
+ * on itself than `goto` is on a real tab reports failures `goto` would not
715
+ * have had.
716
+ * 2. It retries with a doubling budget. One 5s timeout is not evidence of a
717
+ * permanent condition; it is evidence of 5 seconds.
718
+ * 3. It stops early when the Mach name is ABSENT — the one state where more
719
+ * waiting is genuinely pointless — so the real failure is still reported
720
+ * fast while a slow browser gets the benefit of the doubt.
476
721
  */
477
- async function probeRenderer({ timeout = 5e3 } = {}) {
722
+ async function probeRenderer({ timeout, attempts } = {}) {
723
+ const base = timeout ?? envInt("BROWSER_AUTOMATION_PROBE_TIMEOUT", DEFAULT_TIMEOUT);
724
+ const maxAttempts = Math.max(1, attempts ?? envInt("BROWSER_AUTOMATION_PROBE_ATTEMPTS", DEFAULT_ATTEMPTS));
478
725
  const started = Date.now();
479
726
  let pageTargets = 0;
480
727
  try {
481
728
  pageTargets = (await listPageTargets()).length;
482
729
  } catch {}
730
+ const tries = [];
731
+ let evidence;
732
+ for (let i = 0; i < maxAttempts; i++) {
733
+ const budget = base * 2 ** i;
734
+ tries.push(await probeOnce(budget));
735
+ if (tries[tries.length - 1].outcome === "ok") return finish({
736
+ ok: true,
737
+ started,
738
+ pageTargets,
739
+ tries,
740
+ evidence
741
+ });
742
+ evidence ??= gatherEvidence();
743
+ if (evidence.rendezvous === false) break;
744
+ if (i + 1 < maxAttempts) await new Promise((r) => setTimeout(r, RETRY_PAUSE));
745
+ }
746
+ return finish({
747
+ ok: false,
748
+ started,
749
+ pageTargets,
750
+ tries,
751
+ evidence
752
+ });
753
+ }
754
+ function finish({ ok, started, pageTargets, tries, evidence }) {
755
+ const last = tries[tries.length - 1];
756
+ const health = {
757
+ ok,
758
+ ms: Date.now() - started,
759
+ pageTargets,
760
+ reason: last?.reason,
761
+ outcome: last?.outcome ?? "error",
762
+ verdict: rendererVerdict(last?.outcome ?? "error", evidence),
763
+ attempts: tries,
764
+ evidence
765
+ };
766
+ recordProbe(health);
767
+ return health;
768
+ }
769
+ /** One create -> ensure -> close cycle. */
770
+ async function probeOnce(budget) {
771
+ const started = Date.now();
483
772
  let targetId;
484
773
  try {
485
- targetId = await createTab("about:blank");
774
+ targetId = await createTab("about:blank", { timeout: budget });
486
775
  } catch (e) {
487
776
  return {
488
- ok: false,
777
+ outcome: "error",
778
+ budget,
489
779
  ms: Date.now() - started,
490
- pageTargets,
780
+ woke: false,
491
781
  reason: `could not create a target at all: ${e?.message ?? e}`
492
782
  };
493
783
  }
494
784
  try {
495
- const reason = await renderersAnswer(targetId, timeout);
785
+ const r = await ensureRenderer(targetId, {
786
+ grace: budget,
787
+ budget
788
+ });
496
789
  return {
497
- ok: reason === null,
790
+ outcome: r.outcome,
791
+ budget,
498
792
  ms: Date.now() - started,
499
- pageTargets,
500
- reason: reason ?? void 0
793
+ woke: r.woke,
794
+ reason: r.reason
501
795
  };
502
796
  } finally {
503
797
  if (targetId) await closeTab(targetId).catch(() => {});
@@ -506,68 +800,83 @@ async function probeRenderer({ timeout = 5e3 } = {}) {
506
800
  /**
507
801
  * Ask an EXISTING target's renderer to prove it is alive.
508
802
  *
509
- * Returns null when it answers correctly, or a human-readable reason when it
510
- * does not. Used both by the throwaway probe and by `new`, which has just
511
- * created a tab and should check that one rather than manufacture a second.
803
+ * Kept returning `string | null` because that is what `gc` wants (a reason to
804
+ * print beside a tab it is about to close). New callers should prefer
805
+ * `askRenderer`, which says WHICH failure it was.
512
806
  */
513
- async function renderersAnswer(targetId, timeout = 5e3) {
514
- try {
515
- const ws = await targetWsUrl(targetId);
516
- if (!ws) return "the target vanished immediately";
517
- const s = await connect(ws, { timeout });
518
- try {
519
- const value = (await s.send("Runtime.evaluate", {
520
- expression: "1+1",
521
- returnByValue: true
522
- }, timeout))?.result?.value;
523
- return value === 2 ? null : `the renderer answered with ${JSON.stringify(value)} instead of 2`;
524
- } finally {
525
- s.close();
526
- }
527
- } catch (e) {
528
- const msg = String(e?.message ?? e);
529
- return /timed out|timeout/i.test(msg) ? "the target exists, but no renderer ever answered it" : msg;
530
- }
807
+ async function renderersAnswer(targetId, timeout = DEFAULT_TIMEOUT) {
808
+ const r = await askRenderer(targetId, timeout);
809
+ return r.outcome === "ok" ? null : r.reason ?? r.outcome;
531
810
  }
532
811
  /**
533
812
  * The port we are actually talking to.
534
813
  *
535
814
  * NOT always `cdpPort()`: `BROWSER_AUTOMATION_CDP` points the CLI at an
536
- * arbitrary host:port, and everything here that shells out to `pgrep` or
537
- * `launchctl` has to ask about THAT browser. Using the uid-derived port
538
- * instead finds the user's default Chrome and cheerfully reports its health
539
- * as if it were the one being driven — caught while testing this module
540
- * against a second Chrome, where a perfectly healthy browser was accused of
541
- * having lost the bootstrap name that in fact belonged to a different pid.
815
+ * arbitrary host:port, and everything here that shells out to `ps` or
816
+ * `launchctl` has to ask about THAT browser. Using the uid-derived port instead
817
+ * finds the user's default Chrome and cheerfully reports its health as if it
818
+ * were the one being driven — caught while testing this module against a second
819
+ * Chrome, where a perfectly healthy browser was accused of having lost a
820
+ * bootstrap name that in fact belonged to a different pid.
542
821
  */
543
822
  function targetPort() {
544
823
  const explicit = process.env.BROWSER_AUTOMATION_CDP;
545
- if (explicit) {
824
+ if (explicit) try {
546
825
  const p = Number(new URL(explicit).port);
547
826
  if (Number.isInteger(p) && p > 0) return p;
548
- }
827
+ } catch {}
549
828
  return cdpPort();
550
829
  }
551
- /** The pid of the browser process serving the port we are driving, if visible. */
552
- function browserPid() {
830
+ /**
831
+ * The browser process serving our port, and how many renderers it has.
832
+ *
833
+ * One `ps`, not one `pgrep` plus one `ps` per hit: on a Chrome with 40 children
834
+ * that was 41 forks to answer two questions, and it ran on the error path of a
835
+ * browser already thought to be struggling.
836
+ *
837
+ * The executable check is not decoration. Matching on the command line alone
838
+ * (as `pgrep -f` does) hits any process that merely CONTAINS the debugging-port
839
+ * flag — the `grep` looking for it, or a shell running `browser-automation`
840
+ * with the flag as an argument. One of those, having no `--type=`, would have
841
+ * been reported as the browser pid, and its absent Mach name read as the
842
+ * permanent failure. Seen while writing this: a `ugrep` for the flag sat in
843
+ * `ps` output alongside the real Chrome.
844
+ */
845
+ function chromeProcesses() {
846
+ const flag = `--remote-debugging-port=${targetPort()}`;
847
+ const uid = String(process.getuid?.() ?? -1);
848
+ let out;
553
849
  try {
554
- const out = execFileSync("pgrep", [
555
- "-u",
556
- String(process.getuid?.() ?? -1),
557
- "-f",
558
- "--",
559
- `--remote-debugging-port=${targetPort()}`
560
- ], { encoding: "utf8" });
561
- for (const pid of out.split("\n").map((s) => s.trim()).filter(Boolean)) try {
562
- if (!execFileSync("ps", [
563
- "-o",
564
- "command=",
565
- "-p",
566
- pid
567
- ], { encoding: "utf8" }).includes("--type=")) return Number(pid);
568
- } catch {}
569
- } catch {}
570
- return null;
850
+ out = execFileSync("ps", ["-Ao", "pid=,uid=,command="], {
851
+ encoding: "utf8",
852
+ maxBuffer: 64 * 1024 * 1024,
853
+ stdio: [
854
+ "ignore",
855
+ "pipe",
856
+ "ignore"
857
+ ]
858
+ });
859
+ } catch {
860
+ return {
861
+ browser: null,
862
+ renderers: null
863
+ };
864
+ }
865
+ let browser = null;
866
+ let renderers = 0;
867
+ for (const line of out.split("\n")) {
868
+ const m = /^\s*(\d+)\s+(\d+)\s+(.*)$/.exec(line);
869
+ if (!m) continue;
870
+ const [, pid, u, cmd] = m;
871
+ if (u !== uid || !cmd.includes(flag)) continue;
872
+ if (!/chrome|chromium|brave|msedge|thorium/i.test(cmd.split(" --")[0])) continue;
873
+ if (/--type=renderer\b/.test(cmd)) renderers++;
874
+ else if (!cmd.includes("--type=")) browser = Number(pid);
875
+ }
876
+ return {
877
+ browser,
878
+ renderers
879
+ };
571
880
  }
572
881
  /**
573
882
  * macOS only: is the browser's Mach port rendezvous service still registered?
@@ -575,7 +884,7 @@ function browserPid() {
575
884
  * This is the ROOT CAUSE signal, not a symptom — when it is missing, every
576
885
  * child process Chrome launches kills itself on startup. Returns null when we
577
886
  * cannot tell (not macOS, `launchctl` unavailable, pid unknown), which is
578
- * different from `false` and must not be reported as a fault.
887
+ * different from `false` and must never be reported as a fault.
579
888
  */
580
889
  function rendezvousRegistered(pid) {
581
890
  if (process.platform !== "darwin" || !pid) return null;
@@ -593,51 +902,143 @@ function rendezvousRegistered(pid) {
593
902
  return null;
594
903
  }
595
904
  }
905
+ /** Both corroborations, in one pass. Cheap enough to run on every failure. */
906
+ function gatherEvidence() {
907
+ const { browser, renderers } = chromeProcesses();
908
+ return {
909
+ pid: browser,
910
+ renderers: browser === null ? null : renderers,
911
+ rendezvous: rendezvousRegistered(browser)
912
+ };
913
+ }
596
914
  /** Where `launch` writes Chrome's stdout/stderr — Chrome logs the real reason there. */
597
915
  function chromeLogPath() {
598
916
  const tmp = process.env.TMPDIR?.replace(/\/$/, "") || "/tmp";
599
917
  return process.env.BROWSER_AUTOMATION_LOG || `${tmp}/chrome-${targetPort()}.log`;
600
918
  }
919
+ function probeLogPath() {
920
+ return process.env.BROWSER_AUTOMATION_PROBE_LOG || join(homedir(), ".browser-automation", "renderer-probes.jsonl");
921
+ }
922
+ function recordProbe(h) {
923
+ const line = JSON.stringify({
924
+ t: (/* @__PURE__ */ new Date()).toISOString(),
925
+ ok: h.ok,
926
+ verdict: h.verdict,
927
+ outcome: h.outcome,
928
+ ms: h.ms,
929
+ attempts: h.attempts.map((a) => ({
930
+ outcome: a.outcome,
931
+ ms: a.ms,
932
+ budget: a.budget,
933
+ woke: a.woke
934
+ })),
935
+ pageTargets: h.pageTargets,
936
+ evidence: h.evidence
937
+ });
938
+ try {
939
+ const path = probeLogPath();
940
+ mkdirSync(join(path, ".."), { recursive: true });
941
+ try {
942
+ if (statSync(path).size > 256 * 1024) {
943
+ const kept = readFileSync(path, "utf8").split("\n").slice(-500).join("\n");
944
+ writeFileSync(path, kept.endsWith("\n") ? kept : kept + "\n");
945
+ }
946
+ } catch {}
947
+ appendFileSync(path, line + "\n");
948
+ } catch {}
949
+ }
950
+ /** Recent probe timings, for `doctor`. Returns null when there is no history. */
951
+ function recentProbeStats(limit = 50) {
952
+ try {
953
+ const rows = readFileSync(probeLogPath(), "utf8").trim().split("\n").slice(-limit).map((l) => {
954
+ try {
955
+ return JSON.parse(l);
956
+ } catch {
957
+ return null;
958
+ }
959
+ }).filter(Boolean);
960
+ if (!rows.length) return null;
961
+ const okMs = rows.filter((r) => r.ok).map((r) => r.ms).sort((a, b) => a - b);
962
+ return {
963
+ n: rows.length,
964
+ failures: rows.filter((r) => !r.ok).length,
965
+ median: okMs.length ? okMs[Math.floor(okMs.length / 2)] : -1,
966
+ worst: okMs.length ? okMs[okMs.length - 1] : -1
967
+ };
968
+ } catch {
969
+ return null;
970
+ }
971
+ }
972
+ function evidenceLines(e) {
973
+ if (!e) return [];
974
+ const mach = e.rendezvous === true ? `registered for pid ${e.pid} — the permanent failure's signature is ABSENT` : e.rendezvous === false ? `NOT REGISTERED for pid ${e.pid} — this is the permanent failure` : `could not check (${e.pid ? `pid ${e.pid}, ` : "browser pid unknown, "}not macOS or launchctl unavailable)`;
975
+ const rend = e.renderers === null ? `could not count` : `${e.renderers} live renderer process(es) for this browser`;
976
+ return [` mach service: ${mach}`, ` renderers: ${rend}`];
977
+ }
978
+ /** The cheap recovery. Always printed, always before anything expensive. */
979
+ function cheapRecovery() {
980
+ return [
981
+ `Try these first, cheapest first:`,
982
+ ``,
983
+ ` 1. Run the command again. A new tab's renderer has been measured taking`,
984
+ ` 12s and more on a loaded machine, and it is not broken, only late.`,
985
+ ` 2. Use a tab that already works. An existing tab navigates same-origin`,
986
+ ` without needing a new renderer, so it keeps working throughout:`,
987
+ ` browser-automation list`,
988
+ ` browser-automation eval -t <id> "location.href='<url>'"`,
989
+ ` 3. browser-automation doctor — re-measures, and prints recent probe times.`
990
+ ];
991
+ }
601
992
  /**
602
993
  * A ready-to-print explanation of a renderer failure, with the recovery.
603
994
  *
604
995
  * Written to be read by somebody who has just been told a site blocks them, so
605
- * it says what is and is not true before it says what to do.
996
+ * it says what is and is not true before it says what to do — and it says only
997
+ * what was actually established. The four verdicts get four different endings
998
+ * because they need four different actions, and exactly one of them is worth
999
+ * anybody's tabs.
606
1000
  */
607
1001
  function explainRendererFailure(h) {
608
- const pid = browserPid();
609
- const rendezvous = rendezvousRegistered(pid);
1002
+ const e = h.evidence ?? gatherEvidence();
1003
+ const verdict = h.verdict ?? rendererVerdict(h.outcome, e);
1004
+ const tried = h.attempts?.length ?? 1;
1005
+ const longest = h.attempts?.length ? Math.max(...h.attempts.map((a) => a.budget)) : 0;
1006
+ const woke = h.attempts?.some((a) => a.woke);
610
1007
  const lines = [
611
- `Chrome cannot give a new tab a working renderer.`,
1008
+ `Chrome did not give a new tab a working renderer.`,
612
1009
  ``,
613
- ` probe: created a target, ${h.reason ?? "no renderer answered"} (${h.ms}ms)`,
614
- ` page targets: ${h.pageTargets} (context only — this is NOT the cause; a healthy`,
615
- ` Chrome has been driven to 421 tabs with every renderer alive)`
1010
+ ` probe: ${tried} attempt(s), longest budget ${longest}ms, ${h.ms}ms total`,
1011
+ ` ${h.reason ?? "no renderer answered"}`,
1012
+ ...woke ? [` (it was also activated to force a renderer, and still did not answer)`] : [],
1013
+ ` page targets: ${h.pageTargets} (context only — NOT the cause; a healthy Chrome has`,
1014
+ ` been driven to 421 tabs with every renderer alive)`,
1015
+ ...evidenceLines(e),
1016
+ ``
616
1017
  ];
617
- 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.`);
618
- 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()}`);
619
- 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.`);
1018
+ if (verdict === "wedged") lines.push(`VERDICT: this browser process can never make a renderer again.`, ``, `Chrome registers "com.google.Chrome.MachPortRendezvousServer.${e.pid}" once, at`, `startup, and every child process looks that name up to receive its shared`, `memory. The name is gone, so every renderer Chrome launches from now on exits`, `within milliseconds. Nothing re-registers it, and closing tabs does not help.`, ``, `This is NOT the site blocking automation. Two tells: same-origin navigations in`, `tabs that already work keep working (they reuse a renderer that exists), and`, `cross-origin ones fail with ERR_ABORTED (site isolation needs a new renderer).`, ``, ...cheapRecovery(), ``, `Only then, and only because the signature above is confirmed present, a restart`, `is the real fix:`, ``, ` browser-automation launch --restart # closes ALL tabs, for EVERY session`, ``, `Other sessions are driving this Chrome. Their open tabs go with it, and they`, `will not be told why — agree on it first. \`browser-automation list\` shows who`, `holds what.`);
1019
+ else if (verdict === "busy") lines.push(`VERDICT: Chrome is NOT in the permanent, restart-only state.`, ``, `Its Mach rendezvous service is registered and ${e.renderers} renderer processes are`, `alive. Both are absent in that failure, so whatever this is, a restart is not`, `the fix for it — the probe asked ${tried} times, waited up to ${longest}ms, and did not`, `get an answer. That happens on a loaded machine and it usually clears by itself.`, ``, ...cheapRecovery(), ``, `Do NOT restart Chrome on the strength of this message. \`launch --restart\` closes`, `every tab of every session sharing this browser, and the evidence above says`, `this is not the failure a restart fixes.`);
1020
+ else lines.push(`VERDICT: undiagnosed — and specifically, NOT confirmed as the permanent failure.`, ``, `The probe failed, but the signature of the restart-only condition (an ABSENT`, `Mach rendezvous service) could not be confirmed, so this may equally be a slow`, `or heavily loaded browser. Those need opposite responses, and guessing wrong`, `costs every session on this browser its tabs.`, ``, ...cheapRecovery(), ``, `If it keeps failing, get the corroboration before doing anything drastic:`, ``, ` browser-automation doctor`, ` tail -50 ${chromeLogPath()}`, ``, `A \`doctor\` that reports the Mach service ABSENT is the permanent failure, and`, `only that justifies \`launch --restart\` — which closes every tab for every`, `session sharing this Chrome.`);
620
1021
  return lines.join("\n");
621
1022
  }
622
1023
  /**
623
- * Does this error look like it could be the renderer wedge rather than the site?
1024
+ * Does this error look like it could be a renderer failure rather than the site?
624
1025
  *
625
- * Kept deliberately narrow. These three are the ONLY shapes the failure takes
626
- * through the CLI, and each of them has an innocent explanation too — so a hit
627
- * here buys a probe, never a conclusion.
1026
+ * Kept deliberately narrow. These are the ONLY shapes the failure takes through
1027
+ * the CLI, and each of them has an innocent explanation too — so a hit here
1028
+ * buys a probe, never a conclusion.
628
1029
  */
629
1030
  function mayBeRendererFailure(err) {
630
1031
  const m = String(err?.message ?? err);
631
- 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);
1032
+ return /Page\.enable timed out/i.test(m) || /Target\.createTarget 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);
632
1033
  }
633
1034
  /**
634
- * Run `fn`; if it fails in a way the renderer wedge could explain, spend one
1035
+ * Run `fn`; if it fails in a way a renderer failure could explain, spend one
635
1036
  * probe finding out, and re-throw with the diagnosis attached.
636
1037
  *
637
1038
  * The probe only ever runs on the error path, so the happy path pays nothing.
638
1039
  * If the probe comes back healthy the original error is re-thrown untouched —
639
- * the point is to stop misattributing a browser fault to a site, not to blame
640
- * the browser for every timeout.
1040
+ * and since the probe now retries and can wake a late renderer, "healthy" is
1041
+ * the answer a loaded browser gets, which is the September bug not happening.
641
1042
  */
642
1043
  async function withRendererDiagnosis(fn) {
643
1044
  try {
@@ -673,21 +1074,22 @@ const newCommand = define({
673
1074
  const name = ctx.values.session || defaultSessionName();
674
1075
  const url = ctx.positionals[1] ? normalizeUrl(ctx.positionals[1]) : "about:blank";
675
1076
  if (loadSession(name) && !ctx.values.force) consola.warn(`Session "${name}" already maps to a tab. Use --force to open another, or just \`browser-automation goto -s ${name} <url>\`.`);
676
- const targetId = await createTab(url);
1077
+ const targetId = await withRendererDiagnosis(() => createTab(url));
677
1078
  saveSession({
678
1079
  name,
679
1080
  targetId,
680
1081
  url,
681
1082
  createdAt: (/* @__PURE__ */ new Date()).toISOString()
682
1083
  });
683
- const dead = await renderersAnswer(targetId).catch(() => null);
684
- if (dead) {
1084
+ const r = await ensureRenderer(targetId);
1085
+ if (r.woke) consola.warn(`[${name}] the new tab's renderer did not start on its own, so the tab was activated briefly to force one. The Chrome window was raised and handed straight back.`);
1086
+ if (!r.ok) {
685
1087
  const health = await probeRenderer().catch(() => null);
686
1088
  if (health && !health.ok) {
687
1089
  consola.error(`[${name}] tab ${targetId.slice(0, 12)}… was created but has no working renderer.\n\n${explainRendererFailure(health)}`);
688
1090
  process.exit(1);
689
1091
  }
690
- 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.`);
1092
+ consola.warn(`[${name}] tab ${targetId.slice(0, 12)}… did not answer yet (${r.reason ?? r.outcome}). Chrome can still create renderers, so this is likely transient — retry the next command.`);
691
1093
  }
692
1094
  consola.success(`[${name}] opened background tab ${targetId.slice(0, 12)}… → ${url}`);
693
1095
  }
@@ -805,6 +1207,9 @@ const gotoCommand = define({
805
1207
  const target = normalizeUrl(url);
806
1208
  const opts = targetOpts(ctx.values);
807
1209
  const { targetId, created } = await withRendererDiagnosis(() => resolveOrCreateTargetId(opts));
1210
+ if (created) {
1211
+ if ((await ensureRenderer(targetId)).woke) consola.warn("The new tab's renderer did not start on its own, so the tab was activated briefly to force one. The Chrome window was raised and handed straight back.");
1212
+ }
808
1213
  await withRendererDiagnosis(() => navigate(targetId, target));
809
1214
  if (!opts.match && !opts.target) {
810
1215
  const name = opts.session || defaultSessionName();
@@ -2004,6 +2409,10 @@ const listCommand = define({
2004
2409
  type: "boolean",
2005
2410
  description: "Output raw JSON"
2006
2411
  },
2412
+ all: {
2413
+ type: "boolean",
2414
+ description: "Also list stale session bookmarks (tabs that no longer exist), instead of just counting them"
2415
+ },
2007
2416
  frames: {
2008
2417
  type: "boolean",
2009
2418
  description: "Also list cross-origin child iframes (OOPIFs) — their targetIds/URLs let you drive Stripe Elements, embedded SSO widgets, etc. via -F <substr> or -t <id>."
@@ -2022,11 +2431,15 @@ const listCommand = define({
2022
2431
  return;
2023
2432
  }
2024
2433
  const liveIds = new Set(targets.map((t) => t.id));
2025
- if (sessions.length) {
2026
- consola.log(`# sessions (${sessions.length})`);
2027
- for (const s of sessions) consola.log(` ${s.name.padEnd(16)} [${liveIds.has(s.targetId) ? "live" : "stale"}] ${s.url ?? ""}`);
2028
- consola.log("");
2029
- }
2434
+ const live = sessions.filter((s) => liveIds.has(s.targetId));
2435
+ const stale = sessions.filter((s) => !liveIds.has(s.targetId));
2436
+ const shown = ctx.values.all ? sessions : live;
2437
+ if (shown.length) {
2438
+ consola.log(`# sessions (${shown.length}${ctx.values.all ? "" : " live"})`);
2439
+ for (const s of shown) consola.log(` ${s.name.padEnd(16)} [${liveIds.has(s.targetId) ? "live" : "stale"}] ${s.url ?? ""}`);
2440
+ } else if (sessions.length) consola.log(`# sessions (0 live)`);
2441
+ if (stale.length && !ctx.values.all) consola.log(` + ${stale.length} stale bookmark(s) whose tab is gone — \`list --all\` to see them, \`gc --sessions\` to clear them`);
2442
+ if (sessions.length) consola.log("");
2030
2443
  consola.log(`# open tabs (${targets.length}) — address with -t <id> or -m <substr>`);
2031
2444
  for (const t of targets) {
2032
2445
  const owner = sessions.find((s) => s.targetId === t.id);
@@ -2129,11 +2542,11 @@ function launchScriptPath() {
2129
2542
  //#region src/commands/launch.ts
2130
2543
  const launchCommand = define({
2131
2544
  name: "launch",
2132
- description: "Start (idempotent) this user's headed Chrome with the persistent profile",
2545
+ description: "Start (idempotent) this user's headed Chrome with the persistent profile, and verify it can still make renderers",
2133
2546
  args: {
2134
2547
  status: {
2135
2548
  type: "boolean",
2136
- description: "Only report whether the CDP browser is up (exit 0/1)"
2549
+ description: "Only report whether the CDP browser is up (exit 0/1) — reachability, not health"
2137
2550
  },
2138
2551
  restart: {
2139
2552
  type: "boolean",
@@ -2152,7 +2565,25 @@ const launchCommand = define({
2152
2565
  ...ctx.values.status ? ["--status"] : [],
2153
2566
  ...ctx.values.restart ? ["--restart"] : []
2154
2567
  ]], { stdio: "inherit" });
2155
- process.exit(r.status ?? 1);
2568
+ if (r.status !== 0 || ctx.values.status) process.exit(r.status ?? 1);
2569
+ const health = await probeRenderer().catch((e) => ({
2570
+ ok: false,
2571
+ ms: 0,
2572
+ pageTargets: 0,
2573
+ reason: String(e?.message ?? e),
2574
+ outcome: "error",
2575
+ verdict: "unknown",
2576
+ attempts: []
2577
+ }));
2578
+ if (health.ok) {
2579
+ const woke = health.attempts.some((a) => a.woke);
2580
+ consola.success(`Renderer capacity: a new tab got a live renderer in ${health.ms}ms — this Chrome works.` + (woke ? " (It had to be activated to get there — this browser is slow to give background tabs a renderer.)" : ""));
2581
+ return;
2582
+ }
2583
+ consola.error(health.verdict === "wedged" ? "Chrome is up, but it can never make a renderer again — this browser is unusable.\n" : "Chrome is up, but a new tab did not get a working renderer in time.\n");
2584
+ for (const line of explainRendererFailure(health).split("\n")) consola.log(line);
2585
+ consola.log(`\nChrome's own log: ${chromeLogPath()}`);
2586
+ process.exit(1);
2156
2587
  }
2157
2588
  });
2158
2589
  //#endregion
@@ -2220,21 +2651,32 @@ const doctorCommand = define({
2220
2651
  ok: false,
2221
2652
  ms: 0,
2222
2653
  pageTargets: 0,
2223
- reason: String(e?.message ?? e)
2654
+ reason: String(e?.message ?? e),
2655
+ outcome: "error",
2656
+ verdict: "unknown",
2657
+ attempts: []
2224
2658
  }));
2225
2659
  if (health.ok) {
2660
+ const woke = health.attempts.some((a) => a.woke);
2226
2661
  ok(`Renderer capacity: a new tab got a live renderer in ${health.ms}ms`);
2227
- const pid = browserPid();
2228
- if (rendezvousRegistered(pid) === false) {
2229
- consola.log(` ⚠ but the Mach rendezvous service for pid ${pid} is NOT registered —`);
2662
+ if (woke) {
2663
+ consola.log(` ⚠ it only answered after being activated — this Chrome is slow to give`);
2664
+ consola.log(` BACKGROUND tabs a renderer (measured: median 367ms, tail past 30s).`);
2665
+ consola.log(` Commands will work; new tabs may briefly raise the Chrome window.`);
2666
+ }
2667
+ const ev = gatherEvidence();
2668
+ if (ev.rendezvous === false) {
2669
+ consola.log(` ⚠ but the Mach rendezvous service for pid ${ev.pid} is NOT registered —`);
2230
2670
  consola.log(` new renderers are expected to start failing. Restart Chrome soon:`);
2231
2671
  consola.log(` browser-automation launch --restart`);
2232
2672
  }
2233
2673
  } else {
2234
- bad(`Renderer capacity: FAILED`);
2674
+ bad(`Renderer capacity: FAILED (${health.verdict})`);
2235
2675
  for (const line of explainRendererFailure(health).split("\n")) consola.log(` ${line}`);
2236
2676
  consola.log(` Chrome's own log: ${chromeLogPath()}`);
2237
2677
  }
2678
+ const stats = recentProbeStats();
2679
+ if (stats) consola.log(` • last ${stats.n} renderer probe(s): ${stats.failures} failed` + (stats.median >= 0 ? `, median ${stats.median}ms, slowest success ${stats.worst}ms` : ""));
2238
2680
  const sessions = listSessions();
2239
2681
  let live = 0;
2240
2682
  try {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@generativereality/browser-automation",
3
- "version": "0.4.10",
3
+ "version": "0.4.12",
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 — many parallel sessions, no focus stealing, nothing long-lived to crash.",
5
5
  "type": "module",
6
6
  "bin": {
@@ -18,7 +18,7 @@
18
18
  "typecheck": "tsc --noEmit",
19
19
  "check": "npm run typecheck && bash scripts/check-one-port.sh && npm run build && npm test",
20
20
  "test": "node --test \"test/**/*.test.mjs\"",
21
- "release": "bumpp && npm publish",
21
+ "release": "echo 'Releases publish from CI, not here. Bump package.json + .claude-plugin/plugin.json, commit onto master, then: git tag vX.Y.Z && git push origin vX.Y.Z — then approve the gated job in GitHub Actions. `npm publish` from a laptop 404s (granular token). See .github/workflows/release.yml.' >&2; exit 1",
22
22
  "sync-plugin": "bash scripts/sync-plugin.sh",
23
23
  "prepack": "npm run build"
24
24
  },
@@ -11,10 +11,19 @@
11
11
  # A browser process can permanently lose the ability to launch renderers (see
12
12
  # src/core/renderer-health.ts for the mechanism). Every existing tab keeps
13
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.
14
+ # navigation ever will again. Restarting is the only recovery FROM THAT ONE
15
+ # CONDITION — and plain `launch` cannot do it, because it is idempotent by
16
+ # design and correctly reports "already running". Without an explicit flag the
17
+ # only way out was to go and kill Chrome by hand, which is how a diagnosis
18
+ # ends up unactionable.
19
+ #
20
+ # It is a flag and not an automatic step because it closes every tab of every
21
+ # session sharing this browser. That condition is confirmed by ONE thing: the
22
+ # Mach bootstrap name being absent from `launchctl print gui/$UID`. A new tab
23
+ # whose renderer is merely slow to answer looks identical and is not it — for
24
+ # three weeks it was reported as it, and restarting for it twice destroyed
25
+ # another session's unrecoverable work. `browser-automation doctor` now prints
26
+ # which of the two it is; nothing here can tell them apart.
18
27
  #
19
28
  # Why this script exists:
20
29
  # The `browser-automation` skill prefers to drive a real, persistent Chrome
@@ -133,11 +142,23 @@ if [ "$RESTART" = "1" ] && is_up; then
133
142
  sleep 1
134
143
  fi
135
144
 
145
+ # A held port is the ONLY thing this branch establishes. It is emphatically not
146
+ # a health check: a Chrome that can no longer give a new tab a renderer keeps
147
+ # serving this port, answering /json/version and listing targets, while every
148
+ # goto fails. Only a round-trip through a renderer tells the two apart, and
149
+ # that lives in the CLI (src/core/renderer-health.ts) -- `browser-automation
150
+ # launch` runs it right after this script returns and prints the real verdict.
151
+ #
152
+ # This used to print a standing "use --restart if renderers are broken" hint
153
+ # here. It was correct advice and it did not work: printed on every launch,
154
+ # directly under the words "nothing to do", it read as boilerplate rather than
155
+ # as a diagnosis, and an operator burned many minutes on 25-30s `goto`s in
156
+ # 2026-09 without it registering. Advice that is always on screen carries no
157
+ # information. The verdict now appears only when it is true.
136
158
  if is_up; then
137
- echo "Already running on :${PORT} — nothing to do."
159
+ echo "Already running on :${PORT} — the port is held."
138
160
  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)"
161
+ echo "(Port held is not health. Check it works: browser-automation doctor)"
141
162
  exit 0
142
163
  fi
143
164
 
@@ -56,12 +56,26 @@ file under `~/.browser-automation/sessions/`.
56
56
 
57
57
  ```bash
58
58
  npm install -g @generativereality/browser-automation
59
- browser-automation launch # start this user's Chrome (idempotent)
60
- browser-automation doctor # verify Node, Chrome, targets, sessions
59
+ browser-automation launch # start Chrome, and prove it can still make renderers
60
+ browser-automation doctor # verify Node, Chrome, renderer capacity, targets, sessions
61
61
  ```
62
62
 
63
- `launch` is idempotent — safe to call when Chrome is already up. Override the
64
- profile path with `BROWSER_AUTOMATION_PROFILE=...` and the CDP host with
63
+ `launch` is idempotent — safe to call when Chrome is already up. **It also
64
+ verifies the browser works**, which is a different question from whether one is
65
+ running: it ends with either
66
+
67
+ ```
68
+ ✔ Renderer capacity: a new tab got a live renderer in 47ms — this Chrome works.
69
+ ```
70
+
71
+ or a non-zero exit and the full renderer-wedge diagnosis. That matters because a
72
+ held port, a `/json/version` that answers and a `list` full of targets are all
73
+ properties of the browser **process**, and the way a long-lived Chrome dies is
74
+ that it keeps all three while losing the ability to give any new tab a
75
+ **renderer** (see Gotchas). Older CLIs printed `nothing to do.` in exactly that
76
+ state — **if your `launch` ends without a `Renderer capacity:` line, you are on
77
+ one of those; run `doctor`, which is the same probe.** Override the profile path
78
+ with `BROWSER_AUTOMATION_PROFILE=...` and the CDP host with
65
79
  `BROWSER_AUTOMATION_CDP=http://localhost:PORT` if needed.
66
80
 
67
81
  ## Commands
@@ -71,7 +85,7 @@ Page commands take a tab selector — `-s <session>` (default `$BAC_SESSION`, el
71
85
 
72
86
  | Need | Command |
73
87
  |---|---|
74
- | Start/refresh the Chrome | `browser-automation launch` |
88
+ | Start the Chrome + verify it can make renderers | `browser-automation launch` |
75
89
  | Diagnose setup (incl. renderer capacity) | `browser-automation doctor` |
76
90
  | List sessions + every open tab (id, title, url) | `browser-automation list` |
77
91
  | Open a background tab | `browser-automation new -s work [url]` |
@@ -90,7 +104,7 @@ Page commands take a tab selector — `-s <session>` (default `$BAC_SESSION`, el
90
104
  | Inspect network (find the API, headers, bodies) | `browser-automation network -m bank --reload --filter api --headers --body` |
91
105
  | Screenshot a tab | `browser-automation screenshot -m op.fi --full -o shot.png` |
92
106
  | 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` |
107
+ | Restart Chrome (LAST resort — closes ALL tabs, for EVERY session; only once `doctor` confirms the Mach name is absent) | `browser-automation launch --restart` |
94
108
  | Forget a session (tab stays open) | `browser-automation close -s work` |
95
109
  | Forget **and** close the browser tab | `browser-automation close -s work --tab` |
96
110
 
@@ -273,11 +287,49 @@ There's no `state-save`/`state-load` to manage — the profile *is* the auth sto
273
287
  isn't snapshot-interactive. After the drop, `read`/`screenshot`/`network` to
274
288
  confirm processing started, then grab the result (often a download endpoint you
275
289
  can pull with `download --url`).
290
+ - **A NEW tab's renderer can be slow rather than broken — do not restart Chrome for it.**
291
+ ⚠️ **Read this before acting on the wedge diagnosis below.** Measured 2026-09-11 on
292
+ Chrome 152.0.7977.83, time from `Target.createTarget` to the first `Runtime.evaluate`
293
+ returning, 8 trials each:
294
+
295
+ | how the target was created | median | worst |
296
+ |---|---|---|
297
+ | `background: true` (how this tool opens every tab) | 367ms | 12517ms, and >30s once |
298
+ | `background: true` + `Target.activateTarget` | 19ms | 65ms |
299
+ | `background: false` | 18ms | 22ms |
300
+
301
+ The renderer **process exists** in every arm — `ps` gains a `--type=renderer` child either
302
+ way. A background target is simply not given a renderer that answers promptly, and on a
303
+ loaded machine (this one was at load average 38) the tail runs past any budget worth
304
+ waiting. **This is not the wedge**, and a restart does nothing for it.
305
+
306
+ It cost real work to learn: for three weeks `goto` reported this as the permanent,
307
+ restart-only condition below, and `launch --restart` closes every tab of every session
308
+ sharing this Chrome. It twice destroyed unrecoverable work belonging to another session —
309
+ a finished AlternativeTo submission with hand edits, and an Azure signup flow mid-form.
310
+
311
+ **Since fixed (v0.4.12+):** `new`/`goto` wait for a late renderer and, if it still has not
312
+ answered, briefly activate the tab to force one and hand the window straight back (you get
313
+ a `WARN` saying so). The probe retries with a doubling budget, and the verdict now names
314
+ the permanent failure **only when its own signature is present**. On an older CLI, the
315
+ cheap move is to retry, or to drive a tab that already works.
316
+
317
+ **Whatever the version: before restarting anything, check the two corroborations.** Both
318
+ were decisive and neither used to be consulted:
319
+ ```bash
320
+ launchctl print "gui/$(id -u)" | grep MachPortRendezvousServer.<browser-pid>
321
+ ps -Ao command= | grep -c -- '--type=renderer'
322
+ ```
323
+ Mach name **present** + renderers **alive** ⇒ this is slowness, not the wedge. Retry, or use
324
+ a live tab. Mach name **absent** ⇒ it is the wedge, and only then is a restart the answer.
325
+
276
326
  - **"The site is blocking us" — when it is really Chrome that cannot make renderers.**
277
327
  A browser process can permanently lose the ability to launch **renderer processes** while
278
328
  looking perfectly healthy. Every tab that already exists keeps working, so nothing seems wrong
279
329
  until you open a tab or navigate somewhere new, and then the errors read as the remote site's
280
330
  doing. Diagnosed 2026-08-22; it cost an hour of blaming ferry-operator bot protection.
331
+ ⚠️ **This is a real condition and a rare one.** Confirm the Mach name is absent (above)
332
+ before you believe it — a slow background renderer produces every symptom in this list.
281
333
 
282
334
  How it shows up:
283
335
  - `browser-automation new` + `goto` → `CDP Page.enable timed out after 30000ms`, **even for
@@ -291,6 +343,26 @@ There's no `state-save`/`state-load` to manage — the profile *is* the auth sto
291
343
  right URL but an **empty title forever**; every `Runtime.evaluate` against it times out.
292
344
  `Page.captureScreenshot` returns `Internal error`. The target shell exists; the renderer does not.
293
345
 
346
+ **It gets SLOW before it fails outright — that is the early warning.** Observed 2026-09-07 on a
347
+ Chrome that had been up 12 days: every `goto` took ~25–30s, and a batch of three blew a 120s
348
+ timeout, hours before anything failed hard. That was misread as "large files, slow browser" and
349
+ worked around with longer timeouts for many minutes; the actual fix was one `launch --restart`,
350
+ after which the same pages loaded instantly and 14 `file://` tabs opened in two quick batches.
351
+ **A `goto` that has quietly become slow is this, not your page.** Raise the timeout at most once,
352
+ then run `doctor`.
353
+
354
+ **Every cheap signal stays green, so do not take any of them as health.** On that same wedged
355
+ browser: `launch` said `Already running on :9223 — nothing to do.`, `curl :9223/json/version`
356
+ answered normally, and `list` cheerfully returned 10 targets — while `goto` exited 1 and `eval`
357
+ died with `CDP Runtime.evaluate timed out after 30000ms`. Port held, HTTP endpoint answering and
358
+ targets listed are all properties of the **browser** process; the thing that is broken is its
359
+ ability to start a **renderer**, and only a probe that runs code in one can see it.
360
+ **Since fixed:** `launch` now runs that probe itself and exits non-zero with the diagnosis
361
+ instead of reporting "nothing to do", so this particular green-across-the-board trap is closed.
362
+ It still will not restart for you — that stays something you type, because the tabs are not
363
+ only yours. On a CLI old enough to lack it, `doctor` is the same probe; nothing cheaper
364
+ substitutes for either.
365
+
294
366
  **The mechanism** (macOS, from Chrome's own log at `$TMPDIR/chrome-<port>.log` — `launch --restart`
295
367
  keeps the previous browser's log as `chrome-<port>.log.prev`, which is the one you want after a
296
368
  restart):
@@ -332,18 +404,34 @@ There's no `state-save`/`state-load` to manage — the profile *is* the auth sto
332
404
  `Page.enable timed out` now arrives with the diagnosis attached instead of sending you to the
333
405
  site's bot-protection docs.
334
406
 
335
- **Recovery — only a Chrome restart clears it.** The bootstrap name is registered at startup and
336
- never re-registered, so nothing short of a new browser process helps. Closing tabs does not, and
337
- plain `launch` will not either (idempotent by design — it sees a live browser and exits happy):
338
- ```bash
339
- browser-automation launch --restart # SIGTERM (profile flushes cleanly), wait, relaunch
340
- ```
341
- It reports how many tabs it is about to close. **Those tabs belong to every parallel Claude Code
342
- session sharing this Chrome — ask Fred first, never restart unilaterally.**
407
+ **Recovery — cheapest first, and a restart only once the Mach name is confirmed absent.**
408
+
409
+ 1. **Retry.** A new tab's renderer has been measured taking 12s and more on a loaded
410
+ machine, and late is not broken.
411
+ 2. **Drive a tab that already works.** An existing tab navigates same-origin without
412
+ needing a new renderer, so it keeps working throughout even during a genuine wedge:
413
+ ```bash
414
+ browser-automation list
415
+ browser-automation eval -t <id> "location.href='<url>'"
416
+ ```
417
+ 3. **`browser-automation doctor`** — re-measures, prints the two corroborations, and shows
418
+ the recent probe-time distribution from `~/.browser-automation/renderer-probes.jsonl`.
419
+ 4. **Only if `doctor` reports the Mach rendezvous service ABSENT**, restart. The bootstrap
420
+ name is registered at startup and never re-registered, so nothing short of a new browser
421
+ process helps; closing tabs does not, and plain `launch` will not either (idempotent by
422
+ design — it sees a live browser and exits happy):
423
+ ```bash
424
+ browser-automation launch --restart # SIGTERM (profile flushes cleanly), wait, relaunch
425
+ ```
426
+ It reports how many tabs it is about to close. **Those tabs belong to every parallel
427
+ Claude Code session sharing this Chrome — ask Fred first, never restart unilaterally.**
343
428
 
344
429
  **Housekeeping is a different problem** — `browser-automation gc` prunes stale session bookmarks
345
430
  (they are never cleaned up otherwise; this machine had accumulated 234, only 5 of them live) and
346
- closes tabs whose renderer does not answer. Use `--dry` first. It is genuinely useful, but it is
431
+ closes tabs whose renderer does not answer. Use `--dry` first. `list` now counts stale
432
+ bookmarks instead of printing them (`list --all` to see them) — 105 stale lines above a
433
+ 24-tab Chrome is how "there are a hundred tabs open" became the leading theory for a
434
+ renderer failure that has nothing to do with tab count. It is genuinely useful, but it is
347
435
  **not** a fix for the wedge above, and it never closes a working tab unless you pass `--orphans`
348
436
  — tabs get addressed by `-m` and opened by hand, so "no session claims it" is not evidence that
349
437
  nobody wants it.
@@ -354,6 +442,41 @@ There's no `state-save`/`state-load` to manage — the profile *is* the auth sto
354
442
  is a completely different client. Check the browser first: if `doctor` says renderer capacity is
355
443
  fine and a boring cross-origin URL loads, *then* start suspecting the site.
356
444
 
445
+ - **A backgrounded tab may never paint at all — and `read`/`snapshot` will not tell you.** Distinct
446
+ from "still loading": `document.readyState` reaches `complete`, but the SPA never renders, so
447
+ `read` returns a stale shell (e.g. a bare "Loading") and `snapshot` lists none of the real
448
+ controls. The trap is that this looks exactly like *the page does not have that element*, and you
449
+ will go hunting for a different selector or conclude the flow changed. Measured 2026-09-02 on
450
+ Google's `accounts.google.com/v3/signin/challenge/pwd`: `readyState: "complete"`,
451
+ `body.innerText.length: 202` frozen on the previous step's text, and the password field present in
452
+ the DOM but `offsetParent === null` for as long as the tab stayed backgrounded.
453
+ **Diagnose** before changing your selector:
454
+ ```bash
455
+ browser-automation eval -s x '({ready:document.readyState,vis:document.visibilityState,len:document.body.innerText.length})'
456
+ ```
457
+ `visibilityState: "hidden"` with a **stuck `len`** is this, not a selector problem. Note the
458
+ stuck `len` is the whole tell: `hidden` on its own is the normal, healthy state of every
459
+ backgrounded tab — verified 2026-09-07, a background tab reporting `hidden` returned its real
460
+ painted text — so never read `hidden` alone as a diagnosis.
461
+ **Fix:** front the tab. There is no `activate` command — a `click --trusted` on any harmless
462
+ element (a wrapper `div` from the snapshot works; avoid submit buttons and links) brings the tab
463
+ to front and waits for it to be visible, and the page paints immediately. Same root cause as the
464
+ WebAuthn note above, different symptom: that one refuses, this one silently never renders.
465
+
466
+ **Do not confuse this with the renderer wedge above.** Both present to an operator as "the page
467
+ isn't there, but every tool says fine", and the fixes are opposite — one is a per-tab nudge, the
468
+ other closes every tab in the browser. What separates them:
469
+
470
+ | | backgrounded tab never paints | Chrome cannot make renderers |
471
+ |---|---|---|
472
+ | `goto` | succeeds, rc=0 (may be slow) | **rc=1**, or `Page.enable timed out` |
473
+ | `eval` | works, returns a result | **`Runtime.evaluate` times out at 30000ms** |
474
+ | scope | that one tab | **every** new tab / cross-origin nav |
475
+ | `doctor` | `✓ Renderer capacity` | names the wedge + pid |
476
+ | fix | `click --trusted` on the tab | `launch --restart` (**ask first**) |
477
+
478
+ `eval` is the fast discriminator: if it answers at all, the renderer is alive and you are in the
479
+ painting case. If it times out, stop poking the page and run `doctor`.
357
480
  - **Page still loading.** `goto` waits for the load event, but SPAs render after.
358
481
  If a `read`/`snapshot` looks empty, re-run after a moment, or snapshot again
359
482
  once a known element should be present.