@generativereality/browser-automation 0.4.13 → 0.4.14

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "browser-automation",
3
3
  "description": "Daemonless, per-tab-isolated browser automation for Claude Code via the `browser-automation` CLI. Drives one shared headed Chrome (persistent profile + extensions) over per-target CDP — many parallel sessions, no focus stealing, nothing long-lived to crash.",
4
- "version": "0.4.13",
4
+ "version": "0.4.14",
5
5
  "author": {
6
6
  "name": "generativereality"
7
7
  },
package/README.md CHANGED
@@ -180,7 +180,7 @@ same one-action-per-snapshot rule as Playwright refs.
180
180
  repeats a rule is a copy of it, and goes stale the same way code does.
181
181
  `doctor` prints it too, and warns if another user holds it.
182
182
  - `BROWSER_AUTOMATION_CDP` — full CDP host, overriding the port entirely.
183
- - `BROWSER_AUTOMATION_PROFILE` — Chrome profile dir for `launch`.
183
+ - `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
184
  - `BAC_SESSION` — default session name for page commands.
185
185
 
186
186
  ## 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.14";
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,
@@ -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.14",
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": {
@@ -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
@@ -85,6 +85,34 @@ one of those; run `doctor`, which is the same probe.** Override the profile path
85
85
  with `BROWSER_AUTOMATION_PROFILE=...` and the CDP host with
86
86
  `BROWSER_AUTOMATION_CDP=http://localhost:PORT` if needed.
87
87
 
88
+ **The profile lives in `~/.browser-automation/chrome-profile`** (`browser-automation
89
+ profile` prints it). Older CLIs kept it inside Chrome's own folder,
90
+ `~/Library/Application Support/Google/Chrome/browser-automation`, and `launch` moves
91
+ it out the first time it can — logins included; the move is a single rename and
92
+ Chrome's cookie key lives in the Keychain, not in the path. To move it on demand:
93
+
94
+ ```bash
95
+ browser-automation profile --migrate # refuses, changing nothing, if a Chrome has it open
96
+ browser-automation launch --restart # quits Chrome first, then moves it and relaunches
97
+ ```
98
+
99
+ **Why it moved: macOS decides access to Chrome's folder per HOST app.** A session
100
+ started from a terminal that was once allowed reaches it; one started by an app
101
+ that was not — Clerk.AI, denied in 2026-08 and silently refused ever since — gets
102
+ `EPERM`, and Chrome dies with
103
+
104
+ ```
105
+ Failed to create …/browser-automation/SingletonLock: Operation not permitted (1)
106
+ Failed to create a ProcessSingleton for your profile directory. … Aborting now
107
+ ```
108
+
109
+ **That is not a stale lock**, and there is no lock file to delete. It is also why
110
+ the same command works from your terminal and fails from an app. ⛔ **Do not work
111
+ around it with a scratch `--user-data-dir` or `BROWSER_AUTOMATION_PROFILE` pointed
112
+ at an empty folder**: Chrome starts, and the person is signed out of every site in
113
+ the real profile. Run `browser-automation profile --migrate` once from a terminal
114
+ that can reach the old folder; every host reaches the new one.
115
+
88
116
  ## Commands
89
117
 
