pi-browser-harness 0.10.2 → 0.12.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/CHANGELOG.md +54 -0
- package/README.md +21 -10
- package/package.json +6 -3
- package/skills/pi-browser-harness/SKILL.md +30 -1
- package/src/cdp/commands.ts +260 -0
- package/src/cdp/console-buffer.ts +10 -85
- package/src/cdp/discovery.ts +31 -71
- package/src/cdp/errors.ts +4 -0
- package/src/cdp/events.ts +170 -0
- package/src/cdp/network-buffer.ts +42 -109
- package/src/cdp/ownership.ts +0 -17
- package/src/cdp/record-store.ts +61 -0
- package/src/cdp/session.ts +205 -193
- package/src/cdp/target-factory.ts +10 -80
- package/src/cdp/types.ts +21 -12
- package/src/client.ts +39 -95
- package/src/daemon/bridge.ts +375 -265
- package/src/daemon/index.ts +0 -28
- package/src/daemon/protocol.ts +6 -68
- package/src/daemon/queue.ts +85 -0
- package/src/daemon/server.ts +24 -99
- package/src/daemon/spawn.ts +90 -82
- package/src/{cdp/daemon-transport.ts → daemon/transport.ts} +24 -52
- package/src/domains/ax-tree.ts +179 -0
- package/src/domains/box.ts +51 -0
- package/src/domains/cdp-call.ts +55 -0
- package/src/domains/click.ts +19 -37
- package/src/domains/console.ts +48 -4
- package/src/domains/dialog.ts +8 -5
- package/src/domains/drag.ts +8 -7
- package/src/domains/element-call.ts +117 -0
- package/src/domains/files.ts +75 -30
- package/src/domains/fill-engine.ts +80 -0
- package/src/domains/form-batch.ts +64 -0
- package/src/domains/form.ts +115 -112
- package/src/domains/headers.ts +89 -0
- package/src/domains/history.ts +16 -12
- package/src/domains/isolated-tab.ts +26 -55
- package/src/domains/js.ts +32 -51
- package/src/domains/keyboard.ts +38 -34
- package/src/domains/navigate.ts +16 -26
- package/src/domains/network.ts +61 -13
- package/src/domains/page.ts +25 -10
- package/src/domains/readpage/read-page.ts +74 -20
- package/src/domains/readpage/readability.ts +0 -24
- package/src/domains/ref-resolve.ts +24 -58
- package/src/domains/render.ts +6 -27
- package/src/domains/screenshot-capture.ts +80 -0
- package/src/domains/screenshot.ts +9 -90
- package/src/domains/scroll.ts +10 -12
- package/src/domains/search/google-serp.ts +0 -29
- package/src/domains/search/web-search.ts +48 -21
- package/src/domains/setup.ts +1 -13
- package/src/domains/snapshot.ts +36 -280
- package/src/domains/tabs.ts +15 -16
- package/src/domains/target.ts +35 -0
- package/src/domains/viewport.ts +5 -4
- package/src/index.ts +23 -69
- package/src/profile/bind.ts +8 -57
- package/src/profile/browser-process.ts +75 -126
- package/src/profile/command.ts +50 -29
- package/src/profile/launch.ts +22 -40
- package/src/profile/list.ts +14 -54
- package/src/profile/paths.ts +2 -65
- package/src/profile/store.ts +35 -56
- package/src/prompt.ts +22 -122
- package/src/registry.ts +33 -33
- package/src/schemas/parse.ts +23 -0
- package/src/setup.ts +0 -25
- package/src/state.ts +48 -18
- package/src/util/debug.ts +8 -0
- package/src/util/guards.ts +30 -0
- package/src/util/js-template.ts +1 -16
- package/src/util/mutex.ts +0 -5
- package/src/util/paths.ts +11 -1
- package/src/util/result.ts +0 -6
- package/src/util/sharp-shim.ts +12 -19
- package/src/util/tool.ts +17 -42
- package/src/util/truncate.ts +6 -0
- package/tsconfig.json +1 -16
- package/skills/deep-research/SKILL.md +0 -66
- package/src/cdp/event-queue.ts +0 -128
- package/src/cdp/transport.ts +0 -156
- package/src/cdp/window-binding.ts +0 -15
- package/src/deep-research.ts +0 -41
- package/src/domains/forms.ts +0 -355
- package/src/domains/readpage/capture.ts +0 -46
- package/src/domains/search/extract.ts +0 -44
- package/src/profile/picker.ts +0 -73
- package/src/util/keycodes.ts +0 -10
- package/src/util/time.ts +0 -29
package/src/index.ts
CHANGED
|
@@ -1,44 +1,23 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* pi-browser-harness — browser control extension for pi.
|
|
3
|
-
*
|
|
4
|
-
* Gives pi agents full control of a real Chrome browser via CDP.
|
|
5
|
-
* Connects to the user's running Chrome (chrome://inspect/#remote-debugging),
|
|
6
|
-
* registers browser_* tools, and injects browser control guidance into the
|
|
7
|
-
* system prompt.
|
|
8
|
-
*
|
|
9
|
-
* Install:
|
|
10
|
-
* pi install npm:pi-browser-harness
|
|
11
|
-
* # or copy to .pi/extensions/pi-browser-harness/
|
|
12
|
-
*
|
|
13
|
-
* Commands:
|
|
14
|
-
* /browser-setup — guided setup wizard
|
|
15
|
-
* /browser-profile — choose which browser profile the agent uses
|
|
16
|
-
* /browser-status — show client status and current page
|
|
17
|
-
* /browser-reload-daemon — restart the browser client
|
|
18
|
-
* /deep-research <q> — research a question on the web, write a cited report
|
|
19
|
-
*
|
|
20
|
-
* Flags:
|
|
21
|
-
* --browser-namespace <name> — override namespace (default: auto)
|
|
22
|
-
* --browser-debug-clicks — enable debug click overlay
|
|
23
|
-
*/
|
|
24
|
-
|
|
25
1
|
import type { ExtensionAPI } from "@mariozechner/pi-coding-agent";
|
|
26
2
|
import { type BrowserClient, createBrowserClient } from "./client";
|
|
27
3
|
import { getBrowserSystemPrompt } from "./prompt";
|
|
28
4
|
import { registerSetupCommand } from "./setup";
|
|
29
5
|
import { registerProfileCommand } from "./profile/command";
|
|
30
6
|
import { readPin } from "./profile/store";
|
|
31
|
-
import {
|
|
32
|
-
import { type BrowserState, defaultState, persistState, restoreState } from "./state";
|
|
7
|
+
import { type BrowserState, createStatePersister, defaultState, restoreState } from "./state";
|
|
33
8
|
import { registerAllTools } from "./registry";
|
|
34
9
|
import { cleanupTempDirs } from "./util/truncate";
|
|
35
|
-
import {
|
|
10
|
+
import { restoreDownloadBehavior } from "./domains/files";
|
|
11
|
+
import { createDaemonTransport } from "./daemon/transport";
|
|
12
|
+
import { setDebugClicks } from "./util/debug";
|
|
13
|
+
import { asBoolean, asString } from "./util/guards";
|
|
36
14
|
|
|
37
15
|
export default function browserHarnessExtension(pi: ExtensionAPI): void {
|
|
38
|
-
const flagNs = pi.getFlag("browser-namespace")
|
|
16
|
+
const flagNs = asString(pi.getFlag("browser-namespace"));
|
|
39
17
|
const namespace = flagNs ?? `pi-${Math.random().toString(36).slice(2, 10)}`;
|
|
40
18
|
|
|
41
19
|
let state: BrowserState = defaultState(namespace);
|
|
20
|
+
const persister = createStatePersister(pi);
|
|
42
21
|
let client: BrowserClient | null = null;
|
|
43
22
|
let toolsRegistered = false;
|
|
44
23
|
|
|
@@ -106,16 +85,12 @@ export default function browserHarnessExtension(pi: ExtensionAPI): void {
|
|
|
106
85
|
|
|
107
86
|
pi.on("session_start", async (_event, ctx) => {
|
|
108
87
|
state = restoreState(ctx, state.namespace);
|
|
88
|
+
persister.markPersisted(state);
|
|
89
|
+
setDebugClicks(asBoolean(pi.getFlag("browser-debug-clicks")) ?? false);
|
|
109
90
|
|
|
110
|
-
//
|
|
111
|
-
// session termination. Re-read it every session start: another pi session
|
|
112
|
-
// may have changed it since this client was created.
|
|
91
|
+
// Re-read the on-disk profile pin every session start: another pi session may have changed it since this client was created.
|
|
113
92
|
const profilePin = await readPin();
|
|
114
93
|
|
|
115
|
-
// Create the client lazily on first session. The daemon transport
|
|
116
|
-
// is created but NOT connected — that only happens when the user
|
|
117
|
-
// runs /browser-setup or a browser tool call finds an existing socket.
|
|
118
|
-
// This means zero Chrome prompts for non-browser pi sessions.
|
|
119
94
|
if (!client) {
|
|
120
95
|
const transport = createDaemonTransport(state.namespace);
|
|
121
96
|
|
|
@@ -140,70 +115,49 @@ export default function browserHarnessExtension(pi: ExtensionAPI): void {
|
|
|
140
115
|
? { harnessWindowId: snap.harnessWindowId }
|
|
141
116
|
: {}),
|
|
142
117
|
};
|
|
143
|
-
|
|
144
|
-
// including after session replacement when pi's ctx is stale.
|
|
145
|
-
// Persistence is best-effort — failure must not crash the event consumer.
|
|
146
|
-
// ponytail: try/catch is the simplest guard against stale-ctx.
|
|
147
|
-
try { persistState(pi, state); } catch { /* stale ctx — safe to ignore */ }
|
|
118
|
+
try { persister.persist(state); } catch {}
|
|
148
119
|
},
|
|
149
120
|
});
|
|
150
121
|
} else {
|
|
151
|
-
// Client carried over from a previous session — adopt whatever pin is on
|
|
152
|
-
// disk now, which another pi session may have changed.
|
|
153
122
|
client.setProfilePin(profilePin);
|
|
154
123
|
}
|
|
155
124
|
|
|
156
|
-
// Do NOT call client.start() here — browser control is on-demand.
|
|
157
|
-
// The first browser tool call or /browser-setup triggers the actual
|
|
158
|
-
// daemon socket connection and Chrome prompt.
|
|
159
|
-
|
|
160
125
|
if (!toolsRegistered) {
|
|
161
126
|
registerAllTools(pi, client);
|
|
162
127
|
toolsRegistered = true;
|
|
163
128
|
}
|
|
164
129
|
registerSetupCommand(pi, client);
|
|
165
130
|
registerProfileCommand(pi, client);
|
|
166
|
-
registerDeepResearchCommand(pi);
|
|
167
131
|
});
|
|
168
132
|
|
|
169
133
|
pi.on("session_shutdown", async () => {
|
|
170
134
|
if (client) {
|
|
171
135
|
try {
|
|
172
|
-
//
|
|
173
|
-
|
|
136
|
+
// Warn but keep going: detach and tab cleanup still have to run, and a throw here would skip both.
|
|
137
|
+
const restored = await restoreDownloadBehavior(client);
|
|
138
|
+
if (!restored.success) {
|
|
139
|
+
console.warn(`[pi-browser-harness] ${restored.error.message}`);
|
|
140
|
+
}
|
|
174
141
|
await client.detach();
|
|
175
|
-
// Close every tab this session opened so no stale harness tabs linger
|
|
176
|
-
// in the user's browser between sessions. This also clears the persisted
|
|
177
|
-
// ownership + window binding via onOwnershipChange, so the next session
|
|
178
|
-
// starts with a fresh dedicated window rather than reattaching to leftovers.
|
|
179
142
|
await client.closeOwnedTabs();
|
|
180
143
|
} catch (e) {
|
|
181
144
|
console.warn("[pi-browser-harness] browser teardown failed during shutdown:", e);
|
|
182
145
|
}
|
|
183
|
-
//
|
|
184
|
-
// Do NOT call client.stop() or null out client — the daemon connection
|
|
185
|
-
// persists and eliminates the per-session "Allow Remote Debugging" prompt.
|
|
186
|
-
// Only Chrome restart or daemon death triggers a new prompt.
|
|
146
|
+
// Do NOT stop the client or null it out: the surviving daemon connection is what eliminates the per-session "Allow Remote Debugging" prompt.
|
|
187
147
|
}
|
|
188
|
-
|
|
189
|
-
// so this captures the cleared ownership set.
|
|
190
|
-
persistState(pi, state);
|
|
148
|
+
persister.persist(state);
|
|
191
149
|
await cleanupTempDirs();
|
|
192
150
|
});
|
|
193
151
|
|
|
152
|
+
// The branch already holds the restored snapshot: re-appending it only grows the session file.
|
|
194
153
|
pi.on("session_tree", async (_event, ctx) => {
|
|
195
154
|
state = restoreState(ctx, client?.namespace);
|
|
196
|
-
|
|
155
|
+
persister.markPersisted(state);
|
|
197
156
|
});
|
|
198
157
|
|
|
199
158
|
pi.on("before_agent_start", async (event) => {
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
event.systemPrompt +
|
|
204
|
-
`\n\n## Browser Control\n\nBrowser tools (browser_*) are available but the browser is not connected. Run /browser-setup.`,
|
|
205
|
-
};
|
|
206
|
-
}
|
|
207
|
-
return { systemPrompt: event.systemPrompt + getBrowserSystemPrompt() };
|
|
159
|
+
return {
|
|
160
|
+
systemPrompt: event.systemPrompt + getBrowserSystemPrompt(client?.status().alive ?? false),
|
|
161
|
+
};
|
|
208
162
|
});
|
|
209
163
|
}
|
package/src/profile/bind.ts
CHANGED
|
@@ -1,62 +1,30 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Binding the harness session to a pinned profile.
|
|
3
|
-
*
|
|
4
|
-
* Sequence, all of it verified against a live browser:
|
|
5
|
-
* 1. resolve the browser binary and any explicit --user-data-dir
|
|
6
|
-
* 2. launch a window into the profile, marked with a file:// sentinel
|
|
7
|
-
* 3. poll Target.getTargets for the sentinel page — its browserContextId IS
|
|
8
|
-
* the profile's context, which is otherwise undiscoverable (CDP exposes no
|
|
9
|
-
* profile identity)
|
|
10
|
-
* 4. adopt that page as the harness window, blank it, drop the sentinel file
|
|
11
|
-
*
|
|
12
|
-
* If the sentinel never appears the bind FAILS LOUDLY. Falling through to a
|
|
13
|
-
* normal createTarget would put the agent in the focus-derived default profile
|
|
14
|
-
* — the exact bug this feature exists to remove — so the caller gets an
|
|
15
|
-
* actionable error instead.
|
|
16
|
-
*
|
|
17
|
-
* The resolved context id is session-scoped state, never persisted: Chrome
|
|
18
|
-
* mints new context ids on every browser run.
|
|
19
|
-
*/
|
|
20
|
-
|
|
21
1
|
import type { BrowserClient } from "../client";
|
|
2
|
+
import type { ResultOf } from "../cdp/commands";
|
|
22
3
|
import { type CdpError, cdpError } from "../cdp/errors";
|
|
23
4
|
import { type Result, err, ok } from "../util/result";
|
|
24
5
|
import { detectRunningBrowser, resolveBrowserExecutable } from "./browser-process";
|
|
25
6
|
import { openProfileWindow } from "./launch";
|
|
26
7
|
import type { ProfilePin } from "./store";
|
|
27
8
|
|
|
28
|
-
/** The launch delegates through ProcessSingleton, so allow for a cold profile. */
|
|
29
9
|
const SEED_DEADLINE_MS = 15_000;
|
|
30
10
|
const SEED_POLL_MS = 500;
|
|
31
11
|
|
|
32
|
-
type PageTarget =
|
|
33
|
-
readonly targetId: string;
|
|
34
|
-
readonly type: string;
|
|
35
|
-
readonly url: string;
|
|
36
|
-
readonly browserContextId?: string;
|
|
37
|
-
};
|
|
12
|
+
type PageTarget = ResultOf<"Target.getTargets">["targetInfos"][number];
|
|
38
13
|
|
|
39
14
|
const pageTargets = async (client: BrowserClient): Promise<ReadonlyArray<PageTarget>> => {
|
|
40
15
|
const r = await client.session().callBrowser("Target.getTargets");
|
|
41
16
|
if (!r.success) return [];
|
|
42
|
-
|
|
43
|
-
return data.targetInfos.filter((t) => t.type === "page");
|
|
17
|
+
return r.data.targetInfos.filter((t) => t.type === "page");
|
|
44
18
|
};
|
|
45
19
|
|
|
46
20
|
const manualFallbackHint = (pin: ProfilePin): string =>
|
|
47
21
|
`open a window for "${pin.label}" yourself (browser profile menu → ${pin.profileDir}), then retry. ` +
|
|
48
22
|
`Run /browser-profile to pick a different profile, or clear the selection to use whichever window is focused.`;
|
|
49
23
|
|
|
50
|
-
/**
|
|
51
|
-
* Open (and adopt) a harness window inside the pinned profile. Returns the
|
|
52
|
-
* seed tab's target id.
|
|
53
|
-
*/
|
|
54
24
|
export const seedProfileWindow = async (
|
|
55
25
|
client: BrowserClient,
|
|
56
26
|
pin: ProfilePin,
|
|
57
27
|
): Promise<Result<string, CdpError>> => {
|
|
58
|
-
// A pin belongs to one user-data-dir. If the harness is now attached to a
|
|
59
|
-
// different browser, silently seeding the "same" profile name would be wrong.
|
|
60
28
|
const connectedDir = client.userDataDir();
|
|
61
29
|
if (connectedDir && connectedDir !== pin.userDataDir) {
|
|
62
30
|
return err(cdpError(
|
|
@@ -66,9 +34,6 @@ export const seedProfileWindow = async (
|
|
|
66
34
|
));
|
|
67
35
|
}
|
|
68
36
|
|
|
69
|
-
// Identify the browser by the dir we're connected to. With several Chromium
|
|
70
|
-
// browsers running, launching into the wrong one would open a window the
|
|
71
|
-
// harness cannot see — in a browser the user never pointed us at.
|
|
72
37
|
const targetUserDataDir = connectedDir ?? pin.userDataDir;
|
|
73
38
|
const running = await detectRunningBrowser(targetUserDataDir);
|
|
74
39
|
const exePath = await resolveBrowserExecutable(running);
|
|
@@ -82,11 +47,7 @@ export const seedProfileWindow = async (
|
|
|
82
47
|
const launched = await openProfileWindow({
|
|
83
48
|
exePath,
|
|
84
49
|
profileDir: pin.profileDir,
|
|
85
|
-
//
|
|
86
|
-
// ProcessSingleton keys on this path: passing the value the target process
|
|
87
|
-
// itself reports guarantees delegation, whereas supplying a default dir we
|
|
88
|
-
// reconstructed could differ by case or normalisation and start a SECOND
|
|
89
|
-
// browser instead.
|
|
50
|
+
// ProcessSingleton keys on the user-data-dir path, so forward only the value the running browser reports: a reconstructed one may differ by case and start a SECOND browser.
|
|
90
51
|
...(running.explicitUserDataDir ? { explicitUserDataDir: running.explicitUserDataDir } : {}),
|
|
91
52
|
});
|
|
92
53
|
if (!launched.success) {
|
|
@@ -116,22 +77,12 @@ export const seedProfileWindow = async (
|
|
|
116
77
|
const ownership = client.ownership();
|
|
117
78
|
ownership.setHarnessWindow(seed.targetId);
|
|
118
79
|
ownership.add(seed.targetId);
|
|
119
|
-
const win = await client.session().
|
|
120
|
-
if (win.success)
|
|
121
|
-
const windowId = (win.data as { windowId?: number }).windowId;
|
|
122
|
-
if (typeof windowId === "number") ownership.setHarnessWindowId(windowId);
|
|
123
|
-
}
|
|
80
|
+
const win = await client.session().windowId(seed.targetId);
|
|
81
|
+
if (win.success) ownership.setHarnessWindowId(win.data);
|
|
124
82
|
|
|
125
|
-
|
|
126
|
-
// then remove the sentinel file. Best-effort: a failure here costs nothing
|
|
127
|
-
// beyond the placeholder page staying visible.
|
|
128
|
-
const attached = await client.session().callBrowser("Target.attachToTarget", {
|
|
129
|
-
targetId: seed.targetId,
|
|
130
|
-
flatten: true,
|
|
131
|
-
});
|
|
83
|
+
const attached = await client.session().attach(seed.targetId);
|
|
132
84
|
if (attached.success) {
|
|
133
|
-
|
|
134
|
-
await client.session().callOnTarget("Page.navigate", { url: "about:blank" }, sessionId);
|
|
85
|
+
await client.session().callOnTarget("Page.navigate", { url: "about:blank" }, attached.data);
|
|
135
86
|
}
|
|
136
87
|
await cleanup();
|
|
137
88
|
|
|
@@ -1,55 +1,24 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
*
|
|
4
|
-
* Two questions, deliberately kept apart:
|
|
5
|
-
*
|
|
6
|
-
* 1. Is a Chromium-family browser RUNNING? (`detectRunningBrowser().running`)
|
|
7
|
-
* Only live-process evidence may answer this — an installed-but-closed
|
|
8
|
-
* browser must read as "not running", which is why the registry lookup
|
|
9
|
-
* below is never consulted here.
|
|
10
|
-
*
|
|
11
|
-
* 2. Which binary do we invoke to open a window for a chosen profile?
|
|
12
|
-
* (`resolveBrowserExecutable()`) Chromium's ProcessSingleton hands a second
|
|
13
|
-
* launch's argv to the already-running browser instead of starting another
|
|
14
|
-
* one — Windows via WM_COPYDATA (process_singleton_win.cc), Linux and macOS
|
|
15
|
-
* via the socket in the user-data-dir (process_singleton_posix.cc, which is
|
|
16
|
-
* compiled on macOS too). Here an installed path is a fine fallback.
|
|
17
|
-
*
|
|
18
|
-
* Whether the running browser carries an explicit `--user-data-dir` matters:
|
|
19
|
-
* ProcessSingleton keys on that directory, so passing a path that differs from
|
|
20
|
-
* the running browser's by case or normalisation would start a SECOND browser
|
|
21
|
-
* rather than delegating. The flag is forwarded only when the running process
|
|
22
|
-
* already has one.
|
|
23
|
-
*
|
|
24
|
-
* Every probe is best-effort; when nothing can be determined, profile launching
|
|
25
|
-
* degrades to a clear message rather than guessing.
|
|
26
|
-
*
|
|
27
|
-
* Windows note: `wmic` is deliberately unused — Microsoft removed it by default
|
|
28
|
-
* in Windows 11 24H2 and entirely in 25H2. PowerShell CIM is the supported
|
|
29
|
-
* replacement, with `tasklist` for liveness and the documented App Paths
|
|
30
|
-
* registry key for install location.
|
|
31
|
-
*/
|
|
1
|
+
// `running` is derived only from live-process evidence: an installed-but-closed browser must read as "not running".
|
|
2
|
+
// `wmic` is deliberately unused — Microsoft removed it by default in Windows 11 24H2 and entirely in 25H2, so PowerShell CIM plus tasklist replace it.
|
|
32
3
|
|
|
33
4
|
import { execFile } from "node:child_process";
|
|
34
5
|
import { access, readFile, readlink } from "node:fs/promises";
|
|
35
6
|
import { join } from "node:path";
|
|
36
7
|
import { promisify } from "node:util";
|
|
8
|
+
import { Type } from "typebox";
|
|
9
|
+
import { Compile } from "typebox/compile";
|
|
10
|
+
import { parseJson } from "../schemas/parse";
|
|
37
11
|
import { browserNameForUserDataDir } from "./paths";
|
|
38
12
|
|
|
39
|
-
// execFile, not exec: arguments are passed as an array, with no shell involved.
|
|
40
13
|
const run = promisify(execFile);
|
|
41
14
|
const EXEC_TIMEOUT_MS = 5_000;
|
|
42
15
|
|
|
43
16
|
export type RunningBrowser = {
|
|
44
|
-
/** True when a Chromium-family browser process is live. */
|
|
45
17
|
readonly running: boolean;
|
|
46
|
-
/** Absolute path to the running browser's binary, when determinable. */
|
|
47
18
|
readonly exePath?: string;
|
|
48
|
-
/** Value of an explicit --user-data-dir on the running process, if any. */
|
|
49
19
|
readonly explicitUserDataDir?: string;
|
|
50
20
|
};
|
|
51
21
|
|
|
52
|
-
/** Chromium-family process names, lowercase, as they appear per platform. */
|
|
53
22
|
const LINUX_COMMS: ReadonlyArray<string> = [
|
|
54
23
|
"chrome", "chromium", "chromium-browser", "msedge", "microsoft-edge",
|
|
55
24
|
"google-chrome", "brave", "brave-browser",
|
|
@@ -59,22 +28,13 @@ const MAC_BROWSER_NAMES: ReadonlyArray<string> = [
|
|
|
59
28
|
];
|
|
60
29
|
const WIN_IMAGE_NAMES: ReadonlyArray<string> = ["chrome.exe", "msedge.exe", "brave.exe"];
|
|
61
30
|
|
|
62
|
-
|
|
63
|
-
* Chromium tags every child process with `--type=<role>`; only the browser
|
|
64
|
-
* process omits it or carries `--type=browser`. Matching the flag (rather than
|
|
65
|
-
* words like "renderer" anywhere in the string) keeps a user whose install path
|
|
66
|
-
* contains such a word from being filtered out.
|
|
67
|
-
*/
|
|
31
|
+
// Match the `--type=` flag, not words like "renderer" anywhere in the string, or an install path containing one is filtered out.
|
|
68
32
|
const hasChildProcessType = (commandLine: string): boolean => {
|
|
69
33
|
const lower = commandLine.toLowerCase();
|
|
70
34
|
return lower.includes("--type=") && !lower.includes("--type=browser");
|
|
71
35
|
};
|
|
72
36
|
|
|
73
|
-
|
|
74
|
-
* macOS names its child processes in the executable path itself ("Google Chrome
|
|
75
|
-
* Helper (Renderer)", crashpad, updaters), so the process NAME must be filtered
|
|
76
|
-
* too — the same exclusions the previous setup.ts check applied.
|
|
77
|
-
*/
|
|
37
|
+
// macOS names its child processes in the executable path itself, so the process NAME must be filtered too.
|
|
78
38
|
const isMacChildProcessName = (comm: string): boolean => {
|
|
79
39
|
const lower = comm.toLowerCase();
|
|
80
40
|
return (
|
|
@@ -86,13 +46,36 @@ const isMacChildProcessName = (comm: string): boolean => {
|
|
|
86
46
|
);
|
|
87
47
|
};
|
|
88
48
|
|
|
89
|
-
/** One running browser process, as much as the platform will tell us. */
|
|
90
49
|
export type BrowserCandidate = {
|
|
91
50
|
readonly exePath?: string;
|
|
92
51
|
readonly explicitUserDataDir?: string;
|
|
93
52
|
};
|
|
94
53
|
|
|
95
|
-
|
|
54
|
+
// A package upgrade under a running browser makes `/proc/<pid>/exe` read "… (deleted)", which fails to spawn with ENOENT unless the marker comes off.
|
|
55
|
+
const DELETED_SUFFIX = " (deleted)";
|
|
56
|
+
|
|
57
|
+
export const stripDeletedSuffix = (path: string): string | undefined =>
|
|
58
|
+
path.endsWith(DELETED_SUFFIX) && path.length > DELETED_SUFFIX.length
|
|
59
|
+
? path.slice(0, -DELETED_SUFFIX.length)
|
|
60
|
+
: undefined;
|
|
61
|
+
|
|
62
|
+
const exists = async (path: string): Promise<boolean> => {
|
|
63
|
+
try {
|
|
64
|
+
await access(path);
|
|
65
|
+
return true;
|
|
66
|
+
} catch {
|
|
67
|
+
return false;
|
|
68
|
+
}
|
|
69
|
+
};
|
|
70
|
+
|
|
71
|
+
export const spawnableExePath = async (raw: string): Promise<string | undefined> => {
|
|
72
|
+
if (raw.length === 0) return undefined;
|
|
73
|
+
if (await exists(raw)) return raw;
|
|
74
|
+
const stripped = stripDeletedSuffix(raw);
|
|
75
|
+
if (stripped && (await exists(stripped))) return stripped;
|
|
76
|
+
return undefined;
|
|
77
|
+
};
|
|
78
|
+
|
|
96
79
|
const samePath = (a: string, b: string): boolean => {
|
|
97
80
|
const norm = (p: string): string => {
|
|
98
81
|
const unified = p.replace(/\\/g, "/").replace(/\/+$/, "");
|
|
@@ -101,22 +84,11 @@ const samePath = (a: string, b: string): boolean => {
|
|
|
101
84
|
return norm(a) === norm(b);
|
|
102
85
|
};
|
|
103
86
|
|
|
104
|
-
/**
|
|
105
|
-
* Rank a candidate against the user-data-dir the harness is actually connected
|
|
106
|
-
* to. Several Chromium browsers can run at once (Chrome plus Brave, or a second
|
|
107
|
-
* instance on a custom dir), and launching a profile window into the wrong one
|
|
108
|
-
* would open a window the harness cannot see — while disturbing a browser the
|
|
109
|
-
* user never pointed us at.
|
|
110
|
-
*/
|
|
111
87
|
export const rankBrowserCandidate = (candidate: BrowserCandidate, preferUserDataDir?: string): number => {
|
|
112
88
|
if (!preferUserDataDir) return 1;
|
|
113
89
|
if (candidate.explicitUserDataDir) {
|
|
114
|
-
// An explicit dir is decisive in both directions: exact match wins, and a
|
|
115
|
-
// different one means this is definitively another browser instance.
|
|
116
90
|
return samePath(candidate.explicitUserDataDir, preferUserDataDir) ? 4 : 0;
|
|
117
91
|
}
|
|
118
|
-
// No flag: the process uses its default dir. Prefer the one whose executable
|
|
119
|
-
// belongs to the same browser family as the target directory.
|
|
120
92
|
const family = browserNameForUserDataDir(preferUserDataDir).toLowerCase();
|
|
121
93
|
const exe = (candidate.exePath ?? "").toLowerCase();
|
|
122
94
|
if (!exe) return 1;
|
|
@@ -127,7 +99,6 @@ export const rankBrowserCandidate = (candidate: BrowserCandidate, preferUserData
|
|
|
127
99
|
return 1;
|
|
128
100
|
};
|
|
129
101
|
|
|
130
|
-
/** Extract `--user-data-dir=<path>` from a command line, quoted or bare. */
|
|
131
102
|
export const parseUserDataDirFlag = (commandLine: string): string | undefined => {
|
|
132
103
|
const match = /--user-data-dir=(?:"([^"]*)"|'([^']*)'|(\S+))/.exec(commandLine);
|
|
133
104
|
if (!match) return undefined;
|
|
@@ -135,8 +106,6 @@ export const parseUserDataDirFlag = (commandLine: string): string | undefined =>
|
|
|
135
106
|
return value && value.length > 0 ? value : undefined;
|
|
136
107
|
};
|
|
137
108
|
|
|
138
|
-
// ── Linux ──────────────────────────────────────────────────────────────────
|
|
139
|
-
|
|
140
109
|
const collectLinux = async (): Promise<ReadonlyArray<BrowserCandidate>> => {
|
|
141
110
|
let pids: string[];
|
|
142
111
|
try {
|
|
@@ -157,20 +126,19 @@ const collectLinux = async (): Promise<ReadonlyArray<BrowserCandidate>> => {
|
|
|
157
126
|
for (const pid of pids) {
|
|
158
127
|
let cmdline: string;
|
|
159
128
|
try {
|
|
160
|
-
// /proc/<pid>/cmdline is NUL-separated argv.
|
|
161
129
|
cmdline = (await readFile(`/proc/${pid}/cmdline`, "utf8")).replace(/\0/g, " ").trim();
|
|
162
130
|
} catch {
|
|
163
131
|
continue;
|
|
164
132
|
}
|
|
165
133
|
if (!cmdline || hasChildProcessType(cmdline)) continue;
|
|
166
|
-
let
|
|
134
|
+
let link: string | undefined;
|
|
167
135
|
try {
|
|
168
|
-
|
|
169
|
-
} catch {
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
136
|
+
link = await readlink(`/proc/${pid}/exe`);
|
|
137
|
+
} catch {}
|
|
138
|
+
// Chrome rewrites its argv to the bare executable path, so argv[0] is the live install location when /proc/<pid>/exe is unreadable or stale.
|
|
139
|
+
const exePath =
|
|
140
|
+
(link ? await spawnableExePath(link) : undefined) ??
|
|
141
|
+
(await spawnableExePath(cmdline.split(" ")[0] ?? ""));
|
|
174
142
|
const explicit = parseUserDataDirFlag(cmdline);
|
|
175
143
|
candidates.push({
|
|
176
144
|
...(exePath ? { exePath } : {}),
|
|
@@ -180,8 +148,6 @@ const collectLinux = async (): Promise<ReadonlyArray<BrowserCandidate>> => {
|
|
|
180
148
|
return candidates;
|
|
181
149
|
};
|
|
182
150
|
|
|
183
|
-
// ── macOS ──────────────────────────────────────────────────────────────────
|
|
184
|
-
|
|
185
151
|
const collectDarwin = async (): Promise<ReadonlyArray<BrowserCandidate>> => {
|
|
186
152
|
let lines: string[];
|
|
187
153
|
try {
|
|
@@ -206,9 +172,7 @@ const collectDarwin = async (): Promise<ReadonlyArray<BrowserCandidate>> => {
|
|
|
206
172
|
try {
|
|
207
173
|
const { stdout } = await run("ps", ["-ww", "-o", "args=", "-p", pid], { timeout: EXEC_TIMEOUT_MS });
|
|
208
174
|
args = stdout.trim();
|
|
209
|
-
} catch {
|
|
210
|
-
// args are optional — only the --user-data-dir probe needs them
|
|
211
|
-
}
|
|
175
|
+
} catch {}
|
|
212
176
|
if (args && hasChildProcessType(args)) continue;
|
|
213
177
|
const explicit = args ? parseUserDataDirFlag(args) : undefined;
|
|
214
178
|
candidates.push({
|
|
@@ -219,8 +183,6 @@ const collectDarwin = async (): Promise<ReadonlyArray<BrowserCandidate>> => {
|
|
|
219
183
|
return candidates;
|
|
220
184
|
};
|
|
221
185
|
|
|
222
|
-
// ── Windows ────────────────────────────────────────────────────────────────
|
|
223
|
-
|
|
224
186
|
const POWERSHELL_QUERY = [
|
|
225
187
|
"$ErrorActionPreference='SilentlyContinue';",
|
|
226
188
|
"Get-CimInstance Win32_Process",
|
|
@@ -229,7 +191,17 @@ const POWERSHELL_QUERY = [
|
|
|
229
191
|
"| ConvertTo-Json -Compress",
|
|
230
192
|
].join(" ");
|
|
231
193
|
|
|
232
|
-
|
|
194
|
+
const WinProcessSchema = Type.Object(
|
|
195
|
+
{
|
|
196
|
+
ExecutablePath: Type.Optional(Type.Union([Type.String(), Type.Null()])),
|
|
197
|
+
CommandLine: Type.Optional(Type.Union([Type.String(), Type.Null()])),
|
|
198
|
+
},
|
|
199
|
+
{ additionalProperties: true },
|
|
200
|
+
);
|
|
201
|
+
|
|
202
|
+
const WinProcessesSchema = Type.Union([WinProcessSchema, Type.Array(WinProcessSchema)]);
|
|
203
|
+
|
|
204
|
+
const winProcessesValidator = Compile(WinProcessesSchema);
|
|
233
205
|
|
|
234
206
|
const collectWin32 = async (): Promise<ReadonlyArray<BrowserCandidate>> => {
|
|
235
207
|
try {
|
|
@@ -240,37 +212,31 @@ const collectWin32 = async (): Promise<ReadonlyArray<BrowserCandidate>> => {
|
|
|
240
212
|
);
|
|
241
213
|
const trimmed = stdout.trim();
|
|
242
214
|
if (trimmed) {
|
|
243
|
-
const parsed
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
215
|
+
const parsed = parseJson(trimmed, winProcessesValidator);
|
|
216
|
+
if (parsed.success) {
|
|
217
|
+
const rows = Array.isArray(parsed.data) ? parsed.data : [parsed.data];
|
|
218
|
+
const candidates = rows
|
|
219
|
+
.filter((row) => !hasChildProcessType(row.CommandLine ?? ""))
|
|
220
|
+
.map((row): BrowserCandidate => {
|
|
221
|
+
const explicit = parseUserDataDirFlag(row.CommandLine ?? "");
|
|
222
|
+
return {
|
|
223
|
+
...(row.ExecutablePath ? { exePath: row.ExecutablePath } : {}),
|
|
224
|
+
...(explicit ? { explicitUserDataDir: explicit } : {}),
|
|
225
|
+
};
|
|
226
|
+
});
|
|
227
|
+
if (candidates.length > 0) return candidates;
|
|
228
|
+
}
|
|
256
229
|
}
|
|
257
|
-
} catch {
|
|
258
|
-
// PowerShell missing or blocked by policy — fall through to tasklist.
|
|
259
|
-
}
|
|
230
|
+
} catch {}
|
|
260
231
|
|
|
261
|
-
// Liveness-only fallback: tasklist still ships on every supported Windows.
|
|
262
|
-
// It reveals no path, so the candidate is a bare "something is running".
|
|
263
232
|
try {
|
|
264
233
|
const { stdout } = await run("tasklist.exe", [], { timeout: EXEC_TIMEOUT_MS, windowsHide: true });
|
|
265
234
|
const lower = stdout.toLowerCase();
|
|
266
235
|
if (WIN_IMAGE_NAMES.some((n) => lower.includes(n))) return [{}];
|
|
267
|
-
} catch {
|
|
268
|
-
// best-effort
|
|
269
|
-
}
|
|
236
|
+
} catch {}
|
|
270
237
|
return [];
|
|
271
238
|
};
|
|
272
239
|
|
|
273
|
-
/** Installed-browser locations to try when the live process reveals no path. */
|
|
274
240
|
const winInstallCandidates = (): ReadonlyArray<string> => {
|
|
275
241
|
const roots = [
|
|
276
242
|
process.env["PROGRAMFILES"],
|
|
@@ -288,7 +254,6 @@ const winInstallCandidates = (): ReadonlyArray<string> => {
|
|
|
288
254
|
return roots.flatMap((root) => suffixes.map((suffix) => join(root, suffix)));
|
|
289
255
|
};
|
|
290
256
|
|
|
291
|
-
/** Query the Shell's App Paths registration for a browser's install location. */
|
|
292
257
|
const winRegistryExecutable = async (): Promise<string | undefined> => {
|
|
293
258
|
for (const image of WIN_IMAGE_NAMES) {
|
|
294
259
|
for (const hive of ["HKLM", "HKCU"]) {
|
|
@@ -301,23 +266,12 @@ const winRegistryExecutable = async (): Promise<string | undefined> => {
|
|
|
301
266
|
const match = /REG_[A-Z_]+\s+(.+)$/m.exec(stdout.trim());
|
|
302
267
|
const path = match?.[1]?.trim();
|
|
303
268
|
if (path) return path;
|
|
304
|
-
} catch {
|
|
305
|
-
// key absent for this browser/hive — try the next
|
|
306
|
-
}
|
|
269
|
+
} catch {}
|
|
307
270
|
}
|
|
308
271
|
}
|
|
309
272
|
return undefined;
|
|
310
273
|
};
|
|
311
274
|
|
|
312
|
-
// ── Public API ─────────────────────────────────────────────────────────────
|
|
313
|
-
|
|
314
|
-
/**
|
|
315
|
-
* Live-process facts about the running Chromium-family browser. `running` is
|
|
316
|
-
* derived only from process evidence, never from an install location.
|
|
317
|
-
*
|
|
318
|
-
* `preferUserDataDir` should be the dir the harness is connected to; with more
|
|
319
|
-
* than one browser running it decides which process is described.
|
|
320
|
-
*/
|
|
321
275
|
export const detectRunningBrowser = async (preferUserDataDir?: string): Promise<RunningBrowser> => {
|
|
322
276
|
const candidates =
|
|
323
277
|
process.platform === "darwin"
|
|
@@ -327,9 +281,11 @@ export const detectRunningBrowser = async (preferUserDataDir?: string): Promise<
|
|
|
327
281
|
: await collectLinux();
|
|
328
282
|
if (candidates.length === 0) return { running: false };
|
|
329
283
|
|
|
330
|
-
|
|
284
|
+
const [first, ...rest] = candidates;
|
|
285
|
+
if (!first) return { running: false };
|
|
286
|
+
let best = first;
|
|
331
287
|
let bestRank = rankBrowserCandidate(best, preferUserDataDir);
|
|
332
|
-
for (const candidate of
|
|
288
|
+
for (const candidate of rest) {
|
|
333
289
|
const rank = rankBrowserCandidate(candidate, preferUserDataDir);
|
|
334
290
|
if (rank > bestRank) {
|
|
335
291
|
best = candidate;
|
|
@@ -344,17 +300,12 @@ export const detectRunningBrowser = async (preferUserDataDir?: string): Promise<
|
|
|
344
300
|
};
|
|
345
301
|
};
|
|
346
302
|
|
|
347
|
-
/** True when a Chromium-family browser process is running. */
|
|
348
303
|
export const isBrowserRunning = async (): Promise<boolean> => (await detectRunningBrowser()).running;
|
|
349
304
|
|
|
350
|
-
/**
|
|
351
|
-
* The binary to invoke when opening a window for a chosen profile: the running
|
|
352
|
-
* browser's own executable when known, otherwise a documented install location.
|
|
353
|
-
* Undefined when nothing usable is found.
|
|
354
|
-
*/
|
|
355
305
|
export const resolveBrowserExecutable = async (running?: RunningBrowser): Promise<string | undefined> => {
|
|
356
306
|
const detected = running ?? (await detectRunningBrowser());
|
|
357
|
-
|
|
307
|
+
const usable = detected.exePath ? await spawnableExePath(detected.exePath) : undefined;
|
|
308
|
+
if (usable) return usable;
|
|
358
309
|
if (process.platform !== "win32") return undefined;
|
|
359
310
|
|
|
360
311
|
const fromRegistry = await winRegistryExecutable();
|
|
@@ -363,9 +314,7 @@ export const resolveBrowserExecutable = async (running?: RunningBrowser): Promis
|
|
|
363
314
|
try {
|
|
364
315
|
await access(candidate);
|
|
365
316
|
return candidate;
|
|
366
|
-
} catch {
|
|
367
|
-
// not installed here
|
|
368
|
-
}
|
|
317
|
+
} catch {}
|
|
369
318
|
}
|
|
370
319
|
return undefined;
|
|
371
320
|
};
|