aboutsummaryrefslogtreecommitdiff
path: root/test/profile/list-test.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 /test/profile/list-test.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 'test/profile/list-test.ts')
-rw-r--r--test/profile/list-test.ts156
1 files changed, 156 insertions, 0 deletions
diff --git a/test/profile/list-test.ts b/test/profile/list-test.ts
new file mode 100644
index 0000000..ca39b73
--- /dev/null
+++ b/test/profile/list-test.ts
@@ -0,0 +1,156 @@
+/**
+ * Unit tests for profile enumeration — no browser required.
+ *
+ * Builds throwaway user-data-dirs on disk so both tiers (Local State and the
+ * Preferences scan) run against real files.
+ *
+ * Run: npx tsx test/profile/list-test.ts
+ */
+import { mkdtempSync, mkdirSync, writeFileSync, rmSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { formatProfileLabel, listProfiles } from "../../src/profile/list";
+
+let passed = 0;
+let failed = 0;
+const check = (cond: boolean, label: string): void => {
+ if (cond) {
+ passed++;
+ console.log(` ✓ ${label}`);
+ } else {
+ failed++;
+ console.error(` ✗ ${label}`);
+ }
+};
+
+const roots: string[] = [];
+const makeUdd = (): string => {
+ const dir = mkdtempSync(join(tmpdir(), "pi-profile-test-"));
+ roots.push(dir);
+ return dir;
+};
+const writeLocalState = (udd: string, body: unknown): void =>
+ writeFileSync(join(udd, "Local State"), typeof body === "string" ? body : JSON.stringify(body), "utf8");
+const writeProfileDir = (udd: string, dir: string, prefs?: unknown): void => {
+ mkdirSync(join(udd, dir), { recursive: true });
+ if (prefs !== undefined) writeFileSync(join(udd, dir, "Preferences"), JSON.stringify(prefs), "utf8");
+};
+
+async function main(): Promise<void> {
+ // L1: tier 1 — names, emails, ordering, last-used marker
+ {
+ const udd = makeUdd();
+ writeLocalState(udd, {
+ profile: {
+ last_used: "Profile 1",
+ profiles_order: ["Default", "Profile 1", "Profile 2"],
+ info_cache: {
+ "Profile 2": { name: "Second", user_name: "second@example.com" },
+ Default: { name: "vertexcover.io", user_name: "aman@vertexcover.io" },
+ "Profile 1": { name: "Aman", user_name: "aman@personal.com" },
+ },
+ },
+ });
+ const profiles = await listProfiles(udd);
+ check(profiles.length === 3, "L1: all three profiles listed");
+ check(
+ profiles.map((p) => p.dir).join(",") === "Default,Profile 1,Profile 2",
+ "L1: profiles_order drives ordering, not object key order",
+ );
+ check(profiles[1]?.label === "Aman (aman@personal.com)", "L1: label is 'Name (email)'");
+ check(profiles[1]?.lastUsed === true, "L1: last_used profile is marked");
+ check(profiles[0]?.lastUsed === false, "L1: other profiles are not marked");
+ }
+
+ // L2: profile with no signed-in account falls back to the directory
+ {
+ const udd = makeUdd();
+ writeLocalState(udd, { profile: { info_cache: { "Profile 3": { name: "Work" } } } });
+ const profiles = await listProfiles(udd);
+ check(profiles[0]?.label === "Work (Profile 3)", "L2: no account → 'Name (dir)'");
+ check(profiles[0]?.email === undefined, "L2: email stays undefined");
+ }
+
+ // L3: gaia_name backfills a missing name; ephemeral profiles are skipped
+ {
+ const udd = makeUdd();
+ writeLocalState(udd, {
+ profile: {
+ info_cache: {
+ "Profile 4": { gaia_name: "Aman Kumar", user_name: "gaia@example.com" },
+ "Profile 5": { name: "Ghost", user_name: "ghost@example.com", is_ephemeral: true },
+ "System Profile": { name: "System" },
+ },
+ },
+ });
+ const profiles = await listProfiles(udd);
+ check(profiles.length === 1, "L3: ephemeral and System Profile entries are excluded");
+ check(profiles[0]?.label === "Aman Kumar (gaia@example.com)", "L3: gaia_name backfills a missing name");
+ }
+
+ // L4: unlisted profiles are appended alphabetically after profiles_order
+ {
+ const udd = makeUdd();
+ writeLocalState(udd, {
+ profile: {
+ profiles_order: ["Profile 9"],
+ info_cache: {
+ Default: { name: "D" },
+ "Profile 9": { name: "Nine" },
+ "Profile 3": { name: "Three" },
+ },
+ },
+ });
+ const profiles = await listProfiles(udd);
+ check(
+ profiles.map((p) => p.dir).join(",") === "Profile 9,Default,Profile 3",
+ "L4: ordered entries first, remainder alphabetical",
+ );
+ }
+
+ // L5: corrupt Local State falls through to the Preferences scan
+ {
+ const udd = makeUdd();
+ writeLocalState(udd, "{ this is not json");
+ writeProfileDir(udd, "Default", {
+ profile: { name: "Fallback Name" },
+ account_info: [{ email: "fallback@example.com" }],
+ });
+ writeProfileDir(udd, "Crash Reports"); // no Preferences → not a profile
+ const profiles = await listProfiles(udd);
+ check(profiles.length === 1, "L5: only directories holding Preferences count as profiles");
+ check(profiles[0]?.label === "Fallback Name (fallback@example.com)", "L5: tier 2 reads name + account email");
+ }
+
+ // L6: missing info_cache also falls through to tier 2
+ {
+ const udd = makeUdd();
+ writeLocalState(udd, { profile: { last_used: "Default" } });
+ writeProfileDir(udd, "Profile 1", { profile: { name: "Tier Two" } });
+ const profiles = await listProfiles(udd);
+ check(profiles[0]?.label === "Tier Two (Profile 1)", "L6: missing info_cache → Preferences scan");
+ }
+
+ // L7: nothing readable → empty list, never a throw
+ {
+ const profiles = await listProfiles(join(tmpdir(), "pi-profile-does-not-exist-xyz"));
+ check(profiles.length === 0, "L7: unreadable user-data-dir yields an empty list");
+ }
+
+ // L8: label formatting is total
+ {
+ check(formatProfileLabel("A", "a@b.c", "Default") === "A (a@b.c)", "L8: email wins the brackets");
+ check(formatProfileLabel("A", undefined, "Profile 7") === "A (Profile 7)", "L8: dir fills in without an email");
+ check(formatProfileLabel("A", "", "Profile 7") === "A (Profile 7)", "L8: empty email is treated as absent");
+ }
+
+ for (const root of roots) rmSync(root, { recursive: true, force: true });
+
+ console.log(`\n${passed} passed, ${failed} failed`);
+ process.exit(failed === 0 ? 0 : 1);
+}
+
+main().catch((e) => {
+ console.error("profile list test failed:", e);
+ process.exit(1);
+});