@generativereality/browser-automation 0.4.13 → 0.4.15

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,9 +1,10 @@
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.13",
4
+ "version": "0.4.15",
5
5
  "author": {
6
6
  "name": "generativereality"
7
7
  },
8
- "homepage": "https://github.com/generativereality/browser-automation"
8
+ "homepage": "https://github.com/generativereality/browser-automation",
9
+ "license": "MIT"
9
10
  }
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 generativereality
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -42,11 +42,16 @@ browser-automation doctor # verify (incl. renderer capacity)
42
42
  Claude Code skill (so the agent knows how to use it):
43
43
 
44
44
  ```bash
45
- mkdir -p .claude/skills/browser
46
- curl -fsSL https://raw.githubusercontent.com/generativereality/browser-automation/main/skills/browser/SKILL.md \
47
- -o .claude/skills/browser/SKILL.md
45
+ mkdir -p .claude/skills/browser/references
46
+ base=https://raw.githubusercontent.com/generativereality/browser-automation/master/skills/browser
47
+ for f in SKILL.md references/input-and-forms.md references/renderer-health.md references/contributing.md; do
48
+ curl -fsSL "$base/$f" -o ".claude/skills/browser/$f"
49
+ done
48
50
  ```
49
51
 
52
+ The skill is `SKILL.md` plus the `references/` files it points to for the long
53
+ troubleshooting and hard cases; copy all of them.
54
+
50
55
  …or install the plugin from the marketplace:
51
56
 
