@generativereality/browser-automation 0.4.18 → 0.5.0

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.18",
4
+ "version": "0.5.0",
5
5
  "author": {
6
6
  "name": "generativereality"
7
7
  },
package/README.md CHANGED
@@ -186,6 +186,7 @@ same one-action-per-snapshot rule as Playwright refs.
186
186
  repeats a rule is a copy of it, and goes stale the same way code does.
187
187
  `doctor` prints it too, and warns if another user holds it.
188
188
  - `BROWSER_AUTOMATION_CDP` — full CDP host, overriding the port entirely.
189
+ - `CHROME` / `BROWSER_AUTOMATION_CHROME` — the Chrome executable `launch` starts, when it is not in a standard place. Otherwise: macOS `/Applications` then `~/Applications`; Windows Program Files then `%LOCALAPPDATA%`; Linux `google-chrome`/`chromium` on PATH. `doctor` shows which.
189
190
  - `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).
190
191
  - `BAC_SHOW_TAB=1` — `--show` on every `goto`/`new`: select the tab in its window when the automation Chrome is already in front (never raises Chrome over another app). macOS and Windows.
191
192
  - `BAC_SESSION` — default session name for page commands.
package/dist/index.js CHANGED
@@ -3,13 +3,13 @@ import updateNotifier from "update-notifier";
3
3
  import { cli, define } from "gunshi";
4
4
  import consola, { consola as consola$1 } from "consola";
5
5
  import { homedir, tmpdir } from "node:os";
6
- import { basename, dirname, extname, join, resolve } from "node:path";
7
- import { appendFileSync, existsSync, lstatSync, mkdirSync, openSync, readFileSync, readdirSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
6
+ import { basename, delimiter, dirname, extname, join, resolve } from "node:path";
7
+ import { accessSync, appendFileSync, constants, existsSync, lstatSync, mkdirSync, openSync, readFileSync, readdirSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
8
8
  import { execFileSync, spawn, 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.18";
12
+ var version = "0.5.0";
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,
@@ -2931,17 +2931,88 @@ function migrateProfile() {
2931
2931
  };
2932
2932
  }
2933
2933
  //#endregion
2934
+ //#region src/core/chrome-path.ts
2935
+ function executable(p) {
2936
+ try {
2937
+ if (!statSync(p).isFile()) return false;
2938
+ if (process.platform === "win32") return true;
2939
+ accessSync(p, constants.X_OK);
2940
+ return true;
2941
+ } catch {
2942
+ return false;
2943
+ }
2944
+ }
2945
+ const MAC_BINARY = join("Google Chrome.app", "Contents", "MacOS", "Google Chrome");
2946
+ function platformCandidates() {
2947
+ if (process.platform === "darwin") return [{
2948
+ path: join(process.env.BROWSER_AUTOMATION_TEST_SYSTEM_APPS || "/Applications", MAC_BINARY),
2949
+ source: "/Applications"
2950
+ }, {
2951
+ path: join(homedir(), "Applications", MAC_BINARY),
2952
+ source: "~/Applications"
2953
+ }];
2954
+ if (process.platform === "win32") {
2955
+ const out = [];
2956
+ const exe = join("Google", "Chrome", "Application", "chrome.exe");
2957
+ if (process.env.PROGRAMFILES) out.push({
2958
+ path: join(process.env.PROGRAMFILES, exe),
2959
+ source: "Program Files"
2960
+ });
2961
+ if (process.env["PROGRAMFILES(X86)"]) out.push({
2962
+ path: join(process.env["PROGRAMFILES(X86)"], exe),
2963
+ source: "Program Files (x86)"
2964
+ });
2965
+ if (process.env.LOCALAPPDATA) out.push({
2966
+ path: join(process.env.LOCALAPPDATA, exe),
2967
+ source: "%LOCALAPPDATA%"
2968
+ });
2969
+ return out;
2970
+ }
2971
+ const dirs = (process.env.PATH ?? "").split(delimiter).filter(Boolean);
2972
+ return [
2973
+ "google-chrome",
2974
+ "google-chrome-stable",
2975
+ "chromium",
2976
+ "chromium-browser"
2977
+ ].flatMap((name) => dirs.map((d) => ({
2978
+ path: join(d, name),
2979
+ source: `PATH (${name})`
2980
+ })));
2981
+ }
2982
+ function chromeExecutable() {
2983
+ let ignored;
2984
+ for (const name of ["BROWSER_AUTOMATION_CHROME", "CHROME"]) {
2985
+ const v = process.env[name];
2986
+ if (!v) continue;
2987
+ if (executable(v)) return {
2988
+ path: v,
2989
+ source: name
2990
+ };
2991
+ ignored ??= `${name}=${v} is not an executable file`;
2992
+ }
2993
+ const hit = platformCandidates().find((c) => executable(c.path));
2994
+ return hit ? {
2995
+ path: hit.path,
2996
+ source: hit.source,
2997
+ ignored
2998
+ } : {
2999
+ path: null,
3000
+ source: "not found",
3001
+ ignored
3002
+ };
3003
+ }
3004
+ /** Where we looked, for a "not found" message. */
3005
+ function chromeSearchDescription() {
3006
+ if (process.platform === "darwin") return "/Applications and ~/Applications";
3007
+ if (process.platform === "win32") return "Program Files, Program Files (x86) and %LOCALAPPDATA%";
3008
+ return "google-chrome, google-chrome-stable, chromium and chromium-browser on PATH";
3009
+ }
3010
+ //#endregion
2934
3011
  //#region src/core/launch-windows.ts
2935
3012
  const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
2936
- /** chrome.exe: an explicit override, then the per-machine and per-user installs. */
3013
+ /** chrome.exe — decided in one place for every platform (core/chrome-path.ts). */
2937
3014
  function windowsChromeExe() {
2938
- const explicit = process.env.BROWSER_AUTOMATION_CHROME || process.env.CHROME;
2939
- if (explicit) return existsSync(explicit) ? explicit : null;
2940
- return [
2941
- process.env.PROGRAMFILES && join(process.env.PROGRAMFILES, "Google", "Chrome", "Application", "chrome.exe"),
2942
- process.env["PROGRAMFILES(X86)"] && join(process.env["PROGRAMFILES(X86)"], "Google", "Chrome", "Application", "chrome.exe"),
2943
- process.env.LOCALAPPDATA && join(process.env.LOCALAPPDATA, "Google", "Chrome", "Application", "chrome.exe")
2944
- ].filter(Boolean).find((p) => existsSync(p)) ?? null;
3015
+ return chromeExecutable().path;
2945
3016
  }
2946
3017
  /** Is anything answering CDP on this port? (The script's `is_up`.) */
2947
3018
  async function cdpUp(port) {
@@ -3111,7 +3182,13 @@ const launchCommand = define({
3111
3182
  if (m.outcome === "moved") consola$1.success(`Profile ${m.detail} — logins travel with it.`);
3112
3183
  else if (m.outcome === "refused" || m.outcome === "failed") consola$1.warn(`Profile not moved: ${m.detail}`);
3113
3184
  else if (m.outcome === "in-use") consola$1.info(`Profile not moved yet: ${m.detail}`);
3114
- const r = bash(["--profile", m.dir]);
3185
+ const chrome = chromeExecutable();
3186
+ if (chrome.ignored) consola$1.warn(`Ignoring ${chrome.ignored}.`);
3187
+ const r = bash([
3188
+ "--profile",
3189
+ m.dir,
3190
+ ...chrome.path ? ["--chrome", chrome.path] : []
3191
+ ]);
3115
3192
  if (r.status !== 0) process.exit(r.status ?? 1);
3116
3193
  }
3117
3194
  const health = await probeRenderer().catch((e) => ({
@@ -3227,6 +3304,10 @@ const doctorCommand = define({
3227
3304
  consola$1.log(` ⚠ still inside Chrome's own folder, which an app-hosted session may be refused.`);
