@generativereality/browser-automation 0.5.0 → 0.6.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.
- package/.claude-plugin/plugin.json +1 -1
- package/README.md +9 -1
- package/dist/index.js +571 -159
- package/package.json +1 -1
- package/scripts/launch-chrome.sh +2 -2
- package/scripts/release.sh +6 -1
- package/scripts/sync-plugin.sh +5 -1
- package/skills/browser/SKILL.md +60 -11
- package/skills/browser/references/input-and-forms.md +5 -4
|
@@ -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
|
+
"version": "0.6.0",
|
|
5
5
|
"author": {
|
|
6
6
|
"name": "generativereality"
|
|
7
7
|
},
|
package/README.md
CHANGED
|
@@ -101,7 +101,8 @@ browser-automation bind -s bank -m nordnet # …or adopt it into a session
|
|
|
101
101
|
| `doctor` | Diagnose Node, Chrome, targets, sessions — and **renderer capacity** (a browser that can no longer launch renderers passes every other check) |
|
|
102
102
|
| `gc` | Prune stale session bookmarks and dead tabs (`--dry` to preview, `--orphans` to also close unclaimed live tabs) |
|
|
103
103
|
| `list` | List sessions and every open tab (id, title, url) |
|
|
104
|
-
| `new -s <s> [url]` | Open a background tab for a session |
|
|
104
|
+
| `new -s <s> [--context <name>] [url]` | Open a background tab for a session; `--context` opens it in a named login context — a separate Chrome with its own profile and window, for a second account next to your own (started on demand) |
|
|
105
|
+
| `context [stop <name> \| forget <name> [--delete-profile]]` | List login contexts and whether their Chrome is running; quit one; remove one (its profile only with `--delete-profile`) |
|
|
105
106
|
| `goto (-s\|-m\|-t) <url>` | Navigate (session tab created if needed) |
|
|
106
107
|
| `bind -s <name> (-m\|-t)` | Adopt an already-open tab into a session |
|
|
107
108
|
| `snapshot (-s\|-m\|-t)` | List interactive elements with refs (`e1`, `e2`, …) |
|
|
@@ -174,6 +175,13 @@ same one-action-per-snapshot rule as Playwright refs.
|
|
|
174
175
|
`BROWSER_AUTOMATION_CHROME` if `chrome.exe` is somewhere unusual). Anywhere else, start Chrome with
|
|
175
176
|
`--remote-debugging-port=<your port> --user-data-dir="<profile>"` — `browser-automation doctor` prints the port.
|
|
176
177
|
|
|
178
|
+
Any command takes `--context <name>` (or `BAC_CONTEXT=<name>`) to act on a login
|
|
179
|
+
context's Chrome instead of your own; a session opened in a context follows it
|
|
180
|
+
without the flag. A new context starts as a copy of the automation
|
|
181
|
+
profile (its extensions, and its logins and cookies; caches are left out), so
|
|
182
|
+
sign out there of any account it is not for; `--empty-profile` when creating it
|
|
183
|
+
starts it with nothing. Your ordinary Chrome profile is never copied.
|
|
184
|
+
|
|
177
185
|
## Environment
|
|
178
186
|
|
|
179
187
|
- `BROWSER_AUTOMATION_PORT` — the debugging port. **Defaults to one per user**,
|
package/dist/index.js
CHANGED
|
@@ -1,15 +1,16 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import updateNotifier from "update-notifier";
|
|
3
3
|
import { cli, define } from "gunshi";
|
|
4
|
-
import
|
|
4
|
+
import { accessSync, appendFileSync, constants, copyFileSync, existsSync, lstatSync, mkdirSync, openSync, readFileSync, readdirSync, readlinkSync, renameSync, rmSync, statSync, symlinkSync, writeFileSync } from "node:fs";
|
|
5
|
+
import { basename, delimiter, dirname, extname, join, relative, resolve, sep } from "node:path";
|
|
6
|
+
import { createServer } from "node:net";
|
|
5
7
|
import { homedir, tmpdir } from "node:os";
|
|
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
|
+
import consola, { consola as consola$1 } from "consola";
|
|
9
10
|
import { fileURLToPath } from "node:url";
|
|
10
11
|
//#region package.json
|
|
11
12
|
var name = "@generativereality/browser-automation";
|
|
12
|
-
var version = "0.
|
|
13
|
+
var version = "0.6.0";
|
|
13
14
|
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
15
|
var package_default = {
|
|
15
16
|
name,
|
|
@@ -178,29 +179,51 @@ function canonicalize(sub, rest, schema) {
|
|
|
178
179
|
};
|
|
179
180
|
}
|
|
180
181
|
//#endregion
|
|
181
|
-
//#region src/core/
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
return join(DIR, `${encodeURIComponent(name)}.json`);
|
|
182
|
+
//#region src/core/context-store.ts
|
|
183
|
+
function contextsDir() {
|
|
184
|
+
return join(homedir(), ".browser-automation", "contexts");
|
|
185
185
|
}
|
|
186
|
-
function
|
|
187
|
-
return
|
|
186
|
+
function file$1(name) {
|
|
187
|
+
return join(contextsDir(), `${name}.json`);
|
|
188
188
|
}
|
|
189
|
-
function
|
|
190
|
-
|
|
191
|
-
writeFileSync(file(s.name), JSON.stringify(s, null, 2));
|
|
189
|
+
function contextProfileDir(name) {
|
|
190
|
+
return join(contextsDir(), name, "chrome-profile");
|
|
192
191
|
}
|
|
193
|
-
function
|
|
194
|
-
|
|
195
|
-
return existsSync(f) ? JSON.parse(readFileSync(f, "utf8")) : null;
|
|
192
|
+
function validContextName(name) {
|
|
193
|
+
return /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/.test(name);
|
|
196
194
|
}
|
|
197
|
-
function
|
|
198
|
-
|
|
199
|
-
|
|
195
|
+
function loadContextRecord(name) {
|
|
196
|
+
if (!validContextName(name)) return null;
|
|
197
|
+
const f = file$1(name);
|
|
198
|
+
if (!existsSync(f)) return null;
|
|
199
|
+
try {
|
|
200
|
+
const r = JSON.parse(readFileSync(f, "utf8"));
|
|
201
|
+
if (!Number.isInteger(r.port) || typeof r.profileDir !== "string") return null;
|
|
202
|
+
return r;
|
|
203
|
+
} catch {
|
|
204
|
+
return null;
|
|
205
|
+
}
|
|
200
206
|
}
|
|
201
|
-
function
|
|
202
|
-
|
|
203
|
-
|
|
207
|
+
function saveContextRecord(r) {
|
|
208
|
+
mkdirSync(contextsDir(), { recursive: true });
|
|
209
|
+
const tmp = `${file$1(r.name)}.${process.pid}.tmp`;
|
|
210
|
+
writeFileSync(tmp, JSON.stringify(r, null, 2));
|
|
211
|
+
renameSync(tmp, file$1(r.name));
|
|
212
|
+
}
|
|
213
|
+
function removeContextRecord(name) {
|
|
214
|
+
rmSync(file$1(name), { force: true });
|
|
215
|
+
}
|
|
216
|
+
function listContextRecords() {
|
|
217
|
+
if (!existsSync(contextsDir())) return [];
|
|
218
|
+
return readdirSync(contextsDir()).filter((f) => f.endsWith(".json")).map((f) => loadContextRecord(f.slice(0, -5))).filter((r) => r !== null);
|
|
219
|
+
}
|
|
220
|
+
/** The context this process is driving, as set by the entry point. Undefined = the user's own Chrome. */
|
|
221
|
+
function activeContextName() {
|
|
222
|
+
return process.env.BROWSER_AUTOMATION_CONTEXT || void 0;
|
|
223
|
+
}
|
|
224
|
+
function activeContext() {
|
|
225
|
+
const name = activeContextName();
|
|
226
|
+
return name ? loadContextRecord(name) : null;
|
|
204
227
|
}
|
|
205
228
|
//#endregion
|
|
206
229
|
//#region src/core/cdp.ts
|
|
@@ -219,6 +242,8 @@ const FIRST_HUMAN_UID = process.platform === "darwin" ? 501 : 1e3;
|
|
|
219
242
|
* for exactly that.
|
|
220
243
|
*/
|
|
221
244
|
function cdpPort() {
|
|
245
|
+
const ctx = activeContext();
|
|
246
|
+
if (ctx) return ctx.port;
|
|
222
247
|
const explicit = Number(process.env.BROWSER_AUTOMATION_PORT);
|
|
223
248
|
if (Number.isInteger(explicit) && explicit > 0 && explicit < 65536) return explicit;
|
|
224
249
|
const uid = typeof process.getuid === "function" ? process.getuid() : FIRST_HUMAN_UID;
|
|
@@ -227,8 +252,33 @@ function cdpPort() {
|
|
|
227
252
|
return BASE_PORT + offset;
|
|
228
253
|
}
|
|
229
254
|
function cdpHost() {
|
|
255
|
+
if (activeContext()) return `http://localhost:${cdpPort()}`;
|
|
230
256
|
return process.env.BROWSER_AUTOMATION_CDP || `http://localhost:${cdpPort()}`;
|
|
231
257
|
}
|
|
258
|
+
/**
|
|
259
|
+
* Ports for login contexts, decided here like every other port. A block well
|
|
260
|
+
* above the per-user range (BASE_PORT … BASE_PORT+999), so a context can never
|
|
261
|
+
* land on another account's Chrome. The first free one not already given to a
|
|
262
|
+
* context is taken, once, and kept in the context's record.
|
|
263
|
+
*/
|
|
264
|
+
const CONTEXT_PORTS = {
|
|
265
|
+
first: 10323,
|
|
266
|
+
count: 800
|
|
267
|
+
};
|
|
268
|
+
function portIsFree(port) {
|
|
269
|
+
return new Promise((resolve) => {
|
|
270
|
+
const srv = createServer();
|
|
271
|
+
srv.once("error", () => resolve(false));
|
|
272
|
+
srv.listen(port, "127.0.0.1", () => srv.close(() => resolve(true)));
|
|
273
|
+
});
|
|
274
|
+
}
|
|
275
|
+
async function allocateContextPort(taken) {
|
|
276
|
+
for (let p = CONTEXT_PORTS.first; p < CONTEXT_PORTS.first + CONTEXT_PORTS.count; p++) {
|
|
277
|
+
if (taken.includes(p)) continue;
|
|
278
|
+
if (await portIsFree(p)) return p;
|
|
279
|
+
}
|
|
280
|
+
throw new Error(`no free port for a new context in ${CONTEXT_PORTS.first}-${CONTEXT_PORTS.first + CONTEXT_PORTS.count - 1}`);
|
|
281
|
+
}
|
|
232
282
|
/** A target has gone away (tab closed, or Chrome restarted -> new targetIds). */
|
|
233
283
|
var TargetGoneError = class extends Error {
|
|
234
284
|
targetId;
|
|
@@ -345,8 +395,7 @@ async function withPage(targetId, fn) {
|
|
|
345
395
|
* CDP `Input.*` events (and the user-activation they grant) are dropped by the
|
|
346
396
|
* renderer when the tab's `visibilityState` is `hidden` — which it is whenever
|
|
347
397
|
* the automation Chrome window isn't the frontmost OS window (the normal case:
|
|
348
|
-
* the user is in their terminal). `
|
|
349
|
-
* the tab still reports `hidden`. `Emulation.setFocusEmulationEnabled` forces
|
|
398
|
+
* the user is in their terminal). `Emulation.setFocusEmulationEnabled` forces
|
|
350
399
|
* the renderer to treat itself as focused+visible regardless of the real window
|
|
351
400
|
* state (this is how Playwright drives backgrounded/headless pages), and
|
|
352
401
|
* `Page.setWebLifecycleState: active` un-throttles a frozen tab. Together they
|
|
@@ -354,9 +403,20 @@ async function withPage(targetId, fn) {
|
|
|
354
403
|
* drag actually lands and grants user activation — which activation-gated flows
|
|
355
404
|
* (e.g. drop-zone uploaders that only start work inside a user gesture) require.
|
|
356
405
|
*
|
|
357
|
-
*
|
|
406
|
+
* Both are best-effort: older Chrome builds may not expose every command.
|
|
407
|
+
*
|
|
408
|
+
* ⛔ **No `Page.bringToFront` here, and do not add it back.** It used to be the
|
|
409
|
+
* first call, and it makes this tab the SELECTED tab of its Chrome window: the
|
|
410
|
+
* tab the person had showing goes `hidden`, and the next time they bring Chrome
|
|
411
|
+
* forward and type, the keys land in the automated tab. That happened for real
|
|
412
|
+
* (issue #28, 2026-10-14): an agent's quiet `focus` left its Outlook calendar
|
|
413
|
+
* selected, and the person's typing created events named "A", "d", "w", "a",
|
|
414
|
+
* "cti" in their real calendar. It bought nothing: measured the same day on
|
|
415
|
+
* Chrome 155 / macOS 27, a background tab with ONLY the two commands below
|
|
416
|
+
* reports `visible` + `hasFocus()`, takes a CDP mouse click as
|
|
417
|
+
* `isTrusted: true` and a CDP key, and the person's tab stays the visible one
|
|
418
|
+
* throughout and after the probe tab is closed. */
|
|
358
419
|
async function forceForeground(s) {
|
|
359
|
-
await s.send("Page.bringToFront").catch(() => {});
|
|
360
420
|
await s.send("Emulation.setFocusEmulationEnabled", { enabled: true }).catch(() => {});
|
|
361
421
|
await s.send("Page.setWebLifecycleState", { state: "active" }).catch(() => {});
|
|
362
422
|
}
|
|
@@ -503,6 +563,357 @@ async function navigate(targetId, url, { timeout = navTimeout() } = {}) {
|
|
|
503
563
|
});
|
|
504
564
|
}
|
|
505
565
|
//#endregion
|
|
566
|
+
//#region src/core/profile.ts
|
|
567
|
+
/** The default, under ~, reachable by every host. */
|
|
568
|
+
function homeProfileDir() {
|
|
569
|
+
return join(homedir(), ".browser-automation", "chrome-profile");
|
|
570
|
+
}
|
|
571
|
+
/** The old default, inside Google Chrome's own app-data folder. */
|
|
572
|
+
function legacyProfileDir() {
|
|
573
|
+
return join(homedir(), "Library", "Application Support", "Google", "Chrome", "browser-automation");
|
|
574
|
+
}
|
|
575
|
+
/**
|
|
576
|
+
* Does a path exist, as far as this process can tell?
|
|
577
|
+
*
|
|
578
|
+
* `unreadable` is its own answer and callers must not fold it into `absent`:
|
|
579
|
+
* it is what a host denied Chrome's container sees for a profile that is very
|
|
580
|
+
* much there.
|
|
581
|
+
*/
|
|
582
|
+
function presence(p) {
|
|
583
|
+
try {
|
|
584
|
+
lstatSync(p);
|
|
585
|
+
return "present";
|
|
586
|
+
} catch (e) {
|
|
587
|
+
return e?.code === "ENOENT" || e?.code === "ENOTDIR" ? "absent" : "unreadable";
|
|
588
|
+
}
|
|
589
|
+
}
|
|
590
|
+
/**
|
|
591
|
+
* Which profile to use, WITHOUT changing anything on disk.
|
|
592
|
+
*
|
|
593
|
+
* The home folder once it exists; otherwise the legacy folder whenever it
|
|
594
|
+
* might exist (present or unreadable); otherwise the home folder, for Chrome
|
|
595
|
+
* to create on first launch.
|
|
596
|
+
*/
|
|
597
|
+
function resolveProfile() {
|
|
598
|
+
const ctx = activeContext();
|
|
599
|
+
if (ctx) return {
|
|
600
|
+
dir: ctx.profileDir,
|
|
601
|
+
source: "context"
|
|
602
|
+
};
|
|
603
|
+
const explicit = process.env.BROWSER_AUTOMATION_PROFILE;
|
|
604
|
+
if (explicit) return {
|
|
605
|
+
dir: explicit,
|
|
606
|
+
source: "env"
|
|
607
|
+
};
|
|
608
|
+
const home = homeProfileDir();
|
|
609
|
+
if (presence(home) === "present") return {
|
|
610
|
+
dir: home,
|
|
611
|
+
source: "home"
|
|
612
|
+
};
|
|
613
|
+
if (presence(legacyProfileDir()) !== "absent") return {
|
|
614
|
+
dir: legacyProfileDir(),
|
|
615
|
+
source: "legacy"
|
|
616
|
+
};
|
|
617
|
+
return {
|
|
618
|
+
dir: home,
|
|
619
|
+
source: "home"
|
|
620
|
+
};
|
|
621
|
+
}
|
|
622
|
+
/** Is any Chrome of ours running with this --user-data-dir? */
|
|
623
|
+
function inUse(dir) {
|
|
624
|
+
try {
|
|
625
|
+
execFileSync("pgrep", [
|
|
626
|
+
"-u",
|
|
627
|
+
String(process.getuid?.() ?? -1),
|
|
628
|
+
"-f",
|
|
629
|
+
"--",
|
|
630
|
+
`--user-data-dir=${dir}`
|
|
631
|
+
], { stdio: "ignore" });
|
|
632
|
+
return true;
|
|
633
|
+
} catch {
|
|
634
|
+
return false;
|
|
635
|
+
}
|
|
636
|
+
}
|
|
637
|
+
/** Move the legacy profile into the home folder, if that is both needed and safe. */
|
|
638
|
+
function migrateProfile() {
|
|
639
|
+
const choice = resolveProfile();
|
|
640
|
+
if (choice.source === "env" || choice.source === "context") return {
|
|
641
|
+
outcome: "explicit",
|
|
642
|
+
dir: choice.dir
|
|
643
|
+
};
|
|
644
|
+
if (choice.source === "home") return {
|
|
645
|
+
outcome: presence(choice.dir) === "present" ? "current" : "fresh",
|
|
646
|
+
dir: choice.dir
|
|
647
|
+
};
|
|
648
|
+
const legacy = legacyProfileDir();
|
|
649
|
+
const home = homeProfileDir();
|
|
650
|
+
if (presence(legacy) === "unreadable") return {
|
|
651
|
+
outcome: "refused",
|
|
652
|
+
dir: legacy,
|
|
653
|
+
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.`
|
|
654
|
+
};
|
|
655
|
+
if (inUse(legacy)) return {
|
|
656
|
+
outcome: "in-use",
|
|
657
|
+
dir: legacy,
|
|
658
|
+
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\`.`
|
|
659
|
+
};
|
|
660
|
+
try {
|
|
661
|
+
mkdirSync(dirname(home), { recursive: true });
|
|
662
|
+
renameSync(legacy, home);
|
|
663
|
+
} catch (e) {
|
|
664
|
+
const code = e?.code;
|
|
665
|
+
if (code === "EPERM" || code === "EACCES") return {
|
|
666
|
+
outcome: "refused",
|
|
667
|
+
dir: legacy,
|
|
668
|
+
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.`
|
|
669
|
+
};
|
|
670
|
+
return {
|
|
671
|
+
outcome: "failed",
|
|
672
|
+
dir: legacy,
|
|
673
|
+
detail: `could not move ${legacy} to ${home} (${code ?? e?.message}). Nothing was changed; the old profile keeps working.`
|
|
674
|
+
};
|
|
675
|
+
}
|
|
676
|
+
for (const f of [
|
|
677
|
+
"SingletonLock",
|
|
678
|
+
"SingletonSocket",
|
|
679
|
+
"SingletonCookie"
|
|
680
|
+
]) rmSync(join(home, f), { force: true });
|
|
681
|
+
return {
|
|
682
|
+
outcome: "moved",
|
|
683
|
+
dir: home,
|
|
684
|
+
detail: `moved ${legacy} → ${home}`
|
|
685
|
+
};
|
|
686
|
+
}
|
|
687
|
+
//#endregion
|
|
688
|
+
//#region src/core/profile-clone.ts
|
|
689
|
+
/** Top-level entries a profile needs. The rest of a user-data-dir is Chrome-wide state and caches. */
|
|
690
|
+
const TOP = new Set([
|
|
691
|
+
"Local State",
|
|
692
|
+
"First Run",
|
|
693
|
+
"Default"
|
|
694
|
+
]);
|
|
695
|
+
/** Cache folders, anywhere: Chrome rebuilds every one of them. */
|
|
696
|
+
const CACHES = new Set([
|
|
697
|
+
"Cache",
|
|
698
|
+
"Code Cache",
|
|
699
|
+
"GPUCache",
|
|
700
|
+
"DawnCache",
|
|
701
|
+
"DawnGraphiteCache",
|
|
702
|
+
"DawnWebGPUCache",
|
|
703
|
+
"GraphiteDawnCache",
|
|
704
|
+
"GrShaderCache",
|
|
705
|
+
"ShaderCache",
|
|
706
|
+
"GPUPersistentCache",
|
|
707
|
+
"Shared Dictionary",
|
|
708
|
+
"Crashpad",
|
|
709
|
+
"BrowserMetrics",
|
|
710
|
+
"DeferredBrowserMetrics",
|
|
711
|
+
"component_crx_cache",
|
|
712
|
+
"extensions_crx_cache",
|
|
713
|
+
"optimization_guide_model_store",
|
|
714
|
+
"OptGuideOnDeviceModel",
|
|
715
|
+
"OptGuideOnDeviceClassifierModel",
|
|
716
|
+
"OnDeviceHeadSuggestModel"
|
|
717
|
+
]);
|
|
718
|
+
function keep(src, root) {
|
|
719
|
+
const rel = relative(root, src);
|
|
720
|
+
if (rel === "") return true;
|
|
721
|
+
const parts = rel.split(sep);
|
|
722
|
+
if (!TOP.has(parts[0])) return false;
|
|
723
|
+
const name = basename(src);
|
|
724
|
+
if (CACHES.has(name)) return false;
|
|
725
|
+
if (name.startsWith("Singleton") || name === "LOCK" || name === "RunningChromeVersion" || name === "DevToolsActivePort") return false;
|
|
726
|
+
return true;
|
|
727
|
+
}
|
|
728
|
+
const vanished = (e) => e?.code === "ENOENT";
|
|
729
|
+
/**
|
|
730
|
+
* The automation Chrome is usually RUNNING while this copies, and it deletes
|
|
731
|
+
* files under us — database journals, temp files. Node's cpSync aborts on the
|
|
732
|
+
* first one: the first live copy (then the opt-in `--clone-profile`) died 878 MB in, leaving a
|
|
733
|
+
* half-copied profile and no context (2026-10-24). A file that vanished
|
|
734
|
+
* between listing and copying is one Chrome no longer needed, so skip it.
|
|
735
|
+
*/
|
|
736
|
+
function copyTree(src, dst, root) {
|
|
737
|
+
mkdirSync(dst, { recursive: true });
|
|
738
|
+
let entries;
|
|
739
|
+
try {
|
|
740
|
+
entries = readdirSync(src, { withFileTypes: true });
|
|
741
|
+
} catch (e) {
|
|
742
|
+
if (vanished(e)) return;
|
|
743
|
+
throw e;
|
|
744
|
+
}
|
|
745
|
+
for (const ent of entries) {
|
|
746
|
+
const s = join(src, ent.name);
|
|
747
|
+
const d = join(dst, ent.name);
|
|
748
|
+
if (!keep(s, root)) continue;
|
|
749
|
+
try {
|
|
750
|
+
if (ent.isDirectory()) copyTree(s, d, root);
|
|
751
|
+
else if (ent.isSymbolicLink()) symlinkSync(readlinkSync(s), d);
|
|
752
|
+
else if (ent.isFile()) copyFileSync(s, d);
|
|
753
|
+
} catch (e) {
|
|
754
|
+
if (!vanished(e)) throw e;
|
|
755
|
+
}
|
|
756
|
+
}
|
|
757
|
+
}
|
|
758
|
+
/** Copy `from` (a user-data-dir) into the empty `to`. Throws if `to` already holds a profile. */
|
|
759
|
+
function cloneProfile(from, to) {
|
|
760
|
+
if (!existsSync(join(from, "Default"))) throw new Error(`no profile to copy at ${from} (no Default/ in it)`);
|
|
761
|
+
if (existsSync(to) && readdirSync(to).length) throw new Error(`${to} is not empty; only a new context is seeded from the automation profile`);
|
|
762
|
+
try {
|
|
763
|
+
copyTree(from, to, from);
|
|
764
|
+
} catch (e) {
|
|
765
|
+
rmSync(to, {
|
|
766
|
+
recursive: true,
|
|
767
|
+
force: true
|
|
768
|
+
});
|
|
769
|
+
throw e;
|
|
770
|
+
}
|
|
771
|
+
}
|
|
772
|
+
//#endregion
|
|
773
|
+
//#region src/core/session.ts
|
|
774
|
+
const DIR = join(homedir(), ".browser-automation", "sessions");
|
|
775
|
+
function file(name) {
|
|
776
|
+
return join(DIR, `${encodeURIComponent(name)}.json`);
|
|
777
|
+
}
|
|
778
|
+
function defaultSessionName() {
|
|
779
|
+
return process.env.BAC_SESSION || "default";
|
|
780
|
+
}
|
|
781
|
+
function saveSession(s) {
|
|
782
|
+
mkdirSync(DIR, { recursive: true });
|
|
783
|
+
writeFileSync(file(s.name), JSON.stringify(s, null, 2));
|
|
784
|
+
}
|
|
785
|
+
function loadSession(name) {
|
|
786
|
+
const f = file(name);
|
|
787
|
+
return existsSync(f) ? JSON.parse(readFileSync(f, "utf8")) : null;
|
|
788
|
+
}
|
|
789
|
+
function deleteSession(name) {
|
|
790
|
+
const f = file(name);
|
|
791
|
+
if (existsSync(f)) rmSync(f);
|
|
792
|
+
}
|
|
793
|
+
/** Every session, whichever Chrome its tab is in. */
|
|
794
|
+
function listAllSessions() {
|
|
795
|
+
if (!existsSync(DIR)) return [];
|
|
796
|
+
return readdirSync(DIR).filter((f) => f.endsWith(".json")).map((f) => JSON.parse(readFileSync(join(DIR, f), "utf8")));
|
|
797
|
+
}
|
|
798
|
+
/**
|
|
799
|
+
* The sessions whose tab is in the Chrome THIS command drives — the user's
|
|
800
|
+
* own, or the active login context's (core/context-store.ts). Everything that
|
|
801
|
+
* compares sessions against the open tabs uses this: against one Chrome's
|
|
802
|
+
* tabs, another Chrome's sessions all look stale, and `gc` would delete them.
|
|
803
|
+
*/
|
|
804
|
+
function listSessions() {
|
|
805
|
+
const ctx = activeContextName();
|
|
806
|
+
return listAllSessions().filter((s) => (s.context ?? void 0) === ctx);
|
|
807
|
+
}
|
|
808
|
+
//#endregion
|
|
809
|
+
//#region src/core/context-select.ts
|
|
810
|
+
/** Commands that do not address a session's tab: the session cannot decide their Chrome. */
|
|
811
|
+
const SESSIONLESS = new Set([
|
|
812
|
+
"list",
|
|
813
|
+
"ls",
|
|
814
|
+
"launch",
|
|
815
|
+
"doctor",
|
|
816
|
+
"port",
|
|
817
|
+
"profile",
|
|
818
|
+
"context",
|
|
819
|
+
"gc",
|
|
820
|
+
"prune"
|
|
821
|
+
]);
|
|
822
|
+
/** Commands that may bring a new context into being (and start its Chrome). */
|
|
823
|
+
const CREATES = new Set([
|
|
824
|
+
"new",
|
|
825
|
+
"goto",
|
|
826
|
+
"launch"
|
|
827
|
+
]);
|
|
828
|
+
var ContextError = class extends Error {};
|
|
829
|
+
function takeContextFlag(argv) {
|
|
830
|
+
const out = [];
|
|
831
|
+
let name;
|
|
832
|
+
let empty = false;
|
|
833
|
+
for (let i = 0; i < argv.length; i++) {
|
|
834
|
+
const a = argv[i];
|
|
835
|
+
if (a === "--") {
|
|
836
|
+
out.push(...argv.slice(i));
|
|
837
|
+
break;
|
|
838
|
+
}
|
|
839
|
+
if (a === "--context") {
|
|
840
|
+
const v = argv[i + 1];
|
|
841
|
+
if (v === void 0 || v.startsWith("-")) throw new ContextError("--context needs a name, e.g. --context cloudflare-2");
|
|
842
|
+
name = v;
|
|
843
|
+
i++;
|
|
844
|
+
continue;
|
|
845
|
+
}
|
|
846
|
+
if (a.startsWith("--context=")) {
|
|
847
|
+
name = a.slice(10);
|
|
848
|
+
continue;
|
|
849
|
+
}
|
|
850
|
+
if (a === "--empty-profile") {
|
|
851
|
+
empty = true;
|
|
852
|
+
continue;
|
|
853
|
+
}
|
|
854
|
+
out.push(a);
|
|
855
|
+
}
|
|
856
|
+
return {
|
|
857
|
+
argv: out,
|
|
858
|
+
name,
|
|
859
|
+
empty
|
|
860
|
+
};
|
|
861
|
+
}
|
|
862
|
+
/** The `-s`/`--session` value, or the default — only when the tab is chosen by session (no -m/-t/-F). */
|
|
863
|
+
function sessionOf(argv) {
|
|
864
|
+
let session;
|
|
865
|
+
for (let i = 0; i < argv.length; i++) {
|
|
866
|
+
const a = argv[i];
|
|
867
|
+
if (a === "--") break;
|
|
868
|
+
if (a === "-m" || a === "--match" || a === "-t" || a === "--target" || a === "-F" || a === "--frame") return null;
|
|
869
|
+
if (a.startsWith("--match=") || a.startsWith("--target=") || a.startsWith("--frame=")) return null;
|
|
870
|
+
if (a === "-s" || a === "--session") session = argv[i + 1];
|
|
871
|
+
else if (a.startsWith("--session=")) session = a.slice(10);
|
|
872
|
+
}
|
|
873
|
+
return session || defaultSessionName();
|
|
874
|
+
}
|
|
875
|
+
/**
|
|
876
|
+
* Work out the context for `sub` + `argv`, register it if this command may
|
|
877
|
+
* create one, and set BROWSER_AUTOMATION_CONTEXT. Returns argv without the flag.
|
|
878
|
+
*/
|
|
879
|
+
async function selectContext(sub, rawArgv) {
|
|
880
|
+
const { argv, name: flag, empty } = takeContextFlag(rawArgv);
|
|
881
|
+
const asked = flag ?? (process.env.BAC_CONTEXT || void 0);
|
|
882
|
+
const session = sub && !SESSIONLESS.has(sub) ? sessionOf(argv) : null;
|
|
883
|
+
const st = session ? loadSession(session) : null;
|
|
884
|
+
if (asked !== void 0 && st && (st.context ?? void 0) !== asked) throw new ContextError(`session "${st.name}" belongs to ${st.context ? `context "${st.context}"` : "your own Chrome"}, not "${asked}" — use another session name (-s), or forget this one first: browser-automation close -s ${st.name}`);
|
|
885
|
+
const name = asked ?? st?.context;
|
|
886
|
+
if (!name) {
|
|
887
|
+
if (empty) throw new ContextError("--empty-profile is for a NEW login context: use it with --context <name>");
|
|
888
|
+
delete process.env.BROWSER_AUTOMATION_CONTEXT;
|
|
889
|
+
return argv;
|
|
890
|
+
}
|
|
891
|
+
if (!validContextName(name)) throw new ContextError(`invalid context name "${name}": letters, digits, '.', '_' or '-' (max 64), starting with a letter or digit`);
|
|
892
|
+
if (!loadContextRecord(name)) {
|
|
893
|
+
if (!sub || !CREATES.has(sub)) throw new ContextError(`no context named "${name}" — open one with: browser-automation new -s <session> --context ${name} <url>`);
|
|
894
|
+
const port = await allocateContextPort(listContextRecords().map((r) => r.port));
|
|
895
|
+
const profileDir = contextProfileDir(name);
|
|
896
|
+
delete process.env.BROWSER_AUTOMATION_CONTEXT;
|
|
897
|
+
const from = resolveProfile().dir;
|
|
898
|
+
if (!empty && existsSync(join(from, "Default"))) {
|
|
899
|
+
console.error(`Context "${name}": starting from a copy of the automation profile (${from}, caches left out). It has the same extensions — and the same logins: sign out there of any account this context is not for. (--empty-profile starts a context with nothing.)`);
|
|
900
|
+
try {
|
|
901
|
+
cloneProfile(from, profileDir);
|
|
902
|
+
} catch (e) {
|
|
903
|
+
throw new ContextError(`could not copy the automation profile into context "${name}": ${e instanceof Error ? e.message : String(e)} — nothing was kept; run it again, or pass --empty-profile`);
|
|
904
|
+
}
|
|
905
|
+
} else mkdirSync(profileDir, { recursive: true });
|
|
906
|
+
saveContextRecord({
|
|
907
|
+
name,
|
|
908
|
+
port,
|
|
909
|
+
profileDir,
|
|
910
|
+
createdAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
911
|
+
});
|
|
912
|
+
} else if (empty) console.error(`Context "${name}" already exists, so --empty-profile does nothing; its profile is left as it is.`);
|
|
913
|
+
process.env.BROWSER_AUTOMATION_CONTEXT = name;
|
|
914
|
+
return argv;
|
|
915
|
+
}
|
|
916
|
+
//#endregion
|
|
506
917
|
//#region src/core/target.ts
|
|
507
918
|
async function resolveLiveTarget(name, { create = true } = {}) {
|
|
508
919
|
const st = loadSession(name);
|
|
@@ -518,7 +929,8 @@ async function resolveLiveTarget(name, { create = true } = {}) {
|
|
|
518
929
|
name,
|
|
519
930
|
targetId,
|
|
520
931
|
createdAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
521
|
-
url: st?.url
|
|
932
|
+
url: st?.url,
|
|
933
|
+
...st?.context ? { context: st.context } : {}
|
|
522
934
|
});
|
|
523
935
|
return {
|
|
524
936
|
targetId,
|
|
@@ -1227,6 +1639,26 @@ function describeNotShown(outcome) {
|
|
|
1227
1639
|
return null;
|
|
1228
1640
|
}
|
|
1229
1641
|
//#endregion
|
|
1642
|
+
//#region src/core/context-launch.ts
|
|
1643
|
+
async function reachable() {
|
|
1644
|
+
try {
|
|
1645
|
+
return (await fetch(`${cdpHost()}/json/version`, { signal: AbortSignal.timeout(1500) })).ok;
|
|
1646
|
+
} catch {
|
|
1647
|
+
return false;
|
|
1648
|
+
}
|
|
1649
|
+
}
|
|
1650
|
+
async function ensureContextChrome() {
|
|
1651
|
+
const ctx = activeContext();
|
|
1652
|
+
if (!ctx || await reachable()) return;
|
|
1653
|
+
consola$1.info(`Starting the Chrome for context "${ctx.name}": its own window and profile, on :${ctx.port}. Whatever you sign in to or install there is kept.`);
|
|
1654
|
+
if (spawnSync(process.execPath, [
|
|
1655
|
+
process.argv[1],
|
|
1656
|
+
"launch",
|
|
1657
|
+
"--context",
|
|
1658
|
+
ctx.name
|
|
1659
|
+
], { stdio: "inherit" }).status !== 0 || !await reachable()) throw new Error(`could not start the Chrome for context "${ctx.name}" — try: browser-automation launch --context ${ctx.name}`);
|
|
1660
|
+
}
|
|
1661
|
+
//#endregion
|
|
1230
1662
|
//#region src/commands/new.ts
|
|
1231
1663
|
const newCommand = define({
|
|
1232
1664
|
name: "new",
|
|
@@ -1250,13 +1682,16 @@ const newCommand = define({
|
|
|
1250
1682
|
async run(ctx) {
|
|
1251
1683
|
const name = ctx.values.session || defaultSessionName();
|
|
1252
1684
|
const url = ctx.positionals[1] ? normalizeUrl(ctx.positionals[1]) : "about:blank";
|
|
1685
|
+
await ensureContextChrome();
|
|
1686
|
+
const context = activeContextName();
|
|
1253
1687
|
if (loadSession(name) && !ctx.values.force) consola$1.warn(`Session "${name}" already maps to a tab. Use --force to open another, or just \`browser-automation goto -s ${name} <url>\`.`);
|
|
1254
1688
|
const targetId = await withRendererDiagnosis(() => createTab(url));
|
|
1255
1689
|
saveSession({
|
|
1256
1690
|
name,
|
|
1257
1691
|
targetId,
|
|
1258
1692
|
url,
|
|
1259
|
-
createdAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
1693
|
+
createdAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
1694
|
+
...context ? { context } : {}
|
|
1260
1695
|
});
|
|
1261
1696
|
const r = await ensureRenderer(targetId);
|
|
1262
1697
|
if (r.woke) consola$1.warn(`[${name}] the new tab's renderer did not start on its own, so the tab was activated briefly to force one. The Chrome window was raised and handed straight back.`);
|
|
@@ -1275,7 +1710,7 @@ const newCommand = define({
|
|
|
1275
1710
|
const note = describeNotShown(outcome);
|
|
1276
1711
|
if (note) consola$1.info(note);
|
|
1277
1712
|
}
|
|
1278
|
-
consola$1.success(`[${name}] opened ${shown ? "and showed" : "background"} tab ${targetId.slice(0, 12)}
|
|
1713
|
+
consola$1.success(`[${name}] opened ${shown ? "and showed" : "background"} tab ${targetId.slice(0, 12)}…${context ? ` in context "${context}"` : ""} → ${url}`);
|
|
1279
1714
|
}
|
|
1280
1715
|
});
|
|
1281
1716
|
//#endregion
|
|
@@ -1394,6 +1829,8 @@ const gotoCommand = define({
|
|
|
1394
1829
|
}
|
|
1395
1830
|
const target = normalizeUrl(url);
|
|
1396
1831
|
const opts = targetOpts(ctx.values);
|
|
1832
|
+
await ensureContextChrome();
|
|
1833
|
+
const context = activeContextName();
|
|
1397
1834
|
const { targetId, created } = await withRendererDiagnosis(() => resolveOrCreateTargetId(opts));
|
|
1398
1835
|
if (created) {
|
|
1399
1836
|
if ((await ensureRenderer(targetId)).woke) consola$1.warn("The new tab's renderer did not start on its own, so the tab was activated briefly to force one. The Chrome window was raised and handed straight back.");
|
|
@@ -1409,7 +1846,8 @@ const gotoCommand = define({
|
|
|
1409
1846
|
name,
|
|
1410
1847
|
targetId,
|
|
1411
1848
|
url: target,
|
|
1412
|
-
createdAt: loadSession(name)?.createdAt ?? (/* @__PURE__ */ new Date()).toISOString()
|
|
1849
|
+
createdAt: loadSession(name)?.createdAt ?? (/* @__PURE__ */ new Date()).toISOString(),
|
|
1850
|
+
...context ? { context } : {}
|
|
1413
1851
|
});
|
|
1414
1852
|
consola$1.success(`[${name}] ${created ? "opened tab + " : ""}navigated → ${target}`);
|
|
1415
1853
|
} else consola$1.success(`[${targetId.slice(0, 12)}…] navigated → ${target}`);
|
|
@@ -1701,7 +2139,7 @@ const clickCommand = define({
|
|
|
1701
2139
|
},
|
|
1702
2140
|
trusted: {
|
|
1703
2141
|
type: "boolean",
|
|
1704
|
-
description: "Dispatch a real, genuinely-trusted CDP mouse click (Input.dispatchMouseEvent) at the element instead of the default JS-dispatched el.click().
|
|
2142
|
+
description: "Dispatch a real, genuinely-trusted CDP mouse click (Input.dispatchMouseEvent) at the element instead of the default JS-dispatched el.click(). Makes the renderer treat the tab as focused+visible and WAITS until it reports so (CDP input no-ops on a backgrounded tab) — without selecting the tab in its window, so the person's own tab keeps their typing, then waits for the element to be actionable (stable position + unoccluded hit-test) before pressing — mirroring Playwright. Use for widgets that demand isTrusted events AND animate in: artdeco dropdown menu items (LinkedIn More→Connect), Radix dropdown/popover triggers, cmdk comboboxes — which a default click, or an immediate trusted click on stale coordinates, only highlights without firing."
|
|
1705
2143
|
}
|
|
1706
2144
|
},
|
|
1707
2145
|
async run(ctx) {
|
|
@@ -1929,8 +2367,9 @@ const sleep$2 = (ms) => new Promise((r) => setTimeout(r, ms));
|
|
|
1929
2367
|
* # The two ways, and why the quiet one is the default
|
|
1930
2368
|
*
|
|
1931
2369
|
* `Emulation.setFocusEmulationEnabled` makes the renderer treat itself as
|
|
1932
|
-
* focused and visible whatever the real window is doing — no window moves,
|
|
1933
|
-
*
|
|
2370
|
+
* focused and visible whatever the real window is doing — no window moves, the
|
|
2371
|
+
* operator's frontmost app is undisturbed, and the tab their window SHOWS stays
|
|
2372
|
+
* the one it showed (it did not until issue #28: see forceForeground). That is what this does by
|
|
1934
2373
|
* default, and it is how Playwright drives backgrounded pages.
|
|
1935
2374
|
*
|
|
1936
2375
|
* `--raise` additionally calls `Target.activateTarget`, which genuinely brings
|
|
@@ -1941,14 +2380,14 @@ const sleep$2 = (ms) => new Promise((r) => setTimeout(r, ms));
|
|
|
1941
2380
|
*
|
|
1942
2381
|
* # It reports the outcome, not the acceptance
|
|
1943
2382
|
*
|
|
1944
|
-
*
|
|
2383
|
+
* Both CDP commands are best-effort — an older Chrome may not expose one —
|
|
1945
2384
|
* so "sent" says nothing. This reads `document.hasFocus()` and
|
|
1946
2385
|
* `visibilityState` back afterwards and prints what it actually achieved,
|
|
1947
2386
|
* naming what it could not confirm rather than printing a tick over it.
|
|
1948
2387
|
*/
|
|
1949
2388
|
const focusCommand = define({
|
|
1950
2389
|
name: "focus",
|
|
1951
|
-
description: "Make a tab report itself focused + visible, so pages that defer work while hidden (rendering, polling, charts, video) behave as if watched. Quiet by default — no window moves
|
|
2390
|
+
description: "Make a tab report itself focused + visible, so pages that defer work while hidden (rendering, polling, charts, video) behave as if watched. Quiet by default — no window moves, the operator keeps their frontmost app, and their window keeps showing its own tab. Add --raise to genuinely bring the tab to the front, which DOES take the screen.",
|
|
1952
2391
|
args: {
|
|
1953
2392
|
...targetArgs,
|
|
1954
2393
|
raise: {
|
|
@@ -2381,7 +2820,7 @@ function guessMime(p) {
|
|
|
2381
2820
|
}
|
|
2382
2821
|
const dropCommand = define({
|
|
2383
2822
|
name: "drop",
|
|
2384
|
-
description: "Drop local file(s) onto a drop-zone element by ref — for uploaders wired to drag-and-drop (a `drop` listener reading `e.dataTransfer.files`) rather than an <input type=file>. Default fires a genuinely-trusted CDP drag sequence (Input.dispatchDragEvent) carrying the real files from disk:
|
|
2823
|
+
description: "Drop local file(s) onto a drop-zone element by ref — for uploaders wired to drag-and-drop (a `drop` listener reading `e.dataTransfer.files`) rather than an <input type=file>. Default fires a genuinely-trusted CDP drag sequence (Input.dispatchDragEvent) carrying the real files from disk: makes the renderer treat the tab as focused+visible (without selecting it in its window), waits for that, waits for the target to be actionable (stable + unoccluded), then dragEnter→dragOver→drop — mirroring `click --trusted`. Use --js for a synthetic (isTrusted=false) DataTransfer drop that does NOT steal focus, for zones that accept synthetic events. For a static <input type=file> use `setfiles`; for a button that opens a file chooser use `upload`.",
|
|
2385
2824
|
args: {
|
|
2386
2825
|
...targetArgs,
|
|
2387
2826
|
on: {
|
|
@@ -2394,7 +2833,7 @@ const dropCommand = define({
|
|
|
2394
2833
|
},
|
|
2395
2834
|
js: {
|
|
2396
2835
|
type: "boolean",
|
|
2397
|
-
description: "Dispatch a synthetic (isTrusted=false) DataTransfer drop instead of the trusted CDP path.
|
|
2836
|
+
description: "Dispatch a synthetic (isTrusted=false) DataTransfer drop instead of the trusted CDP path. Needs no focus emulation. Injects each file's bytes into the page to build the File objects. Use for drop zones that accept synthetic events; falls short on zones that gate on isTrusted."
|
|
2398
2837
|
}
|
|
2399
2838
|
},
|
|
2400
2839
|
async run(ctx) {
|
|
@@ -2711,7 +3150,7 @@ const listCommand = define({
|
|
|
2711
3150
|
const shown = ctx.values.all ? sessions : live;
|
|
2712
3151
|
if (shown.length) {
|
|
2713
3152
|
consola$1.log(`# sessions (${shown.length}${ctx.values.all ? "" : " live"})`);
|
|
2714
|
-
for (const s of shown) consola$1.log(` ${s.name.padEnd(16)} [${liveIds.has(s.targetId) ? "live" : "stale"}] ${s.url ?? ""}`);
|
|
3153
|
+
for (const s of shown) consola$1.log(` ${s.name.padEnd(16)} [${liveIds.has(s.targetId) ? "live" : "stale"}] ${s.context ? `{${s.context}} ` : ""}${s.url ?? ""}`);
|
|
2715
3154
|
} else if (sessions.length) consola$1.log(`# sessions (0 live)`);
|
|
2716
3155
|
if (stale.length && !ctx.values.all) consola$1.log(` + ${stale.length} stale bookmark(s) whose tab is gone — \`list --all\` to see them, \`gc --sessions\` to clear them`);
|
|
2717
3156
|
if (sessions.length) consola$1.log("");
|
|
@@ -2814,123 +3253,6 @@ function launchScriptPath() {
|
|
|
2814
3253
|
return join(packageRoot(), "scripts", "launch-chrome.sh");
|
|
2815
3254
|
}
|
|
2816
3255
|
//#endregion
|
|
2817
|
-
//#region src/core/profile.ts
|
|
2818
|
-
/** The default, under ~, reachable by every host. */
|
|
2819
|
-
function homeProfileDir() {
|
|
2820
|
-
return join(homedir(), ".browser-automation", "chrome-profile");
|
|
2821
|
-
}
|
|
2822
|
-
/** The old default, inside Google Chrome's own app-data folder. */
|
|
2823
|
-
function legacyProfileDir() {
|
|
2824
|
-
return join(homedir(), "Library", "Application Support", "Google", "Chrome", "browser-automation");
|
|
2825
|
-
}
|
|
2826
|
-
/**
|
|
2827
|
-
* Does a path exist, as far as this process can tell?
|
|
2828
|
-
*
|
|
2829
|
-
* `unreadable` is its own answer and callers must not fold it into `absent`:
|
|
2830
|
-
* it is what a host denied Chrome's container sees for a profile that is very
|
|
2831
|
-
* much there.
|
|
2832
|
-
*/
|
|
2833
|
-
function presence(p) {
|
|
2834
|
-
try {
|
|
2835
|
-
lstatSync(p);
|
|
2836
|
-
return "present";
|
|
2837
|
-
} catch (e) {
|
|
2838
|
-
return e?.code === "ENOENT" || e?.code === "ENOTDIR" ? "absent" : "unreadable";
|
|
2839
|
-
}
|
|
2840
|
-
}
|
|
2841
|
-
/**
|
|
2842
|
-
* Which profile to use, WITHOUT changing anything on disk.
|
|
2843
|
-
*
|
|
2844
|
-
* The home folder once it exists; otherwise the legacy folder whenever it
|
|
2845
|
-
* might exist (present or unreadable); otherwise the home folder, for Chrome
|
|
2846
|
-
* to create on first launch.
|
|
2847
|
-
*/
|
|
2848
|
-
function resolveProfile() {
|
|
2849
|
-
const explicit = process.env.BROWSER_AUTOMATION_PROFILE;
|
|
2850
|
-
if (explicit) return {
|
|
2851
|
-
dir: explicit,
|
|
2852
|
-
source: "env"
|
|
2853
|
-
};
|
|
2854
|
-
const home = homeProfileDir();
|
|
2855
|
-
if (presence(home) === "present") return {
|
|
2856
|
-
dir: home,
|
|
2857
|
-
source: "home"
|
|
2858
|
-
};
|
|
2859
|
-
if (presence(legacyProfileDir()) !== "absent") return {
|
|
2860
|
-
dir: legacyProfileDir(),
|
|
2861
|
-
source: "legacy"
|
|
2862
|
-
};
|
|
2863
|
-
return {
|
|
2864
|
-
dir: home,
|
|
2865
|
-
source: "home"
|
|
2866
|
-
};
|
|
2867
|
-
}
|
|
2868
|
-
/** Is any Chrome of ours running with this --user-data-dir? */
|
|
2869
|
-
function inUse(dir) {
|
|
2870
|
-
try {
|
|
2871
|
-
execFileSync("pgrep", [
|
|
2872
|
-
"-u",
|
|
2873
|
-
String(process.getuid?.() ?? -1),
|
|
2874
|
-
"-f",
|
|
2875
|
-
"--",
|
|
2876
|
-
`--user-data-dir=${dir}`
|
|
2877
|
-
], { stdio: "ignore" });
|
|
2878
|
-
return true;
|
|
2879
|
-
} catch {
|
|
2880
|
-
return false;
|
|
2881
|
-
}
|
|
2882
|
-
}
|
|
2883
|
-
/** Move the legacy profile into the home folder, if that is both needed and safe. */
|
|
2884
|
-
function migrateProfile() {
|
|
2885
|
-
const choice = resolveProfile();
|
|
2886
|
-
if (choice.source === "env") return {
|
|
2887
|
-
outcome: "explicit",
|
|
2888
|
-
dir: choice.dir
|
|
2889
|
-
};
|
|
2890
|
-
if (choice.source === "home") return {
|
|
2891
|
-
outcome: presence(choice.dir) === "present" ? "current" : "fresh",
|
|
2892
|
-
dir: choice.dir
|
|
2893
|
-
};
|
|
2894
|
-
const legacy = legacyProfileDir();
|
|
2895
|
-
const home = homeProfileDir();
|
|
2896
|
-
if (presence(legacy) === "unreadable") return {
|
|
2897
|
-
outcome: "refused",
|
|
2898
|
-
dir: legacy,
|
|
2899
|
-
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.`
|
|
2900
|
-
};
|
|
2901
|
-
if (inUse(legacy)) return {
|
|
2902
|
-
outcome: "in-use",
|
|
2903
|
-
dir: legacy,
|
|
2904
|
-
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\`.`
|
|
2905
|
-
};
|
|
2906
|
-
try {
|
|
2907
|
-
mkdirSync(dirname(home), { recursive: true });
|
|
2908
|
-
renameSync(legacy, home);
|
|
2909
|
-
} catch (e) {
|
|
2910
|
-
const code = e?.code;
|
|
2911
|
-
if (code === "EPERM" || code === "EACCES") return {
|
|
2912
|
-
outcome: "refused",
|
|
2913
|
-
dir: legacy,
|
|
2914
|
-
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.`
|
|
2915
|
-
};
|
|
2916
|
-
return {
|
|
2917
|
-
outcome: "failed",
|
|
2918
|
-
dir: legacy,
|
|
2919
|
-
detail: `could not move ${legacy} to ${home} (${code ?? e?.message}). Nothing was changed; the old profile keeps working.`
|
|
2920
|
-
};
|
|
2921
|
-
}
|
|
2922
|
-
for (const f of [
|
|
2923
|
-
"SingletonLock",
|
|
2924
|
-
"SingletonSocket",
|
|
2925
|
-
"SingletonCookie"
|
|
2926
|
-
]) rmSync(join(home, f), { force: true });
|
|
2927
|
-
return {
|
|
2928
|
-
outcome: "moved",
|
|
2929
|
-
dir: home,
|
|
2930
|
-
detail: `moved ${legacy} → ${home}`
|
|
2931
|
-
};
|
|
2932
|
-
}
|
|
2933
|
-
//#endregion
|
|
2934
3256
|
//#region src/core/chrome-path.ts
|
|
2935
3257
|
function executable(p) {
|
|
2936
3258
|
try {
|
|
@@ -3161,11 +3483,18 @@ const launchCommand = define({
|
|
|
3161
3483
|
process.exit(1);
|
|
3162
3484
|
}
|
|
3163
3485
|
const port = ["--port", String(cdpPort())];
|
|
3486
|
+
const env = {
|
|
3487
|
+
...process.env,
|
|
3488
|
+
BA_CONTEXT_FLAG: activeContextName() ?? ""
|
|
3489
|
+
};
|
|
3164
3490
|
const bash = (extra) => spawnSync("bash", [
|
|
3165
3491
|
script,
|
|
3166
3492
|
...port,
|
|
3167
3493
|
...extra
|
|
3168
|
-
], {
|
|
3494
|
+
], {
|
|
3495
|
+
stdio: "inherit",
|
|
3496
|
+
env
|
|
3497
|
+
});
|
|
3169
3498
|
if (ctx.values.status) process.exit(bash(["--status"]).status ?? 1);
|
|
3170
3499
|
if (ctx.values.restart) {
|
|
3171
3500
|
const tabs = await listPageTargets().then((t) => t.length).catch(() => null);
|
|
@@ -3243,12 +3572,12 @@ async function launchWindows(statusOnly, restart) {
|
|
|
3243
3572
|
switch (r.outcome) {
|
|
3244
3573
|
case "already-running":
|
|
3245
3574
|
consola$1.log(`Already running on :${port} — the port is held.`);
|
|
3246
|
-
consola$1.log(
|
|
3575
|
+
consola$1.log(`Drive it with: browser-automation goto -s <session>${activeContextName() ? ` --context ${activeContextName()} <url> (a session opened in it follows it; later commands need no --context)` : " <url>"}`);
|
|
3247
3576
|
consola$1.log("(Port held is not health. Check it works: browser-automation doctor)");
|
|
3248
3577
|
return true;
|
|
3249
3578
|
case "launched":
|
|
3250
3579
|
consola$1.log(`Chrome launched on :${port} in ${r.seconds}s (profile: ${m.dir}, log: ${chromeLogPath()})`);
|
|
3251
|
-
consola$1.log(
|
|
3580
|
+
consola$1.log(`Drive it with: browser-automation goto -s <session>${activeContextName() ? ` --context ${activeContextName()} <url> (a session opened in it follows it; later commands need no --context)` : " <url>"}`);
|
|
3252
3581
|
return true;
|
|
3253
3582
|
case "not-ours":
|
|
3254
3583
|
consola$1.error(`Something on this computer is already serving CDP on port ${port}, and it is not a Chrome this account started. Driving it would act in ANOTHER user's browser — quit Chrome in that account, or set BROWSER_AUTOMATION_PORT to a free port for this one.`);
|
|
@@ -3504,6 +3833,78 @@ const profileCommand = define({
|
|
|
3504
3833
|
}
|
|
3505
3834
|
});
|
|
3506
3835
|
//#endregion
|
|
3836
|
+
//#region src/commands/context.ts
|
|
3837
|
+
async function running(r) {
|
|
3838
|
+
try {
|
|
3839
|
+
return (await fetch(`http://localhost:${r.port}/json/version`, { signal: AbortSignal.timeout(1500) })).ok;
|
|
3840
|
+
} catch {
|
|
3841
|
+
return false;
|
|
3842
|
+
}
|
|
3843
|
+
}
|
|
3844
|
+
/**
|
|
3845
|
+
* Login contexts (core/context-store.ts): a separate Chrome per extra account,
|
|
3846
|
+
* started by `new`/`goto --context <name>`. This lists, stops and forgets them.
|
|
3847
|
+
*/
|
|
3848
|
+
const contextCommand = define({
|
|
3849
|
+
name: "context",
|
|
3850
|
+
description: "Login contexts — a separate Chrome (own profile, own port, own window) per extra account, so a second login sits next to your own; opened by `new`/`goto --context <name>`, which start it on demand. `context` lists them; `context stop <name>` quits one; `context forget <name>` removes it (its sessions too), keeping its profile unless --delete-profile.",
|
|
3851
|
+
args: { "delete-profile": {
|
|
3852
|
+
type: "boolean",
|
|
3853
|
+
description: "With forget: also delete the context's Chrome profile — its logins and extensions. Not undoable."
|
|
3854
|
+
} },
|
|
3855
|
+
async run(ctx) {
|
|
3856
|
+
const action = ctx.positionals[1] ?? "list";
|
|
3857
|
+
const name = ctx.positionals[2];
|
|
3858
|
+
if (action === "list" || action === "ls") {
|
|
3859
|
+
const all = listContextRecords();
|
|
3860
|
+
if (!all.length) {
|
|
3861
|
+
consola$1.log("No login contexts. Open one with: browser-automation new -s <session> --context <name> <url>");
|
|
3862
|
+
return;
|
|
3863
|
+
}
|
|
3864
|
+
const sessions = listAllSessions();
|
|
3865
|
+
consola$1.log(`# login contexts (${all.length}) — each its own Chrome; profiles under ${contextsDir()}`);
|
|
3866
|
+
for (const r of all) {
|
|
3867
|
+
const users = sessions.filter((s) => s.context === r.name).map((s) => s.name);
|
|
3868
|
+
consola$1.log(` ${r.name.padEnd(20)} :${r.port} [${await running(r) ? "running" : "stopped"}]${users.length ? ` sessions: ${users.join(", ")}` : ""}`);
|
|
3869
|
+
}
|
|
3870
|
+
return;
|
|
3871
|
+
}
|
|
3872
|
+
const r = name ? loadContextRecord(name) : null;
|
|
3873
|
+
if (!r) {
|
|
3874
|
+
consola$1.error(name ? `No context named "${name}" — see \`browser-automation context\`.` : `${action} needs a context name.`);
|
|
3875
|
+
process.exit(1);
|
|
3876
|
+
}
|
|
3877
|
+
if (action === "stop") {
|
|
3878
|
+
if (!await running(r)) {
|
|
3879
|
+
consola$1.info(`"${r.name}" is not running.`);
|
|
3880
|
+
return;
|
|
3881
|
+
}
|
|
3882
|
+
process.env.BROWSER_AUTOMATION_CONTEXT = r.name;
|
|
3883
|
+
await closeBrowser();
|
|
3884
|
+
const users = listAllSessions().filter((s) => s.context === r.name).map((s) => s.name);
|
|
3885
|
+
consola$1.success(`Asked the Chrome for "${r.name}" to quit. Its logins stay in its profile; the next ` + (users.length ? `\`goto -s ${users[0]} <url>\` (or any goto in one of its sessions)` : `\`goto -s <session> --context ${r.name} <url>\``) + " starts it again.");
|
|
3886
|
+
return;
|
|
3887
|
+
}
|
|
3888
|
+
if (action === "forget") {
|
|
3889
|
+
if (await running(r)) {
|
|
3890
|
+
consola$1.error(`"${r.name}" is running — stop it first: browser-automation context stop ${r.name}`);
|
|
3891
|
+
process.exit(1);
|
|
3892
|
+
}
|
|
3893
|
+
const gone = listAllSessions().filter((s) => s.context === r.name);
|
|
3894
|
+
for (const s of gone) deleteSession(s.name);
|
|
3895
|
+
removeContextRecord(r.name);
|
|
3896
|
+
if (ctx.values["delete-profile"]) rmSync(join(contextsDir(), r.name), {
|
|
3897
|
+
recursive: true,
|
|
3898
|
+
force: true
|
|
3899
|
+
});
|
|
3900
|
+
consola$1.success(`Forgot context "${r.name}"${gone.length ? ` and its session(s) ${gone.map((s) => s.name).join(", ")}` : ""}. ` + (ctx.values["delete-profile"] ? "Its profile is deleted." : `Its profile is kept at ${r.profileDir} (--delete-profile removes it).`));
|
|
3901
|
+
return;
|
|
3902
|
+
}
|
|
3903
|
+
consola$1.error(`Unknown action "${action}" — use list, stop <name> or forget <name>.`);
|
|
3904
|
+
process.exit(1);
|
|
3905
|
+
}
|
|
3906
|
+
});
|
|
3907
|
+
//#endregion
|
|
3507
3908
|
//#region src/commands/index.ts
|
|
3508
3909
|
const defaultCommand = define({
|
|
3509
3910
|
name: "browser-automation",
|
|
@@ -3539,7 +3940,8 @@ const subCommands = new Map([
|
|
|
3539
3940
|
["gc", gcCommand],
|
|
3540
3941
|
["prune", gcCommand],
|
|
3541
3942
|
["port", portCommand],
|
|
3542
|
-
["profile", profileCommand]
|
|
3943
|
+
["profile", profileCommand],
|
|
3944
|
+
["context", contextCommand]
|
|
3543
3945
|
]);
|
|
3544
3946
|
function withRealPositionals(cmd, real) {
|
|
3545
3947
|
return {
|
|
@@ -3556,6 +3958,16 @@ async function run() {
|
|
|
3556
3958
|
let argv = process.argv.slice(2);
|
|
3557
3959
|
let commands = subCommands;
|
|
3558
3960
|
const sub = argv[0];
|
|
3961
|
+
try {
|
|
3962
|
+
argv = sub === void 0 ? argv : [sub, ...await selectContext(sub, argv.slice(1))];
|
|
3963
|
+
} catch (e) {
|
|
3964
|
+
if (e instanceof ContextError) {
|
|
3965
|
+
console.error(`Error: ${e.message}`);
|
|
3966
|
+
process.exitCode = 1;
|
|
3967
|
+
return;
|
|
3968
|
+
}
|
|
3969
|
+
throw e;
|
|
3970
|
+
}
|
|
3559
3971
|
const command = sub === void 0 ? void 0 : subCommands.get(sub);
|
|
3560
3972
|
if (sub !== void 0 && command) {
|
|
3561
3973
|
const canonical = canonicalize(sub, argv.slice(1), command.args ?? {});
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@generativereality/browser-automation",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.6.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": {
|
package/scripts/launch-chrome.sh
CHANGED
|
@@ -224,7 +224,7 @@ fi
|
|
|
224
224
|
# information. The verdict now appears only when it is true.
|
|
225
225
|
if is_up; then
|
|
226
226
|
echo "Already running on :${PORT} — the port is held."
|
|
227
|
-
echo "Drive it with: browser-automation goto -s <session
|
|
227
|
+
echo "Drive it with: browser-automation goto -s <session>${BA_CONTEXT_FLAG:+ --context $BA_CONTEXT_FLAG} <url>${BA_CONTEXT_FLAG:+ (a session opened in it follows it; later commands need no --context)}"
|
|
228
228
|
echo "(Port held is not health. Check it works: browser-automation doctor)"
|
|
229
229
|
exit 0
|
|
230
230
|
fi
|
|
@@ -325,7 +325,7 @@ START="$(date +%s)"
|
|
|
325
325
|
for _ in $(seq 1 240); do
|
|
326
326
|
if is_up; then
|
|
327
327
|
echo "Chrome launched on :${PORT} in $(( $(date +%s) - START ))s (profile: ${PROFILE}, log: ${LOG})"
|
|
328
|
-
echo "Drive it with: browser-automation goto -s <session
|
|
328
|
+
echo "Drive it with: browser-automation goto -s <session>${BA_CONTEXT_FLAG:+ --context $BA_CONTEXT_FLAG} <url>${BA_CONTEXT_FLAG:+ (a session opened in it follows it; later commands need no --context)}"
|
|
329
329
|
exit 0
|
|
330
330
|
fi
|
|
331
331
|
sleep 0.25
|
package/scripts/release.sh
CHANGED
|
@@ -199,9 +199,14 @@ finish() {
|
|
|
199
199
|
# for a version the registry is already serving (0.4.17: the version
|
|
200
200
|
# endpoint said 200, install said notarget). And say when it fails — this
|
|
201
201
|
# line used to swallow that and print nothing.
|
|
202
|
-
|
|
202
|
+
# And show npm's own words when it fails: 0.5.1's install failed here with
|
|
203
|
+
# the output thrown away, and the same command by hand minutes later just
|
|
204
|
+
# worked — so whether it was the network or something real went unknown.
|
|
205
|
+
local npmlog; npmlog="$(mktemp "${TMPDIR:-/tmp}/ba-npm.XXXXXX")"
|
|
206
|
+
if npm install -g --prefer-online "$PKG@$v" >"$npmlog" 2>&1; then
|
|
203
207
|
echo " installed $(browser-automation --version)"
|
|
204
208
|
else
|
|
209
|
+
tail -n 8 "$npmlog" | sed 's/^/ npm: /' >&2
|
|
205
210
|
echo " ⚠ could not install $PKG@$v globally — run: npm install -g --prefer-online $PKG@$v" >&2
|
|
206
211
|
fi
|
|
207
212
|
|
package/scripts/sync-plugin.sh
CHANGED
|
@@ -13,7 +13,11 @@ SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
|
|
|
13
13
|
# finish` points it at the released tag, so what ships is what was tagged —
|
|
14
14
|
# while still running THIS copy of the script (an old tag's copy lacks fixes).
|
|
15
15
|
REPO_ROOT="${BA_PLUGIN_SOURCE:-$(dirname "$SCRIPT_DIR")}"
|
|
16
|
-
|
|
16
|
+
# Beside the MAIN checkout, not beside this script: a release run from a linked
|
|
17
|
+
# worktree (scratch dirs, .claude/worktrees/…) has no ../plugins next to it —
|
|
18
|
+
# 0.5.0's finish died there. --git-common-dir is the main checkout's .git.
|
|
19
|
+
MAIN_CHECKOUT="$(dirname "$(git -C "$SCRIPT_DIR" rev-parse --path-format=absolute --git-common-dir)")"
|
|
20
|
+
PLUGINS_DIR="${BA_PLUGINS_DIR:-$MAIN_CHECKOUT/../plugins}" # override for tests
|
|
17
21
|
CHECK_ONLY=false
|
|
18
22
|
[ "${1:-}" = "--check" ] && CHECK_ONLY=true
|
|
19
23
|
|
package/skills/browser/SKILL.md
CHANGED
|
@@ -40,12 +40,23 @@ file under `~/.browser-automation/sessions/`.
|
|
|
40
40
|
background, and nothing fronts a tab as a side effect of ordinary driving:
|
|
41
41
|
`goto`, `read`, `snapshot`, `fill`, `eval`, `screenshot` all leave your
|
|
42
42
|
frontmost app alone. Three things deliberately do more, and only these:
|
|
43
|
-
`focus`
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
`focus` unless a person needs to see
|
|
43
|
+
`focus`, `click --trusted` and `drop` make the RENDERER believe the tab is
|
|
44
|
+
focused and visible (focus emulation; CDP input grants no user activation to
|
|
45
|
+
a renderer that considers itself hidden) — **no window moves, and the tab the
|
|
46
|
+
person's window shows stays the one it showed**. `focus --raise` calls
|
|
47
|
+
`Target.activateTarget` and **genuinely takes the operator's screen**; it is
|
|
48
|
+
the only one that does. Reach for plain `focus` unless a person needs to see
|
|
49
|
+
the tab.
|
|
50
|
+
- ⛔ **Selecting a tab moves where the person's typing goes.** Whatever tab a
|
|
51
|
+
Chrome window shows is where their keystrokes land the next time they bring
|
|
52
|
+
Chrome forward. Before CLI 0.5.1 a plain `focus` (and `click --trusted`,
|
|
53
|
+
`drop`) also selected the session's tab in its window; an agent's quiet
|
|
54
|
+
`focus` left an Outlook calendar selected, and the person's typing created
|
|
55
|
+
events named "A", "d", "w", "a", "cti" in their real calendar (issue #28,
|
|
56
|
+
2026-10-14). So: `--show` and `focus --raise` are the only commands that
|
|
57
|
+
select a tab on purpose — use them when a person is meant to look, and on an
|
|
58
|
+
older CLI avoid `focus` on a tab where stray keys do damage (calendars, chat,
|
|
59
|
+
editors).
|
|
49
60
|
- **Show the work: `--show` / `BAC_SHOW_TAB=1`.** A person watching the Chrome
|
|
50
61
|
window sees whichever tab is SELECTED, and the tabs you work in are background
|
|
51
62
|
tabs — so by default they watch one stale page while titles change elsewhere
|
|
@@ -145,6 +156,8 @@ Page commands take a tab selector — `-s <session>` (default `$BAC_SESSION`, el
|
|
|
145
156
|
| Where the Chrome profile lives / move it out of Chrome's folder | `browser-automation profile` / `profile --migrate` |
|
|
146
157
|
| List sessions + every open tab (id, title, url) | `browser-automation list` |
|
|
147
158
|
| Open a background tab | `browser-automation new -s work [url]` |
|
|
159
|
+
| A SECOND login next to the user's (another account) | `browser-automation new -s cf2 --context cloudflare-2 https://dash.cloudflare.com` |
|
|
160
|
+
| List / stop / remove login contexts | `browser-automation context` / `context stop <name>` / `context forget <name>` |
|
|
148
161
|
| Navigate (session tab created if needed) | `browser-automation goto -s work https://example.com` |
|
|
149
162
|
| Drive a tab the user already opened | `browser-automation snapshot -m nordnet` |
|
|
150
163
|
| Adopt an open tab into a session | `browser-automation bind -s bank -m nordnet` |
|
|
@@ -204,6 +217,42 @@ browser-automation read -s cf # later runs: already authenticate
|
|
|
204
217
|
|
|
205
218
|
There's no `state-save`/`state-load` to manage — the profile *is* the auth store.
|
|
206
219
|
|
|
220
|
+
### A second account next to the first — `--context <name>`
|
|
221
|
+
|
|
222
|
+
The profile holds ONE login per site. For a second account beside it (two
|
|
223
|
+
Cloudflare dashboards, a client's Google account next to the user's), open the
|
|
224
|
+
session in a named **login context**: a separate Chrome with its own profile,
|
|
225
|
+
port and window, started on demand. The user's own Chrome is not touched.
|
|
226
|
+
|
|
227
|
+
```bash
|
|
228
|
+
browser-automation new -s cf2 --context cloudflare-2 https://dash.cloudflare.com
|
|
229
|
+
# FIRST time only: in the new window (a copy of the automation profile), the user
|
|
230
|
+
# signs out of the first account and signs in to the other one
|
|
231
|
+
browser-automation read -s cf2 # follows the session's context — no flag
|
|
232
|
+
```
|
|
233
|
+
|
|
234
|
+
- **A session remembers its context**: later commands on `-s cf2` go to that
|
|
235
|
+
Chrome without `--context`. A session can't change context; use another `-s`.
|
|
236
|
+
- **It is a real profile** (`~/.browser-automation/contexts/<name>/chrome-profile`):
|
|
237
|
+
logins and extensions persist across restarts, like the main profile.
|
|
238
|
+
- **It starts as a copy of the automation profile** (caches left out, ~0.9 GB,
|
|
239
|
+
a few seconds): the same extensions work at once — a password manager, for
|
|
240
|
+
passkeys — and it is signed in to the same accounts. So in the new window,
|
|
241
|
+
**sign out of the account this context is NOT for** (e.g. the first Cloudflare
|
|
242
|
+
account), then sign in to the other. `--empty-profile` (only when the context
|
|
243
|
+
is first made) starts it with nothing instead. The user's ordinary Chrome
|
|
244
|
+
profile is never copied.
|
|
245
|
+
- **Starting it takes the screen once** — a cold Chrome launch comes to the
|
|
246
|
+
front (issue #25). `goto`/`new` start it when it isn't running; `context stop
|
|
247
|
+
<name>` quits it; `context forget <name> [--delete-profile]` removes it.
|
|
248
|
+
- `-m`/`-t`, `list`, `doctor`, `launch` act on the user's Chrome unless given
|
|
249
|
+
`--context <name>` (or `BAC_CONTEXT`).
|
|
250
|
+
- ⛔ **Not a second Chrome profile in the main Chrome, not an incognito-style
|
|
251
|
+
CDP context.** A second profile becomes Chrome's default while its window is
|
|
252
|
+
open — every other session's new tab opens in it, logged out. A CDP
|
|
253
|
+
`createBrowserContext` hides its tabs from extensions (Bitwarden: `No tab with
|
|
254
|
+
id`), so passkeys and autofill fail. Measured in issue #31.
|
|
255
|
+
|
|
207
256
|
## Gotchas
|
|
208
257
|
|
|
209
258
|
- **Values may contain `--` freely.** `fill -s work e3 "see the --native flag"`
|
|
@@ -216,9 +265,9 @@ There's no `state-save`/`state-load` to manage — the profile *is* the auth sto
|
|
|
216
265
|
those refs for one action → re-snapshot. "ref not found" means re-snapshot.
|
|
217
266
|
- **`isTrusted` / synthetic events.** Clicks and fills are JS-dispatched by
|
|
218
267
|
default, so widgets that demand trusted events ignore them. **For clicks, pass
|
|
219
|
-
`--trusted`** — it dispatches a real CDP `Input.dispatchMouseEvent`,
|
|
220
|
-
|
|
221
|
-
|
|
268
|
+
`--trusted`** — it dispatches a real CDP `Input.dispatchMouseEvent`, makes the
|
|
269
|
+
renderer treat the tab as focused+visible (CDP input no-ops on a backgrounded
|
|
270
|
+
tab; the person's window keeps showing its own tab) and waits for the element to be actionable (stable position +
|
|
222
271
|
unoccluded hit-test) before pressing. For fills, pass `--native` to drive
|
|
223
272
|
character insertion through CDP `Input.insertText`, which fires real
|
|
224
273
|
`beforeinput`/`input` events.
|
|
@@ -260,8 +309,8 @@ There's no `state-save`/`state-load` to manage — the profile *is* the auth sto
|
|
|
260
309
|
underlying export URL/endpoint and use `--url`, or the site's API.
|
|
261
310
|
- **File upload — three paths:** `setfiles [ref] [path…]` for a static `<input type=file>`;
|
|
262
311
|
`upload --click [ref] [path…]` for a button that opens a native file chooser; `drop [ref]
|
|
263
|
-
[path…]` for a drag-and-drop zone with no file input (`--js` for a synthetic drop that
|
|
264
|
-
|
|
312
|
+
[path…]` for a drag-and-drop zone with no file input (`--js` for a synthetic drop that needs
|
|
313
|
+
no focus emulation). ⛔ **Upload once, verify by `snapshot`/`screenshot`, and don't blindly
|
|
265
314
|
retry** — each successful run adds another attachment, and apps reset `files` to 0 after
|
|
266
315
|
consuming it. How each path works and when to pick it:
|
|
267
316
|
[`references/input-and-forms.md`](references/input-and-forms.md).
|
|
@@ -118,11 +118,12 @@ under Gotchas; this is the detail and the worked cases behind them.
|
|
|
118
118
|
all — a `drop` listener reading `e.dataTransfer.files` (vocalremover-style audio
|
|
119
119
|
tools, many image/video drop zones). Neither `setfiles` nor `upload` applies;
|
|
120
120
|
use `drop <ref> <path…>`. By default it fires a genuinely-**trusted** CDP drag
|
|
121
|
-
(`Input.dispatchDragEvent`) carrying the real files from disk: it
|
|
122
|
-
the
|
|
123
|
-
focused+visible even when the Chrome window isn't the frontmost OS
|
|
121
|
+
(`Input.dispatchDragEvent`) carrying the real files from disk: it forces the
|
|
122
|
+
tab foreground for the renderer (focus emulation + active lifecycle — so the
|
|
123
|
+
tab reports focused+visible even when the Chrome window isn't the frontmost OS
|
|
124
|
+
window, without selecting it in that window; see issue #28),
|
|
124
125
|
waits for the zone to be actionable, then dragEnter→dragOver→drop. The
|
|
125
|
-
|
|
126
|
+
forced foreground matters: drop-zone uploaders commonly do their work only inside a
|
|
126
127
|
**user activation**, and CDP input grants no activation on a tab the renderer
|
|
127
128
|
considers `hidden` — which it is whenever the window is occluded (the usual
|
|
128
129
|
case while you work in the terminal). vocalremover.org is the canonical example:
|