diff options
| author | Aman Kumar <145339995+amankumarsingh77@users.noreply.github.com> | 2026-07-25 00:23:05 +0530 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2026-07-25 00:23:05 +0530 |
| commit | 6dd79f7c3bafacba54acb2840f8655fcb05318bf (patch) | |
| tree | 1570768785ae836717d3dbb2ff42fe0a13f19585 /src/profile/paths.ts | |
| parent | 0fc1ece6fa4a2f24e87eb4a66eb828a9928e30f7 (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/paths.ts')
| -rw-r--r-- | src/profile/paths.ts | 166 |
1 files changed, 166 insertions, 0 deletions
diff --git a/src/profile/paths.ts b/src/profile/paths.ts new file mode 100644 index 0000000..095687e --- /dev/null +++ b/src/profile/paths.ts @@ -0,0 +1,166 @@ +/** + * Filesystem locations for browser profile discovery and pin persistence. + * + * Two independent path families live here: + * + * 1. Chromium user-data-dir candidates, per platform and channel. A + * user-data-dir holds `Local State` (the profile registry) and + * `DevToolsActivePort`; individual profiles are subdirectories of it + * (`Default`, `Profile 1`, …). + * Reference: https://chromium.googlesource.com/chromium/src/+/HEAD/docs/user_data_dir.md + * + * 2. pi's agent config dir, where the profile pin is stored. + * + * On the agent dir: pi exports `getAgentDir()` from + * `@mariozechner/pi-coding-agent`, but importing it would be a RUNTIME import + * of the host package. Extensions installed via `pi install npm:...` do not + * get pi resolvable from their own node_modules (verified: the installed + * tree's `@mariozechner/` directory is empty), which is why every other import + * in this codebase is `import type` and erased at build time. So the three + * lines of `getAgentDir()` are replicated here instead — env var first, then + * `~/.pi/agent` (pi's dist/config.js: `PI_CODING_AGENT_DIR`, CONFIG_DIR_NAME + * `.pi`). + */ + +import { homedir } from "node:os"; +import { join } from "node:path"; + +// ── pi agent config dir ──────────────────────────────────────────────────── + +/** pi's env override for the agent dir (APP_NAME.toUpperCase() + "_CODING_AGENT_DIR"). */ +const ENV_AGENT_DIR = "PI_CODING_AGENT_DIR"; + +/** + * Expand a leading `~` exactly as pi's expandTildePath does — `~` and `~/…` + * only, never `~\…`, on every platform. This deliberately mirrors pi rather + * than improving on it: the pin has to land in the directory pi itself resolves + * from the same variable, so being more lenient here would put the file + * somewhere pi does not look. + */ +const expandTildePiCompatible = (path: string): string => { + if (path === "~") return homedir(); + if (path.startsWith("~/")) return homedir() + path.slice(1); + return path; +}; + +/** + * Tilde expansion for values this package interprets on its own. Windows users + * write `~\dir` as naturally as `~/dir`, and no compatibility constraint + * applies, so both are accepted. + */ +const expandTildeLenient = (path: string): string => { + if (path === "~") return homedir(); + if (path.startsWith("~/") || path.startsWith("~\\")) return join(homedir(), path.slice(2)); + return path; +}; + +/** pi's agent config directory — `$PI_CODING_AGENT_DIR` or `~/.pi/agent`. */ +export const agentDir = (): string => { + const fromEnv = process.env[ENV_AGENT_DIR]; + if (fromEnv) return expandTildePiCompatible(fromEnv); + return join(homedir(), ".pi", "agent"); +}; + +/** Where the selected-profile pin is persisted. */ +export const pinFilePath = (): string => join(agentDir(), "browser-harness.json"); + +// ── Chromium user-data-dir candidates ────────────────────────────────────── + +/** + * Windows resolves its per-user data root from %LOCALAPPDATA%, which can be + * redirected on roaming / managed accounts. Fall back to the conventional + * layout only when the variable is absent. + */ +const localAppData = (): string => process.env["LOCALAPPDATA"] ?? join(homedir(), "AppData", "Local"); + +/** + * Every known default user-data-dir for Chromium-family browsers on the + * current platform. Order is stable but carries no priority — callers probe + * all of them. + * + * Includes paths the harness previously missed: snap Chromium (the default + * Chromium on Ubuntu) and the Linux-only `$CHROME_USER_DATA_DIR` override + * documented in user_data_dir.md. + */ +export const userDataDirCandidates = (): ReadonlyArray<string> => { + const home = homedir(); + const dirs: string[] = []; + + // A user-set override wins a spot at the front regardless of platform. + const envOverride = process.env["CHROME_USER_DATA_DIR"]; + if (envOverride) dirs.push(expandTildeLenient(envOverride)); + + if (process.platform === "darwin") { + const support = join(home, "Library", "Application Support"); + dirs.push( + join(support, "Google/Chrome"), + join(support, "Google/Chrome Beta"), + join(support, "Google/Chrome Dev"), + join(support, "Google/Chrome Canary"), + join(support, "Chromium"), + join(support, "BraveSoftware/Brave-Browser"), + join(support, "BraveSoftware/Brave-Browser-Beta"), + join(support, "BraveSoftware/Brave-Browser-Nightly"), + join(support, "BraveSoftware/Brave-Browser-Dev"), + join(support, "Microsoft Edge"), + join(support, "Microsoft Edge Beta"), + join(support, "Microsoft Edge Dev"), + join(support, "Microsoft Edge Canary"), + ); + } else if (process.platform === "win32") { + const lad = localAppData(); + dirs.push( + join(lad, "Google/Chrome/User Data"), + join(lad, "Google/Chrome Beta/User Data"), + join(lad, "Google/Chrome Dev/User Data"), + join(lad, "Google/Chrome SxS/User Data"), + join(lad, "Chromium/User Data"), + join(lad, "BraveSoftware/Brave-Browser/User Data"), + join(lad, "BraveSoftware/Brave-Browser-Beta/User Data"), + join(lad, "Microsoft/Edge/User Data"), + join(lad, "Microsoft/Edge Beta/User Data"), + join(lad, "Microsoft/Edge Dev/User Data"), + join(lad, "Microsoft/Edge SxS/User Data"), + ); + } else { + dirs.push( + join(home, ".config/google-chrome"), + join(home, ".config/google-chrome-beta"), + join(home, ".config/google-chrome-unstable"), + join(home, ".config/chromium"), + join(home, ".config/chromium-browser"), + join(home, ".config/BraveSoftware/Brave-Browser"), + join(home, ".config/BraveSoftware/Brave-Browser-Beta"), + join(home, ".config/BraveSoftware/Brave-Browser-Nightly"), + join(home, ".config/microsoft-edge"), + join(home, ".config/microsoft-edge-beta"), + join(home, ".config/microsoft-edge-dev"), + // snap (Ubuntu's default Chromium) — confined to ~/snap/<pkg>/common + join(home, "snap/chromium/common/chromium"), + // flatpak + join(home, ".var/app/org.chromium.Chromium/config/chromium"), + join(home, ".var/app/com.google.Chrome/config/google-chrome"), + join(home, ".var/app/com.brave.Browser/config/BraveSoftware/Brave-Browser"), + join(home, ".var/app/com.microsoft.Edge/config/microsoft-edge"), + ); + } + + // De-duplicate while preserving order — an env override may repeat a default. + return Array.from(new Set(dirs)); +}; + +/** + * Human-readable browser name for a user-data-dir, used to disambiguate the + * picker when more than one browser is installed. Falls back to the directory + * name, which is already descriptive for every path we generate. + */ +export const browserNameForUserDataDir = (userDataDir: string): string => { + const p = userDataDir.replace(/\\/g, "/"); + const has = (needle: string): boolean => p.toLowerCase().includes(needle); + if (has("brave")) return "Brave"; + if (has("edge")) return "Edge"; + if (has("chromium")) return "Chromium"; + if (has("chrome")) return "Chrome"; + const last = p.split("/").filter(Boolean).pop(); + return last ?? userDataDir; +}; |
