aboutsummaryrefslogtreecommitdiff
path: root/src/setup.ts
AgeCommit message (Collapse)Author
2026-07-25feat: pin the agent to a chosen browser profile (#16)Aman Kumar
* 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>
2026-07-13feat: support Brave + Chrome channels, fix stale DevToolsActivePort ↵Aman Kumar
discovery (#13) * feat: support Brave + Chrome channels, fix stale DevToolsActivePort discovery Broadens browser detection and hardens CDP endpoint discovery, based on the investigation and approach in #4 (Brave Beta on macOS with a leftover Chrome DevToolsActivePort file). Browser detection (src/setup.ts, src/cdp/discovery.ts): - checkChromeRunning() now recognizes Brave (macOS "brave browser", Linux brave/brave-browser, Windows brave.exe), alongside the existing Chrome/ Chromium/Edge detection. Also excludes gpu/updater sub-processes that can linger after a browser quits. - profileDirs() gains Brave (Stable/Beta/Nightly/Dev) and Chrome Beta/Dev/ Canary/Chromium profile paths across macOS, Linux, and Windows. Stale DevToolsActivePort handling (src/cdp/discovery.ts): Previously discovery trusted the first readable DevToolsActivePort file. A browser that has quit leaves its file behind, so if another browser later binds the same port (e.g. 9222), discovery returned a WS URL carrying the dead browser's UUID against the live browser's server, and the connection failed. discoverWsUrl() now: - collects all readable candidates instead of committing to the first; - when candidates share a port, keeps the most-recently-written file (mtime); - skips candidates whose port isn't live via a fast single-shot probe (no 30s waitForPort block on stale files); - asks each live browser for its canonical webSocketDebuggerUrl via /json/version, falling back to the file's WS path when that endpoint is disabled (some browsers only expose it via --remote-debugging-port); - falls back to probing well-known ports (9222, plus BU_CDP_PORTS) when no profile file is readable — covering sandboxed harnesses (EPERM/EACCES) and non-default install locations. Setup guidance updated to mention brave://inspect / edge://inspect and the --remote-debugging-port launch flag. Verified: typecheck clean; queryLiveWsUrl / mtime-dedup / fallback-port logic exercised against a mock /json/version server; checkChromeRunning() matches the single main process against live macOS ps output, excluding all helpers. Closes #4 Co-authored-by: Trevor Whitney <trevorjwhitney@gmail.com> * fix: harden discovery against malformed port files + stale-then-fallback Addresses two issues raised in review of the discovery rewrite: - Validate the port parsed from DevToolsActivePort before building a candidate. A truncated/corrupt file (non-numeric or out-of-range first line) yielded NaN, and net.connect throws ERR_SOCKET_BAD_PORT synchronously for NaN / <=0 / >=65536 — which escaped discoverWsUrl as an unhandled rejection instead of surfacing as a Result error. Such entries are now skipped. - Fall back to well-known ports (9222 / BU_CDP_PORTS) after all discovered candidates prove stale. Previously the fallback ran only when no port file was readable, so a leftover file for a quit browser caused a ~30s waitForPort block and failure without ever trying a live fallback port. Ports already covered by a candidate are skipped to avoid re-probing. --------- Co-authored-by: Trevor Whitney <trevorjwhitney@gmail.com>
2026-07-12fix: make browser daemon setup work on Windows (#7) (#12)Aman Kumar
The Unix socket daemon introduced in v0.6.0 made several POSIX-only assumptions that break setup on Windows: - protocol.ts hardcoded a Unix socket path (/tmp/pi-browser-daemon.sock). Node IPC on Windows requires a named pipe (\\.\pipe\<name>); a /tmp path is not a valid net listen/connect target there. - spawn.ts spawned the bare tsx binary / `npx` and probed the non-Windows .bin/tsx shim. On Windows npm binaries are .cmd shims that must run via a shell, and spawning them directly fails with EINVAL / ENOENT. - isDaemonRunning() pre-checked the socket with fs.access(), which always fails for a named pipe and would report a live daemon as dead. - stale-socket unlink() would throw on a named pipe path. Changes: - DAEMON_SOCKET_PATH is now platform-aware: named pipe on win32, Unix socket elsewhere. - spawnDaemon() resolves tsx.cmd / npx.cmd on Windows, runs via shell with per-token quoting (paths with spaces) and windowsVerbatimArguments. - isDaemonRunning() skips the fs.access pre-check on Windows and probes the pipe directly. - stale-socket cleanup is a no-op on Windows (named pipes self-clean). - setup.ts daemon-failure message uses the actual DAEMON_SOCKET_PATH. Closes #7
2026-06-21release: v0.6.0 — per-tab isolation, Unix socket daemon, on-demand init (#6)Aman Kumar
* feat: Unix socket daemon with auto-reconnect for persistent Chrome CDP Eliminates the 'Allow Remote Debugging' Chrome prompt that appeared on every pi session by multiplexing pi instances through a single persistent daemon process. Key additions: - Unix socket IPC (net.createServer + readline JSON framing) - CdpBridge with ID multiplexer + event router - DaemonTransport implementing CdpTransport interface - Auto-spawn with ensureDaemon() (lazy, checks socket) Fixes since initial implementation: - Bridge auto-reconnects to Chrome with exponential backoff (1s-60s). Previously the bridge tried once at startup and permanently failed if Chrome wasn't ready — causing 'Chrome not connected' on every browser tool call. - Daemon spawn uses project-local tsx binary instead of global --import flag, fixing silent spawn failure (ERR_MODULE_NOT_FOUND). - Stale ctx crash: persistState in onOwnershipChange wrapped in try/catch to prevent CDP event consumer crashes. 49 test assertions across 4 test files. Zero TypeScript errors. * feat: on-demand browser initialization Browser daemon no longer auto-starts on session_start. Instead: - session_start creates the client lazily but does NOT connect or spawn the daemon. Zero Chrome prompts for non-browser pi sessions. - Browser tool wrapper checks for daemon socket before each call. Socket missing → clear error: 'Run /browser-setup first'. Socket exists → proceeds silently (daemon already running). - /browser-setup is the explicit, one-time init point. It spawns the daemon and connects to Chrome only when the user opts in. - SKILL.md updated with Connection Setup instructions telling agents to direct users to /browser-setup when socket is missing. * fix: checkChromeRunning on macOS — match by substring not exact ps -A -o comm= returns full executable paths on modern macOS (e.g. /Applications/Google Chrome.app/Contents/MacOS/Google Chrome), not the basename. The old exact-match check (browserProcesses.includes(l)) never matched, causing false 'No browser instance running' errors. Changed to substring includes() with helper/renderer/crashpad filtering. * feat: browser_setup as agent-callable tool The agent can now self-recover from 'Browser harness not initialized' errors by calling browser_setup directly — no user mediation needed. - Extracted shared performSetup() from the slash command into setup.ts - Created src/domains/setup.ts with ensureAlive:false to bypass the socket guard (this tool IS the setup, can't require itself) - Registered browser_setup in the tool registry - Updated SKILL.md: agent calls browser_setup directly, not ask user - Removed stale test/manual/spawn-test.ts * release: v0.6.0 — per-tab isolation, Unix socket daemon, on-demand init
2026-05-04docs: add speed-optimizations research; chore: improve browser detection in ↵amankumarsingh77
setup
2026-05-02refactor: drop legacy daemon usage from index/setup; trim state; move 4 ↵amankumarsingh77
files to strict tsconfig Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-29Replace socket daemon with direct CDP WebSocket connectionamankumarsingh77
Drops the Unix socket subprocess in favor of talking CDP directly over WebSocket from the extension. Removes the protocol's send/health helpers, simplifies setup to just verifying Chrome's remote debugging port, and tightens types in dynamic-tools. Bumps Node engine to >=22 and adds the ws dependency.
2026-04-29Initial release: pi-browser-harnessamankumarsingh77
Browser control extension for pi — 20 browser_* tools for navigating, clicking, typing, screenshotting, and extracting data from real Chrome via CDP. Includes self-extending harness (register_tool/remove_tool), guided /browser-setup, session persistence, and custom TUI renderers.