3228
3305
  consola$1.log(` Move it (logins included): browser-automation profile --migrate`);
3229
3306
  }
3307
+ const chrome = chromeExecutable();
3308
+ if (chrome.path) consola$1.log(` • Chrome binary: ${chrome.path} (${chrome.source})`);
3309
+ else bad(`Chrome binary: not found (looked in ${chromeSearchDescription()}) — \`launch\` cannot start one. Install Chrome, or set CHROME.`);
3310
+ if (chrome.ignored) consola$1.log(` ⚠ ignoring ${chrome.ignored}`);
3230
3311
  let version;
3231
3312
  try {
3232
3313
  version = await (await fetch(`${cdpHost()}/json/version`)).json();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@generativereality/browser-automation",
3
- "version": "0.4.18",
3
+ "version": "0.5.0",
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": {
@@ -56,6 +56,7 @@ ask_cli_for_port() {
56
56
 
57
57
  PORT=""
58
58
  PROFILE=""
59
+ CHROME_ARG=""
59
60
  RESTART=0
60
61
  STOP_ONLY=0
61
62
  ARGS=()
@@ -63,6 +64,7 @@ while [ $# -gt 0 ]; do
63
64
  case "$1" in
64
65
  --port) PORT="${2:-}"; shift 2 ;;
65
66
  --profile) PROFILE="${2:-}"; shift 2 ;;
67
+ --chrome) CHROME_ARG="${2:-}"; shift 2 ;;
66
68
  --restart) RESTART=1; shift ;;
67
69
  # Quit our Chrome and stop there. `launch --restart` uses it so the profile
68
70
  # can be moved while nothing has it open, before the relaunch.
@@ -227,22 +229,41 @@ if is_up; then
227
229
  exit 0
228
230
  fi
229
231
 