90
118
  Page commands take a tab selector — `-s <session>` (default `$BAC_SESSION`, else
@@ -94,6 +122,7 @@ Page commands take a tab selector — `-s <session>` (default `$BAC_SESSION`, el
94
122
  |---|---|
95
123
  | Start the Chrome + verify it can make renderers | `browser-automation launch` |
96
124
  | Diagnose setup (incl. renderer capacity) | `browser-automation doctor` |
125
+ | Where the Chrome profile lives / move it out of Chrome's folder | `browser-automation profile` / `profile --migrate` |
97
126
  | List sessions + every open tab (id, title, url) | `browser-automation list` |
98
127
  | Open a background tab | `browser-automation new -s work [url]` |
99
128
  | Navigate (session tab created if needed) | `browser-automation goto -s work https://example.com` |
@@ -180,6 +209,22 @@ There's no `state-save`/`state-load` to manage — the profile *is* the auth sto
180
209
  no `name`** (Viking Line's booking selectors — the visible fields are display
181
210
  shells; the real state lives in the framework, so `fill` and DOM value-setting
182
211
  do nothing at all).
212
+ - **There is NO way to send real keystrokes, and `fill --native` is not one.** `--native` uses CDP
213
+ `Input.insertText`, which fires `beforeinput`/`input` but **never `keydown`**. A combobox that
214
+ filters its list on keystrokes therefore stays empty: the value lands in the DOM and no options
215
+ ever render. npm’s "Select packages and scopes" picker is the canonical case (2026-08-22) — the
216
+ field showed `generativereality` and the list stayed blank through `fill`, `fill --native`, and a
217
+ React native-setter `eval`. There is no `press` or `type` command to escalate to.
218
+ ⇒ Drop to raw CDP on the tab’s `webSocketDebuggerUrl` and dispatch `Input.dispatchKeyEvent`
219
+ per character. Two traps, both hit:
220
+ **(1) `keyDown` carrying `text` already inserts the character** — sending a `char` event as well
221
+ types everything twice (`ggeenneerraattiivvee…`), which reads as a flaky page rather than a double
222
+ dispatch. Send `keyDown` + `keyUp` only.
223
+ **(2) Clear with real Backspaces, not select-all+Delete.** A value written by a JS setter is
224
+ invisible to the component’s own state, so the framework keeps the old string and you end up
225
+ appending to it. Backspacing drives the same path a person would.
226
+ Also: the dropdown must actually be **open** first — typing into a collapsed picker’s hidden input
227
+ does nothing, and looks identical to the events not landing.
183
228
  **Do NOT hand-roll a raw-CDP trusted click.** Burned 2026-08-22: wrote a
184
229
  bespoke `Input.dispatchMouseEvent` helper for exactly this, and it clicked
185
230
  stale coordinates (the panel had animated in) — `--trusted` already solves that
@@ -429,9 +474,15 @@ There's no `state-save`/`state-load` to manage — the profile *is* the auth sto
429
474
  process helps; closing tabs does not, and plain `launch` will not either (idempotent by
430
475
  design — it sees a live browser and exits happy):
431
476
  ```bash
432
- browser-automation launch --restart # SIGTERM (profile flushes cleanly), wait, relaunch
477
+ browser-automation launch --restart # quit (CDP, then SIGTERM), wait for the profile, relaunch
433
478
  ```
434
- It reports how many tabs it is about to close. **Those tabs belong to every parallel
479
+ It reports how many tabs it is about to close. `Chrome released its profile but left its
480
+ process running (normal on macOS); ending it.` is the **expected** line, not a fault: on
481
+ macOS 27 / Chrome 153 the browser process never exits on its own after quitting, but it
482
+ does flush and release the profile first, and that release is what the restart waits for.
483
+ (Older CLIs waited only for the port to close and relaunched on top of the still-running
484
+ Chrome — two browsers on one profile. If you see `Chrome did not exit on SIGTERM`, or no
485
+ such line and then odd profile errors, you are on one of those.) **Those tabs belong to every parallel
435
486
  Claude Code session sharing this Chrome — ask Fred first, never restart unilaterally.**
436
487
 
437
488
  **Housekeeping is a different problem** — `browser-automation gc` prunes stale session bookmarks
@@ -567,6 +618,26 @@ working around it forever**:
567
618
  If it says the port is held by ANOTHER user, that is not your Chrome and
568
619
  driving it would act in their session — quit Chrome in that account, or set
569
620
  `BROWSER_AUTOMATION_PORT`.
621
+ - **`SingletonLock: Operation not permitted` / "Failed to create a ProcessSingleton"**
622
+ → macOS refused the app this session runs under access to **Chrome's** folder,
623
+ where old CLIs kept the profile (see Setup). Not a stale lock; do not delete
624
+ anything. Upgrade the CLI (`npm install -g @generativereality/browser-automation@latest`)
625
+ and `launch` again: current versions start Chrome through `open(1)`, under
626
+ Chrome's own identity, so it opens its folder whatever app you run under, and
627
+ they move the profile to `~/.browser-automation/` when they can.
628
+
629
+ **What to tell the person — and what NOT to.** ⛔ **Do not ask them to grant
630
+ Full Disk Access** (to the app, to the terminal, to anything). It does work, and
631
+ it hands that app every file on the Mac to fix a problem that needs none of it:
632
+ an agent in Mind My Money said exactly that on 2026-09 — *"let Mind My Money
633
+ reach that folder. Full Disk Access does it, but it also opens far more than
634
+ Chrome"* — when the real fix was a CLI upgrade. Also do not suggest a fresh
635
+ profile or `BROWSER_AUTOMATION_PROFILE` pointed at an empty folder: that signs
636
+ them out of every bank and portal. If `launch` still reports `Profile not moved`
637
+ after upgrading, the browser works anyway (the old folder is still used); the
638
+ one-time move needs a host macOS allows into Chrome's folder, so the ask is small
639
+ and exact: *open Terminal and run `browser-automation profile --migrate`; if macOS
640
+ asks whether Terminal may access data from other apps, allow it.*
570
641
  - **`command not found: browser-automation`** → `npm install -g @generativereality/browser-automation`.
571
642
  - **Chrome was restarted** → nothing to do; the next `goto` recreates the
572
643
  session's tab automatically (sessions self-heal; `list` shows `stale`).