@generativereality/browser-automation 0.4.11 → 0.4.13

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/dist/index.js CHANGED
@@ -1,15 +1,15 @@
1
1
  #!/usr/bin/env node
2
2
  import updateNotifier from "update-notifier";
3
3
  import { cli, define } from "gunshi";
4
- import { consola } from "consola";
4
+ import consola, { consola as consola$1 } 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.11";
12
+ var version = "0.4.13";
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,
@@ -388,6 +388,26 @@ async function createTab(url = "about:blank", { timeout } = {}) {
388
388
  }, timeout)).targetId;
389
389
  }, timeout);
390
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 });
409
+ });
410
+ }
391
411
  async function closeTab(targetId) {
392
412
  return withBrowser(async (s) => {
393
413
  return !!(await s.send("Target.closeTarget", { targetId })).success;
@@ -433,13 +453,37 @@ async function captureScreenshot(targetId, { fullPage = false } = {}) {
433
453
  });
434
454
  }
435
455
  /** Navigate a page target and wait for load (or timeout). */
436
- async function navigate(targetId, url, { timeout = 3e4 } = {}) {
456
+ /**
457
+ * How long to wait for a page's load event before giving up on confirming it.
458
+ *
459
+ * Read from the environment so the suite can exercise the give-up path without
460
+ * spending 30 real seconds on it. Deliberately NOT used by the test that checks
461
+ * a prompt exit: shrinking the timeout there would shrink the leak it exists to
462
+ * catch, and it would pass against the bug.
463
+ */
464
+ function navTimeout() {
465
+ const v = Number(process.env.BROWSER_AUTOMATION_NAV_TIMEOUT);
466
+ return Number.isFinite(v) && v > 0 ? Math.floor(v) : 3e4;
467
+ }
468
+ async function navigate(targetId, url, { timeout = navTimeout() } = {}) {
437
469
  return withPage(targetId, async (s) => {
438
470
  await s.send("Page.enable");
439
- const loaded = new Promise((resolve) => s.on("Page.loadEventFired", () => resolve()));
471
+ let seen = false;
472
+ const loaded = new Promise((resolve) => s.on("Page.loadEventFired", () => {
473
+ seen = true;
474
+ resolve();
475
+ }));
440
476
  const r = await s.send("Page.navigate", { url });
441
477
  if (r.errorText) throw new Error(`navigate failed: ${r.errorText}`);
442
- await Promise.race([loaded, new Promise((res) => setTimeout(res, timeout))]);
478
+ let timer;
479
+ try {
480
+ await Promise.race([loaded, new Promise((res) => {
481
+ timer = setTimeout(res, timeout);
482
+ })]);
483
+ } finally {
484
+ if (timer !== void 0) clearTimeout(timer);
485
+ }
486
+ return { loaded: seen };
443
487
  });
444
488
  }
445
489
  //#endregion
@@ -475,39 +519,303 @@ function normalizeUrl(input) {
475
519
  return `https://${input}`;
476
520
  }
477
521
  //#endregion
522
+ //#region src/core/renderer-wake.ts
523
+ /** How long a new tab gets to produce a renderer on its own before we wake it. */
524
+ const DEFAULT_GRACE = 2e3;
525
+ /** How long the woken tab then gets. Generous: waking is the expensive step. */
526
+ const DEFAULT_BUDGET = 1e4;
527
+ function envInt(name, fallback) {
528
+ const v = Number(process.env[name]);
529
+ return Number.isFinite(v) && v > 0 ? Math.floor(v) : fallback;
530
+ }
531
+ /**
532
+ * Ask ONE existing target's renderer to evaluate `1+1`.
533
+ *
534
+ * Deliberately not a navigation: the question is "can this renderer execute",
535
+ * which is the narrowest thing that separates a busy browser from a broken one
536
+ * without involving the network or the site.
537
+ */
538
+ async function askRenderer(targetId, timeout = 5e3) {
539
+ const started = Date.now();
540
+ const ms = () => Date.now() - started;
541
+ let ws;
542
+ try {
543
+ ws = await targetWsUrl(targetId);
544
+ } catch (e) {
545
+ return {
546
+ outcome: "error",
547
+ ms: ms(),
548
+ reason: String(e?.message ?? e)
549
+ };
550
+ }
551
+ if (!ws) return {
552
+ outcome: "gone",
553
+ ms: ms(),
554
+ reason: "the target vanished before we could attach to it"
555
+ };
556
+ let session;
557
+ try {
558
+ session = await connect(ws, { timeout });
559
+ } catch (e) {
560
+ const msg = String(e?.message ?? e);
561
+ return /timed out|timeout|WebSocket error/i.test(msg) ? {
562
+ outcome: "unattachable",
563
+ ms: ms(),
564
+ reason: `the target is listed, but its CDP connection would not open within ${timeout}ms (${msg})`
565
+ } : {
566
+ outcome: "error",
567
+ ms: ms(),
568
+ reason: msg
569
+ };
570
+ }
571
+ try {
572
+ const value = (await session.send("Runtime.evaluate", {
573
+ expression: "1+1",
574
+ returnByValue: true
575
+ }, timeout))?.result?.value;
576
+ if (value === 2) return {
577
+ outcome: "ok",
578
+ ms: ms()
579
+ };
580
+ return {
581
+ outcome: "wrong-answer",
582
+ ms: ms(),
583
+ reason: `the renderer answered with ${JSON.stringify(value)} instead of 2`
584
+ };
585
+ } catch (e) {
586
+ const msg = String(e?.message ?? e);
587
+ return /timed out|timeout/i.test(msg) ? {
588
+ outcome: "silent",
589
+ ms: ms(),
590
+ reason: `attached to the target, but its renderer did not answer within ${timeout}ms`
591
+ } : {
592
+ outcome: "error",
593
+ ms: ms(),
594
+ reason: msg
595
+ };
596
+ } finally {
597
+ session.close();
598
+ }
599
+ }
600
+ /**
601
+ * The macOS app currently in front, as a bundle path we can hand focus back to.
602
+ *
603
+ * `lsappinfo`, not AppleScript: `tell application "System Events" to get name
604
+ * of first application process whose frontmost is true` needs Accessibility
605
+ * permission, and a permission dialog appearing in the middle of an automated
606
+ * command is worse than the focus steal it is trying to undo. `lsappinfo` needs
607
+ * nothing and is present on every macOS.
608
+ */
609
+ function frontmostApp() {
610
+ if (process.platform !== "darwin") return null;
611
+ try {
612
+ const asn = execFileSync("lsappinfo", ["front"], {
613
+ encoding: "utf8",
614
+ stdio: [
615
+ "ignore",
616
+ "pipe",
617
+ "ignore"
618
+ ]
619
+ }).trim();
620
+ if (!asn) return null;
621
+ const info = execFileSync("lsappinfo", [
622
+ "info",
623
+ "-only",
624
+ "bundlepath",
625
+ asn
626
+ ], {
627
+ encoding: "utf8",
628
+ stdio: [
629
+ "ignore",
630
+ "pipe",
631
+ "ignore"
632
+ ]
633
+ });
634
+ return /"LSBundlePath"="([^"]+)"/.exec(info)?.[1] ?? null;
635
+ } catch {
636
+ return null;
637
+ }
638
+ }
639
+ /** Put the operator's app back in front. Best effort, and never fatal. */
640
+ function raiseApp(bundlePath) {
641
+ if (!bundlePath || process.platform !== "darwin") return;
642
+ if (/Google Chrome\.app|Chromium\.app/.test(bundlePath)) return;
643
+ try {
644
+ execFileSync("open", ["-a", bundlePath], { stdio: "ignore" });
645
+ } catch {}
646
+ }
647
+ /**
648
+ * Which tab the operator is looking at, so it can be put back afterwards.
649
+ *
650
+ * Chrome lists page targets most-recently-active first. That is an observation,
651
+ * not a documented guarantee — it held in every trial here, and when it is
652
+ * wrong the cost is that the window comes back to a different tab of the
653
+ * automation browser, not a failure.
654
+ */
655
+ async function activePageId() {
656
+ try {
657
+ return (await listPageTargets())[0]?.id;
658
+ } catch {
659
+ return;
660
+ }
661
+ }
662
+ /**
663
+ * Make sure `targetId` has a renderer that answers — cheaply if possible.
664
+ *
665
+ * Grace period first (the common case: no focus is taken at all), then one
666
+ * wake, then the verdict. `allowWake: false` (or BROWSER_AUTOMATION_NO_WAKE=1)
667
+ * keeps the window untouched for callers who would rather fail than flicker.
668
+ */
669
+ async function ensureRenderer(targetId, { grace, budget, allowWake = !process.env.BROWSER_AUTOMATION_NO_WAKE } = {}) {
670
+ const graceMs = grace ?? envInt("BROWSER_AUTOMATION_RENDERER_GRACE", DEFAULT_GRACE);
671
+ const budgetMs = budget ?? envInt("BROWSER_AUTOMATION_RENDERER_BUDGET", DEFAULT_BUDGET);
672
+ const started = Date.now();
673
+ const first = await askRenderer(targetId, graceMs);
674
+ if (first.outcome === "ok") return {
675
+ ...first,
676
+ ok: true,
677
+ woke: false,
678
+ ms: Date.now() - started
679
+ };
680
+ if (!allowWake || first.outcome !== "silent" && first.outcome !== "unattachable") return {
681
+ ...first,
682
+ ok: false,
683
+ woke: false,
684
+ ms: Date.now() - started
685
+ };
686
+ const previousApp = frontmostApp();
687
+ const previousTab = await activePageId();
688
+ try {
689
+ await activateTab(targetId);
690
+ } catch (e) {
691
+ return {
692
+ ...first,
693
+ ok: false,
694
+ woke: false,
695
+ ms: Date.now() - started,
696
+ reason: `${first.reason}; and it could not be activated either (${e?.message ?? e})`
697
+ };
698
+ }
699
+ const second = await askRenderer(targetId, budgetMs);
700
+ if (previousTab && previousTab !== targetId) await activateTab(previousTab).catch(() => {});
701
+ raiseApp(previousApp);
702
+ return {
703
+ ...second,
704
+ ok: second.outcome === "ok",
705
+ woke: true,
706
+ ms: Date.now() - started
707
+ };
708
+ }
709
+ //#endregion
478
710
  //#region src/core/renderer-health.ts
