aboutsummaryrefslogtreecommitdiff
path: root/src/profile/bind.ts
diff options
context:
space:
mode:
authorAman Kumar <145339995+amankumarsingh77@users.noreply.github.com>2026-07-25 00:23:05 +0530
committerGitHub <noreply@github.com>2026-07-25 00:23:05 +0530
commit6dd79f7c3bafacba54acb2840f8655fcb05318bf (patch)
tree1570768785ae836717d3dbb2ff42fe0a13f19585 /src/profile/bind.ts
parent0fc1ece6fa4a2f24e87eb4a66eb828a9928e30f7 (diff)
feat: pin the agent to a chosen browser profile (#16)
* feat: pin the agent to a chosen browser profile (#15) Harness tabs were created with a bare Target.createTarget, which places them in Chrome's defaultBrowserContextId — and that value follows window focus. Which profile the agent acted as therefore depended on which browser window the user last clicked, so the same task could run as a work account on one run and a personal account on the next. /browser-profile lists the connected browser's profiles as "Name (email)" and pins one to ~/.pi/agent/browser-harness.json, so the choice outlives the session. The same picker appears on first browser_setup when nothing is pinned; with no interactive UI, or on cancel, setup continues with a note and the previous behavior. Chrome offers no direct route to another profile: Target.createTarget rejects a foreign browserContextId, and openerId does not inherit the opener's context. The window is opened through the browser's own command line (--profile-directory, handed to the running browser by Chromium's ProcessSingleton) and identified by a unique file:// sentinel page, since a bare about:blank#token argument is discarded. Further tabs come from window.open evaluated with userGesture: true — the only CDP-reachable way to place a tab in a non-default browser context — correlated by a unique token so concurrent isolated tabs stay distinct. A failed handshake is reported, never silently redirected to another profile. All four tab-creation sites now funnel through cdp/target-factory, so open_urls and the isolated tabs behind web_search / read_page cannot run with a different profile's cookies than the visible tabs. Also fixed along the way: snap Chromium is discovered, Windows uses %LOCALAPPDATA%, browsers launched with an explicit --user-data-dir are found, the running browser is chosen by ranking candidates against the connected user-data-dir rather than taking the first process found, and an installed-but-closed browser no longer reads as running. CI runs the profile suites and a real-browser end-to-end test on ubuntu, macOS, and Windows — profile discovery is the one part of the harness whose behavior genuinely differs per OS. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * fix: single-flight harness window creation Isolated tabs run concurrently (browser_read_page is registered unserialized), so several could each find "no harness window" and create one — two blank windows before this feature, two LAUNCHED profile windows after it. ensureHarnessWindow now shares one in-flight creation per client. Sharing introduces a second hazard: freshlyCreated is a claim on the seed tab, and if every waiter received it, they would all drive the same tab. Only the caller that started the creation keeps the claim; the rest open their own tab beside it. Covered by test/manual/profile-concurrency-test.ts (five concurrent isolated tabs, pinned and unpinned: distinct targets, one window, correct profile), wired into CI on Linux only — the coordination is pure JS and identical across platforms. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * fix: tilde expansion differs by purpose on Windows CI on windows-latest caught this: join("~", "x") yields "~\x" there, and expandTilde only handled "~/". The two uses are not the same, so they no longer share a helper. The agent dir stays byte-compatible with pi's own expandTildePath ("~/" only, every platform) — being more lenient would put the pin file somewhere pi never looks. $CHROME_USER_DATA_DIR is ours to interpret, so it accepts "~\" as well, which is what a Windows user would type. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Diffstat (limited to 'src/profile/bind.ts')
-rw-r--r--src/profile/bind.ts138
1 files changed, 138 insertions, 0 deletions
diff --git a/src/profile/bind.ts b/src/profile/bind.ts
new file mode 100644
index 0000000..aeb59d3
--- /dev/null
+++ b/src/profile/bind.ts
@@ -0,0 +1,138 @@
+/**
+ * Binding the harness session to a pinned profile.
+ *
+ * Sequence, all of it verified against a live browser:
+ * 1. resolve the browser binary and any explicit --user-data-dir
+ * 2. launch a window into the profile, marked with a file:// sentinel
+ * 3. poll Target.getTargets for the sentinel page — its browserContextId IS
+ * the profile's context, which is otherwise undiscoverable (CDP exposes no
+ * profile identity)
+ * 4. adopt that page as the harness window, blank it, drop the sentinel file
+ *
+ * If the sentinel never appears the bind FAILS LOUDLY. Falling through to a
+ * normal createTarget would put the agent in the focus-derived default profile
+ * — the exact bug this feature exists to remove — so the caller gets an
+ * actionable error instead.
+ *
+ * The resolved context id is session-scoped state, never persisted: Chrome
+ * mints new context ids on every browser run.
+ */
+
+import type { BrowserClient } from "../client";
+import { type CdpError, cdpError } from "../cdp/errors";
+import { type Result, err, ok } from "../util/result";
+import { detectRunningBrowser, resolveBrowserExecutable } from "./browser-process";
+import { openProfileWindow } from "./launch";
+import type { ProfilePin } from "./store";
+
+/** The launch delegates through ProcessSingleton, so allow for a cold profile. */
+const SEED_DEADLINE_MS = 15_000;
+const SEED_POLL_MS = 500;
+
+type PageTarget = {
+ readonly targetId: string;
+ readonly type: string;
+ readonly url: string;
+ readonly browserContextId?: string;
+};
+
+const pageTargets = async (client: BrowserClient): Promise<ReadonlyArray<PageTarget>> => {
+ const r = await client.session().callBrowser("Target.getTargets");
+ if (!r.success) return [];
+ const data = r.data as { targetInfos: ReadonlyArray<PageTarget> };
+ return data.targetInfos.filter((t) => t.type === "page");
+};
+
+const manualFallbackHint = (pin: ProfilePin): string =>
+ `open a window for "${pin.label}" yourself (browser profile menu → ${pin.profileDir}), then retry. ` +
+ `Run /browser-profile to pick a different profile, or clear the selection to use whichever window is focused.`;
+
+/**
+ * Open (and adopt) a harness window inside the pinned profile. Returns the
+ * seed tab's target id.
+ */
+export const seedProfileWindow = async (
+ client: BrowserClient,
+ pin: ProfilePin,
+): Promise<Result<string, CdpError>> => {
+ // A pin belongs to one user-data-dir. If the harness is now attached to a
+ // different browser, silently seeding the "same" profile name would be wrong.
+ const connectedDir = client.userDataDir();
+ if (connectedDir && connectedDir !== pin.userDataDir) {
+ return err(cdpError(
+ "discovery_failed",
+ `the selected profile "${pin.label}" belongs to ${pin.userDataDir}, but the harness is connected to ${connectedDir}. ` +
+ `Run /browser-profile to choose a profile in the browser you're using.`,
+ ));
+ }
+
+ // Identify the browser by the dir we're connected to. With several Chromium
+ // browsers running, launching into the wrong one would open a window the
+ // harness cannot see — in a browser the user never pointed us at.
+ const targetUserDataDir = connectedDir ?? pin.userDataDir;
+ const running = await detectRunningBrowser(targetUserDataDir);
+ const exePath = await resolveBrowserExecutable(running);
+ if (!exePath) {
+ return err(cdpError(
+ "discovery_failed",
+ `could not locate the browser executable needed to open "${pin.label}" — ${manualFallbackHint(pin)}`,
+ ));
+ }
+
+ const launched = await openProfileWindow({
+ exePath,
+ profileDir: pin.profileDir,
+ // Forward the user-data-dir ONLY when the running browser advertises one.
+ // ProcessSingleton keys on this path: passing the value the target process
+ // itself reports guarantees delegation, whereas supplying a default dir we
+ // reconstructed could differ by case or normalisation and start a SECOND
+ // browser instead.
+ ...(running.explicitUserDataDir ? { explicitUserDataDir: running.explicitUserDataDir } : {}),
+ });
+ if (!launched.success) {
+ return err(cdpError("discovery_failed", `${launched.error} — ${manualFallbackHint(pin)}`));
+ }
+
+ const { sentinelUrl, cleanup } = launched.data;
+ const deadline = Date.now() + SEED_DEADLINE_MS;
+ let seed: PageTarget | undefined;
+ while (Date.now() < deadline && !seed) {
+ await new Promise((r) => setTimeout(r, SEED_POLL_MS));
+ seed = (await pageTargets(client)).find((t) => t.url === sentinelUrl);
+ }
+
+ if (!seed) {
+ await cleanup();
+ return err(cdpError(
+ "timeout",
+ `couldn't open a window in "${pin.label}" automatically — ${manualFallbackHint(pin)}`,
+ ));
+ }
+
+ // The sentinel's context is the profile's context — the only way to learn it.
+ if (seed.browserContextId) client.setProfileContextId(seed.browserContextId);
+
+ const ownership = client.ownership();
+ ownership.setHarnessWindow(seed.targetId);
+ ownership.add(seed.targetId);
+ const win = await client.session().callBrowser("Browser.getWindowForTarget", { targetId: seed.targetId });
+ if (win.success) {
+ const windowId = (win.data as { windowId?: number }).windowId;
+ if (typeof windowId === "number") ownership.setHarnessWindowId(windowId);
+ }
+
+ // Blank the handshake page so the seed tab behaves like any other fresh tab,
+ // then remove the sentinel file. Best-effort: a failure here costs nothing
+ // beyond the placeholder page staying visible.
+ const attached = await client.session().callBrowser("Target.attachToTarget", {
+ targetId: seed.targetId,
+ flatten: true,
+ });
+ if (attached.success) {
+ const sessionId = (attached.data as { sessionId: string }).sessionId;
+ await client.session().callOnTarget("Page.navigate", { url: "about:blank" }, sessionId);
+ }
+ await cleanup();
+
+ return ok(seed.targetId);
+};