230
- # Resolve Chrome binary across macOS / Linux.
231
- case "$(uname -s)" in
232
- Darwin)
233
- CHROME="/Applications/Google Chrome.app/Contents/MacOS/Google Chrome"
234
- ;;
235
- Linux)
236
- CHROME="$(command -v google-chrome || command -v google-chrome-stable || command -v chromium || true)"
237
- ;;
238
- *)
239
- echo "Error: unsupported OS $(uname -s). Launch Chrome manually with --remote-debugging-port=${PORT} --user-data-dir=\"${PROFILE}\"." >&2
240
- exit 1
241
- ;;
242
- esac
232
+ # Resolve the Chrome binary. **Asked for, like the port and the profile**:
233
+ # `chromeExecutable()` in src/core/chrome-path.ts decides, and `launch` passes it
234
+ # with --chrome. The order below only repeats it for a person running this by
235
+ # hand: an explicit $BROWSER_AUTOMATION_CHROME / $CHROME that is executable, then
236
+ # /Applications, then ~/Applications.
237
+ #
238
+ # This used to hardcode /Applications/Google Chrome.app and OVERWRITE $CHROME, so
239
+ # a Chrome in ~/Applications — where Mind My Money installs it for an account
240
+ # that cannot write /Applications — could not be launched at all (2026-10-05).
241
+ CHROME_FROM_ENV="${CHROME:-}" # read BEFORE reusing the name below
242
+ CHROME=""
243
+ for c in "$CHROME_ARG" "${BROWSER_AUTOMATION_CHROME:-}" "$CHROME_FROM_ENV"; do
244
+ if [ -n "$c" ] && [ -x "$c" ] && [ ! -d "$c" ]; then CHROME="$c"; break; fi
245
+ done
246
+ if [ -z "$CHROME" ]; then
247
+ case "$(uname -s)" in
248
+ Darwin)
249
+ for c in "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome" \
250
+ "$HOME/Applications/Google Chrome.app/Contents/MacOS/Google Chrome"; do
251
+ if [ -x "$c" ]; then CHROME="$c"; break; fi
252
+ done
253
+ ;;
254
+ Linux)
255
+ CHROME="$(command -v google-chrome || command -v google-chrome-stable || command -v chromium || command -v chromium-browser || true)"
256
+ ;;
257
+ *)
258
+ echo "Error: this script is for macOS and Linux (got $(uname -s)). On Windows, run \`browser-automation launch\` — it does not use this script." >&2
259
+ exit 1
260
+ ;;
261
+ esac
262
+ fi
243
263
 
244
- if [ ! -x "$CHROME" ]; then
245
- echo "Error: Chrome not found. Install it (or set CHROME=... if it lives elsewhere)." >&2
264
+ if [ -z "$CHROME" ] || [ ! -x "$CHROME" ]; then
265
+ echo "Error: Chrome not found (looked in /Applications and ~/Applications on macOS, PATH on Linux)." >&2
266
+ echo " Install it, or set CHROME=/path/to/chrome if it lives elsewhere." >&2
246
267
  exit 1
247
268
  fi
248
269
 
@@ -31,6 +31,9 @@ PKG=@generativereality/browser-automation
31
31
  die() { echo "Error: $*" >&2; exit 1; }
32
32
  say() { printf '\n== %s\n' "$*"; }
33
33
 
34
+ # HTTP status of one version on the registry: 200 published, 404 not.
35
+ registry_code() { curl -s -o /dev/null -w '%{http_code}' "https://registry.npmjs.org/${PKG/\//%2F}/$1"; }
36
+
34
37
  last_tag() { git -C "$ROOT" describe --tags --abbrev=0 "$BASE" 2>/dev/null || true; }
35
38
 
36
39
  plan() {
@@ -78,7 +81,13 @@ cut() {
78
81
  [0-9]*.[0-9]*.[0-9]*) next="$want" ;;
79
82
  *) die "unknown version '$want'" ;;
80
83
  esac
84
+ # A tag is never moved or re-pushed, and a version is never re-used: on
85
+ # 2026-09-23 v0.4.15 was re-created on another commit after it had published,
86
+ # so npm's 0.4.15 and the git tag still name different commits. Ask the remote
87
+ # and the registry, not just this clone's tags.
81
88
  git rev-parse -q --verify "refs/tags/v$next" >/dev/null && die "v$next already exists"
89
+ [ -z "$(git ls-remote origin "refs/tags/v$next")" ] || die "v$next already exists on origin"
90
+ [ "$(registry_code "$next")" = 404 ] || die "$next is already on npm (or the registry did not answer 404) — pick another version"
82
91
  [ -z "$(git log --format=%h "$(last_tag)..HEAD")" ] && die "nothing unreleased since $(last_tag)"
83
92
 
84
93
  say "Releasing $cur -> $next"