711
+ /** First attempt's budget. Later attempts double it. */
712
+ const DEFAULT_TIMEOUT = 5e3;
713
+ /** How many times we ask before we are willing to call a browser broken. */
714
+ const DEFAULT_ATTEMPTS = 3;
715
+ /** Breathing room between attempts — a browser mid-GC deserves a second look. */
716
+ const RETRY_PAUSE = 400;
717
+ /**
718
+ * The verdict, from the probe and the corroborations — and from nothing else.
719
+ *
720
+ * Pure, and separate from the probing, because this is the decision that was
721
+ * wrong: every failure used to become 'wedged' by default. Now 'wedged'
722
+ * requires `rendezvous === false`, which is the only thing that has ever
723
+ * actually meant it.
724
+ */
725
+ function rendererVerdict(outcome, e) {
726
+ if (outcome === "ok") return "healthy";
727
+ if (e?.rendezvous === false) return "wedged";
728
+ if (e?.rendezvous === true && (e.renderers ?? 0) > 0) return "busy";
729
+ return "unknown";
730
+ }
479
731
  /**
480
732
  * Create a throwaway tab, make its renderer prove it is alive, close it.
481
733
  *
482
- * Deliberately uses `about:blank` and `Runtime.evaluate`, not a navigation:
483
- * we are asking "can a new renderer exist and execute", which is the narrowest
484
- * question that separates a wedged browser from a slow network or a hostile
485
- * site. Nothing here touches the caller's tabs.
734
+ * Three things changed after 2026-09-11, and each of them is load-bearing:
735
+ *
736
+ * 1. It goes through `ensureRenderer`, so the probe opens its tab the way the
737
+ * tool opens tabs AND gets the same wake treatment. A probe that is harsher
738
+ * on itself than `goto` is on a real tab reports failures `goto` would not
739
+ * have had.
740
+ * 2. It retries with a doubling budget. One 5s timeout is not evidence of a
741
+ * permanent condition; it is evidence of 5 seconds.
742
+ * 3. It stops early when the Mach name is ABSENT — the one state where more
743
+ * waiting is genuinely pointless — so the real failure is still reported
744
+ * fast while a slow browser gets the benefit of the doubt.
486
745
  */