52
57
  ```bash
@@ -180,9 +185,9 @@ same one-action-per-snapshot rule as Playwright refs.
180
185
  repeats a rule is a copy of it, and goes stale the same way code does.
181
186
  `doctor` prints it too, and warns if another user holds it.
182
187
  - `BROWSER_AUTOMATION_CDP` — full CDP host, overriding the port entirely.
183
- - `BROWSER_AUTOMATION_PROFILE` — Chrome profile dir for `launch`.
188
+ - `BROWSER_AUTOMATION_PROFILE` — Chrome profile dir for `launch`. Default `~/.browser-automation/chrome-profile`; a profile still at the old location inside Chrome's own folder is moved there on launch (`browser-automation profile --migrate` to do it by hand).
184
189
  - `BAC_SESSION` — default session name for page commands.
185
190
 
186
191
  ## License
187
192
 
188
- MIT
193
+ MIT — see [`LICENSE`](LICENSE).
package/dist/index.js CHANGED
@@ -4,12 +4,12 @@ import { cli, define } from "gunshi";
4
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 { appendFileSync, existsSync, mkdirSync, readFileSync, readdirSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
7
+ import { appendFileSync, existsSync, lstatSync, 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.13";
12
+ var version = "0.4.15";
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": "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",
32
+ "release": "bash scripts/release.sh",
33
33
  "sync-plugin": "bash scripts/sync-plugin.sh",
34
34
  "prepack": "npm run build"
35
35
  },
@@ -408,6 +408,22 @@ async function activateTab(targetId) {
408
408
  await s.send("Target.activateTarget", { targetId });
409
409
  });
410
410
  }
411
+ /**
412
+ * Ask Chrome to quit, the way its own menu does.
413
+ *
414
+ * `launch --restart` used to rely on SIGTERM, and on macOS 27 / Chrome 153 the
415
+ * browser process never exits on it: the DevTools port and helpers go, the
416
+ * process stays asleep. Measured 2026-09-23, every restart of every Chrome,
417
+ * however launched. The script then escalates to SIGKILL, which skips the
418
+ * profile flush that keeps the logins — so quit it properly first and leave the
419
+ * signals as the fallback. Resolves once the request is sent; the connection
420
+ * dropping as Chrome goes is the expected outcome, not an error.
421
+ */
422
+ async function closeBrowser() {
423
+ await withBrowser(async (s) => {
424
+ await s.send("Browser.close", {}, 3e3).catch(() => {});
425
+ }, 3e3);
426
+ }
411
427
  async function closeTab(targetId) {
412
428
  return withBrowser(async (s) => {
413
429
  return !!(await s.send("Target.closeTarget", { targetId })).success;
@@ -2646,6 +2662,123 @@ function launchScriptPath() {
2646
2662
  return join(packageRoot(), "scripts", "launch-chrome.sh");
2647
2663
  }
2648
2664
  //#endregion
2665
+ //#region src/core/profile.ts
2666
+ /** The default, under ~, reachable by every host. */
2667
+ function homeProfileDir() {
2668
+ return join(homedir(), ".browser-automation", "chrome-profile");
2669
+ }
2670
+ /** The old default, inside Google Chrome's own app-data folder. */
2671
+ function legacyProfileDir() {
2672
+ return join(homedir(), "Library", "Application Support", "Google", "Chrome", "browser-automation");
2673
+ }
2674
+ /**
2675
+ * Does a path exist, as far as this process can tell?
2676
+ *
2677
+ * `unreadable` is its own answer and callers must not fold it into `absent`:
2678
+ * it is what a host denied Chrome's container sees for a profile that is very
2679
+ * much there.
2680
+ */
2681
+ function presence(p) {
2682
+ try {
2683
+ lstatSync(p);
2684
+ return "present";
2685
+ } catch (e) {
2686
+ return e?.code === "ENOENT" || e?.code === "ENOTDIR" ? "absent" : "unreadable";
2687
+ }
2688
+ }
2689
+ /**
2690
+ * Which profile to use, WITHOUT changing anything on disk.
2691
+ *
2692
+ * The home folder once it exists; otherwise the legacy folder whenever it
2693
+ * might exist (present or unreadable); otherwise the home folder, for Chrome
2694
+ * to create on first launch.
2695
+ */
2696
+ function resolveProfile() {
2697
+ const explicit = process.env.BROWSER_AUTOMATION_PROFILE;
2698
+ if (explicit) return {
2699
+ dir: explicit,
2700
+ source: "env"
2701
+ };
2702
+ const home = homeProfileDir();
2703
+ if (presence(home) === "present") return {
2704
+ dir: home,
2705
+ source: "home"
2706
+ };
2707
+ if (presence(legacyProfileDir()) !== "absent") return {
2708
+ dir: legacyProfileDir(),
2709
+ source: "legacy"
2710
+ };
2711
+ return {
2712
+ dir: home,
2713
+ source: "home"
2714
+ };
2715
+ }
2716
+ /** Is any Chrome of ours running with this --user-data-dir? */
2717
+ function inUse(dir) {
2718
+ try {
2719
+ execFileSync("pgrep", [
2720
+ "-u",
2721
+ String(process.getuid?.() ?? -1),
2722
+ "-f",
2723
+ "--",
2724
+ `--user-data-dir=${dir}`
2725
+ ], { stdio: "ignore" });
2726
+ return true;
2727
+ } catch {
2728
+ return false;
2729
+ }
2730
+ }
2731
+ /** Move the legacy profile into the home folder, if that is both needed and safe. */
2732
+ function migrateProfile() {
2733
+ const choice = resolveProfile();
2734
+ if (choice.source === "env") return {
2735
+ outcome: "explicit",
2736
+ dir: choice.dir
2737
+ };
2738
+ if (choice.source === "home") return {
2739
+ outcome: presence(choice.dir) === "present" ? "current" : "fresh",
2740
+ dir: choice.dir
2741
+ };
2742
+ const legacy = legacyProfileDir();
2743
+ const home = homeProfileDir();
2744
+ if (presence(legacy) === "unreadable") return {
2745
+ outcome: "refused",
2746
+ dir: legacy,
2747
+ detail: `this process may not read ${legacy}. On macOS that is the app-data permission ("… would like to access data from other apps") for the app this is running under. Run \`browser-automation profile --migrate\` once from a terminal that can reach it, and every host will use the new location from then on.`
2748
+ };
2749
+ if (inUse(legacy)) return {
2750
+ outcome: "in-use",
2751
+ dir: legacy,
2752
+ detail: `a running Chrome has ${legacy} open, and a profile is never moved underneath one. It moves on the next launch after that Chrome quits — or now, with \`browser-automation launch --restart\`.`
2753
+ };
2754
+ try {
2755
+ mkdirSync(dirname(home), { recursive: true });
2756
+ renameSync(legacy, home);
2757
+ } catch (e) {
2758
+ const code = e?.code;
2759
+ if (code === "EPERM" || code === "EACCES") return {
2760
+ outcome: "refused",
2761
+ dir: legacy,
2762
+ detail: `could not move ${legacy} (${code}): this process may not write Chrome's folder. On macOS that is the app-data grant for the app this is running under. Nothing was changed; the old profile keeps working. Run \`browser-automation profile --migrate\` once from a terminal that can reach it.`
2763
+ };
2764
+ return {
2765
+ outcome: "failed",
2766
+ dir: legacy,
2767
+ detail: `could not move ${legacy} to ${home} (${code ?? e?.message}). Nothing was changed; the old profile keeps working.`
2768
+ };
2769
+ }
2770
+ for (const f of [
2771
+ "SingletonLock",
2772
+ "SingletonSocket",
2773
+ "SingletonCookie"
2774
+ ]) rmSync(join(home, f), { force: true });
2775
+ return {
2776
+ outcome: "moved",
2777
+ dir: home,
2778
+ detail: `moved ${legacy} → ${home}`
2779
+ };
2780
+ }
2781
+ //#endregion
2649
2782
  //#region src/commands/launch.ts