@@ -134,8 +143,19 @@ TXT
134
143
  finish() {
135
144
  git fetch -q origin --tags
136
145
  local tag; tag="$(last_tag)"; local v="${tag#v}"
137
- local run; run="$(gh run list --repo "$REPO" --workflow release.yml --branch "$tag" --limit 1 --json databaseId --jq '.[0].databaseId')"
138
- [ -n "$run" ] || die "no release run for $tag"
146
+ # GitHub's run LISTING lags the run: at 0.4.18 `gh run list --branch <tag>`
147
+ # answered nothing for minutes while `gh run view <id>` said success — so
148
+ # finish died "no release run" twice on a release that had shipped. Retry.
149
+ # The run for the tag's CURRENT commit: a tag that was ever re-pushed has a
150
+ # run per push (v0.4.15 had two), and the newest is not necessarily it.
151
+ local sha; sha="$(git rev-parse "$tag^{commit}")"
152
+ local run=""
153
+ for _ in $(seq 1 18); do
154
+ run="$(gh run list --repo "$REPO" --workflow release.yml --branch "$tag" --limit 10 --json databaseId,headSha --jq "[.[] | select(.headSha == \"$sha\")][0].databaseId // empty")"
155
+ [ -n "$run" ] && break
156
+ sleep 10
157
+ done
158
+ [ -n "$run" ] || die "no release run for $tag after 3 minutes"
139
159
 
140
160
  say "Waiting for the release run of $tag"
141
161
  local s
@@ -153,13 +173,17 @@ finish() {
153
173
  # The registry, not `npm view`: publishing reports success minutes before
154
174
  # the version is served (3.5 min for 0.4.13), and `npm view` also caches.
155
175
  say "Waiting for $v on the registry"
156
- local name="${PKG/\//%2F}"
157
176
  for _ in $(seq 1 60); do
158
- [ "$(curl -s -o /dev/null -w '%{http_code}' "https://registry.npmjs.org/$name/$v")" = 200 ] && break
177
+ [ "$(registry_code "$v")" = 200 ] && break
159
178
  sleep 10
160
179
  done
161
- [ "$(curl -s -o /dev/null -w '%{http_code}' "https://registry.npmjs.org/$name/$v")" = 200 ] || die "$v not on the registry after 10 minutes"
162
- echo " $PKG@$v is live"
180
+ [ "$(registry_code "$v")" = 200 ] || die "$v not on the registry after 10 minutes"
181
+ # And it is the tag's commit: npm records the commit it packed as gitHead.
182
+ # This is how 0.4.15's mismatch was found, two weeks late.
183
+ local head
184
+ head="$(curl -s "https://registry.npmjs.org/${PKG/\//%2F}/$v" | node -pe 'JSON.parse(require("fs").readFileSync(0)).gitHead')"
185
+ [ "$head" = "$sha" ] || die "npm's $v was packed from $head, but $tag is $sha — stop and tell the maintainer"
186
+ echo " $PKG@$v is live, packed from $tag ($(git rev-parse --short "$sha"))"
163
187
 
164
188
  say "Plugin marketplace"
165
189
  # Sync from the released tag, not from whatever this checkout has.
@@ -170,7 +194,16 @@ finish() {
170
194
  BA_PLUGIN_SOURCE="$RELEASE_WT" bash "$ROOT/scripts/sync-plugin.sh"
171
195
 
172
196
  say "This machine"
173
- npm install -g "$PKG@$v" >/dev/null 2>&1 && echo " installed $(browser-automation --version)"
197
+ # --prefer-online: npm caches the package's metadata, so right after a
198
+ # publish `npm install -g pkg@<new>` answers ETARGET "No matching version"
199
+ # for a version the registry is already serving (0.4.17: the version
200
+ # endpoint said 200, install said notarget). And say when it fails — this
201
+ # line used to swallow that and print nothing.
202
+ if npm install -g --prefer-online "$PKG@$v" >/dev/null 2>&1; then
203
+ echo " installed $(browser-automation --version)"
204
+ else
205
+ echo " ⚠ could not install $PKG@$v globally — run: npm install -g --prefer-online $PKG@$v" >&2
206
+ fi
174
207
 
175
208
  say "Downstream — not done by this script"
176
209
  cat <<TXT
@@ -55,46 +55,63 @@ if [ "$CHECK_ONLY" = true ]; then
55
55
  exit 0
56
56
  fi
57
57
 
58
- # Sync files
59
- for rel in "${PAYLOAD_FILES[@]}"; do
60
- mkdir -p "$(dirname "$PLUGINS_DIR/plugins/browser-automation/$rel")"
61
- cp -p "$REPO_ROOT/$rel" "$PLUGINS_DIR/plugins/browser-automation/$rel"
62
- done
58
+ # **Start from the latest marketplace, then copy on top.** Never commit first and
59
+ # rebase after: the payload is generated from a release, so the only thing a
60
+ # rebase can conflict with is an OLDER sync of this same plugin made from another
61
+ # checkout — which is exactly what happened at 0.4.16 (0.4.15 had been synced
62
+ # elsewhere). Copying onto an up-to-date tree has nothing to conflict with.
63
+ cd "$PLUGINS_DIR"
64
+ BRANCH="$(git rev-parse --abbrev-ref HEAD)"
65
+ [ "$BRANCH" = "main" ] || { echo "Error: plugins repo is on '$BRANCH', not main. Not syncing into a branch." >&2; exit 1; }
66
+ # Other plugins sync from here too. Their uncommitted or unpushed work is not
67
+ # ours to carry, drop or rebase — stop and say so.
68
+ if [ -n "$(git status --porcelain)" ]; then
69
+ echo "Error: $PLUGINS_DIR has uncommitted changes; not syncing on top of someone's work:" >&2
70
+ git status --short >&2; exit 1
71
+ fi
72
+ git fetch -q origin main
73
+ if [ -n "$(git rev-list origin/main..HEAD)" ]; then
74
+ echo "Error: $PLUGINS_DIR has commits not on origin/main — push or drop them first:" >&2
75
+ git log --oneline origin/main..HEAD >&2; exit 1
76
+ fi
63
77
 
64
- # Remove .mcp.json from plugins repo if it lingers from an older sync (the plugin no longer ships an MCP server).
65
- rm -f "$PLUGINS_DIR/plugins/browser-automation/.mcp.json"
78
+ SRC_VERSION="$(node -p "require('$REPO_ROOT/.claude-plugin/plugin.json').version")"
79
+ sync_on_top() {
80
+ git merge -q --ff-only origin/main
81
+ # Never replace a newer published plugin with an older one.
82
+ local have
83
+ have="$(node -p "try{require('./plugins/browser-automation/.claude-plugin/plugin.json').version}catch{''}" 2>/dev/null)"
84
+ if [ -n "$have" ] && [ "$(printf '%s\n%s\n' "$have" "$SRC_VERSION" | sort -V | tail -1)" != "$SRC_VERSION" ]; then
85
+ echo "Error: the marketplace already has browser-automation $have, newer than $SRC_VERSION. Not downgrading." >&2
86
+ exit 1
87
+ fi
88
+ for rel in "${PAYLOAD_FILES[@]}"; do
89
+ mkdir -p "$(dirname "plugins/browser-automation/$rel")"
90
+ cp -p "$REPO_ROOT/$rel" "plugins/browser-automation/$rel"
91
+ done
92
+ # Remove .mcp.json if it lingers from an older sync (no MCP server any more).
93
+ rm -f "plugins/browser-automation/.mcp.json"
94
+ }
66
95
 
67
- cd "$PLUGINS_DIR"
96
+ sync_on_top
68
97
  if git diff --quiet -- plugins/browser-automation && [ -z "$(git ls-files --others --exclude-standard -- plugins/browser-automation)" ]; then
69
98
  echo "Plugins repo already up to date"
70
99
  exit 0
71
100
  fi
72
-
73
- # **Other plugins publish to this repo too.** The 0.4.14 sync was rejected
74
- # because a cctabs sync had landed on origin/main in between — the marketplace
75
- # is shared, so "behind origin" is the normal state, not an error. Commit ONLY
76
- # our directory, then replay it on top of whatever arrived and push; our
77
- # commit touches nothing outside plugins/browser-automation, so the rebase
78
- # cannot conflict with another plugin's sync. It can conflict with a sync of
79
- # THIS plugin from another checkout — then stop rather than guess.
80
- BRANCH="$(git rev-parse --abbrev-ref HEAD)"
81
- if [ "$BRANCH" != "main" ]; then
82
- echo "Error: plugins repo is on '$BRANCH', not main. Not syncing into a branch." >&2
83
- exit 1
84
- fi
85
- VERSION="$(node -p "require('$REPO_ROOT/package.json').version" 2>/dev/null || echo '?')"
86
101
  git add plugins/browser-automation
87
- git commit -q -m "chore: sync browser-automation plugin to $VERSION"
102
+ git commit -q -m "chore: sync browser-automation plugin to $SRC_VERSION"
103
+
104
+ # Someone may push between our fetch and our push. Then drop OUR commit (we
105
+ # verified above that nothing else was local), take theirs, and copy again.
88
106
  for attempt in 1 2 3; do
89
- git fetch -q origin main
90
- if ! git rebase -q origin/main; then
91
- git rebase --abort
92
- echo "Error: rebasing the sync onto origin/main conflicted — something else changed" >&2
93
- echo " plugins/browser-automation. Resolve in $PLUGINS_DIR, then push." >&2
94
- exit 1
95
- fi
96
107
  git push -q origin main && break
97
108
  [ "$attempt" = 3 ] && { echo "Error: push kept being rejected; see $PLUGINS_DIR." >&2; exit 1; }
109
+ git fetch -q origin main
110
+ git reset -q --hard origin/main
111
+ sync_on_top
112
+ git diff --quiet -- plugins/browser-automation && { echo "Plugins repo already up to date"; exit 0; }
113
+ git add plugins/browser-automation
114
+ git commit -q -m "chore: sync browser-automation plugin to $SRC_VERSION"
98
115
  done
99
116
 
100
- echo "Synced browser-automation to plugins repo"
117
+ echo "Synced browser-automation $SRC_VERSION to plugins repo"
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  name: browser
3
3
  description: Drive a real browser from the shell via the `browser-automation` CLI — open pages, click, type, fill forms, read text, capture snapshots, all against one shared headed Chrome with a persistent profile (cookies + extensions survive). Daemonless and per-tab isolated, so many parallel Claude Code sessions can each drive their own tab without interfering. Use whenever you need to interact with a web page (especially behind a login) and there's no CLI or API that already covers the task.
4
- allowed-tools: Bash(browser-automation:*) Bash(npm:*)
4
+ allowed-tools: Bash(browser-automation list:*) Bash(browser-automation snapshot:*) Bash(browser-automation read:*) Bash(browser-automation screenshot:*) Bash(browser-automation doctor:*) Bash(browser-automation port:*)
5
5
  ---
6
6
 
7
7
  # Browser automation via `browser-automation`
@@ -295,6 +295,38 @@ There's no `state-save`/`state-load` to manage — the profile *is* the auth sto
295
295
  Chrome by hand on Windows any more; that was the workaround for CLIs older than
296
296
  0.4.18, which refused with `unsupported OS MINGW64_NT`. A cold start brings
297
297
  Chrome to the front once, on every platform.
298
+ → **Read [`references/windows.md`](references/windows.md)** before driving from
299
+ Git Bash or PowerShell: the CLI is often not on `PATH` there, `list` cannot tell
300
+ you whether a browser is up, and `|` in an `eval` breaks through the `.cmd` shim.
301
+ - ⛔ **Every `eval` on a session shares ONE JavaScript context**, so a `const` from
302
+ an earlier call is still declared, and reusing the name fails with
303
+ `SyntaxError: Identifier 'b' has already been declared`, which reads as a
304
+ quoting problem in the expression you just wrote. ⇒ Wrap every `eval` body in
305
+ an IIFE: `(() => { const t = …; return …; })()`.
306
+ - ⛔ **`read` is not a byte-exact transport.** It returns *rendered* text, so
307
+ soft-wrap points leak into long unbroken strings: the same JSON endpoint read
308
+ twice gave `696febae99cb770065879511` and `696 febae99cb770065879511`. Nothing
309
+ errors and it still parses. ⇒ When the bytes matter (JSON you will commit or
310
+ diff, anything hashed), use `download --url [endpoint]`, which was byte-identical
311
+ across repeated reads.
312
+ - ⛔ **A background tab's cross-origin iframes screenshot as blank space** (payment
313
+ forms, embedded PDF viewers, widgets) while everything around them renders, so
314
+ it reads as a broken page. The renderer is simply not painting them: run `focus`
315
+ on the tab first, and capture the **viewport**, not `--full` (with
316
+ `captureBeyondViewport` they composite at their pre-capture width, narrow and
317
+ clipped). A blank region on a page with no cross-origin iframes is a real finding.
318
+ - **Controls that ignore `click`** (Radix menus, `click` vs `--trusted`), hidden
319
+ dialogs, stalled infinite scroll, React composers and GitHub image attachments:
320
+ **[`references/page-recipes.md`](references/page-recipes.md)**.
321
+ - **This needs the operator's machine, awake.** The shared headed Chrome and its
322
+ logins live there, so a cloud run (a scheduled remote agent) cannot use it, and a
323
+ closed lid sleeps the machine (`caffeinate` prevents idle sleep, not lid-close
324
+ sleep). Split the work: browser- and login-bound steps locally; research and
325
+ repo work wherever.
326
+ - **`screencapture` / `osascript` are not a fallback without macOS grants.**
327
+ Ungranted, they fail with `could not create image from display` and AppleEvent
328
+ `-1712`: Screen Recording and Automation permissions, not missing capability.
329
+ Probe with one line before relying on them.
298
330
 
299
331
  ## Network insights — find the API behind a page
300
332
 
@@ -333,6 +365,13 @@ code lives, how to validate with `node dist/index.js`, and the PR steps:
333
365
 
334
366
  ## Troubleshooting
335
367
 
368
+ - **Which Chrome `launch` starts:** `CHROME` / `BROWSER_AUTOMATION_CHROME` when it
369
+ points at an executable; otherwise macOS `/Applications` then **`~/Applications`**
370
+ (where an account that cannot write `/Applications` gets Chrome installed),
371
+ Windows Program Files then the per-user `%LOCALAPPDATA%` install, Linux
372
+ `google-chrome`/`chromium` on PATH. `doctor` prints the one it found — check that
373
+ line before concluding "Chrome is not installed". Before 0.4.19 the macOS launcher
374
+ only knew `/Applications` and ignored `CHROME`.
336
375
  - **`No CDP browser on http://localhost:<port>`** → `browser-automation launch`.
337
376
  If it says the port is held by ANOTHER user, that is not your Chrome and
338
377
  driving it would act in their session — quit Chrome in that account, or set
@@ -358,6 +397,13 @@ code lives, how to validate with `node dist/index.js`, and the PR steps:
358
397
  and exact: *open Terminal and run `browser-automation profile --migrate`; if macOS
359
398
  asks whether Terminal may access data from other apps, allow it.*
360
399
  - **`command not found: browser-automation`** → `npm install -g @generativereality/browser-automation`.
400
+ - **The Chrome on the port is on a profile you did not expect** → someone worked
401
+ around a launch failure by hand (`BROWSER_AUTOMATION_PROFILE`, a typed
402
+ `--user-data-dir`), and that instance has few or no logins. Read the live
403
+ browser's profile before trusting a drive:
404
+ `ps -p $(lsof -ti:9223) -o command= | tr ' ' '\n' | grep user-data-dir`. The
405
+ shared profile is `~/.browser-automation/chrome-profile`. ⚠️ Do not just kill it;
406
+ it may be the operator's live browser. Ask, then `launch`.
361
407
  - **Chrome was restarted** → nothing to do; the next `goto` recreates the
362
408
  session's tab automatically (sessions self-heal; `list` shows `stale`).
363
409
  - **A login wall on a repeat run** → the profile lost cookies (rare) or the site
@@ -0,0 +1,125 @@
1
+ # Page recipes — controls that need more than `click`
2
+
3
+ Each of these looks like "the site is broken" or "the ref went stale" the first time, and
4
+ each cost a real session at least one wrong diagnosis.
5
+
6
+ ## Clicks: synthetic and trusted are BOTH needed, on different controls
7
+
8
+ Never generalise from one control. On the same site, a dropdown menu ignored untrusted
9
+ clicks and needed `click --trusted`, while a link-styled **Withdraw** anchor was the
10
+ reverse: `Input.dispatchMouseEvent` at its centre silently did nothing, and `el.click()`
11
+ opened the confirm dialog every time. Try both before concluding a control is broken.
12
+
13
+ ## Radix menus open on `pointerdown`
14
+
15
+ A Radix `DropdownMenu` or a row "⋯" trigger will not open from `click`, nor from a bare
16
+ `element.click()`. Radix listens on `pointerdown`, so you get a snapshot with no
17
+ `[role=menuitem]` in it. Send pointer events **plus** a real click, and return the items
18
+ in the same call so you see at once whether it opened:
19
+
20
+ ```bash
21
+ browser-automation eval -s app '(() => {
22
+ const b = [...document.querySelectorAll("button")].find(x => /Open menu/.test(x.getAttribute("aria-label") || x.textContent));
23
+ const o = { bubbles: true, cancelable: true, pointerId: 1, isPrimary: true, button: 0 };
24
+ b.dispatchEvent(new PointerEvent("pointerdown", o));
25
+ b.dispatchEvent(new PointerEvent("pointerup", o));
26
+ b.click();
27
+ return [...document.querySelectorAll("[role=menuitem]")].map(x => x.textContent.trim()).join(" | ");
28
+ })()'
29
+ ```
30
+
31
+ ⚠️ **Do not fire `click` and then this sequence.** Two activations toggle the menu open
32
+ and shut again, which looks identical to it never opening. Once it is open, the menu
33
+ items and dialog buttons take an ordinary `click [ref]` after a re-snapshot; only the
34
+ trigger needs pointer events.
35
+
36
+ ## Dialogs: filter by visibility, not by role
37
+
38
+ A page can hold several hidden `[role=dialog]` nodes (search overlays, ad-option panels).
39
+ `querySelector('[role=dialog]')` returns an empty one, and your automation reports "no
40
+ button" after an action that actually worked. Match `offsetParent !== null` (or `.open`)
41
+ **plus** the text you expect.
42
+
43
+ ## Infinite scroll stalls in a background tab
44
+
45
+ Chrome throttles timers and IntersectionObservers in unfocused tabs, so a lazy-loading
46
+ list stops after a page or two however you scroll it, and it fails by **stalling
47
+ silently**, which reads as "the list is capped". Measured on a 144-row list: window
48
+ scroll, container `scrollTop`, synthetic `wheel` events and a 12000px emulated viewport
49
+ all stalled at 30 rows; bringing the tab to the front walked the same loop to 144,
50
+ matching the count in the page's own header.
51
+
52
+ So when a list "won't paginate", **make the tab render before concluding anything about
53
+ the site**: `focus -s [session]` first, and if the count still stalls, `focus --raise`,
54
+ which really fronts the tab. ⚠️ `--raise` takes the operator's screen, so keep it to a
55
+ bounded step and tell them. Then scroll until the row count stops rising, and check it
56
+ against whatever count the page displays.
57
+
58
+ ⛔ **`Emulation.clearDeviceMetricsOverride` does not reliably restore the real
59
+ viewport.** If you override device metrics, set them back to the real size explicitly.
60
+ Otherwise `getBoundingClientRect` coordinates are computed in a viewport the window does
61
+ not have, and every coordinate-based click lands nowhere and reports success.
62
+
63
+ ## Rich composers accept `fill` and still submit nothing
64
+
65
+ `contenteditable` composers wired to React show your text in the DOM while React's state
66
+ stays empty, so the **Send** button never enables, and re-reading the element confirms
67
+ your text, which makes it look like a UI bug. Use `fill --native` on such a composer from
68
+ the start. ⛔ Clearing it with `el.innerHTML = ""` makes it worse: it can collapse the
69
+ whole action row until a reload.
70
+
71
+ ## Log out, then navigate, as separate calls
72
+
73
+ A logout `fetch` and a `goto` in one chain race: the logout returns `{"success":true}`
74
+ and you still land on the signed-in page, because the navigation resolves against a
75
+ session the request has not finished clearing. The tell is a login URL that renders
76
+ signed-in content. Issue the request, confirm it returned, then `goto` in a **separate**
77
+ invocation and assert `location.pathname`.
78
+
79
+ ## Attach an image to a GitHub PR or issue
80
+
81
+ A committed image cannot be shown in a PR body on a **private** repo: GitHub's image
82
+ proxy fetches without the viewer's credentials, so `…/blob/[sha]/x.png?raw=true` renders
83
+ broken (`naturalWidth: 0`). Only a **user-attachment** renders, and that exists only
84
+ because a browser uploaded it.
85
+
86
+ ⭐ **Stamp the ref yourself.** The comment form's file input is `display:none`, so
87
+ `snapshot` never gives it an `eN` ref, and `setfiles` needs one. Setting the attribute
88
+ by hand is enough:
89
+
90
+ ```bash
91
+ browser-automation goto -s pr "https://github.com/[org]/[repo]/pull/[n]"
92
+ # 1. The comment form is lazy-rendered; wait until it exists.
93
+ browser-automation eval -s pr 'document.querySelector("input#fc-new_comment_field") ? "ready" : "waiting"'
94
+ # 2. Stamp a ref on the input, then setfiles.
95
+ browser-automation eval -s pr '(() => { document.querySelector("input#fc-new_comment_field").setAttribute("data-ba-ref", "e998"); return "ok"; })()'
96
+ browser-automation setfiles -s pr e998 /abs/one.png /abs/two.png
97
+ # 3. Poll the textarea until every upload has landed, then read the URLs out.
98
+ browser-automation eval -s pr '(() => String((document.querySelector("textarea#new_comment_field").value.match(/user-attachments\/assets\/[0-9a-f-]+/g) || []).length))()'
99
+ browser-automation eval -s pr 'document.querySelector("textarea#new_comment_field").value'
100
+ # 4. Clear the draft with the native value setter. Do NOT submit the comment.
101
+ browser-automation eval -s pr '(() => { const t = document.querySelector("textarea#new_comment_field"); Object.getOwnPropertyDescriptor(HTMLTextAreaElement.prototype, "value").set.call(t, ""); t.dispatchEvent(new Event("input", { bubbles: true })); return t.value === ""; })()'
102
+ # 5. Put the harvested <img> tags into the body: gh pr edit --body-file …
103
+ ```
104
+
105
+ The uploaded URLs are plain text from then on, so **harvest them, don't re-upload**, and
106
+ place them anywhere, including the PR description via `gh pr edit`. If ref-stamping ever
107
+ stops working, raw per-tab CDP `DOM.setFileInputFiles` on `input[type="file"]` is what
108
+ `setfiles` does internally, and it fires the trusted `input`/`change` GitHub listens for.
109
+
110
+ Traps:
111
+
112
+ - ⛔ **`upload --click` on "Paste, drop, or click to add files" reports success and
113
+ stages nothing.** *"delivered N file(s) to the page's file handler via chooser"* means
114
+ delivery to *a* handler, not GitHub accepting the files; the textarea stays empty.
115
+ - `snapshot` caps at about 200 elements, so on a long PR the attach control never gets a
116
+ ref. A hand-stamped ref must be shaped `e[number]`; anything else is rejected.
117
+ - The description editor itself is not reachable this way (its menu renders lazily).
118
+ Use `gh pr edit` for the body and the browser only for the upload.
119
+ - **Verify the images render, not that the markup is there.** Attachments go through a
120
+ proxy, so filter on `alt` rather than `src`, force lazy images to load
121
+ (`img.loading = "eager"`), and assert `naturalWidth > 0`. An image below the fold
122
+ reports 0 only because it has not loaded.
123
+ - A mid-session "Single sign-on to [org]" wall is normal on an enterprise org; its
124
+ **Continue** resumes an already-valid IdP session. If it asks for credentials or MFA,
125
+ stop and hand back to the operator.
@@ -0,0 +1,60 @@
1
+ # Driving the CLI on Windows
2
+
3
+ `launch` runs on Windows since 0.4.18 (see Troubleshooting in `SKILL.md`). These are the
4
+ traps after that, all measured driving a real site from Git Bash and PowerShell.
5
+
6
+ ## The CLI is installed but `command not found`
7
+
8
+ The npm global dir holds three shims — `browser-automation`, `.cmd` and `.ps1` — and on a
9
+ stock setup the bare name resolves in neither Git Bash nor PowerShell. `command not found`
10
+ then reads as "not installed" when it is. The same goes for `pnpm`. Invoke the `.cmd`
11
+ through PowerShell:
12
+
13
+ ```powershell
14
+ & "$env:APPDATA\npm\browser-automation.cmd" --version
15
+ ```
16
+
17
+ ## `list` cannot tell you whether a browser is running
18
+
19
+ With **zero open tabs**, `list` prints the full saved-session list — every row flagged
20
+ `[stale]` — and exits 255. That looks exactly like the no-browser case, because `[stale]`
21
+ describes a saved session whose tab is gone, not the browser's health. The tell is the
22
+ `# open tabs (0)` line at the **end** of the output, easy to miss under a long listing.
23
+
24
+ ⭐ **Ask the CDP endpoint instead.** It answers in one call and names the browser:
25
+
26
+ ```powershell
27
+ Invoke-RestMethod -Uri "http://127.0.0.1:9223/json/version" -TimeoutSec 5 # Browser : Chrome/…
28
+ ```
29
+
30
+ A stale session list plus a live `/json/version` means **open a tab**
31
+ (`new -s [name] [url]`), not relaunch the browser. It also tells you *which* browser is
32
+ on the port: a Chrome started by hand, or an Edge standing in for Chrome, answers the same
33
+ way.
34
+
35
+ ## `|`, `&` and parentheses break through the `.cmd` shim
36
+
37
+ `cmd.exe` reads `|` as a pipe, and it appears in ordinary **regex alternation**:
38
+ `eval "…match(/(connections|followers)/)…"` dies with `'followers)' is not recognized as an
39
+ internal or external command`, which reads as a broken CLI rather than quoting. `&` does
40
+ the same, and parentheses or nested quotes in an `eval` expression fail with
41
+ `Positional argument 'expr' is required`.
42
+
43
+ ⭐ **The robust pattern is `read` plus host-side parsing**, so no JS crosses the shim:
44
+
45
+ ```powershell
46
+ $t = & "$env:APPDATA\npm\browser-automation.cmd" read -s [session] | Out-String
47
+ [regex]::Matches($t,'[\d,\.]+K?\s*(?:connections|followers)') | ForEach-Object { $_.Value }
48
+ ```
49
+
50
+ When you genuinely need `eval`, write **quote-free JS**: regex literals instead of string
51
+ literals, `.join()` with no argument instead of `join("\n")`. `eval` has no `--file`
52
+ option, so there is no other escape hatch.
53
+
54
+ ## A global install fails behind a TLS-intercepting proxy
55
+
56
+ `npm install -g` can fail with `SELF_SIGNED_CERT_IN_CHAIN` or
57
+ `UNABLE_TO_GET_ISSUER_CERT_LOCALLY` behind a corporate proxy. That is npm's certificate
58
+ configuration (`npm config set cafile …`), not this tool. Note that `npm install -g` reads
59
+ the **user** `~/.npmrc`, not a project's `.npmrc`, so a registry or CA set only in the
60
+ project does not apply to it.