487
- async function probeRenderer({ timeout = 5e3 } = {}) {
746
+ async function probeRenderer({ timeout, attempts } = {}) {
747
+ const base = timeout ?? envInt("BROWSER_AUTOMATION_PROBE_TIMEOUT", DEFAULT_TIMEOUT);
748
+ const maxAttempts = Math.max(1, attempts ?? envInt("BROWSER_AUTOMATION_PROBE_ATTEMPTS", DEFAULT_ATTEMPTS));
488
749
  const started = Date.now();
489
750
  let pageTargets = 0;
490
751
  try {
491
752
  pageTargets = (await listPageTargets()).length;
492
753
  } catch {}
754
+ const tries = [];
755
+ let evidence;
756
+ for (let i = 0; i < maxAttempts; i++) {
757
+ const budget = base * 2 ** i;
758
+ tries.push(await probeOnce(budget));
759
+ if (tries[tries.length - 1].outcome === "ok") return finish({
760
+ ok: true,
761
+ started,
762
+ pageTargets,
763
+ tries,
764
+ evidence
765
+ });
766
+ evidence ??= gatherEvidence();
767
+ if (evidence.rendezvous === false) break;
768
+ if (i + 1 < maxAttempts) await new Promise((r) => setTimeout(r, RETRY_PAUSE));
769
+ }
770
+ return finish({
771
+ ok: false,
772
+ started,
773
+ pageTargets,
774
+ tries,
775
+ evidence
776
+ });
777
+ }
778
+ function finish({ ok, started, pageTargets, tries, evidence }) {
779
+ const last = tries[tries.length - 1];
780
+ const health = {
781
+ ok,
782
+ ms: Date.now() - started,
783
+ pageTargets,
784
+ reason: last?.reason,
785
+ outcome: last?.outcome ?? "error",
786
+ verdict: rendererVerdict(last?.outcome ?? "error", evidence),
787
+ attempts: tries,
788
+ evidence
789
+ };
790
+ recordProbe(health);
791
+ return health;
792
+ }
793
+ /** One create -> ensure -> close cycle. */
794
+ async function probeOnce(budget) {
795
+ const started = Date.now();
493
796
  let targetId;
494
797
  try {
495
- targetId = await createTab("about:blank", { timeout });
798
+ targetId = await createTab("about:blank", { timeout: budget });
496
799
  } catch (e) {
497
800
  return {
498
- ok: false,
801
+ outcome: "error",
802
+ budget,
499
803
  ms: Date.now() - started,
500
- pageTargets,
804
+ woke: false,
501
805
  reason: `could not create a target at all: ${e?.message ?? e}`
502
806
  };
503
807
  }
504
808
  try {
505
- const reason = await renderersAnswer(targetId, timeout);
809
+ const r = await ensureRenderer(targetId, {
810
+ grace: budget,
811
+ budget
812
+ });
506
813
  return {
507
- ok: reason === null,
814
+ outcome: r.outcome,
815
+ budget,
508
816
  ms: Date.now() - started,
509
- pageTargets,
510
- reason: reason ?? void 0
817
+ woke: r.woke,
818
+ reason: r.reason
511
819
  };
512
820
  } finally {
513
821
  if (targetId) await closeTab(targetId).catch(() => {});
@@ -516,68 +824,83 @@ async function probeRenderer({ timeout = 5e3 } = {}) {
516
824
  /**
517
825
  * Ask an EXISTING target's renderer to prove it is alive.
518
826
  *
519
- * Returns null when it answers correctly, or a human-readable reason when it
520
- * does not. Used both by the throwaway probe and by `new`, which has just
521
- * created a tab and should check that one rather than manufacture a second.
827
+ * Kept returning `string | null` because that is what `gc` wants (a reason to
828
+ * print beside a tab it is about to close). New callers should prefer
829
+ * `askRenderer`, which says WHICH failure it was.
522
830
  */
523
- async function renderersAnswer(targetId, timeout = 5e3) {
524
- try {
525
- const ws = await targetWsUrl(targetId);
526
- if (!ws) return "the target vanished immediately";
527
- const s = await connect(ws, { timeout });
528
- try {
529
- const value = (await s.send("Runtime.evaluate", {
530
- expression: "1+1",
531
- returnByValue: true
532
- }, timeout))?.result?.value;
533
- return value === 2 ? null : `the renderer answered with ${JSON.stringify(value)} instead of 2`;
534
- } finally {
535
- s.close();
536
- }
537
- } catch (e) {
538
- const msg = String(e?.message ?? e);
539
- return /timed out|timeout/i.test(msg) ? "the target exists, but no renderer ever answered it" : msg;
540
- }
831
+ async function renderersAnswer(targetId, timeout = DEFAULT_TIMEOUT) {
832
+ const r = await askRenderer(targetId, timeout);
833
+ return r.outcome === "ok" ? null : r.reason ?? r.outcome;
541
834
  }
542
835
  /**
543
836
  * The port we are actually talking to.
544
837
  *
545
838
  * NOT always `cdpPort()`: `BROWSER_AUTOMATION_CDP` points the CLI at an
546
- * arbitrary host:port, and everything here that shells out to `pgrep` or
547
- * `launchctl` has to ask about THAT browser. Using the uid-derived port
548
- * instead finds the user's default Chrome and cheerfully reports its health
549
- * as if it were the one being driven — caught while testing this module
550
- * against a second Chrome, where a perfectly healthy browser was accused of
551
- * having lost the bootstrap name that in fact belonged to a different pid.
839
+ * arbitrary host:port, and everything here that shells out to `ps` or
840
+ * `launchctl` has to ask about THAT browser. Using the uid-derived port instead
841
+ * finds the user's default Chrome and cheerfully reports its health as if it
842
+ * were the one being driven — caught while testing this module against a second
843
+ * Chrome, where a perfectly healthy browser was accused of having lost a
844
+ * bootstrap name that in fact belonged to a different pid.
552
845
  */
553
846
  function targetPort() {
554
847
  const explicit = process.env.BROWSER_AUTOMATION_CDP;
555
- if (explicit) {
848
+ if (explicit) try {
556
849
  const p = Number(new URL(explicit).port);
557
850
  if (Number.isInteger(p) && p > 0) return p;
558
- }
851
+ } catch {}
559
852
  return cdpPort();
560
853
  }
561
- /** The pid of the browser process serving the port we are driving, if visible. */
562
- function browserPid() {
854
+ /**
855
+ * The browser process serving our port, and how many renderers it has.
856
+ *
857
+ * One `ps`, not one `pgrep` plus one `ps` per hit: on a Chrome with 40 children
858
+ * that was 41 forks to answer two questions, and it ran on the error path of a
859
+ * browser already thought to be struggling.
860
+ *
861
+ * The executable check is not decoration. Matching on the command line alone
862
+ * (as `pgrep -f` does) hits any process that merely CONTAINS the debugging-port
863
+ * flag — the `grep` looking for it, or a shell running `browser-automation`
864
+ * with the flag as an argument. One of those, having no `--type=`, would have
865
+ * been reported as the browser pid, and its absent Mach name read as the
866
+ * permanent failure. Seen while writing this: a `ugrep` for the flag sat in
867
+ * `ps` output alongside the real Chrome.
868
+ */
869
+ function chromeProcesses() {
870
+ const flag = `--remote-debugging-port=${targetPort()}`;
871
+ const uid = String(process.getuid?.() ?? -1);
872
+ let out;
563
873
  try {
564
- const out = execFileSync("pgrep", [
565
- "-u",
566
- String(process.getuid?.() ?? -1),
567
- "-f",
568
- "--",
569
- `--remote-debugging-port=${targetPort()}`
570
- ], { encoding: "utf8" });
571
- for (const pid of out.split("\n").map((s) => s.trim()).filter(Boolean)) try {
572
- if (!execFileSync("ps", [
573
- "-o",
574
- "command=",
575
- "-p",
576
- pid
577
- ], { encoding: "utf8" }).includes("--type=")) return Number(pid);
578
- } catch {}
579
- } catch {}
580
- return null;
874
+ out = execFileSync("ps", ["-Ao", "pid=,uid=,command="], {
875
+ encoding: "utf8",
876
+ maxBuffer: 64 * 1024 * 1024,
877
+ stdio: [
878
+ "ignore",
879
+ "pipe",
880
+ "ignore"
881
+ ]
882
+ });
883
+ } catch {
884
+ return {
885
+ browser: null,
886
+ renderers: null
887
+ };
888
+ }
889
+ let browser = null;
890
+ let renderers = 0;
891
+ for (const line of out.split("\n")) {
892
+ const m = /^\s*(\d+)\s+(\d+)\s+(.*)$/.exec(line);
893
+ if (!m) continue;
894
+ const [, pid, u, cmd] = m;
895
+ if (u !== uid || !cmd.includes(flag)) continue;
896
+ if (!/chrome|chromium|brave|msedge|thorium/i.test(cmd.split(" --")[0])) continue;
897
+ if (/--type=renderer\b/.test(cmd)) renderers++;
898
+ else if (!cmd.includes("--type=")) browser = Number(pid);
899
+ }
900
+ return {
901
+ browser,
902
+ renderers
903
+ };
581
904
  }
582
905
  /**
583
906
  * macOS only: is the browser's Mach port rendezvous service still registered?
@@ -585,7 +908,7 @@ function browserPid() {
585
908
  * This is the ROOT CAUSE signal, not a symptom — when it is missing, every
586
909
  * child process Chrome launches kills itself on startup. Returns null when we
587
910
  * cannot tell (not macOS, `launchctl` unavailable, pid unknown), which is
588
- * different from `false` and must not be reported as a fault.
911
+ * different from `false` and must never be reported as a fault.
589
912
  */
590
913
  function rendezvousRegistered(pid) {
591
914
  if (process.platform !== "darwin" || !pid) return null;
@@ -603,51 +926,143 @@ function rendezvousRegistered(pid) {
603
926
  return null;
604
927
  }
605
928
  }
929
+ /** Both corroborations, in one pass. Cheap enough to run on every failure. */
930
+ function gatherEvidence() {
931
+ const { browser, renderers } = chromeProcesses();
932
+ return {
933
+ pid: browser,
934
+ renderers: browser === null ? null : renderers,
935
+ rendezvous: rendezvousRegistered(browser)
936
+ };
937
+ }
606
938
  /** Where `launch` writes Chrome's stdout/stderr — Chrome logs the real reason there. */
607
939
  function chromeLogPath() {
608
940
  const tmp = process.env.TMPDIR?.replace(/\/$/, "") || "/tmp";
609
941
  return process.env.BROWSER_AUTOMATION_LOG || `${tmp}/chrome-${targetPort()}.log`;
610
942
  }
943
+ function probeLogPath() {
944
+ return process.env.BROWSER_AUTOMATION_PROBE_LOG || join(homedir(), ".browser-automation", "renderer-probes.jsonl");
945
+ }
946
+ function recordProbe(h) {
947
+ const line = JSON.stringify({
948
+ t: (/* @__PURE__ */ new Date()).toISOString(),
949
+ ok: h.ok,
950
+ verdict: h.verdict,
951
+ outcome: h.outcome,
952
+ ms: h.ms,
953
+ attempts: h.attempts.map((a) => ({
954
+ outcome: a.outcome,
955
+ ms: a.ms,
956
+ budget: a.budget,
957
+ woke: a.woke
958
+ })),
959
+ pageTargets: h.pageTargets,
960
+ evidence: h.evidence
961
+ });
962
+ try {
963
+ const path = probeLogPath();
964
+ mkdirSync(join(path, ".."), { recursive: true });
965
+ try {
966
+ if (statSync(path).size > 256 * 1024) {
967
+ const kept = readFileSync(path, "utf8").split("\n").slice(-500).join("\n");
968
+ writeFileSync(path, kept.endsWith("\n") ? kept : kept + "\n");
969
+ }
970
+ } catch {}
971
+ appendFileSync(path, line + "\n");
972
+ } catch {}
973
+ }
974
+ /** Recent probe timings, for `doctor`. Returns null when there is no history. */
975
+ function recentProbeStats(limit = 50) {
976
+ try {
977
+ const rows = readFileSync(probeLogPath(), "utf8").trim().split("\n").slice(-limit).map((l) => {
978
+ try {
979
+ return JSON.parse(l);
980
+ } catch {
981
+ return null;
982
+ }
983
+ }).filter(Boolean);
984
+ if (!rows.length) return null;
985
+ const okMs = rows.filter((r) => r.ok).map((r) => r.ms).sort((a, b) => a - b);
986
+ return {
987
+ n: rows.length,
988
+ failures: rows.filter((r) => !r.ok).length,
989
+ median: okMs.length ? okMs[Math.floor(okMs.length / 2)] : -1,
990
+ worst: okMs.length ? okMs[okMs.length - 1] : -1
991
+ };
992
+ } catch {
993
+ return null;
994
+ }
995
+ }
996
+ function evidenceLines(e) {
997
+ if (!e) return [];
998
+ 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)`;
999
+ const rend = e.renderers === null ? `could not count` : `${e.renderers} live renderer process(es) for this browser`;
1000
+ return [` mach service: ${mach}`, ` renderers: ${rend}`];
1001
+ }
1002
+ /** The cheap recovery. Always printed, always before anything expensive. */
1003
+ function cheapRecovery() {
1004
+ return [
1005
+ `Try these first, cheapest first:`,
1006
+ ``,
1007
+ ` 1. Run the command again. A new tab's renderer has been measured taking`,
1008
+ ` 12s and more on a loaded machine, and it is not broken, only late.`,
1009
+ ` 2. Use a tab that already works. An existing tab navigates same-origin`,
1010
+ ` without needing a new renderer, so it keeps working throughout:`,
1011
+ ` browser-automation list`,
1012
+ ` browser-automation eval -t <id> "location.href='<url>'"`,
1013
+ ` 3. browser-automation doctor — re-measures, and prints recent probe times.`
1014
+ ];
1015
+ }
611
1016
  /**
612
1017
  * A ready-to-print explanation of a renderer failure, with the recovery.
613
1018
  *
614
1019
  * Written to be read by somebody who has just been told a site blocks them, so
615
- * it says what is and is not true before it says what to do.
1020
+ * it says what is and is not true before it says what to do — and it says only
1021
+ * what was actually established. The four verdicts get four different endings
1022
+ * because they need four different actions, and exactly one of them is worth
1023
+ * anybody's tabs.
616
1024
  */
617
1025
  function explainRendererFailure(h) {
618
- const pid = browserPid();
619
- const rendezvous = rendezvousRegistered(pid);
1026
+ const e = h.evidence ?? gatherEvidence();
1027
+ const verdict = h.verdict ?? rendererVerdict(h.outcome, e);
1028
+ const tried = h.attempts?.length ?? 1;
1029
+ const longest = h.attempts?.length ? Math.max(...h.attempts.map((a) => a.budget)) : 0;
1030
+ const woke = h.attempts?.some((a) => a.woke);
620
1031
  const lines = [
621
- `Chrome cannot give a new tab a working renderer.`,
1032
+ `Chrome did not give a new tab a working renderer.`,
622
1033
  ``,
623
- ` probe: created a target, ${h.reason ?? "no renderer answered"} (${h.ms}ms)`,
624
- ` page targets: ${h.pageTargets} (context only — this is NOT the cause; a healthy`,
625
- ` Chrome has been driven to 421 tabs with every renderer alive)`
1034
+ ` probe: ${tried} attempt(s), longest budget ${longest}ms, ${h.ms}ms total`,
1035
+ ` ${h.reason ?? "no renderer answered"}`,
1036
+ ...woke ? [` (it was also activated to force a renderer, and still did not answer)`] : [],
1037
+ ` page targets: ${h.pageTargets} (context only — NOT the cause; a healthy Chrome has`,
1038
+ ` been driven to 421 tabs with every renderer alive)`,
1039
+ ...evidenceLines(e),
1040
+ ``
626
1041
  ];
627
- 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.`);
628
- 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()}`);
629
- 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 now DETECTS this (it runs this same`, `probe and fails), but it will never restart a browser other sessions may be`, `using without being told to. Restarting is always something you type.`, ``, ` 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.`);
1042
+ 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.`);
1043
+ 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.`);
1044
+ 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.`);
630
1045
  return lines.join("\n");
631
1046
  }
632
1047
  /**
633
- * Does this error look like it could be the renderer wedge rather than the site?
1048
+ * Does this error look like it could be a renderer failure rather than the site?
634
1049
  *
635
- * Kept deliberately narrow. These three are the ONLY shapes the failure takes
636
- * through the CLI, and each of them has an innocent explanation too — so a hit
637
- * here buys a probe, never a conclusion.
1050
+ * Kept deliberately narrow. These are the ONLY shapes the failure takes through
1051
+ * the CLI, and each of them has an innocent explanation too — so a hit here
1052
+ * buys a probe, never a conclusion.
638
1053
  */