2650
2783
  const launchCommand = define({
2651
2784
  name: "launch",
@@ -2666,13 +2799,30 @@ const launchCommand = define({
2666
2799
  consola$1.error(`launch-chrome.sh not found at ${script}. Reinstall the package.`);
2667
2800
  process.exit(1);
2668
2801
  }
2669
- const r = spawnSync("bash", [script, ...[
2670
- "--port",
2671
- String(cdpPort()),
2672
- ...ctx.values.status ? ["--status"] : [],
2673
- ...ctx.values.restart ? ["--restart"] : []
2674
- ]], { stdio: "inherit" });
2675
- if (r.status !== 0 || ctx.values.status) process.exit(r.status ?? 1);
2802
+ const port = ["--port", String(cdpPort())];
2803
+ const bash = (extra) => spawnSync("bash", [
2804
+ script,
2805
+ ...port,
2806
+ ...extra
2807
+ ], { stdio: "inherit" });
2808
+ if (ctx.values.status) process.exit(bash(["--status"]).status ?? 1);
2809
+ if (ctx.values.restart) {
2810
+ const tabs = await listPageTargets().then((t) => t.length).catch(() => null);
2811
+ if (tabs !== null) consola$1.info(`Restarting Chrome on :${cdpPort()} — closing ${tabs} open tab(s).`);
2812
+ await closeBrowser().catch(() => {});
2813
+ const stop = bash([
2814
+ "--stop",
2815
+ "--profile",
2816
+ resolveProfile().dir
2817
+ ]);
2818
+ if (stop.status !== 0) process.exit(stop.status ?? 1);
2819
+ }
2820
+ const m = migrateProfile();
2821
+ if (m.outcome === "moved") consola$1.success(`Profile ${m.detail} — logins travel with it.`);
2822
+ else if (m.outcome === "refused" || m.outcome === "failed") consola$1.warn(`Profile not moved: ${m.detail}`);
2823
+ else if (m.outcome === "in-use") consola$1.info(`Profile not moved yet: ${m.detail}`);
2824
+ const r = bash(["--profile", m.dir]);
2825
+ if (r.status !== 0) process.exit(r.status ?? 1);
2676
2826
  const health = await probeRenderer().catch((e) => ({
2677
2827
  ok: false,
2678
2828
  ms: 0,
@@ -2695,7 +2845,6 @@ const launchCommand = define({
2695
2845
  });
2696
2846
  //#endregion
2697
2847
  //#region src/commands/doctor.ts
2698
- const PROFILE = process.env.BROWSER_AUTOMATION_PROFILE || `${homedir()}/Library/Application Support/Google/Chrome/browser-automation`;
2699
2848
  /**
2700
2849
  * Does a Chrome THIS user started serve our CDP port?
2701
2850
  *
@@ -2731,7 +2880,12 @@ const doctorCommand = define({
2731
2880
  if (Number(process.versions.node.split(".")[0]) >= 22) ok(`Node ${process.versions.node} (global WebSocket available)`);
2732
2881
  else bad(`Node ${process.versions.node} — need >= 22 for the global WebSocket CDP client`);
2733
2882
  consola$1.log(` • CDP host: ${cdpHost()} (port ${cdpPort()} — derived from uid ${process.getuid?.() ?? "?"})`);
2734
- consola$1.log(` • Profile: ${PROFILE}`);
2883
+ const profile = resolveProfile();
2884
+ consola$1.log(` • Profile: ${profile.dir}`);
2885
+ if (profile.source === "legacy") {
2886
+ consola$1.log(` ⚠ still inside Chrome's own folder, which an app-hosted session may be refused.`);
2887
+ consola$1.log(` Move it (logins included): browser-automation profile --migrate`);
2888
+ }
2735
2889
  let version;
2736
2890
  try {
2737
2891
  version = await (await fetch(`${cdpHost()}/json/version`)).json();
@@ -2894,6 +3048,40 @@ const portCommand = define({
2894
3048
  }
2895
3049
  });
2896
3050
  //#endregion
3051
+ //#region src/commands/profile.ts
3052
+ const profileCommand = define({
3053
+ name: "profile",
3054
+ description: "Print the Chrome profile directory this user's automation browser uses (one path, for scripts). --migrate moves a profile from the old location inside Chrome's own folder to ~/.browser-automation/chrome-profile, keeping every login.",
3055
+ args: { migrate: {
3056
+ type: "boolean",
3057
+ description: "Move the profile out of ~/Library/Application Support/Google/Chrome/ into ~/.browser-automation/chrome-profile. Refuses — and changes nothing — if a Chrome has it open or this process may not move it."
3058
+ } },
3059
+ async run(ctx) {
3060
+ if (!ctx.values.migrate) {
3061
+ process.stdout.write(`${resolveProfile().dir}\n`);
3062
+ return;
3063
+ }
3064
+ const m = migrateProfile();
3065
+ switch (m.outcome) {
3066
+ case "moved":
3067
+ consola$1.success(`Profile ${m.detail}. Logins travel with it.`);
3068
+ return;
3069
+ case "current":
3070
+ consola$1.info(`Profile already at ${m.dir}.`);
3071
+ return;
3072
+ case "fresh":
3073
+ consola$1.info(`No existing profile. Chrome will create ${m.dir} on first launch.`);
3074
+ return;
3075
+ case "explicit":
3076
+ consola$1.info(`BROWSER_AUTOMATION_PROFILE is set (${m.dir}); leaving it where you put it.`);
3077
+ return;
3078
+ default:
3079
+ consola$1.warn(`Profile not moved — ${m.detail}`);
3080
+ process.exitCode = 1;
3081
+ }
3082
+ }
3083
+ });
3084
+ //#endregion
2897
3085
  //#region src/commands/index.ts
2898
3086
  const defaultCommand = define({
2899
3087
  name: "browser-automation",
@@ -2928,7 +3116,8 @@ const subCommands = new Map([
2928
3116
  ["doctor", doctorCommand],
2929
3117
  ["gc", gcCommand],
2930
3118
  ["prune", gcCommand],
2931
- ["port", portCommand]
3119
+ ["port", portCommand],
3120
+ ["profile", profileCommand]
2932
3121
  ]);
2933
3122
  function withRealPositionals(cmd, real) {
2934
3123
  return {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@generativereality/browser-automation",
3
- "version": "0.4.13",
3
+ "version": "0.4.15",
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": "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",
21
+ "release": "bash scripts/release.sh",
22
22
  "sync-plugin": "bash scripts/sync-plugin.sh",
23
23
  "prepack": "npm run build"
24
24
  },
@@ -55,12 +55,18 @@ ask_cli_for_port() {
55
55
  }
56
56
 
57
57
  PORT=""
58
+ PROFILE=""
58
59
  RESTART=0
60
+ STOP_ONLY=0
59
61
  ARGS=()
60
62
  while [ $# -gt 0 ]; do
61
63
  case "$1" in
62
64
  --port) PORT="${2:-}"; shift 2 ;;
65
+ --profile) PROFILE="${2:-}"; shift 2 ;;
63
66
  --restart) RESTART=1; shift ;;
67
+ # Quit our Chrome and stop there. `launch --restart` uses it so the profile
68
+ # can be moved while nothing has it open, before the relaunch.
69
+ --stop) RESTART=1; STOP_ONLY=1; shift ;;
64
70
  *) ARGS+=("$1"); shift ;;
65
71
  esac
66
72
  done
@@ -73,7 +79,23 @@ if [ -z "${PORT}" ]; then
73
79
  exit 1
74
80
  fi
75
81
 
76
- PROFILE="${BROWSER_AUTOMATION_PROFILE:-$HOME/Library/Application Support/Google/Chrome/browser-automation}"
82
+ # **Asked for, never hardcoded** — same reason as the port. `resolveProfile()`
83
+ # in src/core/profile.ts decides it (and knows about the move out of Chrome's
84
+ # own folder); the CLI passes it with --profile, and a person running this by
85
+ # hand gets the same answer from `browser-automation profile`.
86
+ ask_cli_for_profile() {
87
+ local dist="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)/dist/index.js"
88
+ if [ -f "$dist" ] && command -v node >/dev/null 2>&1; then
89
+ node "$dist" profile 2>/dev/null && return 0
90
+ fi
91
+ command -v browser-automation >/dev/null 2>&1 && browser-automation profile 2>/dev/null
92
+ }
93
+ PROFILE="${PROFILE:-$(ask_cli_for_profile || true)}"
94
+ if [ -z "${PROFILE}" ]; then
95
+ echo "Error: could not work out which profile to use — pass --profile, or set" >&2
96
+ echo " BROWSER_AUTOMATION_PROFILE." >&2
97
+ exit 1
98
+ fi
77
99
  # Under the caller's OWN temp dir: /tmp is shared and sticky, so with a
78
100
  # machine-global name the second user cannot write the first user's log.
79
101
  LOG="${BROWSER_AUTOMATION_LOG:-${TMPDIR:-/tmp}/chrome-${PORT}.log}"
@@ -119,22 +141,60 @@ fi
119
141
  # profile (cookies, extension state, session) on a clean quit, and that profile
120
142
  # is the whole reason this browser is long-lived. Only escalate if it will not
121
143
  # go, and say so when it happens.
122
- if [ "$RESTART" = "1" ] && is_up; then
144
+ if [ "$RESTART" = "1" ] && port_is_ours; then
123
145
  if ! port_is_ours; then
124
146
  echo "Error: refusing to restart a Chrome this account did not start." >&2
125
147
  exit 1
126
148
  fi
127
- TABS="$(curl -fs "http://localhost:${PORT}/json/list" 2>/dev/null | grep -c '"type": "page"' || true)"
128
- echo "Restarting Chrome on :${PORT} — closing ${TABS:-?} open tab(s)."
149
+ if is_up; then
150
+ TABS="$(curl -fs "http://localhost:${PORT}/json/list" 2>/dev/null | grep -c '"type": "page"' || true)"
151
+ echo "Restarting Chrome on :${PORT} — closing ${TABS:-?} open tab(s)."
152
+ fi
129
153
  pkill -u "$(id -u)" -f -- "--remote-debugging-port=${PORT}" 2>/dev/null || true
154
+ # **Wait for Chrome to let go of the PROFILE, not for the port to close.**
155
+ #
156
+ # Chrome shuts its DevTools listener and helpers early in shutdown, so a
157
+ # closed port says nothing. Waiting on it relaunched on top of a Chrome still
158
+ # holding the profile: two browsers with one profile open, the corruption
159
+ # Chrome's SingletonLock exists to prevent.
160
+ #
161
+ # Nor can we wait for the process to exit. Measured 2026-09-23 on macOS 27 /
162
+ # Chrome 153: after SIGTERM or CDP Browser.close the browser process NEVER
163
+ # exits — still asleep after a minute, every restart, however launched. It has
164
+ # done the part that matters, though: SingletonLock is gone, i.e. the profile
165
+ # is flushed and released, and what is left is a Mac app with no windows.
166
+ # Ending that is harmless. Ending a Chrome that still holds the lock is not.
167
+ profile_released() {
168
+ # Only if we can actually SEE the profile. A host macOS has refused
169
+ # Chrome's folder cannot, and "no lock visible" would then read as
170
+ # "released" and kill a Chrome mid-flush.
171
+ ls "$PROFILE" >/dev/null 2>&1 || return 1
172
+ [ ! -L "$PROFILE/SingletonLock" ] && [ ! -e "$PROFILE/SingletonLock" ]
173
+ }
130
174
  for _ in $(seq 1 40); do
131
- is_up || break
175
+ port_is_ours || break
176
+ profile_released && break
132
177
  sleep 0.25
133
178
  done
134
- if is_up; then
135
- echo "Chrome did not quit on SIGTERM after 10s; sending SIGKILL." >&2
179
+ if port_is_ours; then
180
+ if profile_released; then
181
+ echo "Chrome released its profile but left its process running (normal on macOS); ending it."
182
+ elif ! ls "$PROFILE" >/dev/null 2>&1; then
183
+ # Not evidence of a hung Chrome — we simply cannot look. It has had 10s
184
+ # since being asked to quit, which is ample for a release we cannot see.
185
+ echo "Cannot see ${PROFILE} from this app (macOS keeps Chrome's folder from it), so cannot confirm it was released; ending Chrome after 10s." >&2
186
+ else
187
+ echo "Chrome still held its profile after 10s; sending SIGKILL." >&2
188
+ fi
136
189
  pkill -9 -u "$(id -u)" -f -- "--remote-debugging-port=${PORT}" 2>/dev/null || true
137
- sleep 2
190
+ for _ in $(seq 1 20); do
191
+ port_is_ours || break
192
+ sleep 0.25
193
+ done
194
+ fi
195
+ if port_is_ours; then
196
+ echo "Error: Chrome on :${PORT} would not exit, even on SIGKILL. Not relaunching on top of it." >&2
197
+ exit 1
138
198
  fi
139
199
  # Chrome unregisters its bootstrap names and releases the port on the way out;
140
200
  # relaunching before that finishes produces a second browser that cannot serve
@@ -142,6 +202,11 @@ if [ "$RESTART" = "1" ] && is_up; then
142
202
  sleep 1
143
203
  fi
144
204
 
205
+ if [ "$STOP_ONLY" = "1" ]; then
206
+ port_is_ours && { echo "Error: Chrome on :${PORT} is still running." >&2; exit 1; }
207
+ exit 0
208
+ fi
209
+
145
210
  # A held port is the ONLY thing this branch establishes. It is emphatically not
146
211
  # a health check: a Chrome that can no longer give a new tab a renderer keeps
147
212
  # serving this port, answering /json/version and listing targets, while every
@@ -193,23 +258,64 @@ if [ -s "$LOG" ]; then
193
258
  mv -f "$LOG" "${LOG}.prev" 2>/dev/null || true
194
259
  fi
195
260
 
196
- nohup "$CHROME" \
197
- --remote-debugging-port="$PORT" \
198
- --user-data-dir="$PROFILE" \
199
- --no-first-run \
200
- --no-default-browser-check \
201
- 'about:blank' >"$LOG" 2>&1 &
202
- disown
261
+ # On macOS, launch the .app through open(1), never by exec'ing the binary inside
262
+ # it. macOS protects an application's own data directory under
263
+ # ~/Library/Application Support, and the default profile lives under
264
+ # .../Google/Chrome. A process started from a terminal is refused there — for
265
+ # reads as well as writes — so a directly exec'd Chrome cannot even create its
266
+ # own SingletonLock and aborts with "Failed to create a ProcessSingleton for
267
+ # your profile directory". The message names the lock, so it reads as a stale
268
+ # lock from a crashed Chrome; it is not. Measured 2026-09-18 on Darwin 27.0.0
269
+ # with Chrome 153: the profile dir was mode 0700, owned by the user, carried no
270
+ # BSD flags and held no Singleton* files, while ~/Library/Application Support
271
+ # and .../Google both accepted writes from the same shell. LaunchServices gives
272
+ # Chrome its own identity, and the same binary, profile and flags then start.
273
+ #
274
+ # -n: a new instance even when the user's everyday Chrome is running.
275
+ # -g: do not bring it to the front. Chrome's stdout/stderr still reach $LOG via
276
+ # --stdout/--stderr (a healthy start writes "DevTools listening on ws://…").
277
+ app_bundle_of() {
278
+ case "$1" in
279
+ *.app/Contents/MacOS/*) printf '%s.app\n' "${1%%.app/Contents/MacOS/*}" ;;
280
+ *) return 1 ;;
281
+ esac
282
+ }
283
+
284
+ CHROME_FLAGS=(
285
+ --remote-debugging-port="$PORT"
286
+ --user-data-dir="$PROFILE"
287
+ --no-first-run
288
+ --no-default-browser-check
289
+ 'about:blank'
290
+ )
291
+ if [ "$(uname -s)" = "Darwin" ] && APP="$(app_bundle_of "$CHROME")"; then
292
+ open -n -g -a "$APP" --stdout "$LOG" --stderr "$LOG" --args "${CHROME_FLAGS[@]}"
293
+ else
294
+ nohup "$CHROME" "${CHROME_FLAGS[@]}" >"$LOG" 2>&1 &
295
+ disown
296
+ fi
203
297
 
204
- # Wait briefly for CDP to come up so the caller can attach immediately.
205
- for _ in $(seq 1 20); do
298
+ # Wait for CDP so the caller can attach immediately. A cold start against a
299
+ # long-lived profile (extensions, logins, restored session) measured 10.6s and
300
+ # 16.4s through open(1), so a 5s window reported failure over a browser that
301
+ # was still coming up. The elapsed time is printed so a window that is too
302
+ # short again is visible rather than guessed at.
303
+ START="$(date +%s)"
304
+ for _ in $(seq 1 240); do
206
305
  if is_up; then
207
- echo "Chrome launched on :${PORT} (profile: ${PROFILE}, log: ${LOG})"
306
+ echo "Chrome launched on :${PORT} in $(( $(date +%s) - START ))s (profile: ${PROFILE}, log: ${LOG})"
208
307
  echo "Drive it with: browser-automation goto -s <session> <url>"
209
308
  exit 0
210
309
  fi
211
310
  sleep 0.25
212
311
  done
213
312
 
214
- echo "Error: Chrome did not start within 5s. Check ${LOG}." >&2
313
+ echo "Error: Chrome did not serve CDP on :${PORT} within 60s. Last lines of ${LOG}:" >&2
314
+ tail -n 8 "$LOG" 2>/dev/null | sed 's/^/ /' >&2
315
+ if grep -qE 'Failed to create a ProcessSingleton|SingletonLock: Operation not permitted' "$LOG" 2>/dev/null; then
316
+ echo "" >&2
317
+ echo "macOS refused this Chrome its own profile directory — not a stale lock." >&2
318
+ echo "Chrome was exec'd directly rather than launched through open(1); see the" >&2
319
+ echo "comment above app_bundle_of in this script." >&2
320
+ fi
215
321
  exit 1