639
1054
  function mayBeRendererFailure(err) {
640
1055
  const m = String(err?.message ?? err);
641
- 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);
1056
+ 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);
642
1057
  }
643
1058
  /**
644
- * Run `fn`; if it fails in a way the renderer wedge could explain, spend one
1059
+ * Run `fn`; if it fails in a way a renderer failure could explain, spend one
645
1060
  * probe finding out, and re-throw with the diagnosis attached.
646
1061
  *
647
1062
  * The probe only ever runs on the error path, so the happy path pays nothing.
648
1063
  * If the probe comes back healthy the original error is re-thrown untouched —
649
- * the point is to stop misattributing a browser fault to a site, not to blame
650
- * the browser for every timeout.
1064
+ * and since the probe now retries and can wake a late renderer, "healthy" is
1065
+ * the answer a loaded browser gets, which is the September bug not happening.
651
1066
  */
652
1067
  async function withRendererDiagnosis(fn) {
653
1068
  try {
@@ -682,24 +1097,25 @@ const newCommand = define({
682
1097
  async run(ctx) {
683
1098
  const name = ctx.values.session || defaultSessionName();
684
1099
  const url = ctx.positionals[1] ? normalizeUrl(ctx.positionals[1]) : "about:blank";
685
- 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>\`.`);
686
- const targetId = await createTab(url);
1100
+ if (loadSession(name) && !ctx.values.force) consola$1.warn(`Session "${name}" already maps to a tab. Use --force to open another, or just \`browser-automation goto -s ${name} <url>\`.`);
1101
+ const targetId = await withRendererDiagnosis(() => createTab(url));
687
1102
  saveSession({
688
1103
  name,
689
1104
  targetId,
690
1105
  url,
691
1106
  createdAt: (/* @__PURE__ */ new Date()).toISOString()
692
1107
  });
693
- const dead = await renderersAnswer(targetId).catch(() => null);
694
- if (dead) {
1108
+ const r = await ensureRenderer(targetId);
1109
+ if (r.woke) consola$1.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.`);
1110
+ if (!r.ok) {
695
1111
  const health = await probeRenderer().catch(() => null);
696
1112
  if (health && !health.ok) {
697
- consola.error(`[${name}] tab ${targetId.slice(0, 12)}… was created but has no working renderer.\n\n${explainRendererFailure(health)}`);
1113
+ consola$1.error(`[${name}] tab ${targetId.slice(0, 12)}… was created but has no working renderer.\n\n${explainRendererFailure(health)}`);
698
1114
  process.exit(1);
699
1115
  }
700
- 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.`);
1116
+ consola$1.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.`);
701
1117
  }
702
- consola.success(`[${name}] opened background tab ${targetId.slice(0, 12)}… → ${url}`);
1118
+ consola$1.success(`[${name}] opened background tab ${targetId.slice(0, 12)}… → ${url}`);
703
1119
  }
704
1120
  });
705
1121
  //#endregion
@@ -809,13 +1225,16 @@ const gotoCommand = define({
809
1225
  async run(ctx) {
810
1226
  const url = ctx.positionals[1];
811
1227
  if (!url) {
812
- consola.error("URL is required");
1228
+ consola$1.error("URL is required");
813
1229
  process.exit(1);
814
1230
  }
815
1231
  const target = normalizeUrl(url);
816
1232
  const opts = targetOpts(ctx.values);
817
1233
  const { targetId, created } = await withRendererDiagnosis(() => resolveOrCreateTargetId(opts));
818
- await withRendererDiagnosis(() => navigate(targetId, target));
1234
+ if (created) {
1235
+ if ((await ensureRenderer(targetId)).woke) consola$1.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.");
1236
+ }
1237
+ if (!(await withRendererDiagnosis(() => navigate(targetId, target))).loaded) consola$1.warn("No load event arrived, so the page may still be loading. The navigation itself was accepted; this is a statement about what could not be confirmed.");
819
1238
  if (!opts.match && !opts.target) {
820
1239
  const name = opts.session || defaultSessionName();
821
1240
  saveSession({
@@ -824,8 +1243,8 @@ const gotoCommand = define({
824
1243
  url: target,
825
1244
  createdAt: loadSession(name)?.createdAt ?? (/* @__PURE__ */ new Date()).toISOString()
826
1245
  });
827
- consola.success(`[${name}] ${created ? "opened tab + " : ""}navigated → ${target}`);
828
- } else consola.success(`[${targetId.slice(0, 12)}…] navigated → ${target}`);
1246
+ consola$1.success(`[${name}] ${created ? "opened tab + " : ""}navigated → ${target}`);
1247
+ } else consola$1.success(`[${targetId.slice(0, 12)}…] navigated → ${target}`);
829
1248
  }
830
1249
  });
831
1250
  //#endregion
@@ -1091,18 +1510,18 @@ const snapshotCommand = define({
1091
1510
  return;
1092
1511
  }
1093
1512
  const overlayNote = snap.overlayCount ? ` (${snap.overlayCount} in an open overlay, listed first)` : "";
1094
- consola.log(`# ${snap.title}\n# ${snap.url}\n# ${snap.count} interactive elements${overlayNote}`);
1095
- if (snap.overlayText) consola.log(`# overlay: ${snap.overlayText}`);
1513
+ consola$1.log(`# ${snap.title}\n# ${snap.url}\n# ${snap.count} interactive elements${overlayNote}`);
1514
+ if (snap.overlayText) consola$1.log(`# overlay: ${snap.overlayText}`);
1096
1515
  for (const el of snap.elements) {
1097
1516
  const label = el.type ? `${el.role}[${el.type}]` : el.role;
1098
1517
  const st = el.state ? `[${el.state}] ` : "";
1099
- consola.log(`${el.ref.padEnd(5)} ${label.padEnd(18)} ${st}${el.name}`);
1518
+ consola$1.log(`${el.ref.padEnd(5)} ${label.padEnd(18)} ${st}${el.name}`);
1100
1519
  }
1101
1520
  }
1102
1521
  });
1103
1522
  //#endregion
1104
1523
  //#region src/commands/click.ts
1105
- const sleep$1 = (ms) => new Promise((r) => setTimeout(r, ms));
1524
+ const sleep$2 = (ms) => new Promise((r) => setTimeout(r, ms));
1106
1525
  const clickCommand = define({
1107
1526
  name: "click",
1108
1527
  description: "Click an element by ref (from the latest snapshot)",
@@ -1120,7 +1539,7 @@ const clickCommand = define({
1120
1539
  async run(ctx) {
1121
1540
  const ref = ctx.positionals[1];
1122
1541
  if (!ref || !isValidRef(ref)) {
1123
- consola.error("A ref like \"e7\" is required (run `browser-automation snapshot` first)");
1542
+ consola$1.error("A ref like \"e7\" is required (run `browser-automation snapshot` first)");
1124
1543
  process.exit(1);
1125
1544
  }
1126
1545
  const targetId = await resolveExistingTargetId(targetOpts(ctx.values));
@@ -1143,7 +1562,7 @@ const clickCommand = define({
1143
1562
  while (Date.now() < focusDeadline) {
1144
1563
  const f = await evalIn(`({f:document.hasFocus(),v:document.visibilityState})`);
1145
1564
  if (f && f.f && f.v === "visible") break;
1146
- await sleep$1(50);
1565
+ await sleep$2(50);
1147
1566
  }
1148
1567
  let prev = null;
1149
1568
  let point = null;
@@ -1152,7 +1571,7 @@ const clickCommand = define({
1152
1571
  while (Date.now() < actDeadline) {
1153
1572
  const a = await evalIn(actionabilityExpr(ref));
1154
1573
  if (a?.err) {
1155
- consola.error(a.err);
1574
+ consola$1.error(a.err);
1156
1575
  process.exit(1);
1157
1576
  }
1158
1577
  const stable = prev !== null && Math.abs(prev.x - a.x) < .5 && Math.abs(prev.y - a.y) < .5;
@@ -1169,10 +1588,10 @@ const clickCommand = define({
1169
1588
  x: a.x,
1170
1589
  y: a.y
1171
1590
  };
1172
- await sleep$1(60);
1591
+ await sleep$2(60);
1173
1592
  }
1174
1593
  if (!point) {
1175
- consola.error(`<${ref}> not actionable for a trusted click: ${lastReason}`);
1594
+ consola$1.error(`<${ref}> not actionable for a trusted click: ${lastReason}`);
1176
1595
  process.exit(1);
1177
1596
  }
1178
1597
  const { x, y } = point;
@@ -1184,7 +1603,7 @@ const clickCommand = define({
1184
1603
  buttons: 0,
1185
1604
  pointerType: "mouse"
1186
1605
  });
1187
- await sleep$1(20);
1606
+ await sleep$2(20);
1188
1607
  await s.send("Input.dispatchMouseEvent", {
1189
1608
  type: "mousePressed",
1190
1609
  x,
@@ -1206,15 +1625,15 @@ const clickCommand = define({
1206
1625
  });
1207
1626
  return point.tag;
1208
1627
  });
1209
- consola.success(`clicked ${ref} <${trustedTag}> (trusted)`);
1628
+ consola$1.success(`clicked ${ref} <${trustedTag}> (trusted)`);
1210
1629
  return;
1211
1630
  }
1212
1631
  const r = await evaluate(targetId, clickExpr(ref));
1213
1632
  if (r.err) {
1214
- consola.error(r.err);
1633
+ consola$1.error(r.err);
1215
1634
  process.exit(1);
1216
1635
  }
1217
- consola.success(`clicked ${ref} <${r.tag}>`);
1636
+ consola$1.success(`clicked ${ref} <${r.tag}>`);
1218
1637
  }
1219
1638
  });
1220
1639
  //#endregion
@@ -1249,11 +1668,11 @@ const fillCommand = define({
1249
1668
  const ref = ctx.positionals[1];
1250
1669
  const value = ctx.positionals[2];
1251
1670
  if (!ref || !isValidRef(ref)) {
1252
- consola.error("A ref like \"e3\" is required (run `browser-automation snapshot` first)");
1671
+ consola$1.error("A ref like \"e3\" is required (run `browser-automation snapshot` first)");
1253
1672
  process.exit(1);
1254
1673
  }
1255
1674
  if (value === void 0) {
1256
- consola.error("A value is required");
1675
+ consola$1.error("A value is required");
1257
1676
  process.exit(1);
1258
1677
  }
1259
1678
  const targetId = await resolveExistingTargetId(targetOpts(ctx.values));
@@ -1262,7 +1681,7 @@ const fillCommand = define({
1262
1681
  if (native) {
1263
1682
  const focus = await evaluate(targetId, focusAndSelectExpr(ref));
1264
1683
  if (focus.err) {
1265
- consola.error(focus.err);
1684
+ consola$1.error(focus.err);
1266
1685
  process.exit(1);
1267
1686
  }
1268
1687
  await withPage(targetId, async (s) => {
@@ -1285,23 +1704,23 @@ const fillCommand = define({
1285
1704
  } else {
1286
1705
  const r = await evaluate(targetId, fillExpr(ref, value, submit));
1287
1706
  if (r.err) {
1288
- consola.error(r.err);
1707
+ consola$1.error(r.err);
1289
1708
  process.exit(1);
1290
1709
  }
1291
1710
  }
1292
1711
  if (ctx.values.verify) {
1293
1712
  const v = await evaluate(targetId, readValueAndTrackerExpr(ref));
1294
- if (v.err) consola.warn(`verify failed to re-read field: ${v.err}`);
1713
+ if (v.err) consola$1.warn(`verify failed to re-read field: ${v.err}`);
1295
1714
  else {
1296
1715
  const domMatches = v.value === value;
1297
1716
  const trackerKnown = v.trackerValue !== null && v.trackerValue !== void 0;
1298
1717
  const trackerMatches = !trackerKnown || v.trackerValue === value;
1299
- if (!domMatches) consola.warn(`verify: DOM value is "${v.value}" but you requested "${value}" — wrong element selected, or the page rewrote it.`);
1300
- else if (!trackerMatches) consola.warn(`verify: DOM shows "${value}" but React's _valueTracker still holds "${v.trackerValue}". The form library will likely submit the stale value. Try --native, or capture the form's PUT endpoint and call it directly (see SKILL.md "Controlled-form state stickiness").`);
1301
- else if (v.hasReactFiber && !trackerKnown && !native) consola.info(`verify: field has a React fiber but no _valueTracker — if the next submit serializes the old value, try --native.`);
1718
+ if (!domMatches) consola$1.warn(`verify: DOM value is "${v.value}" but you requested "${value}" — wrong element selected, or the page rewrote it.`);
1719
+ else if (!trackerMatches) consola$1.warn(`verify: DOM shows "${value}" but React's _valueTracker still holds "${v.trackerValue}". The form library will likely submit the stale value. Try --native, or capture the form's PUT endpoint and call it directly (see SKILL.md "Controlled-form state stickiness").`);
1720
+ else if (v.hasReactFiber && !trackerKnown && !native) consola$1.info(`verify: field has a React fiber but no _valueTracker — if the next submit serializes the old value, try --native.`);
1302
1721
  }
1303
1722
  }
1304
- consola.success(`filled ${ref} = "${value}"${native ? " [native]" : ""}${submit ? " + submitted" : ""}`);
1723
+ consola$1.success(`filled ${ref} = "${value}"${native ? " [native]" : ""}${submit ? " + submitted" : ""}`);
1305
1724
  }
1306
1725
  });
1307
1726
  //#endregion
@@ -1317,6 +1736,89 @@ const readCommand = define({
1317
1736
  }
1318
1737
  });
1319
1738
  //#endregion
1739
+ //#region src/commands/focus.ts
1740
+ const sleep$1 = (ms) => new Promise((r) => setTimeout(r, ms));
1741
+ /**
1742
+ * Make a tab believe it is the visible one.
1743
+ *
1744
+ * # Why this exists
1745
+ *
1746
+ * A backgrounded tab is not merely unwatched — it reports itself hidden, and
1747
+ * pages act on that. Measured 2026-09-14 on an ordinary tab this CLI had opened:
1748
+ *
1749
+ * {"visibility":"hidden","hasFocus":false,"hidden":true}
1750
+ *
1751
+ * Anything gated on `document.visibilityState` behaves differently there:
1752
+ * deferred rendering, paused polling and animation, charts that never draw,
1753
+ * carousels and videos that never start. `core/renderer-wake.ts` measures the
1754
+ * same deprioritisation one layer down — a background target's renderer answers
1755
+ * in a median 367ms against 19ms once activated, with a tail past 12s.
1756
+ *
1757
+ * Until now nothing exposed this. `click --trusted` and `drop` both force it as
1758
+ * a side effect of needing trusted input to land, so the capability was in the
1759
+ * codebase and reachable only by clicking something.
1760
+ *
1761
+ * # The two ways, and why the quiet one is the default
1762
+ *
1763
+ * `Emulation.setFocusEmulationEnabled` makes the renderer treat itself as
1764
+ * focused and visible whatever the real window is doing — no window moves, and
1765
+ * the operator's frontmost app is undisturbed. That is what this does by
1766
+ * default, and it is how Playwright drives backgrounded pages.
1767
+ *
1768
+ * `--raise` additionally calls `Target.activateTarget`, which genuinely brings
1769
+ * the tab to the front and **takes the operator's screen** — measured in
1770
+ * renderer-wake.ts: every route to a real activation moved the frontmost app
1771
+ * from the terminal to Chrome, and there is no quiet variant. Use it when a
1772
+ * person needs to SEE the tab, not to make a page render.
1773
+ *
1774
+ * # It reports the outcome, not the acceptance
1775
+ *
1776
+ * All three CDP commands are best-effort — an older Chrome may not expose one —
1777
+ * so "sent" says nothing. This reads `document.hasFocus()` and
1778
+ * `visibilityState` back afterwards and prints what it actually achieved,
1779
+ * naming what it could not confirm rather than printing a tick over it.
1780
+ */
1781
+ const focusCommand = define({
1782
+ name: "focus",
1783
+ description: "Make a tab report itself focused + visible, so pages that defer work while hidden (rendering, polling, charts, video) behave as if watched. Quiet by default — no window moves and the operator keeps their frontmost app. Add --raise to genuinely bring the tab to the front, which DOES take the screen.",
1784
+ args: {
1785
+ ...targetArgs,
1786
+ raise: {
1787
+ type: "boolean",
1788
+ short: "r",
1789
+ description: "Also bring the tab to the front for real (Target.activateTarget). This takes the operator's screen — Chrome comes forward over whatever they are using. Only for when a person needs to see the tab."
1790
+ }
1791
+ },
1792
+ async run(ctx) {
1793
+ const raise = ctx.values.raise;
1794
+ const targetId = await resolveExistingTargetId(targetOpts(ctx.values));
1795
+ if (raise) await activateTab(targetId);
1796
+ const state = await withPage(targetId, async (s) => {
1797
+ await forceForeground(s);
1798
+ const deadline = Date.now() + 2e3;
1799
+ let last = {
1800
+ focused: false,
1801
+ visibility: "unknown"
1802
+ };
1803
+ while (Date.now() < deadline) {
1804
+ last = (await s.send("Runtime.evaluate", {
1805
+ expression: "({focused:document.hasFocus(),visibility:document.visibilityState})",
1806
+ returnByValue: true
1807
+ })).result?.value ?? last;
1808
+ if (last.focused && last.visibility === "visible") break;
1809
+ await sleep$1(50);
1810
+ }
1811
+ return last;
1812
+ });
1813
+ const how = raise ? "raised to the front" : "no window focus taken";
1814
+ if (state.focused && state.visibility === "visible") {
1815
+ consola.success(`[${targetId.slice(0, 12)}…] focused + visible (${how})`);
1816
+ return;
1817
+ }
1818
+ consola.warn(`[${targetId.slice(0, 12)}…] hasFocus=${state.focused} visibilityState=${state.visibility} (${how}). The page may still defer work it gates on focus. ` + (raise ? "" : "If the page needs a genuinely front tab, re-run with --raise."));
1819
+ }
1820
+ });
1821
+ //#endregion
1320
1822
  //#region src/commands/eval.ts
1321
1823
  const evalCommand = define({
1322
1824
  name: "eval",
@@ -1331,7 +1833,7 @@ const evalCommand = define({
1331
1833
  async run(ctx) {
1332
1834
  const expr = ctx.positionals[1];
1333
1835
  if (!expr) {
1334
- consola.error("A JS expression is required");
1836
+ consola$1.error("A JS expression is required");
1335
1837
  process.exit(1);
1336
1838
  }
1337
1839
  const v = await evaluate(await resolveExistingTargetId(targetOpts(ctx.values)), expr);
@@ -1424,15 +1926,15 @@ const downloadCommand = define({
1424
1926
  const click = ctx.values.click;
1425
1927
  const url = ctx.values.url;
1426
1928
  if (!click && !url) {
1427
- consola.error("Provide --click <ref> or --url <url> to trigger the download");
1929
+ consola$1.error("Provide --click <ref> or --url <url> to trigger the download");
1428
1930
  process.exit(1);
1429
1931
  }
1430
1932
  if (click && !isValidRef(click)) {
1431
- consola.error(`--click expects a ref like e42 (run snapshot first)`);
1933
+ consola$1.error(`--click expects a ref like e42 (run snapshot first)`);
1432
1934
  process.exit(1);
1433
1935
  }
1434
1936
  const r = await captureDownload(await resolveExistingTargetId(targetOpts(ctx.values)), ctx.values.dir || DEFAULT_DIR$1, click ? clickTriggerExpr(click) : urlTriggerExpr(url), ctx.values.timeout ?? 3e4);
1435
- consola.success(`Downloaded ${r.filename} (${r.bytes} bytes)`);
1937
+ consola$1.success(`Downloaded ${r.filename} (${r.bytes} bytes)`);
1436
1938
  process.stdout.write(r.path + "\n");
1437
1939
  }
1438
1940
  });
@@ -1572,7 +2074,7 @@ function absFiles$2(paths) {
1572
2074
  return paths.map((p) => {
1573
2075
  const abs = resolve(p);
1574
2076
  if (!existsSync(abs) || !statSync(abs).isFile()) {
1575
- consola.error(`no such file: ${abs}`);
2077
+ consola$1.error(`no such file: ${abs}`);
1576
2078
  process.exit(1);
1577
2079
  }
1578
2080
  return abs;
@@ -1596,16 +2098,16 @@ const setfilesCommand = define({
1596
2098
  const ref = ctx.positionals[1];
1597
2099
  const paths = ctx.positionals.slice(2);
1598
2100
  if (!ref || !isValidRef(ref)) {
1599
- consola.error("A ref like \"e7\" is required (run `browser-automation snapshot` first)");
2101
+ consola$1.error("A ref like \"e7\" is required (run `browser-automation snapshot` first)");
1600
2102
  process.exit(1);
1601
2103
  }
1602
2104
  if (paths.length === 0) {
1603
- consola.error("At least one file path is required");
2105
+ consola$1.error("At least one file path is required");
1604
2106
  process.exit(1);
1605
2107
  }
1606
2108
  const files = absFiles$2(paths);
1607
2109
  const r = await setFilesByRef(await resolveExistingTargetId(targetOpts(ctx.values)), ref, files);
1608
- consola.success(`set ${r.files.length} file(s) on ${ref} <${r.tag} type=${r.type}>:`);
2110
+ consola$1.success(`set ${r.files.length} file(s) on ${ref} <${r.tag} type=${r.type}>:`);
1609
2111
  for (const f of r.files) process.stdout.write(f + "\n");
1610
2112
  }
1611
2113
  });
@@ -1616,7 +2118,7 @@ function absFiles$1(paths) {
1616
2118
  return paths.map((p) => {
1617
2119
  const abs = resolve(p);
1618
2120
  if (!existsSync(abs) || !statSync(abs).isFile()) {
1619
- consola.error(`no such file: ${abs}`);
2121
+ consola$1.error(`no such file: ${abs}`);
1620
2122
  process.exit(1);
1621
2123
  }
1622
2124
  return abs;
@@ -1644,28 +2146,28 @@ const uploadCommand = define({
1644
2146
  const click = ctx.values.click;
1645
2147
  const paths = ctx.positionals.slice(1);
1646
2148
  if (!click) {
1647
- consola.error("--click <ref> is required (the button that opens the file chooser)");
2149
+ consola$1.error("--click <ref> is required (the button that opens the file chooser)");
1648
2150
  process.exit(1);
1649
2151
  }
1650
2152
  if (!isValidRef(click)) {
1651
- consola.error("--click expects a ref like e42 (run `browser-automation snapshot` first)");
2153
+ consola$1.error("--click expects a ref like e42 (run `browser-automation snapshot` first)");
1652
2154
  process.exit(1);
1653
2155
  }
1654
2156
  if (paths.length === 0) {
1655
- consola.error("At least one file path is required");
2157
+ consola$1.error("At least one file path is required");
1656
2158
  process.exit(1);
1657
2159
  }
1658
2160
  const files = absFiles$1(paths);
1659
2161
  const r = await uploadViaChooser(await resolveExistingTargetId(targetOpts(ctx.values)), click, files, ctx.values.timeout ?? 15e3);
1660
2162
  if (r.delivered === 0) {
1661
- 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.`);
2163
+ consola$1.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.`);
1662
2164
  process.exit(1);
1663
2165
  }
1664
2166
  const note = r.reconnected ? " (input was detached — re-attached and re-dispatched input/change so the page's handler fired)" : "";
1665
- consola.success(`delivered ${r.files.length} file(s) to the page's file handler via chooser (backendNodeId ${r.backendNodeId})${note}:`);
2167
+ consola$1.success(`delivered ${r.files.length} file(s) to the page's file handler via chooser (backendNodeId ${r.backendNodeId})${note}:`);
1666
2168
  for (const f of r.files) process.stdout.write(f + "\n");
1667
- if (r.count === 0) consola.info("The app consumed the file and reset the input (normal). This confirms delivery, not staging — re-snapshot or screenshot to verify the attachment chip/preview actually appeared before submitting.");
1668
- else consola.info("Re-snapshot to confirm the attachment chip/preview appeared before submitting — the DOM changed.");
2169
+ if (r.count === 0) consola$1.info("The app consumed the file and reset the input (normal). This confirms delivery, not staging — re-snapshot or screenshot to verify the attachment chip/preview actually appeared before submitting.");
2170
+ else consola$1.info("Re-snapshot to confirm the attachment chip/preview appeared before submitting — the DOM changed.");
1669
2171
  }
1670
2172
  });
1671
2173
  //#endregion
@@ -1676,7 +2178,7 @@ function absFiles(paths) {
1676
2178
  return paths.map((p) => {
1677
2179
  const abs = resolve(p);
1678
2180
  if (!existsSync(abs) || !statSync(abs).isFile()) {
1679
- consola.error(`no such file: ${abs}`);
2181
+ consola$1.error(`no such file: ${abs}`);
1680
2182
  process.exit(1);
1681
2183
  }
1682
2184
  return abs;
@@ -1731,11 +2233,11 @@ const dropCommand = define({
1731
2233
  const ref = ctx.positionals[1];
1732
2234
  const paths = ctx.positionals.slice(2);
1733
2235
  if (!ref || !isValidRef(ref)) {
1734
- consola.error("A ref like \"e7\" is required (run `browser-automation snapshot` first)");
2236
+ consola$1.error("A ref like \"e7\" is required (run `browser-automation snapshot` first)");
1735
2237
  process.exit(1);
1736
2238
  }
1737
2239
  if (paths.length === 0) {
1738
- consola.error("At least one file path is required");
2240
+ consola$1.error("At least one file path is required");
1739
2241
  process.exit(1);
1740
2242
  }
1741
2243
  const files = absFiles(paths);
@@ -1747,10 +2249,10 @@ const dropCommand = define({
1747
2249
  b64: readFileSync(p).toString("base64")
1748
2250
  }))));
1749
2251
  if (r.err) {
1750
- consola.error(r.err);
2252
+ consola$1.error(r.err);
1751
2253
  process.exit(1);
1752
2254
  }
1753
- consola.success(`dropped ${r.count} file(s) on ${ref} <${r.tag}> (synthetic — re-snapshot/screenshot to confirm the zone accepted them):`);
2255
+ consola$1.success(`dropped ${r.count} file(s) on ${ref} <${r.tag}> (synthetic — re-snapshot/screenshot to confirm the zone accepted them):`);
1754
2256
  for (const f of files) process.stdout.write(f + "\n");
1755
2257
  return;
1756
2258
  }
@@ -1781,7 +2283,7 @@ const dropCommand = define({
1781
2283
  while (Date.now() < actDeadline) {
1782
2284
  const a = await evalIn(actionabilityExpr(ref));
1783
2285
  if (a?.err) {
1784
- consola.error(a.err);
2286
+ consola$1.error(a.err);
1785
2287
  process.exit(1);
1786
2288
  }
1787
2289
  const stable = prev !== null && Math.abs(prev.x - a.x) < .5 && Math.abs(prev.y - a.y) < .5;
@@ -1801,7 +2303,7 @@ const dropCommand = define({
1801
2303
  await sleep(60);
1802
2304
  }
1803
2305
  if (!point) {
1804
- consola.error(`<${ref}> not actionable for a drop: ${lastReason}`);
2306
+ consola$1.error(`<${ref}> not actionable for a drop: ${lastReason}`);
1805
2307
  process.exit(1);
1806
2308
  }
1807
2309
  const { x, y } = point;
@@ -1831,9 +2333,9 @@ const dropCommand = define({
1831
2333
  });
1832
2334
  return point.tag;
1833
2335
  });
1834
- consola.success(`dropped ${files.length} file(s) on ${ref} <${tag}> (trusted):`);
2336
+ consola$1.success(`dropped ${files.length} file(s) on ${ref} <${tag}> (trusted):`);
1835
2337
  for (const f of files) process.stdout.write(f + "\n");
1836
- consola.info("Re-snapshot or screenshot to confirm the zone accepted the drop — the DOM changed.");
2338
+ consola$1.info("Re-snapshot or screenshot to confirm the zone accepted the drop — the DOM changed.");
1837
2339
  }
1838
2340
  });
1839
2341
  //#endregion
@@ -1946,7 +2448,7 @@ const networkCommand = define({
1946
2448
  async run(ctx) {
1947
2449
  const click = ctx.values.click;
1948
2450
  if (click && !isValidRef(click)) {
1949
- consola.error("--click expects a ref like e42");
2451
+ consola$1.error("--click expects a ref like e42");
1950
2452
  process.exit(1);
1951
2453
  }
1952
2454
  const entries = await captureNetwork(await resolveExistingTargetId(targetOpts(ctx.values)), {
@@ -1962,14 +2464,14 @@ const networkCommand = define({
1962
2464
  process.stdout.write(JSON.stringify(entries, null, 2) + "\n");
1963
2465
  return;
1964
2466
  }
1965
- consola.log(`# ${entries.length} requests`);
2467
+ consola$1.log(`# ${entries.length} requests`);
1966
2468
  for (const e of entries) {
1967
- consola.log(`${(e.method ?? "").padEnd(5)} ${String(e.status ?? "—").padEnd(4)} ${(e.type ?? "").padEnd(9)} ${e.url.slice(0, 100)}`);
2469
+ consola$1.log(`${(e.method ?? "").padEnd(5)} ${String(e.status ?? "—").padEnd(4)} ${(e.type ?? "").padEnd(9)} ${e.url.slice(0, 100)}`);
1968
2470
  if (ctx.values.headers) {
1969
- if (e.postData) consola.log(` ↑ body: ${e.postData.slice(0, 200)}`);
1970
- for (const [k, v] of Object.entries(e.requestHeaders ?? {})) if (/^(authorization|cookie|x-|content-type)/i.test(k)) consola.log(` ↑ ${k}: ${String(v).slice(0, 120)}`);
2471
+ if (e.postData) consola$1.log(` ↑ body: ${e.postData.slice(0, 200)}`);
2472
+ for (const [k, v] of Object.entries(e.requestHeaders ?? {})) if (/^(authorization|cookie|x-|content-type)/i.test(k)) consola$1.log(` ↑ ${k}: ${String(v).slice(0, 120)}`);
1971
2473
  }
1972
- if (ctx.values.body && e.body) consola.log(` ↓ ${e.body.replace(/\s+/g, " ").slice(0, 300)}`);
2474
+ if (ctx.values.body && e.body) consola$1.log(` ↓ ${e.body.replace(/\s+/g, " ").slice(0, 300)}`);
1973
2475
  }
1974
2476
  }
1975
2477
  });
@@ -2000,7 +2502,7 @@ const screenshotCommand = define({
2000
2502
  out = join(DEFAULT_DIR, `${((await listPageTargets()).find((p) => p.id === targetId)?.title || "page").replace(/[^a-z0-9]+/gi, "-").replace(/^-|-$/g, "").slice(0, 40) || "page"}.png`);
2001
2503
  }
2002
2504
  writeFileSync(out, png);
2003
- consola.success(`Saved screenshot (${png.length} bytes)`);
2505
+ consola$1.success(`Saved screenshot (${png.length} bytes)`);
2004
2506
  process.stdout.write(out + "\n");
2005
2507
  }
2006
2508
  });
@@ -2014,6 +2516,10 @@ const listCommand = define({
2014
2516
  type: "boolean",
2015
2517
  description: "Output raw JSON"
2016
2518
  },
2519
+ all: {
2520
+ type: "boolean",
2521
+ description: "Also list stale session bookmarks (tabs that no longer exist), instead of just counting them"
2522
+ },
2017
2523
  frames: {
2018
2524
  type: "boolean",
2019
2525
  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>."
@@ -2032,23 +2538,27 @@ const listCommand = define({
2032
2538
  return;
2033
2539
  }
2034
2540
  const liveIds = new Set(targets.map((t) => t.id));
2035
- if (sessions.length) {
2036
- consola.log(`# sessions (${sessions.length})`);
2037
- for (const s of sessions) consola.log(` ${s.name.padEnd(16)} [${liveIds.has(s.targetId) ? "live" : "stale"}] ${s.url ?? ""}`);
2038
- consola.log("");
2039
- }
2040
- consola.log(`# open tabs (${targets.length}) — address with -t <id> or -m <substr>`);
2541
+ const live = sessions.filter((s) => liveIds.has(s.targetId));
2542
+ const stale = sessions.filter((s) => !liveIds.has(s.targetId));
2543
+ const shown = ctx.values.all ? sessions : live;
2544
+ if (shown.length) {
2545
+ consola$1.log(`# sessions (${shown.length}${ctx.values.all ? "" : " live"})`);
2546
+ for (const s of shown) consola$1.log(` ${s.name.padEnd(16)} [${liveIds.has(s.targetId) ? "live" : "stale"}] ${s.url ?? ""}`);
2547
+ } else if (sessions.length) consola$1.log(`# sessions (0 live)`);
2548
+ if (stale.length && !ctx.values.all) consola$1.log(` + ${stale.length} stale bookmark(s) whose tab is gone — \`list --all\` to see them, \`gc --sessions\` to clear them`);
2549
+ if (sessions.length) consola$1.log("");
2550
+ consola$1.log(`# open tabs (${targets.length}) — address with -t <id> or -m <substr>`);
2041
2551
  for (const t of targets) {
2042
2552
  const owner = sessions.find((s) => s.targetId === t.id);
2043
2553
  const title = (t.title ?? "").replace(/\s+/g, " ").slice(0, 28);
2044
- consola.log(` ${t.id.slice(0, 12)} ${owner ? `(${owner.name}) ` : ""}${title.padEnd(28)} ${(t.url ?? "").slice(0, 70)}`);
2554
+ consola$1.log(` ${t.id.slice(0, 12)} ${owner ? `(${owner.name}) ` : ""}${title.padEnd(28)} ${(t.url ?? "").slice(0, 70)}`);
2045
2555
  }
2046
2556
  if (ctx.values.frames) {
2047
- consola.log("");
2048
- consola.log(`# cross-origin iframes (${frames.length}) — address with -F <substr> or -t <id>`);
2557
+ consola$1.log("");
2558
+ consola$1.log(`# cross-origin iframes (${frames.length}) — address with -F <substr> or -t <id>`);
2049
2559
  for (const f of frames) {
2050
2560
  const title = (f.title ?? "").replace(/\s+/g, " ").slice(0, 28);
2051
- consola.log(` ${f.id.slice(0, 12)} ${title.padEnd(28)} ${(f.url ?? "").slice(0, 70)}`);
2561
+ consola$1.log(` ${f.id.slice(0, 12)} ${title.padEnd(28)} ${(f.url ?? "").slice(0, 70)}`);
2052
2562
  }
2053
2563
  }
2054
2564
  }
@@ -2071,12 +2581,12 @@ const closeCommand = define({
2071
2581
  try {
2072
2582
  targetId = await resolveExistingTargetId(opts);
2073
2583
  } catch (e) {
2074
- consola.warn(e instanceof Error ? e.message : String(e));
2584
+ consola$1.warn(e instanceof Error ? e.message : String(e));
2075
2585
  return;
2076
2586
  }
2077
2587
  if (ctx.values.tab) {
2078
2588
  const ok = await closeTab(targetId).catch(() => false);
2079
- consola.log(ok ? `Closed tab ${targetId.slice(0, 12)}….` : `Tab ${targetId.slice(0, 12)}… was already gone.`);
2589
+ consola$1.log(ok ? `Closed tab ${targetId.slice(0, 12)}….` : `Tab ${targetId.slice(0, 12)}… was already gone.`);
2080
2590
  }
2081
2591
  const forgotten = [];
2082
2592
  for (const s of listSessions()) if (s.targetId === targetId) {
@@ -2090,8 +2600,8 @@ const closeCommand = define({
2090
2600
  forgotten.push(name);
2091
2601
  }
2092
2602
  }
2093
- if (forgotten.length) consola.success(`Forgot session(s): ${forgotten.join(", ")}.`);
2094
- else if (!ctx.values.tab) consola.info("No session bound to that tab and --tab not given — nothing to do.");
2603
+ if (forgotten.length) consola$1.success(`Forgot session(s): ${forgotten.join(", ")}.`);
2604
+ else if (!ctx.values.tab) consola$1.info("No session bound to that tab and --tab not given — nothing to do.");
2095
2605
  }
2096
2606
  });
2097
2607
  //#endregion
@@ -2105,7 +2615,7 @@ const bindCommand = define({
2105
2615
  const match = ctx.values.match;
2106
2616
  const target = ctx.values.target;
2107
2617
  if (!match && !target) {
2108
- consola.error("Pick the tab to adopt with -m <url/title substr> or -t <targetId>. See `browser-automation list`.");
2618
+ consola$1.error("Pick the tab to adopt with -m <url/title substr> or -t <targetId>. See `browser-automation list`.");
2109
2619
  process.exit(1);
2110
2620
  }
2111
2621
  let targetId;
@@ -2124,7 +2634,7 @@ const bindCommand = define({
2124
2634
  url,
2125
2635
  createdAt: (/* @__PURE__ */ new Date()).toISOString()
2126
2636
  });
2127
- consola.success(`Bound session "${name}" → ${url ?? targetId}`);
2637
+ consola$1.success(`Bound session "${name}" → ${url ?? targetId}`);
2128
2638
  }
2129
2639
  });
2130
2640
  //#endregion
@@ -2153,7 +2663,7 @@ const launchCommand = define({
2153
2663
  async run(ctx) {
2154
2664
  const script = launchScriptPath();
2155
2665
  if (!existsSync(script)) {
2156
- consola.error(`launch-chrome.sh not found at ${script}. Reinstall the package.`);
2666
+ consola$1.error(`launch-chrome.sh not found at ${script}. Reinstall the package.`);
2157
2667
  process.exit(1);
2158
2668
  }
2159
2669
  const r = spawnSync("bash", [script, ...[
@@ -2167,15 +2677,19 @@ const launchCommand = define({
2167
2677
  ok: false,
2168
2678
  ms: 0,
2169
2679
  pageTargets: 0,
2170
- reason: String(e?.message ?? e)
2680
+ reason: String(e?.message ?? e),
2681
+ outcome: "error",
2682
+ verdict: "unknown",
2683
+ attempts: []
2171
2684
  }));
2172
2685
  if (health.ok) {
2173
- consola.success(`Renderer capacity: a new tab got a live renderer in ${health.ms}ms — this Chrome works.`);
2686
+ const woke = health.attempts.some((a) => a.woke);
2687
+ consola$1.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.)" : ""));
2174
2688
  return;
2175
2689
  }
2176
- consola.error("Chrome is up, but it cannot make renderers — this browser is unusable.\n");
2177
- for (const line of explainRendererFailure(health).split("\n")) consola.log(line);
2178
- consola.log(`\nChrome's own log: ${chromeLogPath()}`);
2690
+ consola$1.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");
2691
+ for (const line of explainRendererFailure(health).split("\n")) consola$1.log(line);
2692
+ consola$1.log(`\nChrome's own log: ${chromeLogPath()}`);
2179
2693
  process.exit(1);
2180
2694
  }
2181
2695
  });
@@ -2212,12 +2726,12 @@ const doctorCommand = define({
2212
2726
  description: "Diagnose the setup: Node, this user's Chrome, targets, sessions",
2213
2727
  args: {},
2214
2728
  async run() {
2215
- const ok = (m) => consola.log(` ✓ ${m}`);
2216
- const bad = (m) => consola.log(` ✗ ${m}`);
2729
+ const ok = (m) => consola$1.log(` ✓ ${m}`);
2730
+ const bad = (m) => consola$1.log(` ✗ ${m}`);
2217
2731
  if (Number(process.versions.node.split(".")[0]) >= 22) ok(`Node ${process.versions.node} (global WebSocket available)`);
2218
2732
  else bad(`Node ${process.versions.node} — need >= 22 for the global WebSocket CDP client`);
2219
- consola.log(` • CDP host: ${cdpHost()} (port ${cdpPort()} — derived from uid ${process.getuid?.() ?? "?"})`);
2220
- consola.log(` • Profile: ${PROFILE}`);
2733
+ consola$1.log(` • CDP host: ${cdpHost()} (port ${cdpPort()} — derived from uid ${process.getuid?.() ?? "?"})`);
2734
+ consola$1.log(` • Profile: ${PROFILE}`);
2221
2735
  let version;
2222
2736
  try {
2223
2737
  version = await (await fetch(`${cdpHost()}/json/version`)).json();
@@ -2236,7 +2750,7 @@ const doctorCommand = define({
2236
2750
  for (const t of targets) byType[t.type] = (byType[t.type] ?? 0) + 1;
2237
2751
  const summary = Object.entries(byType).map(([k, v]) => `${v} ${k}`).join(", ");
2238
2752
  ok(`${targets.length} targets (${summary})`);
2239
- consola.log(` (per-target CDP — target count never wedges this CLI)`);
2753
+ consola$1.log(` (per-target CDP — target count never wedges this CLI)`);
2240
2754
  } catch {
2241
2755
  bad("Could not enumerate targets");
2242
2756
  }
@@ -2244,21 +2758,32 @@ const doctorCommand = define({
2244
2758
  ok: false,
2245
2759
  ms: 0,
2246
2760
  pageTargets: 0,
2247
- reason: String(e?.message ?? e)
2761
+ reason: String(e?.message ?? e),
2762
+ outcome: "error",
2763
+ verdict: "unknown",
2764
+ attempts: []
2248
2765
  }));
2249
2766
  if (health.ok) {
2767
+ const woke = health.attempts.some((a) => a.woke);
2250
2768
  ok(`Renderer capacity: a new tab got a live renderer in ${health.ms}ms`);
2251
- const pid = browserPid();
2252
- if (rendezvousRegistered(pid) === false) {
2253
- consola.log(` ⚠ but the Mach rendezvous service for pid ${pid} is NOT registered —`);
2254
- consola.log(` new renderers are expected to start failing. Restart Chrome soon:`);
2255
- consola.log(` browser-automation launch --restart`);
2769
+ if (woke) {
2770
+ consola$1.log(` ⚠ it only answered after being activated — this Chrome is slow to give`);
2771
+ consola$1.log(` BACKGROUND tabs a renderer (measured: median 367ms, tail past 30s).`);
2772
+ consola$1.log(` Commands will work; new tabs may briefly raise the Chrome window.`);
2773
+ }
2774
+ const ev = gatherEvidence();
2775
+ if (ev.rendezvous === false) {
2776
+ consola$1.log(` ⚠ but the Mach rendezvous service for pid ${ev.pid} is NOT registered —`);
2777
+ consola$1.log(` new renderers are expected to start failing. Restart Chrome soon:`);
2778
+ consola$1.log(` browser-automation launch --restart`);
2256
2779
  }
2257
2780
  } else {
2258
- bad(`Renderer capacity: FAILED`);
2259
- for (const line of explainRendererFailure(health).split("\n")) consola.log(` ${line}`);
2260
- consola.log(` Chrome's own log: ${chromeLogPath()}`);
2781
+ bad(`Renderer capacity: FAILED (${health.verdict})`);
2782
+ for (const line of explainRendererFailure(health).split("\n")) consola$1.log(` ${line}`);
2783
+ consola$1.log(` Chrome's own log: ${chromeLogPath()}`);
2261
2784
  }
2785
+ const stats = recentProbeStats();
2786
+ if (stats) consola$1.log(` • last ${stats.n} renderer probe(s): ${stats.failures} failed` + (stats.median >= 0 ? `, median ${stats.median}ms, slowest success ${stats.worst}ms` : ""));
2262
2787
  const sessions = listSessions();
2263
2788
  let live = 0;
2264
2789
  try {
@@ -2266,13 +2791,13 @@ const doctorCommand = define({
2266
2791
  live = sessions.filter((s) => liveIds.has(s.targetId)).length;
2267
2792
  } catch {}
2268
2793
  const stale = sessions.length - live;
2269
- consola.log(` • ${sessions.length} known session(s): ${live} live, ${stale} stale`);
2794
+ consola$1.log(` • ${sessions.length} known session(s): ${live} live, ${stale} stale`);
2270
2795
  if (sessions.length) {
2271
2796
  const names = sessions.map((s) => s.name);
2272
2797
  const shown = names.slice(0, 12).join(", ");
2273
- consola.log(` ${shown}${names.length > 12 ? `, … (+${names.length - 12} more — \`browser-automation list\`)` : ""}`);
2798
+ consola$1.log(` ${shown}${names.length > 12 ? `, … (+${names.length - 12} more — \`browser-automation list\`)` : ""}`);
2274
2799
  }
2275
- if (stale > 20) consola.log(` ${stale} stale bookmarks point at tabs that no longer exist — \`browser-automation gc --dry\` to review.`);
2800
+ if (stale > 20) consola$1.log(` ${stale} stale bookmarks point at tabs that no longer exist — \`browser-automation gc --dry\` to review.`);
2276
2801
  }
2277
2802
  });
2278
2803
  //#endregion
@@ -2330,10 +2855,10 @@ const gcCommand = define({
2330
2855
  const stale = sessions.filter((s) => !liveIds.has(s.targetId));
2331
2856
  for (const s of stale) {
2332
2857
  if (!dry) deleteSession(s.name);
2333
- consola.log(` session ${act} ${s.name} (tab gone: ${s.targetId.slice(0, 12)}…)`);
2858
+ consola$1.log(` session ${act} ${s.name} (tab gone: ${s.targetId.slice(0, 12)}…)`);
2334
2859
  }
2335
2860
  if (ctx.values.sessions) {
2336
- consola.success(`${stale.length} stale session bookmark(s) ${act}. No tabs touched.`);
2861
+ consola$1.success(`${stale.length} stale session bookmark(s) ${act}. No tabs touched.`);
2337
2862
  return;
2338
2863
  }
2339
2864
  const claimed = new Map(sessions.filter((s) => liveIds.has(s.targetId)).map((s) => [s.targetId, s.name]));
@@ -2345,17 +2870,17 @@ const gcCommand = define({
2345
2870
  for (const { t, dead: why } of dead) {
2346
2871
  const owner = claimed.get(t.id);
2347
2872
  if (!dry) await closeTab(t.id).catch(() => {});
2348
- consola.log(` dead tab ${actTab} ${t.id.slice(0, 12)}… ${owner ? `(${owner}) ` : ""}${(t.url ?? "").slice(0, 60) || "(no url)"} — ${why}`);
2873
+ consola$1.log(` dead tab ${actTab} ${t.id.slice(0, 12)}… ${owner ? `(${owner}) ` : ""}${(t.url ?? "").slice(0, 60) || "(no url)"} — ${why}`);
2349
2874
  }
2350
2875
  const orphans = probes.filter((p) => !p.dead && !claimed.has(p.t.id));
2351
2876
  if (ctx.values.orphans) for (const { t } of orphans) {
2352
2877
  if (!dry) await closeTab(t.id).catch(() => {});
2353
- consola.log(` orphan ${actTab} ${t.id.slice(0, 12)}… ${(t.title ?? "").slice(0, 28).padEnd(28)} ${(t.url ?? "").slice(0, 50)}`);
2878
+ consola$1.log(` orphan ${actTab} ${t.id.slice(0, 12)}… ${(t.title ?? "").slice(0, 28).padEnd(28)} ${(t.url ?? "").slice(0, 50)}`);
2354
2879
  }
2355
- consola.log("");
2356
- 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}` : "") + ".");
2357
- 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.`);
2358
- 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.");
2880
+ consola$1.log("");
2881
+ consola$1.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}` : "") + ".");
2882
+ if (!ctx.values.orphans && orphans.length) consola$1.log(` ${orphans.length} live tab(s) no session claims were left alone — \`gc --orphans --dry\` to review them.`);
2883
+ if (dead.length && dead.length === pages.length && pages.length > 0) consola$1.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.");
2359
2884
  }
2360
2885
  });
2361
2886
  //#endregion
@@ -2386,6 +2911,7 @@ const subCommands = new Map([
2386
2911
  ["click", clickCommand],
2387
2912
  ["fill", fillCommand],
2388
2913
  ["read", readCommand],
2914
+ ["focus", focusCommand],
2389
2915
  ["eval", evalCommand],
2390
2916
  ["download", downloadCommand],
2391
2917
  ["setfiles", setfilesCommand],