diff --git a/.github/scripts/sync-version.cjs b/.github/scripts/sync-version.cjs
index a95b21768..6d11ba6cb 100644
--- a/.github/scripts/sync-version.cjs
+++ b/.github/scripts/sync-version.cjs
@@ -19,12 +19,15 @@
*
* The release workflows take the published version from the release tag, so what is written here
* is what the app reports in a development or a locally packaged build.
+ *
+ * `--dry-run` prints the version without writing it.
*/
const { execFileSync } = require('node:child_process');
const { readFileSync, writeFileSync } = require('node:fs');
const { join } = require('node:path');
const root = join(__dirname, '..', '..');
+const dryRun = process.argv.includes('--dry-run');
const git = (...args) => execFileSync('git', args, { cwd: root, encoding: 'utf8' }).trim();
const lines = (out) => (out ? out.split('\n') : []);
@@ -33,14 +36,16 @@ const packageText = readFileSync(packagePath, 'utf8');
const current = JSON.parse(packageText).version;
const major = current.split('.')[0];
-const exists = (ref) => {
+/** Whether a git command succeeds (its exit status is the answer) */
+const succeeds = (...args) => {
try {
- execFileSync('git', ['rev-parse', '--verify', ref], { cwd: root, stdio: 'ignore' });
+ execFileSync('git', args, { cwd: root, stdio: 'ignore' });
return true;
} catch {
return false;
}
};
+const exists = (ref) => succeeds('rev-parse', '--verify', ref);
// Without the release tag there is nothing to count from: leave the version as it is rather than
// guess one (a shallow clone, or a major raised before its release was tagged)
@@ -63,6 +68,18 @@ if (!exists(`refs/tags/${anchor}`)) {
* branch's own line are taken for pull requests.
*/
const mainRef = ['refs/remotes/origin/main', 'refs/heads/main'].find(exists);
+
+// The tag must be on the history that is counted. A tag made before main's history was rewritten
+// shares no history with it, and `git fetch` never moves a tag that already exists locally, so a
+// checkout can keep such a tag: counting from it would take every pull request main ever merged
+const counted = mainRef ?? 'HEAD';
+if (!succeeds('merge-base', '--is-ancestor', anchor, counted)) {
+ console.log(
+ `[sync-version] the ${anchor} tag is not on ${counted}'s history (a tag from before a rewrite? ` +
+ `\`git fetch --tags --force\` takes the remote's), keeping ${current}`
+ );
+ process.exit(0);
+}
// Merges only, newest first: listing every commit's parents outgrew execFileSync's output
// buffer on a long history
const listMerges = (...args) => lines(git('rev-list', '--merges', '--parents', ...args)).map((line) => {
@@ -87,8 +104,8 @@ if (mainRef) {
const patch = lines(git('rev-list', '--first-parent', '--no-merges', 'HEAD', '--not', anchor, ...merges.slice(0, 1))).length;
const version = `${major}.${merges.length}.${patch}`;
-if (version === current) {
- console.log(`[sync-version] ${version}`);
+if (version === current || dryRun) {
+ console.log(`[sync-version] ${version === current ? version : `${current} -> ${version} (dry run, not written)`}`);
process.exit(0);
}
diff --git a/.gitignore b/.gitignore
index 8a18ea571..75bf75492 100644
--- a/.gitignore
+++ b/.gitignore
@@ -115,3 +115,8 @@ playwright/.cache/
# is not, because it holds absolute machine paths
.claude/settings.local.json
/shared_docs
+
+# Local files
+.agents
+media
+demo
diff --git a/CLAUDE.md b/CLAUDE.md
index 328e46020..38e232b0b 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -30,9 +30,10 @@ reviews, requests changes (same session continues) or merges.
an open PR stays in Human Review (PR Created); Merge PR (`src/main/ai/runners/github/pr-merger.ts`) pulls the target
branch into the task branch, lets the merge agent (`src/main/ai/runners/merge-agent.ts`, Claude Code) resolve
conflicts, checks that no line the target added was lost, pushes and merges the PR, then moves the task to Done
-- **Connectors** — MCP servers added to a task's Claude Code session (`--mcp-config`: Context7, Electron, Puppeteer,
+- **Connectors** — MCP servers added to a task's Claude Code session (`--mcp-config`: Context7, Electron, Playwright,
user-added servers) with app-wide defaults in Settings and per-task choices in the task dialog; a server stays
- disabled until it can start
+ disabled until it can start. Playwright's browsers run headless; Claude chats' browsers show in the browser drawer
+ inside Workbench, task runs' stay unseen
- **Graphify memory graph** — Optional [Graphify](https://github.com/Graphify-Labs/graphify) knowledge graph of a
project's code, built into `.workbench/knowledge` and offered to agents
- **Self-improve** — Optional project memory: Claude Code's auto memory kept in `.workbench/compeng` and shared by
@@ -169,6 +170,7 @@ workbench/
│ │ ├── task-resync/ # Out-of-date tasks take in a merged branch
│ │ ├── self-improve/ # Project memory (Claude Code auto memory in .workbench/compeng)
│ │ ├── live-agent/ # Live agent graph: hooks setup and relay worker
+│ │ ├── browser-drawer/ # Browser drawer: Playwright's registry, the browser bridge
│ │ ├── updater/ # Release selection for app updates
│ │ ├── claude-profile/ # Multi-profile credentials, token refresh, usage
│ │ ├── terminal/ # PTY processes, lifecycle, CLI integration, session menu
@@ -195,6 +197,12 @@ workbench/
without a worktree it uses `--permission-mode auto`) and the triage model/effort.
- `validate`: same session runs checks, reviews the diff with fresh eyes (`/code-review` or a subagent), commits,
returns a structured `ValidationReport`. `revise` mode applies "request changes" feedback, then validates again.
+ - Workflows (`workflows.ts`): when triage sizes a task `large`, validation asks for a Claude Code workflow that
+ reviews the diff from several angles and has each finding checked before it counts, and implementation may use
+ one for many-file changes. Settings > Agents > Limits sets `workflowSizeGuideline` (passed with `--settings`) and
+ `CLAUDE_CODE_WORKFLOW_MAX_CONCURRENT_AGENTS`, or turns workflows off. Launches are recorded in
+ `ClaudeRunInfo.workflows`, so a step continued after a stop or usage limit relaunches its run with
+ `resumeFromRunId` (finished agents reuse their results; a profile swap copies the session's directory with them).
- State in `/claude_run.json` (`ClaudeRunInfo`: session id, triage, plan, phases with cost, `system/init`
info, subagents, validation) so stopped / rate-limited runs continue; logs in `task_logs.json`. Claude Code's
task list (TaskCreate/TaskUpdate, enabled with `CLAUDE_CODE_ENABLE_TODO_TOOLS=1`) is mirrored as the task's subtasks.
@@ -228,31 +236,165 @@ enters (state machine transitions and manual moves) and on the files its Claude
MultiEdit, NotebookEdit tool calls). `src/main/task-changelog-writer.ts` turns them into the project's
`.workbench/changelog.jsonl` (one JSON entry per line; state entries carry every file the task's branch changes).
At every phase, `buildParallelTasksPrompt()` (`src/main/task-changelog.ts`) adds a "Parallel tasks" section to the
-task's system prompt: the other tasks with unmerged changes and the files they touch, so Claude Code can stay clear of
-them and avoid merge conflicts.
+task's system prompt: the other tasks with unmerged changes and the files they touch. Tasks edit whatever files they
+need (git merges changes to different parts of a file by itself); the prompt asks them to skip churn in shared files
+and to agree via `message_task` when both need the same lines.
### Task messaging and resync
With Task messaging on (Settings > Agents, `claudeCodeTasks.taskMessaging`, on by default), task runs get Workbench's
`message_task` and `list_parallel_tasks` tools (`src/main/task-messaging/`, served by the task tools server with a
-token per run) and `[Workbench]` notices (`notices.ts`: a task started, finished or was merged, two tasks change the
-same files). The broker (`broker.ts`) writes a message to a live run's stdin or keeps it in the target's
-`task_inbox.json` for its next phase. When a task is merged, the other tasks based on that branch go back to In
+token per run) and `[Workbench]` notices (`notices.ts`: a task started, finished or was merged, two tasks' changes
+conflict). After a task edits a file another task changes, `conflict-check.ts` test-merges both tasks' work
+(uncommitted edits snapshotted with a temp index, `git merge-tree --write-tree`) and names the conflicting files and
+lines; when that can't run, sharing the file is announced instead. The broker (`broker.ts`) writes a message to a live
+run's stdin or keeps it in the target's `task_inbox.json` for its next phase. With Messages from your Claude sessions on
+(`claudeCodeTasks.sessionMessages`, on by default), task runs also accept Claude Code's built-in SendMessage from the
+user's other sessions (`--settings {"crossSessionInbound":"accept"}`): agent windows are told the task session names
+(`task-messaging/window-hint.ts`), and the Claude chat gets `message_task` (through the broker) plus ListAgents /
+SendMessage with the Kanban button. When a task is merged, the other tasks based on that branch go back to In
Progress to take it in (`task-messaging/merge-sync.ts` → `src/main/task-resync/`), also while messaging is off.
### MCP Connectors
Settings > Connectors (`settings.mcpConnectors`, `McpConnectorSettings`) holds the defaults: Context7, Electron and
-Puppeteer, plus custom servers, which must pass a connection test before they can be switched on. New tasks copy the
+Playwright, plus custom servers, which must pass a connection test before they can be switched on. New tasks copy the
enabled ids into `TaskMetadata.mcpConnectors` and can change them in the task dialog. When a task runs,
`buildMcpConfig()` (`src/main/claude-code/mcp-config.ts`) turns that task's ids into `--mcp-config` for its Claude Code
session, on top of the user's own Claude Code MCP configuration. Helpers live in `src/shared/utils/mcp-connectors.ts`.
+Data saved before the browser connector moved from Puppeteer to Playwright (id `puppeteer`, `puppeteerEnabled`,
+`puppeteerBrowser`) is renamed where it is read (`migrate*` helpers there: the settings file in `settings-utils.ts`,
+task metadata in the project store, drafts, chats), so nothing else knows the old names.
+
+Playwright is Microsoft's `@playwright/mcp`, pinned (`PLAYWRIGHT_MCP_PACKAGE` in `browser-profiles/managed.ts`, with the
+browser builds that version needs, `PLAYWRIGHT_BUILDS`: bump them together). Its row picks a browser profile
+(`McpConnectorSettings.playwrightBrowser`): `src/main/browser-profiles/` finds Chrome, Edge, Brave, Chromium and
+Firefox profiles (`Local State`, `profiles.ini`) once at startup, and each run gets a copy of the chosen profile in the
+app's data folder, `/browser-profiles///` (in WSL
+`~/.cache/workbench/browser-profiles` in the distro; snap Chromium, which runs confined, in its own
+`~/snap/chromium/common/workbench-profiles`; never inside the project, where Claude sessions could read its
+cookies; Chrome 136+ refuses remote debugging on its default data dir). Each copy names its Workbench process
+(`.workbench-copy-owner.json`, its time refreshed while in use), so sweeps never remove another running Workbench's
+copies. Each copy also holds the run's Playwright config (`.workbench-playwright.json`, `playwrightProfileConfig()`),
+passed with `--config`: Chromium browsers run their executable on the copy with `--profile-directory`, the sandbox on
+and without Playwright's `--password-store=basic` / `--use-mock-keychain` (so copied sign-ins decrypt); the user's
+Firefox runs over WebDriver BiDi (channel `moz-firefox`, which Playwright calls experimental; Playwright's plain
+`firefox` is its own patched build) with Sync prefs off. Without a copy (Playwright's own browsers, the availability
+check, a failed copy) the server gets `--browser` / `--executable-path` and `--isolated` (a profile in memory;
+Playwright's own Chromium also `--sandbox`, which Playwright leaves off on Linux). Runs
+pass `--output-dir` to their temporary folder, since Playwright otherwise saves snapshots and screenshots in the
+session's working folder (`.playwright-mcp` in the worktree). The task dialog's Playwright row picks a profile for
+that task (`TaskMetadata.playwrightBrowser`, null for Playwright's own Chromium; unset follows Settings), which its runs
+use instead; sweeps keep the copies of every profile Settings or a task still chooses
+(`browser-profiles/choices-in-use.ts`). Why that server and not chrome-devtools-mcp is noted at the top of
+`mcp-config.ts`. The default is Playwright's own Chromium (Chrome for Testing, `--browser chromium`, never the
+installed Chrome); the picker also lists Playwright's Firefox and WebKit (`managed.ts`, found in Playwright's cache
+`ms-playwright/-` once `INSTALLATION_COMPLETE` is there) as disabled items with a download button
+that opens a terminal running `npx -y @playwright/mcp@ install-browser ` (`MCP_INSTALL_BROWSER`; the
+main process picks the command, then watches the cache, sends the new list and checks the connector again). Safari is
+listed but can't be used; WebKit is the closest engine. Microsoft Store Firefox is found by the profiles its package keeps
+(`%LOCALAPPDATA%\Packages\\LocalCache\Roaming\Mozilla\Firefox`) and run through its app execution alias's target
+(`app-alias.ts`). Profiles a browser never opened (no activity files) are left out after a week.
+
+In WSL mode Windows profiles work without anything installed on Windows (`detect.ts`): a Windows Firefox profile is
+copied into the distribution and run by a Firefox there (an installed one at least the profile's version, else
+Playwright's with `--allow-downgrade`), keeping its sign-ins. A Windows Chromium browser (Edge, Chrome) runs on Windows
+through `browser-profiles/windows-browser-launcher.cjs`, the server's command run by the distribution's node: it starts
+the browser through interop on a copy kept on Windows (headless, `--no-startup-window`, Edge's Alt+Tab tabs off with
+`--disable-features=msWindowTabManagerPublic`, no `--force-device-scale-factor`, which leaves the drawer's screencast
+without frames), relays a local port to its
+DevTools port through `windows-cdp-relay.cjs` (Workbench's executable as Node, on Windows) and starts Playwright with
+`--cdp-endpoint`; the relay's `--keep` mode (started with the browser, given its `DevToolsActivePort` file, so a browser slow to
+start is closed too) closes the browser and removes a temporary profile when the launcher goes, even when it is killed. Those profiles are marked "Saved sign-ins don't carry over": Chrome and Edge encrypt cookies
+with an app-bound key that only opens in the browser's own profile folder, never in a copy.
`src/main/mcp-availability.ts` starts each connector's server once where Claude Code runs, as a run would, until it
-answers `initialize` (Puppeteer is also asked to navigate once, since it needs a browser; `mcp-commands.ts` finds the
+answers `initialize` (Playwright is also asked to open `about:blank` with `browser_navigate`, headless, since it needs
+a browser; a missing build of Playwright's own browser offers its install-browser command; `mcp-commands.ts` finds the
command, and the built-in servers need npx from Node.js). Until a server is ready, its switch is off and disabled on
the Connectors page, in the task dialog and in the chat's MCP menu, and runs leave out unavailable servers. An
-unavailable result is checked again when asked for after 30 seconds.
+unavailable result is checked again when asked for after 30 seconds. Runs copy the chosen browser profile, and an
+open browser keeps it locked and half written (`browser-profiles/in-use.ts` reads its lock), so each profile also has
+one saved copy, made in the background whenever the browser is found closed: a run that starts while the browser is
+open copies the saved one instead. Only an open browser with no saved copy yet makes Playwright unavailable; the
+switch's tooltip asks to close it once, and closing it enables the connector within a few seconds. A task's own
+browser is probed for its runs apart from the windows' result (`checkRunServer`). Custom servers never take a
+built-in's id (moved to `-custom` when the settings are read).
+
+Runs' browsers are headless (`--headless` on every Playwright server's command line, also over a profile copy's config),
+so no browser window opens. Task runs' browsers stay that way, unseen; Claude chats' browsers are watched and driven in
+the **browser drawer** at the main window's right edge (`src/main/browser-drawer/`, `components/browser-drawer/`,
+`browser-drawer-store.ts`), Workbench's own UI: a tab per page of the project's chat browsers (a + button opens a new tab in the shown tab's browser), a toolbar (back, forward,
+reload, address), the live page below. The drawer is on the Claude page only and shows only the chat's own browser (below);
+closed, the chat opens it again from a button in its top-right corner (with a dot while the chat's browser is open), and
+other pages have no drawer or handle (the browsers keep running). Its width is resizable and remembered: widening it
+until the chat is narrower than 500px closes the chat history, then collapses the app's sidebar (not saved; narrowing
+the drawer opens them again in the other order, only what the drawer closed), and it stops where the chat keeps 500px
+beside the collapsed sidebar; each chat keeps its own view (open or closed, the tab shown).
+@playwright/mcp binds every browser it launches into Playwright's machine-wide registry (`/ms-playwright/b`, one
+JSON file per browser: title = the MCP client's name, workspace folder, socket, its playwright-core), which
+`registry.ts` reads every 2 seconds (live = its socket answers; browsers the bridge is connected to aren't asked, its link
+reports when they go). Only chats' browsers belong to a project (`project-match.ts`): a chat browser's holder works in
+its own temp folder, registered for its project while it runs (with WSL interop off, a chat's server works in the turn's temp folder,
+registered while the turn runs). A task run's browser (its workspace is the task's worktree or the project) matches no
+project, so no window lists it and the bridge never connects to it. A session the drawer shows that starts opens the drawer on its page. Once a drawer
+opens, the browser bridge runs until quit (`browser-bridge.cjs`, started by `bridge-process.ts` with Workbench's
+executable as Node; messages over its stdin/stdout as JSON headers with raw bytes for frames, `bridge-framing.ts`): it
+connects to the projects' browsers with each one's own playwright-core
+(`require(playwrightLib)` from the npx cache: nothing of Playwright ships with the app, the client always matches the
+server; disconnecting leaves the browser running) and reports their pages, each given Workbench's theme as its
+`prefers-color-scheme` (`page.emulateMedia`; every window sends the theme, also when it changes, from `useBrowserDrawerSync`); the page a window shows gets its viewport set
+to the drawer's page area (debounced on resize; the agent sees that size too) and streams JPEG frames
+(`page.screencast`, quality 100) to that window only, one at a time: the window acknowledges each frame it draws
+(`BROWSER_DRAWER_FRAME_DRAWN`), the next waits for that (or a second), and frames waiting meanwhile are replaced by
+newer ones, so the browser makes no more frames than the drawer draws. Frames are drawn on a canvas at their CSS size,
+the viewport a whole, even number of device pixels (`alignedViewportLength`) and the canvas moved onto whole device
+pixels, since at a fractional devicePixelRatio (1.25, 1.5) anything else resamples the frame and blurs its text. The
+canvas's mouse, wheel, keys and pasted text are replayed with `page.mouse` / `page.keyboard` from a queue per page,
+mouse moves and wheel steps waiting behind a slow one merged into the newest (a busy page answers each late: replaying
+every move held a click up for seconds), each step given at most 5 seconds. Frames are asked at the window's devicePixelRatio,
+and on HiDPI screens the browsers render that many pixels: `browser-drawer/display-scale.ts` follows the screens'
+largest scale factor (up to 2) into the runs' Playwright config (`setPlaywrightDisplayScale`: `deviceScaleFactor`, plus
+`--force-device-scale-factor` for Chromium, whose screencast otherwise stays at CSS size, rounded up to a whole factor:
+a fractional one leaves the screencast without frames once the viewport is set), a small config file for runs
+without a profile copy; screenshots for agents stay in CSS pixels. The renderer gets bytes and text only (no remote content, no webview).
+The availability probe's browser is titled with Playwright's internal prefix, so it never shows. In WSL mode the
+browsers, their registry and their Unix sockets are inside the distribution, which Windows can't connect to: the bridge
+runs there with the distribution's node (`spawnTool`, script read through `/mnt`), the registry is read through
+`\\wsl.localhost` (the distribution's `~/.cache/ms-playwright/b`), a running bridge also says which of its browsers answer
+(`probe`, `setRegistryAccess` in `registry.ts`; a check never starts it: until a drawer does, the chat browsers
+Workbench holds open count as live), and workspace folders are matched to projects as Windows paths
+(`toHostPath`). Chat browsers' holders run in the distribution too, their folders in its `~/.cache/workbench/tmp`
+(`runtimeTempParent()`; a profile on a Windows drive is slow for a browser), which the startup sweep also looks in.
+
+**Chat browsers** (`browser-drawer/chat-browsers.ts`) — each Claude chat has at most one browser, owned by Workbench, not
+by a turn: it stays open between turns and while the user is on other chats or pages, so the user and the chat work in
+the same pages (the user signs in or passes multi-factor checks by hand, then asks the chat to carry on). A long-lived
+Playwright MCP server Workbench starts itself (the holder: the turn's server and browser options for the chat's browser,
+its profile copy, `--idle-timeout 0`, a profile in its folder instead of `--isolated`) initializes with the chat's bind
+title (`Workbench chat `) and opens `about:blank`, so its browser is bound under that title; a turn's Playwright
+gets `--endpoint ` and attaches to it (`contexts()[0]`). The chat's guard asks Workbench to open the browser
+before each tool call (`open_chat_browser`, a token per turn on the task tools server) and refuses `browser_close`;
+inside WSL2 with NAT networking (no way to the app's 127.0.0.1) it sends that call through the task tools bridge
+(`task-tools-bridge.cjs`, a Windows process it starts once through interop: `WORKBENCH_CHAT_BROWSER_RELAY`), and with
+interop off chats fall back to a browser per turn. The
+drawer's empty state on the Claude page has the chat's browser profile picker (`InsightsModelConfig.playwrightBrowser`;
+unset = Settings > Connectors; the New chat page starts from Settings) and an Open browser button, which also switches
+Playwright on for the chat; the picker shows only while the chat has no browser (one profile per chat at a time). The
+New chat page's browser (chat id `new`) moves to the conversation its first message creates. A chat browser closes when
+the user closes its last tab, its chat is deleted, its browser goes away (its registry entry stops answering) or the
+app quits.
+
+**Crash leftovers** — Workbench's folders in the system temp folder (`temp-folders.ts`: `workbench-task-`,
+`workbench-insights-`, `workbench-chat-browser-`, `workbench-browser-bridge-`, `workbench-mcp-probe-`) are made with an
+owner file naming the Workbench process (`folder-owner.ts`, the same one profile copies have), and a task phase's or chat
+turn's also names its Claude Code process. At startup (`removeCrashLeftovers()` in `index.ts`, in the background),
+`browser-drawer/chat-browser-restore.ts` looks at the chat browsers a crash left: each holder folder keeps a record
+(`.workbench-chat-browser.json`: project, chat, browser, profile copy, open tabs from the bridge), and a chat that still
+exists keeps its newest one for 7 days (this process takes over the folder and its profile copy, which sweeps and
+quitting then leave). The drawer offers it (`ChatBrowserInfo.status: 'restorable'`): the chat's next browser with the
+same profile starts from that profile and reopens its tabs; another profile discards it. Then the temp folders no
+running Workbench or run holds go (folders without an owner file only after an hour), then profile copies.
### Graphify Memory Graph
@@ -277,12 +419,20 @@ headless stream-json run built in `insights/claude-code-runner.ts`, on the proje
- **One session per chat** — the first message starts a session (`--session-id`, named `Workbench chat: `),
later turns `--resume` it, and editing a sent message or regenerating a reply forks it at the earlier reply
(`--resume --resume-session-at --fork-session`), leaving the original session as it was. Chats are saved
- in `.workbench/chats/` (`session-storage.ts`); a new chat is saved only once it has a message. Stop ends the reply,
- as does leaving its chat.
+ in `.workbench/chats/` (`session-storage.ts`); a new chat is saved only once it has a message.
+- **Chats reply at the same time** — one reply runs per chat (`insights-executor.ts`, keyed by project and chat), and
+ switching chats, opening a new chat or leaving the page never stops one; Stop ends the reply of the chat it is pressed
+ in, and deleting a chat stops its reply and closes its browser. Every event (stream chunks, status, errors) names its
+ chat: the renderer streams the shown chat's reply and keeps the others' in `backgroundRuns` until they end (each is
+ saved in its own chat), so a chat opened again shows its reply still streaming; the history marks replying chats.
- **Can't change the project's files** — `--tools` gives Read, Glob, Grep, WebFetch and WebSearch, plus Bash only for
graphify's searches (Use Graphify on) and read-only `gh` / `glab` commands (the GitHub / GitLab buttons,
`INSIGHTS_GITHUB_COMMANDS` / `INSIGHTS_GITLAB_COMMANDS` in `insights/prompts.ts`), and Edit/Write only for
`.workbench/compeng/**` (Self-improve on). `--permission-mode dontAsk` denies everything else without asking.
+ Playwright runs through `insights/playwright-guard.cjs`, in the turn's own folder without the client's roots, so
+ its workspace root (where files a tool call names are written) is that folder, not the project; the guard also
+ leaves out `browser_run_code_unsafe`. The chat may read that folder (`--add-dir`), where snapshots are linked.
+ It attaches to the chat's own browser (see Chat browsers above); in WSL with interop off each turn launches its own.
- **MCP per chat** — `--strict-mcp-config` loads only the servers chosen in the chat's MCP menu
(`InsightsMcpMenu.tsx`, the Connectors defaults until changed) and, with the Kanban button on, Workbench's task tools
(`insights/task-tools.ts`, served over local MCP HTTP by `task-tools-server.ts` with a token per turn): they create,
@@ -311,8 +461,9 @@ Switching off moves the memories aside to `.workbench/compeng.disabled` unless g
The Live agent switch (Settings > Agents) shows agent-flow's graph of a project's Claude Code sessions next to each
agent window (`src/main/live-agent/`, `src/renderer/components/live-agent/`). It installs `.workbench/flow/hook.cjs`
and Claude Code hooks in the project's and its worktrees' `.claude/settings.local.json` (`project-setup.ts`); the
-`.workbench/flow` folder's existence is the setting. A relay worker (`live-agent-relay.ts`, `relay/`) runs while any
-project has it on; each window's graph shows only the sessions run in it, never headless ones.
+`.workbench/flow` folder's existence is the setting, switched on when a project is set up. A relay worker
+(`live-agent-relay.ts`, `relay/`) runs while any project has it on; each window's graph shows only the sessions run in
+it, never headless ones.
### Electron MCP (testing the app from a task)
@@ -354,7 +505,7 @@ Project, Connectors, Developer, Simulation (`npm run dev` builds only, `IS_DEV_B
notifications.
- **Accounts** — Claude accounts, API profiles and Metrics (spending per project, `src/main/project-metrics.ts`).
- **Agents** — how tasks run (triage, planning, validation, Fable, fallback model, Task messaging, Live agent) and
- limits such as Maximum parallel tasks.
+ limits such as Maximum parallel tasks and the workflow size and concurrency.
- **Project** — the selected project's page: Project (Project index: CLAUDE.md written by Claude Code's `/init`,
`src/main/project-index.ts`; Knowledge index: Graphify; Memory index: Self-improve), Knowledge (Use CLAUDE.md, Use
Graphify, Self-improve), Tasks, Branches. The project's `useClaudeMd`, `maxBudgetUsd` (budget per task),
diff --git a/README.md b/README.md
index 59a312757..2f526c13c 100644
--- a/README.md
+++ b/README.md
@@ -6,7 +6,7 @@
-**Workbench is a cross-platform desktop app based on Claude Code harness, built for proactive engineers.** It brings together what Claude Code and the tools around it already offer, sets each piece up for your project with a switch instead of a config file, and gives you a space to manage your project tasks and hand each one to an agent that works in its own git worktree, so your main branch stays untouched until you review and merge. Every task starts with a short triage run that efficiently picks the model and the thinking effort based on the task description, and decides whether the work needs planning, so a one-line fix doesn't burn an Opus run and a refactor across a dozen files doesn't get handed to Haiku. From there, the same session plans, implements, runs your project's checks, reviews its own diff with fresh eyes, and commits, while parallel tasks are told which files the other unmerged branches touch so they stay out of each other's way.
+**Workbench is a cross-platform desktop app based on Claude Code harness, built for proactive engineers.** It brings together what Claude Code and the tools around it already offer, sets each piece up for your project with a switch instead of a config file, and gives you a space to manage your project tasks and hand each one to an agent that works in its own git worktree, so your main branch stays untouched until you review and merge. Every task starts with a short triage run that efficiently picks the model and the thinking effort based on the task description, and decides whether the work needs planning, so a one-line fix doesn't burn an Opus run and a refactor across a dozen files doesn't get handed to Haiku. From there, the same session plans, implements, runs your project's checks, reviews its own diff with fresh eyes, and commits, while parallel tasks are told which files the other unmerged branches touch, and Workbench test-merges their work so they hear about it when two tasks change the same lines.
diff --git a/package-lock.json b/package-lock.json
index 873bdb97e..7018b6100 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "workbench",
- "version": "1.4.67",
+ "version": "1.5.65",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "workbench",
- "version": "1.4.67",
+ "version": "1.5.65",
"hasInstallScript": true,
"dependencies": {
"@anthropic-ai/sdk": "^0.78.0",
diff --git a/package.json b/package.json
index a15d20cc2..c639c3caa 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
{
"name": "workbench",
- "version": "1.4.67",
+ "version": "1.5.65",
"author": {
"name": "Artyom Vancyan",
"email": "44609997+artyomvancyan@users.noreply.github.com"
diff --git a/src/__tests__/integration/terminal-copy-paste.test.ts b/src/__tests__/integration/terminal-copy-paste.test.ts
index c44c45661..1d7d29d4f 100644
--- a/src/__tests__/integration/terminal-copy-paste.test.ts
+++ b/src/__tests__/integration/terminal-copy-paste.test.ts
@@ -71,6 +71,21 @@ vi.mock('@xterm/addon-serialize', () => ({
})
}));
+/** Fire a paste event (as the browser does after Ctrl+V) carrying the given clipboard contents */
+function firePaste(target: Element, clipboard: { text?: string; files?: File[] }): Event {
+ const files = clipboard.files ?? [];
+ const event = new Event('paste', { bubbles: true, cancelable: true });
+ Object.defineProperty(event, 'clipboardData', {
+ value: {
+ files,
+ items: files.map((file) => ({ kind: 'file', type: file.type })),
+ getData: (type: string) => (type === 'text/plain' ? clipboard.text ?? '' : ''),
+ },
+ });
+ target.dispatchEvent(event);
+ return event;
+}
+
describe('Terminal copy/paste integration', () => {
let mockClipboard: {
writeText: Mock;
@@ -293,7 +308,7 @@ describe('Terminal copy/paste integration', () => {
});
});
- describe('clipboard read with xterm paste integration', () => {
+ describe("the browser's paste event with xterm paste integration", () => {
let originalNavigatorPlatform: string;
beforeEach(() => {
@@ -309,7 +324,7 @@ describe('Terminal copy/paste integration', () => {
});
});
- it('should integrate clipboard.readText() with xterm.paste()', async () => {
+ it("should integrate the browser's paste event with xterm.paste()", async () => {
const { useXterm } = await import('../../renderer/components/terminal/useXterm');
// Mock Windows platform
@@ -370,37 +385,33 @@ describe('Terminal copy/paste integration', () => {
};
});
- mockClipboard.readText.mockResolvedValue('pasted text');
-
// Create a test wrapper component that provides the DOM element
const TestWrapper = () => {
const { terminalRef } = useXterm({ terminalId: 'test-terminal' });
return React.createElement('div', { ref: terminalRef });
};
- render(React.createElement(TestWrapper));
+ const { container } = render(React.createElement(TestWrapper));
+ let keyEvent: KeyboardEvent | undefined;
+ let handled: boolean | undefined;
await act(async () => {
- const event = new KeyboardEvent('keydown', {
- key: 'v',
- ctrlKey: true
- });
-
- if (keyEventHandler) {
- keyEventHandler(event);
- // Wait for clipboard read and paste
- await new Promise(resolve => setTimeout(resolve, 0));
- }
+ keyEvent = new KeyboardEvent('keydown', { key: 'v', ctrlKey: true, cancelable: true });
+ handled = keyEventHandler?.(keyEvent);
+ // The browser's paste event follows the shortcut
+ firePaste(container.firstElementChild!, { text: 'pasted text' });
});
- // Verify integration: clipboard.readText() called
- expect(mockClipboard.readText).toHaveBeenCalled();
+ // xterm doesn't send ^V, and the browser's paste goes ahead
+ expect(handled).toBe(false);
+ expect(keyEvent?.defaultPrevented).toBe(false);
- // Verify integration: xterm.paste() called with clipboard content
+ // Verify integration: the paste event's text goes to xterm.paste(), without reading the clipboard
expect(mockPaste).toHaveBeenCalledWith('pasted text');
+ expect(mockClipboard.readText).not.toHaveBeenCalled();
});
- it('should not paste when clipboard is empty', async () => {
+ it('sends the empty paste xterm would when the clipboard has neither text nor files (Linux)', async () => {
const { useXterm } = await import('../../renderer/components/terminal/useXterm');
// Mock Linux platform
@@ -461,8 +472,9 @@ describe('Terminal copy/paste integration', () => {
};
});
- // Mock empty clipboard
- mockClipboard.readText.mockResolvedValue('');
+ // Under WSLg a file copied in Windows arrives as an empty paste: the main process reads the clipboard's files
+ const readClipboardFilePaths = vi.fn(async () => [] as string[]);
+ (window as unknown as { electronAPI: unknown }).electronAPI = { sendTerminalInput: vi.fn(), readClipboardFilePaths };
// Create a test wrapper component that provides the DOM element
const TestWrapper = () => {
@@ -470,26 +482,18 @@ describe('Terminal copy/paste integration', () => {
return React.createElement('div', { ref: terminalRef });
};
- render(React.createElement(TestWrapper));
+ const { container } = render(React.createElement(TestWrapper));
await act(async () => {
- const event = new KeyboardEvent('keydown', {
- key: 'v',
- ctrlKey: true
- });
-
- if (keyEventHandler) {
- keyEventHandler(event);
- // Wait for clipboard read
- await new Promise(resolve => setTimeout(resolve, 0));
- }
+ keyEventHandler?.(new KeyboardEvent('keydown', { key: 'v', ctrlKey: true, cancelable: true }));
+ firePaste(container.firstElementChild!, {});
+ await new Promise(resolve => setTimeout(resolve, 0));
});
- // Verify clipboard was read
- expect(mockClipboard.readText).toHaveBeenCalled();
-
- // Verify paste was NOT called for empty clipboard
- expect(mockPaste).not.toHaveBeenCalled();
+ // No files either: the empty paste xterm would have sent (Claude Code then looks for an image)
+ expect(readClipboardFilePaths).toHaveBeenCalled();
+ expect(mockPaste).toHaveBeenCalledWith('');
+ expect(mockClipboard.readText).not.toHaveBeenCalled();
});
});
@@ -724,20 +728,13 @@ describe('Terminal copy/paste integration', () => {
const mockInput = vi.fn();
const mockSendTerminalInput = vi.fn();
let onDataCallback: ((data: string) => void) | undefined;
- let errorLogged = false;
- const consoleErrorSpy = vi.spyOn(console, 'error').mockImplementation(function(...args: unknown[]) {
- if (String(args[0]).includes('[useXterm]')) {
- errorLogged = true;
- }
- });
-
- // Mock clipboard error
- mockClipboard.readText = vi.fn().mockRejectedValue(new Error('Clipboard denied'));
-
- // Mock window.electronAPI with sendTerminalInput
- (window as unknown as { electronAPI: { sendTerminalInput: Mock } }).electronAPI = {
- sendTerminalInput: mockSendTerminalInput
+ // Pasted files' paths can't be translated for the terminal's runtime (the call fails)
+ const copied = new File(['x'], 'notes.txt', { type: 'text/plain' });
+ (window as unknown as { electronAPI: unknown }).electronAPI = {
+ sendTerminalInput: mockSendTerminalInput,
+ getPathForFile: () => 'C:\\notes.txt',
+ toTerminalRuntimePaths: vi.fn().mockRejectedValue(new Error('Clipboard denied')),
};
// Override XTerm mock to be constructable
@@ -797,24 +794,17 @@ describe('Terminal copy/paste integration', () => {
return React.createElement('div', { ref: terminalRef });
};
- render(React.createElement(TestWrapper));
+ const { container } = render(React.createElement(TestWrapper));
await act(async () => {
- // Try to paste (will fail)
- const pasteEvent = new KeyboardEvent('keydown', {
- key: 'v',
- ctrlKey: true
- });
-
- if (keyEventHandler) {
- keyEventHandler(pasteEvent);
- // Wait for clipboard error
- await new Promise(resolve => setTimeout(resolve, 0));
- }
+ // Paste a copied file (translating its path fails)
+ keyEventHandler?.(new KeyboardEvent('keydown', { key: 'v', ctrlKey: true, cancelable: true }));
+ firePaste(container.firstElementChild!, { files: [copied] });
+ await new Promise(resolve => setTimeout(resolve, 0));
});
- // Verify error was logged
- expect(errorLogged).toBe(true);
+ // The paste falls back to the path as it was
+ expect(mockPaste).toHaveBeenCalledWith('C:\\notes.txt');
// Verify terminal still works (can accept input through onData callback)
const inputData = 'test command';
@@ -825,8 +815,6 @@ describe('Terminal copy/paste integration', () => {
// Verify input was sent to electronAPI (terminal still functional)
expect(mockSendTerminalInput).toHaveBeenCalledWith('test-terminal', 'test command');
-
- consoleErrorSpy.mockRestore();
});
});
});
diff --git a/src/main/__tests__/connector-migration.test.ts b/src/main/__tests__/connector-migration.test.ts
new file mode 100644
index 000000000..f1fa0dc22
--- /dev/null
+++ b/src/main/__tests__/connector-migration.test.ts
@@ -0,0 +1,59 @@
+/**
+ * Data saved before the browser connector moved from Puppeteer to Playwright is renamed where it is
+ * read: the settings file (every main-process reader) and the chats' MCP menu ids
+ */
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
+import path from 'path';
+import os from 'os';
+import { mkdtemp, mkdir, rm, writeFile } from 'fs/promises';
+
+const mocks = vi.hoisted(() => ({ userData: '' }));
+vi.mock('electron', () => ({ app: { getPath: () => mocks.userData } }));
+
+import { readSettingsFile, readSettingsFileAsync } from '../settings-utils';
+import { SessionStorage } from '../insights/session-storage';
+import type { InsightsPaths } from '../insights/paths';
+
+describe('connector data from before Playwright', () => {
+ let root: string;
+
+ beforeEach(async () => {
+ root = await mkdtemp(path.join(os.tmpdir(), 'connector-migration-'));
+ mocks.userData = root;
+ });
+
+ afterEach(async () => {
+ await rm(root, { recursive: true, force: true });
+ });
+
+ it('reads the settings file with the connector keys renamed', async () => {
+ const browser = { id: 'chrome:Default', browser: 'chrome', engine: 'chromium' };
+ await writeFile(path.join(root, 'settings.json'), JSON.stringify({
+ theme: 'dark',
+ mcpConnectors: { puppeteerEnabled: true, puppeteerBrowser: browser },
+ }));
+
+ const expected = { theme: 'dark', mcpConnectors: { playwrightEnabled: true, playwrightBrowser: browser } };
+ expect(await readSettingsFileAsync()).toEqual(expected);
+ expect(readSettingsFile()).toEqual(expected);
+ });
+
+ it("reads a chat's MCP menu with the old connector id renamed", async () => {
+ const sessionsDir = path.join(root, 'chats');
+ await mkdir(sessionsDir, { recursive: true });
+ const session = {
+ id: 's1', projectId: 'p1', title: 'Chat', messages: [],
+ createdAt: '2026-10-01T00:00:00Z', updatedAt: '2026-10-01T00:00:00Z',
+ modelConfig: { profileId: 'balanced', model: 'sonnet', thinkingLevel: 'medium', mcpConnectors: ['context7', 'puppeteer'] },
+ };
+ await writeFile(path.join(sessionsDir, 's1.json'), JSON.stringify(session));
+ const paths = {
+ getSessionsDir: () => sessionsDir,
+ getSessionPath: (_project: string, id: string) => path.join(sessionsDir, `${id}.json`),
+ } as unknown as InsightsPaths;
+ const storage = new SessionStorage(paths);
+
+ expect(storage.loadSessionById('/project', 's1')?.modelConfig?.mcpConnectors).toEqual(['context7', 'playwright']);
+ expect(storage.listSessions('/project')[0].modelConfig?.mcpConnectors).toEqual(['context7', 'playwright']);
+ });
+});
diff --git a/src/main/__tests__/ensure-onboarding-complete.test.ts b/src/main/__tests__/ensure-onboarding-complete.test.ts
index 4d5d4329e..a1a53605f 100644
--- a/src/main/__tests__/ensure-onboarding-complete.test.ts
+++ b/src/main/__tests__/ensure-onboarding-complete.test.ts
@@ -54,6 +54,7 @@ vi.mock('../claude-profile-manager', () => ({
}));
vi.mock('../project-account', () => ({ projectAccount: vi.fn() }));
+vi.mock('../task-messaging/window-hint', () => ({ agentWindowMessagingHint: () => '' }));
vi.mock('../claude-profile/credential-utils', () => ({
getFullCredentialsFromKeychain: vi.fn(),
diff --git a/src/main/__tests__/insights-edit-message.test.ts b/src/main/__tests__/insights-edit-message.test.ts
index f06ae1cd0..0db133992 100644
--- a/src/main/__tests__/insights-edit-message.test.ts
+++ b/src/main/__tests__/insights-edit-message.test.ts
@@ -4,12 +4,12 @@ import { tmpdir } from 'node:os';
import { join } from 'node:path';
const execute = vi.fn();
-const cancel = vi.fn((_projectId: string) => false);
+const cancel = vi.fn((_projectId: string, _sessionId?: string) => false);
vi.mock('../insights/insights-executor', async () => {
const { EventEmitter } = await import('events');
class FakeExecutor extends EventEmitter {
- cancelSession(projectId: string) { return cancel(projectId); }
+ cancelSession(projectId: string, sessionId?: string) { return cancel(projectId, sessionId); }
execute(...args: unknown[]) { return execute(...args); }
}
return { InsightsExecutor: FakeExecutor };
@@ -163,7 +163,7 @@ describe('Claude Code sessions of a chat', () => {
});
});
-describe('a reply running when the user leaves its chat', () => {
+describe('a reply running when the user leaves its chat (it goes on)', () => {
/** The next reply runs until it is stopped, then ends as a stopped reply with what it wrote */
function answerUntilStopped(text = 'Partial') {
execute.mockImplementationOnce(() => new Promise((resolve) => {
@@ -180,21 +180,31 @@ describe('a reply running when the user leaves its chat', () => {
return { ids, stop: () => service.off('session-updated', listener) };
}
- it('stops when a new chat opens and stays in its own chat', async () => {
- answerUntilStopped();
+ /** The next reply runs until `finish` is called (or it is stopped) */
+ function answerLater(text = 'Full reply') {
+ let finish: () => void = () => undefined;
+ execute.mockImplementationOnce(() => new Promise((resolve) => {
+ finish = () => resolve({ fullResponse: text, toolsUsed: [] });
+ }));
+ return { finish: () => finish() };
+ }
+
+ it('keeps running when a new chat opens, and is saved in its own chat', async () => {
+ const reply = answerLater();
const sending = service.sendMessage(pid, projectDir, 'first');
const chatId = service.loadSession(pid, projectDir)!.id;
service.startNewChat(pid, projectDir);
+ expect(cancel).not.toHaveBeenCalled();
+ reply.finish();
await sending;
- expect(cancel).toHaveBeenCalled();
- // The new chat stays empty; the stopped reply is kept in the chat it belongs to
+ // The new chat stays empty; the reply is kept in the chat it belongs to
expect(service.loadSession(pid, projectDir)).toBeNull();
const chat = service.switchSession(pid, projectDir, chatId)!;
expect(chat.messages.map((m) => [m.role, m.content, m.stopped])).toEqual([
['user', 'first', undefined],
- ['assistant', 'Partial', true],
+ ['assistant', 'Full reply', undefined],
]);
});
@@ -214,24 +224,47 @@ describe('a reply running when the user leaves its chat', () => {
expect(service.loadSession(pid, projectDir)).toBeNull();
});
- it('stops when the user switches to another chat, which stays the open one', async () => {
+ it('keeps running when the user switches to another chat, which stays the open one', async () => {
answer('Other reply');
await service.sendMessage(pid, projectDir, 'other chat');
const otherId = service.loadSession(pid, projectDir)!.id;
service.startNewChat(pid, projectDir);
- answerUntilStopped();
+ const reply = answerLater();
const sending = service.sendMessage(pid, projectDir, 'first');
const chatId = service.loadSession(pid, projectDir)!.id;
expect(chatId).not.toBe(otherId);
service.switchSession(pid, projectDir, otherId);
+ expect(cancel).not.toHaveBeenCalled();
+ reply.finish();
await sending;
- expect(cancel).toHaveBeenCalled();
expect(service.loadSession(pid, projectDir)!.id).toBe(otherId);
expect(service.loadSession(pid, projectDir)!.messages).toHaveLength(2);
- expect(service.switchSession(pid, projectDir, chatId)!.messages.at(-1)).toMatchObject({ content: 'Partial', stopped: true });
+ expect(service.switchSession(pid, projectDir, chatId)!.messages.at(-1)).toMatchObject({ content: 'Full reply' });
+ });
+
+ it('replies in two chats at once; stop and a new message act on their own chat only', async () => {
+ const replyA = answerLater('Reply A');
+ const sendingA = service.sendMessage(pid, projectDir, 'question A');
+ const chatA = service.loadSession(pid, projectDir)!.id;
+ service.startNewChat(pid, projectDir);
+ answerUntilStopped('Partial B');
+ const sendingB = service.sendMessage(pid, projectDir, 'question B');
+ const chatB = service.loadSession(pid, projectDir)!.id;
+
+ // Sending in B stopped only B's own earlier reply (none)
+ expect(cancel.mock.calls.every(([, id]) => id === chatB)).toBe(true);
+ service.stopMessage(pid, chatB);
+ await sendingB;
+ expect(cancel).toHaveBeenLastCalledWith(pid, chatB);
+ expect(cancel).not.toHaveBeenCalledWith(pid, chatA);
+
+ replyA.finish();
+ await sendingA;
+ expect(service.switchSession(pid, projectDir, chatA)!.messages.at(-1)).toMatchObject({ content: 'Reply A' });
+ expect(service.switchSession(pid, projectDir, chatB)!.messages.at(-1)).toMatchObject({ content: 'Partial B', stopped: true });
});
it('keeps running when another chat is deleted or its own chat is opened again', async () => {
@@ -247,7 +280,7 @@ describe('a reply running when the user leaves its chat', () => {
service.deleteSession(pid, projectDir, otherId);
service.switchSession(pid, projectDir, chatId);
- expect(cancel).not.toHaveBeenCalled();
+ expect(cancel).not.toHaveBeenCalledWith(pid, chatId);
service.stopMessage(pid);
await sending;
diff --git a/src/main/__tests__/mcp-availability.test.ts b/src/main/__tests__/mcp-availability.test.ts
index ce9ac481e..6eb21c155 100644
--- a/src/main/__tests__/mcp-availability.test.ts
+++ b/src/main/__tests__/mcp-availability.test.ts
@@ -1,9 +1,10 @@
-import { describe, it, expect, vi, beforeEach } from 'vitest';
+import { describe, it, expect, vi, beforeEach, afterAll } from 'vitest';
import { EventEmitter } from 'events';
+import { existsSync } from 'fs';
/** Installed commands and where they are */
const installed = new Map();
-const servers: Record void> = {};
+const servers: Record void> = {};
class FakeProcess extends EventEmitter {
stdout = new EventEmitter();
@@ -13,6 +14,8 @@ class FakeProcess extends EventEmitter {
const mocks = vi.hoisted(() => ({
windows: false,
+ browserOpen: false,
+ inUse: vi.fn(),
spawnTool: vi.fn(),
killRuntimeProcessTree: vi.fn(),
resolveCommand: vi.fn(),
@@ -23,15 +26,33 @@ vi.mock('../mcp-commands', () => ({
resolveCommand: mocks.resolveCommand,
resetCommandLookups: mocks.resetCommandLookups,
}));
-vi.mock('../platform/shell-runtime', () => ({ getWslInfo: () => null, whenShellRuntimeReady: async () => undefined }));
+vi.mock('../platform/shell-runtime', () => ({ getWslInfo: () => null, whenShellRuntimeReady: async () => undefined, toRuntimePath: (p: string) => p }));
vi.mock('../platform/runtime-exec', () => ({
spawnTool: mocks.spawnTool,
killRuntimeProcessTree: mocks.killRuntimeProcessTree,
toRuntimeArg: (arg: string) => arg,
}));
-vi.mock('../platform', () => ({ isWindows: () => mocks.windows }));
+vi.mock('../platform', () => ({ isWindows: () => mocks.windows, isLinux: () => process.platform === 'linux' }));
vi.mock('../cli-utils', () => ({ getToolEnvAsync: async () => ({ PATH: '/usr/bin' }) }));
-vi.mock('../app-logger', () => ({ appLog: { warn: vi.fn() } }));
+vi.mock('../browser-profiles/profile-copy', () => ({ browserProfileCopyBlocked: (browser: unknown) => mocks.inUse(browser) }));
+vi.mock('../app-logger', () => ({ appLog: { warn: vi.fn(), info: vi.fn() } }));
+// Probe folders go into the suite's own folder (a probe left waiting when a test ends keeps its folder)
+const probeParent = vi.hoisted(() => {
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
+ const { mkdtempSync } = require('fs') as typeof import('fs');
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
+ const { join } = require('path') as typeof import('path');
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
+ return mkdtempSync(join((require('os') as typeof import('os')).tmpdir(), 'mcp-availability-test-'));
+});
+vi.mock('../temp-folders', async (importOriginal) => {
+ const actual = await importOriginal();
+ return { ...actual, makeTempFolder: (prefix: Parameters[0]) => actual.makeTempFolder(prefix, probeParent) };
+});
+afterAll(async () => {
+ const { rm } = await import('fs/promises');
+ await rm(probeParent, { recursive: true, force: true });
+});
let getMcpAvailability: typeof import('../mcp-availability').getMcpAvailability;
let onMcpAvailabilityChange: typeof import('../mcp-availability').onMcpAvailabilityChange;
@@ -39,6 +60,18 @@ let usableMcpConnectorIds: typeof import('../mcp-availability').usableMcpConnect
let resetMcpAvailability: typeof import('../mcp-availability').resetMcpAvailability;
let stopMcpProbes: typeof import('../mcp-availability').stopMcpProbes;
let UNAVAILABLE_RECHECK_MS: number;
+let describeLeftOutConnector: typeof import('../mcp-availability').describeLeftOutConnector;
+
+/** A probe's own folder for Playwright's files */
+const PROBE_DIR = expect.stringMatching(/workbench-mcp-probe-/);
+
+/** The pinned Playwright server, as npx is given it */
+const PACKAGE = '@playwright/mcp@0.0.83';
+const PW = `-y ${PACKAGE}`;
+
+/** Playwright's tool error when its Chromium isn't downloaded */
+const NOT_INSTALLED = '### Error\nError: Browser "chrome-for-testing" is not installed; expected executable at ' +
+ '/home/me/.cache/ms-playwright/chromium-1247/chrome-linux64/chrome. Run `npx @playwright/mcp install-browser chrome-for-testing` to install';
const answer = (proc: FakeProcess) => proc.stdout.emit('data', Buffer.from('{"jsonrpc":"2.0","id":1,"result":{}}\n'));
const crash = (proc: FakeProcess) => {
@@ -54,45 +87,49 @@ describe('MCP availability', () => {
installed.clear();
for (const key of Object.keys(servers)) delete servers[key];
mocks.windows = false;
+ mocks.browserOpen = false;
+ mocks.inUse.mockImplementation(async () => mocks.browserOpen);
mocks.resolveCommand.mockImplementation(async (command: string) => installed.get(command) ?? null);
mocks.spawnTool.mockImplementation((_tool: string, args: string[]) => {
const proc = new FakeProcess();
- setTimeout(() => servers[args.join(' ')]?.(proc), 0);
+ // A server by its whole command line, else by its package (`-y `)
+ setTimeout(() => (servers[args.join(' ')] ?? servers[args.slice(0, 2).join(' ')])?.(proc, args), 0);
return proc;
});
vi.resetModules();
({
getMcpAvailability, onMcpAvailabilityChange, usableMcpConnectorIds, resetMcpAvailability, stopMcpProbes, UNAVAILABLE_RECHECK_MS,
+ describeLeftOutConnector,
} = await import('../mcp-availability'));
});
it('is preparing until the server answers, then ready or unavailable', async () => {
installed.set('npx', '/usr/bin/npx');
servers['-y @upstash/context7-mcp@latest'] = answer;
- servers['-y @modelcontextprotocol/server-puppeteer'] = crash;
+ servers[PW] = crash;
const changes: Record = {};
const stop = onMcpAvailabilityChange((id, availability) => {
changes[id] = availability.state;
});
- expect(getMcpAvailability(['context7', 'puppeteer'], undefined)).toEqual({
+ expect(getMcpAvailability(['context7', 'playwright'], undefined)).toEqual({
context7: { state: 'preparing' },
- puppeteer: { state: 'preparing' },
+ playwright: { state: 'preparing' },
});
// A run still includes servers being prepared
- expect(usableMcpConnectorIds(['context7', 'puppeteer'], undefined)).toEqual(['context7', 'puppeteer']);
+ expect(await usableMcpConnectorIds(['context7', 'playwright'], undefined)).toEqual(['context7', 'playwright']);
- await vi.waitFor(() => expect(changes).toEqual({ context7: 'ready', puppeteer: 'unavailable' }));
- expect(getMcpAvailability(['puppeteer'], undefined).puppeteer).toEqual({ state: 'unavailable', message: 'npm error 404 Not Found' });
+ await vi.waitFor(() => expect(changes).toEqual({ context7: 'ready', playwright: 'unavailable' }));
+ expect(getMcpAvailability(['playwright'], undefined).playwright).toEqual({ state: 'unavailable', message: 'npm error 404 Not Found' });
// ...and leaves out the ones that can't start
- expect(usableMcpConnectorIds(['context7', 'puppeteer'], undefined)).toEqual(['context7']);
+ expect(await usableMcpConnectorIds(['context7', 'playwright'], undefined)).toEqual(['context7']);
stop();
});
- it("checks Puppeteer's browser and says how to install it", async () => {
+ it("checks Playwright's browser and says how to install it", async () => {
installed.set('npx', '/usr/bin/npx');
const calls: unknown[] = [];
- servers['-y @modelcontextprotocol/server-puppeteer'] = (proc) => {
+ servers[PW] = (proc) => {
proc.stdin.write.mockImplementation((line: string) => {
const message = JSON.parse(line);
calls.push(message);
@@ -100,25 +137,73 @@ describe('MCP availability', () => {
proc.stdout.emit('data', Buffer.from(JSON.stringify({
jsonrpc: '2.0',
id: 2,
- error: { code: -32603, message: 'Could not find Chrome (ver. 131.0.6778.204). This can occur if either\n 1. you did not install it' },
+ result: { isError: true, content: [{ type: 'text', text: NOT_INSTALLED }] },
}) + '\n'));
}
});
answer(proc);
};
const settings = { customServers: [] };
- getMcpAvailability(['puppeteer'], settings);
- await vi.waitFor(() => expect(getMcpAvailability(['puppeteer'], settings).puppeteer.state).toBe('unavailable'));
- expect(getMcpAvailability(['puppeteer'], settings).puppeteer).toEqual({
+ getMcpAvailability(['playwright'], settings);
+ await vi.waitFor(() => expect(getMcpAvailability(['playwright'], settings).playwright.state).toBe('unavailable'));
+ expect(getMcpAvailability(['playwright'], settings).playwright).toEqual({
state: 'unavailable',
- message: 'Could not find Chrome (ver. 131.0.6778.204)',
- fixCommand: 'npx puppeteer browsers install chrome@131.0.6778.204',
+ message: 'Browser "chrome-for-testing" is not installed; expected executable at /home/me/.cache/ms-playwright/chromium-1247/chrome-linux64/chrome',
+ // The install the pinned server needs, not the one its message names
+ fixCommand: `npx -y ${PACKAGE} install-browser chromium`,
});
- // It opened a blank page in a hidden browser
+ // It opened a blank page in a headless Chromium of Playwright's, with a profile in memory
expect(calls).toContainEqual(expect.objectContaining({
method: 'tools/call',
- params: { name: 'puppeteer_navigate', arguments: { url: 'about:blank', launchOptions: { headless: true } } },
+ params: { name: 'browser_navigate', arguments: { url: 'about:blank' } },
}));
+ expect(mocks.spawnTool.mock.calls[0][1]).toEqual(['-y', PACKAGE, '--browser', 'chromium', '--isolated', '--sandbox', '--headless', '--output-dir', PROBE_DIR]);
+ // Its folder for Playwright's files goes once the server has stopped
+ await vi.waitFor(() => expect(existsSync(mocks.spawnTool.mock.calls[0][1].at(-1) as string)).toBe(false), { timeout: 10_000 });
+ }, 20_000);
+
+ it('checks the chosen browser, offers no install command, and checks again for another choice', async () => {
+ installed.set('npx', '/usr/bin/npx');
+ servers[PW] = (proc) => {
+ proc.stdin.write.mockImplementation((line: string) => {
+ if (JSON.parse(line).method === 'tools/call') {
+ proc.stdout.emit('data', Buffer.from(JSON.stringify({
+ jsonrpc: '2.0',
+ id: 2,
+ error: { code: -32603, message: 'Browser was not found at the configured executablePath (/opt/gone/chrome)' },
+ }) + '\n'));
+ }
+ });
+ answer(proc);
+ };
+ const choice = {
+ id: 'chrome:Default', browser: 'chrome' as const, engine: 'chromium' as const, profileName: 'Me',
+ executablePath: '/opt/gone/chrome', userDataDir: '/home/me/.config/google-chrome', profileDirectory: 'Default',
+ profilePath: '/home/me/.config/google-chrome/Default',
+ };
+ const settings = { playwrightBrowser: choice };
+ getMcpAvailability(['playwright'], settings);
+ await vi.waitFor(() => expect(getMcpAvailability(['playwright'], settings).playwright.state).toBe('unavailable'));
+ expect(getMcpAvailability(['playwright'], settings).playwright).toEqual({
+ state: 'unavailable',
+ message: 'Browser was not found at the configured executablePath (/opt/gone/chrome)',
+ });
+ // The chosen executable reaches the server, never a profile folder
+ expect(mocks.spawnTool.mock.calls[0][1]).toEqual(
+ ['-y', PACKAGE, '--browser', 'chrome', '--executable-path', '/opt/gone/chrome', '--isolated', '--headless', '--output-dir', PROBE_DIR]
+ );
+
+ servers[PW] = (proc) => {
+ proc.stdin.write.mockImplementation((line: string) => {
+ if (JSON.parse(line).method === 'tools/call') {
+ proc.stdout.emit('data', Buffer.from('{"jsonrpc":"2.0","id":2,"result":{"content":[]}}\n'));
+ }
+ });
+ answer(proc);
+ };
+ const other = { playwrightBrowser: { ...choice, id: 'chrome:Profile 1', executablePath: '/opt/google/chrome/chrome' } };
+ expect(getMcpAvailability(['playwright'], other).playwright).toEqual({ state: 'preparing' });
+ await vi.waitFor(() => expect(getMcpAvailability(['playwright'], other).playwright.state).toBe('ready'));
});
it('names the missing command', async () => {
@@ -159,8 +244,8 @@ describe('MCP availability', () => {
it('stops probes still running (on app quit)', async () => {
installed.set('npx', '/usr/bin/npx');
// A server that never answers
- servers['-y @modelcontextprotocol/server-puppeteer'] = () => undefined;
- getMcpAvailability(['puppeteer'], undefined);
+ servers[PW] = () => undefined;
+ getMcpAvailability(['playwright'], undefined);
await vi.waitFor(() => expect(mocks.spawnTool).toHaveBeenCalledTimes(1));
const proc = mocks.spawnTool.mock.results[0].value as FakeProcess;
stopMcpProbes();
@@ -173,30 +258,30 @@ describe('MCP availability', () => {
it('checks an unavailable server again after a while, keeping ready ones', async () => {
installed.set('npx', '/usr/bin/npx');
servers['-y @upstash/context7-mcp@latest'] = answer;
- servers['-y @modelcontextprotocol/server-puppeteer'] = crash;
+ servers[PW] = crash;
let now = 1_000_000;
vi.spyOn(Date, 'now').mockImplementation(() => now);
- getMcpAvailability(['context7', 'puppeteer'], undefined);
- await vi.waitFor(() => expect(usableMcpConnectorIds(['context7', 'puppeteer'], undefined)).toEqual(['context7']));
+ getMcpAvailability(['context7', 'playwright'], undefined);
+ await vi.waitFor(async () => expect(await usableMcpConnectorIds(['context7', 'playwright'], undefined)).toEqual(['context7']));
expect(mocks.spawnTool).toHaveBeenCalledTimes(2);
// The user fixed it (the browser opens now): nothing is checked again right away
- servers['-y @modelcontextprotocol/server-puppeteer'] = (proc) => {
+ servers[PW] = (proc) => {
proc.stdin.write.mockImplementation((line: string) => {
if (JSON.parse(line).method === 'tools/call') proc.stdout.emit('data', Buffer.from('{"jsonrpc":"2.0","id":2,"result":{}}\n'));
});
answer(proc);
};
- getMcpAvailability(['context7', 'puppeteer'], undefined);
+ getMcpAvailability(['context7', 'playwright'], undefined);
expect(mocks.spawnTool).toHaveBeenCalledTimes(2);
now += UNAVAILABLE_RECHECK_MS;
// It still reads unavailable (and stays out of runs) while it is checked again...
- expect(getMcpAvailability(['context7', 'puppeteer'], undefined).puppeteer.state).toBe('unavailable');
- expect(usableMcpConnectorIds(['context7', 'puppeteer'], undefined)).toEqual(['context7']);
+ expect(getMcpAvailability(['context7', 'playwright'], undefined).playwright.state).toBe('unavailable');
+ expect(await usableMcpConnectorIds(['context7', 'playwright'], undefined)).toEqual(['context7']);
// ...with the command looked up again
await vi.waitFor(() => expect(mocks.resolveCommand).toHaveBeenLastCalledWith('npx', { refresh: true }));
- await vi.waitFor(() => expect(getMcpAvailability(['puppeteer'], undefined).puppeteer.state).toBe('ready'));
+ await vi.waitFor(() => expect(getMcpAvailability(['playwright'], undefined).playwright.state).toBe('ready'));
// Only the unavailable server was started again
expect(mocks.spawnTool).toHaveBeenCalledTimes(3);
});
@@ -216,21 +301,478 @@ describe('MCP availability', () => {
it("ignores a probe's result that a reset made stale", async () => {
installed.set('npx', '/usr/bin/npx');
- servers['-y @modelcontextprotocol/server-puppeteer'] = () => undefined;
- getMcpAvailability(['puppeteer'], undefined);
+ servers[PW] = () => undefined;
+ getMcpAvailability(['playwright'], undefined);
await vi.waitFor(() => expect(mocks.spawnTool).toHaveBeenCalledTimes(1));
const first = mocks.spawnTool.mock.results[0].value as FakeProcess;
- servers['-y @modelcontextprotocol/server-puppeteer'] = answer;
+ servers[PW] = answer;
resetMcpAvailability();
expect(mocks.killRuntimeProcessTree).toHaveBeenCalledWith(first);
- getMcpAvailability(['puppeteer'], undefined);
+ getMcpAvailability(['playwright'], undefined);
// The stopped probe exits without an answer, which must not count
first.emit('close', null);
await vi.waitFor(() => expect(mocks.spawnTool).toHaveBeenCalledTimes(2));
const second = mocks.spawnTool.mock.results[1].value as FakeProcess;
- // Puppeteer also needs its tool call answered
+ // Playwright also needs its tool call answered
second.stdout.emit('data', Buffer.from('{"jsonrpc":"2.0","id":2,"result":{}}\n'));
- await vi.waitFor(() => expect(getMcpAvailability(['puppeteer'], undefined).puppeteer.state).toBe('ready'));
+ await vi.waitFor(() => expect(getMcpAvailability(['playwright'], undefined).playwright.state).toBe('ready'));
+ });
+ it("leaves Playwright out while its chosen browser is open, and back in once it's closed", async () => {
+ installed.set('npx', '/usr/bin/npx');
+ servers[PW] = (proc) => {
+ proc.stdin.write.mockImplementation((line: string) => {
+ if (JSON.parse(line).method === 'tools/call') proc.stdout.emit('data', Buffer.from('{"jsonrpc":"2.0","id":2,"result":{}}\n'));
+ });
+ answer(proc);
+ };
+ const settings = {
+ playwrightBrowser: {
+ id: 'firefox:x.default', browser: 'firefox' as const, engine: 'firefox' as const, profileName: 'default',
+ executablePath: '/usr/lib/firefox/firefox', userDataDir: '/home/me/.mozilla/firefox', profilePath: '/home/me/.mozilla/firefox/x.default',
+ },
+ };
+ getMcpAvailability(['playwright'], settings);
+ await vi.waitFor(() => expect(getMcpAvailability(['playwright'], settings).playwright.state).toBe('ready'));
+
+ mocks.browserOpen = true;
+ expect(await usableMcpConnectorIds(['playwright'], settings)).toEqual([]);
+ expect(getMcpAvailability(['playwright'], settings).playwright).toEqual({ state: 'unavailable', browserOpen: true });
+
+ mocks.browserOpen = false;
+ expect(await usableMcpConnectorIds(['playwright'], settings)).toEqual(['playwright']);
+ stopMcpProbes();
+ });
+
+ const firefoxProfile = {
+ id: 'firefox:x.default', browser: 'firefox' as const, engine: 'firefox' as const, profileName: 'default',
+ executablePath: '/usr/lib/firefox/firefox', userDataDir: '/home/me/.mozilla/firefox', profilePath: '/home/me/.mozilla/firefox/x.default',
+ };
+
+ it("keeps Playwright unavailable when its probe ends while the chosen browser is open", async () => {
+ installed.set('npx', '/usr/bin/npx');
+ let finishProbe: (() => void) | undefined;
+ servers[PW] = (proc) => {
+ proc.stdin.write.mockImplementation((line: string) => {
+ if (JSON.parse(line).method === 'tools/call') {
+ finishProbe = () => proc.stdout.emit('data', Buffer.from('{"jsonrpc":"2.0","id":2,"result":{}}\n'));
+ }
+ });
+ answer(proc);
+ };
+ mocks.browserOpen = true;
+ const settings = { playwrightBrowser: firefoxProfile };
+ const changes: unknown[] = [];
+ const stop = onMcpAvailabilityChange((_id, availability) => changes.push(availability));
+
+ getMcpAvailability(['playwright'], settings);
+ await vi.waitFor(() => expect(changes).toContainEqual({ state: 'unavailable', browserOpen: true }));
+ await vi.waitFor(() => expect(finishProbe).toBeDefined());
+ const before = changes.length;
+ finishProbe?.();
+ await vi.waitFor(() => expect(changes.length).toBeGreaterThan(before));
+ // The server is fine, but the open browser still keeps it out
+ expect(changes.at(-1)).toEqual({ state: 'unavailable', browserOpen: true });
+ expect(getMcpAvailability(['playwright'], settings).playwright).toEqual({ state: 'unavailable', browserOpen: true });
+ stop();
+ stopMcpProbes();
+ });
+
+ it('stops looking at an open browser once another one is chosen', async () => {
+ vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] });
+ try {
+ installed.set('npx', '/usr/bin/npx');
+ servers[PW] = (proc) => {
+ proc.stdin.write.mockImplementation((line: string) => {
+ if (JSON.parse(line).method === 'tools/call') proc.stdout.emit('data', Buffer.from('{"jsonrpc":"2.0","id":2,"result":{}}\n'));
+ });
+ answer(proc);
+ };
+ mocks.browserOpen = true;
+ const profile = { playwrightEnabled: true, playwrightBrowser: firefoxProfile };
+ getMcpAvailability(['playwright'], profile);
+ await vi.waitFor(() => expect(getMcpAvailability(['playwright'], profile).playwright).toEqual({ state: 'unavailable', browserOpen: true }));
+
+ // Playwright's own Firefox is chosen, then the profile's browser closes
+ const managed = {
+ playwrightEnabled: true,
+ playwrightBrowser: {
+ ...firefoxProfile, id: 'playwright:firefox', managed: true, executablePath: '/home/me/.cache/ms-playwright/firefox-1553/firefox/firefox',
+ },
+ };
+ const changes: unknown[] = [];
+ const stop = onMcpAvailabilityChange((_id, availability) => changes.push(availability));
+ getMcpAvailability(['playwright'], managed);
+ await vi.waitFor(() => expect(getMcpAvailability(['playwright'], managed).playwright.state).toBe('ready'));
+ mocks.browserOpen = false;
+ const looks = mocks.inUse.mock.calls.length;
+ await vi.advanceTimersByTimeAsync(10_000);
+
+ // The old profile isn't looked at again, and nothing goes back to its entry
+ expect(mocks.inUse.mock.calls.length).toBe(looks);
+ expect(changes.at(-1)).toEqual({ state: 'ready' });
+ // Playwright's own Firefox build, found by Playwright itself
+ expect(mocks.spawnTool.mock.calls.at(-1)?.[1]).toEqual(['-y', PACKAGE, '--browser', 'firefox', '--isolated', '--headless', '--output-dir', PROBE_DIR]);
+ stop();
+ stopMcpProbes();
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+ /** A Playwright server whose browser call fails with `error`, or succeeds without one */
+ const playwrightServer = (error?: string) => (proc: FakeProcess) => {
+ proc.stdin.write.mockImplementation((line: string) => {
+ if (JSON.parse(line).method !== 'tools/call') return;
+ proc.stdout.emit('data', Buffer.from(JSON.stringify(error
+ ? { jsonrpc: '2.0', id: 2, error: { code: -32603, message: error } }
+ : { jsonrpc: '2.0', id: 2, result: {} }) + '\n'));
+ });
+ answer(proc);
+ };
+
+ it("offers a download only when Playwright's browser isn't downloaded", async () => {
+ installed.set('npx', '/usr/bin/npx');
+ servers[PW] = playwrightServer(
+ 'Failed to launch the browser process! [0101/000000.000:FATAL:zygote_host_impl_linux.cc(127)] No usable sandbox!'
+ );
+ getMcpAvailability(['playwright'], undefined);
+ await vi.waitFor(() => expect(getMcpAvailability(['playwright'], undefined).playwright.state).toBe('unavailable'));
+ const launchFailure = getMcpAvailability(['playwright'], undefined).playwright;
+ expect(launchFailure.fixCommand).toBeUndefined();
+ expect(launchFailure.message).toContain('Failed to launch the browser process');
+
+ resetMcpAvailability();
+ // Playwright's own Firefox, chosen and not downloaded
+ servers[PW] = playwrightServer('Browser "firefox" is not installed; expected executable at /f. Run `npx @playwright/mcp install-browser firefox` to install');
+ const managed = { playwrightBrowser: { ...firefoxProfile, id: 'playwright:firefox', managed: true, executablePath: '/f' } };
+ getMcpAvailability(['playwright'], managed);
+ await vi.waitFor(() => expect(getMcpAvailability(['playwright'], managed).playwright.state).toBe('unavailable'));
+ expect(getMcpAvailability(['playwright'], managed).playwright.fixCommand).toBe(`npx -y ${PACKAGE} install-browser firefox`);
+ });
+
+ it('keeps the latest choice when the browser is switched back while its first check runs', async () => {
+ installed.set('npx', '/usr/bin/npx');
+ // Each probe waits until the test answers it
+ const pending: Array<() => void> = [];
+ servers[PW] = (proc) => {
+ proc.stdin.write.mockImplementation((line: string) => {
+ if (JSON.parse(line).method === 'tools/call') {
+ pending.push(() => proc.stdout.emit('data', Buffer.from('{"jsonrpc":"2.0","id":2,"result":{}}\n')));
+ }
+ });
+ answer(proc);
+ };
+ const a = { playwrightBrowser: { ...firefoxProfile, id: 'playwright:firefox', managed: true, executablePath: '/a/firefox' } };
+ const b = { playwrightBrowser: { ...firefoxProfile, id: 'playwright:webkit', browser: 'webkit' as const, engine: 'webkit' as const, managed: true, executablePath: '/b/webkit' } };
+ const changes: string[] = [];
+ const stop = onMcpAvailabilityChange((_id, availability) => changes.push(availability.state));
+
+ expect(getMcpAvailability(['playwright'], a).playwright.state).toBe('preparing');
+ await vi.waitFor(() => expect(pending).toHaveLength(1));
+ expect(getMcpAvailability(['playwright'], b).playwright.state).toBe('preparing');
+ await vi.waitFor(() => expect(pending).toHaveLength(2));
+ // Back to A, whose first check is still running: no second check of A
+ expect(getMcpAvailability(['playwright'], a).playwright.state).toBe('preparing');
+ expect(mocks.spawnTool).toHaveBeenCalledTimes(2);
+
+ // B finishes first: it no longer counts
+ pending[1]();
+ await new Promise((resolve) => setTimeout(resolve, 10));
+ expect(getMcpAvailability(['playwright'], a).playwright.state).toBe('preparing');
+ expect(changes.at(-1)).toBe('preparing');
+ // A's result is the one kept and sent
+ pending[0]();
+ await vi.waitFor(() => expect(changes.at(-1)).toBe('ready'));
+ expect(getMcpAvailability(['playwright'], a).playwright.state).toBe('ready');
+ stop();
+ stopMcpProbes();
+ });
+
+ it('keeps looking at an open browser chosen again within moments', async () => {
+ vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] });
+ try {
+ installed.set('npx', '/usr/bin/npx');
+ servers[PW] = playwrightServer();
+ mocks.browserOpen = true;
+ const profile = { playwrightEnabled: true, playwrightBrowser: firefoxProfile };
+ const managed = { playwrightEnabled: true, playwrightBrowser: { ...firefoxProfile, id: 'playwright:firefox', managed: true, executablePath: '/m/firefox' } };
+ getMcpAvailability(['playwright'], profile);
+ await vi.waitFor(() => expect(getMcpAvailability(['playwright'], profile).playwright).toEqual({ state: 'unavailable', browserOpen: true }));
+
+ // Another choice stops the poll; choosing the profile again right away (its open state is
+ // still fresh) starts it again
+ getMcpAvailability(['playwright'], managed);
+ getMcpAvailability(['playwright'], profile);
+ const changes: unknown[] = [];
+ const stop = onMcpAvailabilityChange((_id, availability) => changes.push(availability));
+ mocks.browserOpen = false;
+ await vi.advanceTimersByTimeAsync(5_000);
+ await vi.waitFor(() => expect(changes).toContainEqual(expect.objectContaining({ state: expect.not.stringMatching('unavailable') })));
+ expect(getMcpAvailability(['playwright'], profile).playwright.browserOpen).toBeUndefined();
+ stop();
+ stopMcpProbes();
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it('tells a run, the log and every window when it leaves a connector out', async () => {
+ installed.set('npx', '/usr/bin/npx');
+ servers[PW] = playwrightServer();
+ const settings = { playwrightBrowser: firefoxProfile };
+ getMcpAvailability(['playwright'], settings);
+ await vi.waitFor(() => expect(getMcpAvailability(['playwright'], settings).playwright.state).toBe('ready'));
+
+ mocks.browserOpen = true;
+ const changes: unknown[] = [];
+ const stop = onMcpAvailabilityChange((id, availability) => changes.push([id, availability]));
+ const leftOut: unknown[] = [];
+ expect(await usableMcpConnectorIds(['playwright'], settings, (id, availability) => leftOut.push([id, availability]))).toEqual([]);
+ expect(leftOut).toEqual([['playwright', { state: 'unavailable', browserOpen: true }]]);
+ expect(changes).toContainEqual(['playwright', { state: 'unavailable', browserOpen: true }]);
+ const { appLog } = await import('../app-logger');
+ expect(appLog.info).toHaveBeenCalledWith(expect.stringContaining('Playwright connector left out of this run: Firefox (profile default) is open'));
+ stop();
+ stopMcpProbes();
+ });
+
+ it('leaves Playwright out when its browser is open even if a reset forgot the answer', async () => {
+ installed.set('npx', '/usr/bin/npx');
+ servers[PW] = playwrightServer();
+ const settings = { playwrightBrowser: firefoxProfile };
+ let answerLook: ((open: boolean) => void) | undefined;
+ mocks.inUse.mockImplementation(() => new Promise((resolve) => { answerLook = resolve; }));
+ const usable = usableMcpConnectorIds(['playwright'], settings);
+ await vi.waitFor(() => expect(answerLook).toBeDefined());
+ // Tool paths changed while the lock was looked at
+ resetMcpAvailability();
+ answerLook?.(true);
+ expect(await usable).toEqual([]);
+ // The check it started spawns its server after the folder for Playwright's files is made
+ await vi.waitFor(() => expect(mocks.spawnTool).toHaveBeenCalled());
+ stopMcpProbes();
+ });
+
+ it('describes why a connector was left out', () => {
+ expect(describeLeftOutConnector('py', { state: 'unavailable', missingCommand: 'uvx' }, {
+ customServers: [{ id: 'py', name: 'Py tools', type: 'command', command: 'uvx' }],
+ })).toBe('Py tools connector left out of this run: uvx is not installed');
+ expect(describeLeftOutConnector('context7', { state: 'unavailable', message: 'npm error 404' }, undefined))
+ .toBe('Context7 connector left out of this run: npm error 404');
+ });
+
+ it('gives a probe\'s result to every connector with the same connection details', async () => {
+ installed.set('npx', '/usr/bin/npx');
+ let finish: (() => void) | undefined;
+ servers['-y @upstash/context7-mcp@latest'] = (proc) => {
+ finish = () => answer(proc);
+ };
+ // A custom server with the built-in Context7's command, and two HTTP servers with one URL
+ const settings = {
+ customServers: [
+ { id: 'my-context7', name: 'My Context7', type: 'command' as const, command: 'npx', args: ['-y', '@upstash/context7-mcp@latest'], verified: true },
+ ],
+ };
+ const changes: Array<[string, string]> = [];
+ const stop = onMcpAvailabilityChange((id, availability) => changes.push([id, availability.state]));
+ expect(getMcpAvailability(['context7', 'my-context7'], settings)).toEqual({
+ context7: { state: 'preparing' },
+ 'my-context7': { state: 'preparing' },
+ });
+ await vi.waitFor(() => expect(finish).toBeDefined());
+ // One probe for both
+ expect(mocks.spawnTool).toHaveBeenCalledTimes(1);
+ finish?.();
+ await vi.waitFor(() => expect(getMcpAvailability(['my-context7'], settings)['my-context7'].state).toBe('ready'));
+ expect(getMcpAvailability(['context7'], settings).context7.state).toBe('ready');
+ expect(changes).toContainEqual(['context7', 'ready']);
+ expect(changes).toContainEqual(['my-context7', 'ready']);
+ stop();
+
+ const fetchMock = vi.spyOn(globalThis, 'fetch').mockResolvedValue(new Response('', { status: 405 }));
+ const http = {
+ customServers: [
+ { id: 'one', name: 'One', type: 'http' as const, url: 'http://localhost:9000/mcp', verified: true },
+ { id: 'two', name: 'Two', type: 'http' as const, url: 'http://localhost:9000/mcp', verified: true },
+ ],
+ };
+ getMcpAvailability(['one', 'two'], http);
+ await vi.waitFor(() => expect(getMcpAvailability(['one', 'two'], http)).toEqual({ one: { state: 'ready' }, two: { state: 'ready' } }));
+ expect(fetchMock).toHaveBeenCalledTimes(1);
+ });
+
+ const chromeProfile = {
+ id: 'chrome:Default', browser: 'chrome' as const, engine: 'chromium' as const, profileName: 'Default',
+ executablePath: '/usr/bin/google-chrome', userDataDir: '/home/me/.config/google-chrome', profilePath: '/home/me/.config/google-chrome/Default',
+ };
+
+ it("keeps each browser's open state: a late look at the old choice doesn't change the new one's", async () => {
+ installed.set('npx', '/usr/bin/npx');
+ servers[PW] = playwrightServer();
+ const looks = new Map void>();
+ mocks.inUse.mockImplementation((browser: { id: string }) => new Promise((resolve) => looks.set(browser.id, resolve)));
+ const a = { playwrightBrowser: firefoxProfile };
+ const b = { playwrightBrowser: chromeProfile };
+
+ getMcpAvailability(['playwright'], a);
+ getMcpAvailability(['playwright'], b);
+ await vi.waitFor(() => expect([...looks.keys()]).toEqual([firefoxProfile.id, chromeProfile.id]));
+ looks.get(chromeProfile.id)?.(false);
+ await vi.waitFor(() => expect(getMcpAvailability(['playwright'], b).playwright.state).toBe('ready'));
+ // A (no longer chosen) turns out open: B stays usable
+ looks.get(firefoxProfile.id)?.(true);
+ await new Promise((resolve) => setTimeout(resolve, 10));
+ expect(getMcpAvailability(['playwright'], b).playwright).toEqual({ state: 'ready' });
+ stopMcpProbes();
+ });
+
+ it("lets a run with older settings look at its browser without changing the chosen one", async () => {
+ vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] });
+ try {
+ installed.set('npx', '/usr/bin/npx');
+ servers[PW] = playwrightServer();
+ const open = new Set([chromeProfile.id]);
+ mocks.inUse.mockImplementation(async (browser: { id: string }) => open.has(browser.id));
+ const older = { playwrightEnabled: true, playwrightBrowser: firefoxProfile };
+ const latest = { playwrightEnabled: true, playwrightBrowser: chromeProfile };
+ // The user chose B (open): it is looked at every few seconds
+ getMcpAvailability(['playwright'], latest);
+ await vi.waitFor(() => expect(getMcpAvailability(['playwright'], latest).playwright).toEqual({ state: 'unavailable', browserOpen: true }));
+
+ // A run started with A looks at A only
+ expect(await usableMcpConnectorIds(['playwright'], older)).toEqual(['playwright']);
+ const changes: unknown[] = [];
+ const stop = onMcpAvailabilityChange((_id, availability) => changes.push(availability));
+ // B's poll goes on: closing B enables the connector
+ open.clear();
+ await vi.advanceTimersByTimeAsync(5_000);
+ expect(mocks.inUse.mock.calls.filter(([browser]) => browser.id === chromeProfile.id).length).toBeGreaterThan(1);
+ await vi.waitFor(() => expect(changes.at(-1)).toEqual(expect.objectContaining({ state: expect.not.stringMatching('unavailable') })));
+ stop();
+ stopMcpProbes();
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it("looks at a task's own browser for its run, leaving the windows' result alone", async () => {
+ installed.set('npx', '/usr/bin/npx');
+ servers[PW] = playwrightServer();
+ const open = new Set();
+ mocks.inUse.mockImplementation(async (browser: { id: string }) => open.has(browser.id));
+ const settings = { playwrightEnabled: true, playwrightBrowser: chromeProfile };
+ getMcpAvailability(['playwright'], settings);
+ await vi.waitFor(() => expect(getMcpAvailability(['playwright'], settings).playwright.state).toBe('ready'));
+
+ // The task's browser is open: its run leaves Playwright out, the windows still read it ready
+ open.add(firefoxProfile.id);
+ const changes: unknown[] = [];
+ const stop = onMcpAvailabilityChange((_id, availability) => changes.push(availability));
+ expect(await usableMcpConnectorIds(['playwright'], settings, undefined, firefoxProfile)).toEqual([]);
+ expect(changes).not.toContainEqual({ state: 'unavailable', browserOpen: true });
+ expect(getMcpAvailability(['playwright'], settings).playwright.state).toBe('ready');
+
+ // The Settings browser is open, the task's isn't (or the task uses Playwright's own Chromium)
+ open.clear();
+ open.add(chromeProfile.id);
+ expect(await usableMcpConnectorIds(['playwright'], settings)).toEqual([]);
+ expect(await usableMcpConnectorIds(['playwright'], settings, undefined, firefoxProfile)).toEqual(['playwright']);
+ expect(await usableMcpConnectorIds(['playwright'], settings, undefined, null)).toEqual(['playwright']);
+ stop();
+ stopMcpProbes();
+ });
+
+ it("checks a task's own browser with its own probe, not the Settings browser's", async () => {
+ installed.set('npx', '/usr/bin/npx');
+ // Playwright's own Chromium and Firefox aren't downloaded; the installed Chrome works
+ servers[PW] = (proc, args) => playwrightServer(args.includes('--executable-path') ? undefined : 'Browser "firefox" is not installed')(proc);
+ const managedFirefox = { ...firefoxProfile, id: 'playwright:firefox', managed: true, executablePath: '/f' };
+ const changes: unknown[] = [];
+ const stop = onMcpAvailabilityChange((_id, availability) => changes.push(availability));
+
+ // Settings: Playwright's Chromium, unavailable. The task picked Chrome: its run isn't dropped for it
+ const settings = { playwrightEnabled: true };
+ getMcpAvailability(['playwright'], settings);
+ await vi.waitFor(() => expect(getMcpAvailability(['playwright'], settings).playwright.state).toBe('unavailable'));
+ expect(await usableMcpConnectorIds(['playwright'], settings, undefined, chromeProfile)).toEqual(['playwright']);
+
+ // Settings: Chrome, ready. The task picked Playwright's Firefox, not downloaded: its run leaves it out
+ const chrome = { playwrightEnabled: true, playwrightBrowser: chromeProfile };
+ getMcpAvailability(['playwright'], chrome);
+ await vi.waitFor(() => expect(getMcpAvailability(['playwright'], chrome).playwright.state).toBe('ready'));
+ expect(await usableMcpConnectorIds(['playwright'], chrome, undefined, managedFirefox)).toEqual(['playwright']);
+ await vi.waitFor(async () => expect(await usableMcpConnectorIds(['playwright'], chrome, undefined, managedFirefox)).toEqual([]));
+ // The windows' result stays the Settings browser's
+ expect(getMcpAvailability(['playwright'], chrome).playwright.state).toBe('ready');
+ expect(changes.filter((change) => (change as { state: string }).state === 'preparing')).toHaveLength(2);
+ stop();
+ stopMcpProbes();
+ });
+
+ it('keeps looking at an open browser while Playwright is off, so closing it enables the switch', async () => {
+ vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] });
+ try {
+ installed.set('npx', '/usr/bin/npx');
+ servers[PW] = playwrightServer();
+ mocks.browserOpen = true;
+ // Off by default: its switch is disabled while the browser is open, so it can't be switched on first
+ const off = { playwrightBrowser: firefoxProfile };
+ const changes: Array<[string, string]> = [];
+ const stop = onMcpAvailabilityChange((id, availability) => changes.push([id, availability.state]));
+ getMcpAvailability(['playwright'], off);
+ await vi.waitFor(() => expect(getMcpAvailability(['playwright'], off).playwright).toEqual({ state: 'unavailable', browserOpen: true }));
+ // The server's probe has ended (its folder for Playwright's files, made and removed on disk, is gone).
+ // The folder goes a second after the server exits; waitFor moves the fake clock 50ms a try, so
+ // that second takes about one of real time, and slow runners (Windows) need more than the default
+ await vi.waitFor(() => {
+ expect(mocks.spawnTool).toHaveBeenCalled();
+ expect(existsSync(mocks.spawnTool.mock.calls[0][1].at(-1) as string)).toBe(false);
+ }, { timeout: 10_000 });
+ const looks = mocks.inUse.mock.calls.length;
+ await vi.advanceTimersByTimeAsync(10_000);
+ expect(mocks.inUse.mock.calls.length).toBeGreaterThan(looks + 1);
+
+ // Closed: the next look sends the change, with no window asking again
+ changes.length = 0;
+ mocks.browserOpen = false;
+ await vi.advanceTimersByTimeAsync(4_000);
+ expect(changes).toContainEqual(['playwright', 'ready']);
+ // And the looks stop once it is closed
+ const closedLooks = mocks.inUse.mock.calls.length;
+ await vi.advanceTimersByTimeAsync(20_000);
+ expect(mocks.inUse.mock.calls.length).toBe(closedLooks);
+ stop();
+ stopMcpProbes();
+ } finally {
+ vi.useRealTimers();
+ }
+ }, 20_000);
+
+ it("never lets a server that was only started vouch for Playwright's browser", async () => {
+ installed.set('npx', '/usr/bin/npx');
+ const calls: string[] = [];
+ servers[PW] = (proc) => {
+ proc.stdin.write.mockImplementation((line: string) => {
+ const { method } = JSON.parse(line);
+ calls.push(method);
+ if (method === 'tools/call') {
+ proc.stdout.emit('data', Buffer.from(JSON.stringify({ jsonrpc: '2.0', id: 2, error: { code: -32603, message: 'Failed to launch the browser process' } }) + '\n'));
+ }
+ });
+ answer(proc);
+ };
+ // A custom server with the built-in Playwright's command line: it is ready once it starts
+ const settings = {
+ customServers: [
+ { id: 'my-playwright', name: 'My Playwright', type: 'command' as const, command: 'npx', args: ['-y', PACKAGE, '--browser', 'chromium', '--isolated', '--sandbox', '--headless'], verified: true },
+ ],
+ };
+ getMcpAvailability(['my-playwright', 'playwright'], settings);
+ await vi.waitFor(() => expect(getMcpAvailability(['my-playwright'], settings)['my-playwright'].state).toBe('ready'));
+ // The built-in one gets its own probe, which asks for a browser
+ await vi.waitFor(() => expect(getMcpAvailability(['playwright'], settings).playwright.state).toBe('unavailable'));
+ expect(mocks.spawnTool).toHaveBeenCalledTimes(2);
+ expect(calls).toContain('tools/call');
+ stopMcpProbes();
});
});
diff --git a/src/main/__tests__/task-changelog.test.ts b/src/main/__tests__/task-changelog.test.ts
index f99a82e70..f9c7cb76c 100644
--- a/src/main/__tests__/task-changelog.test.ts
+++ b/src/main/__tests__/task-changelog.test.ts
@@ -89,10 +89,18 @@ describe('buildParallelTasksPrompt', () => {
const prompt = await buildParallelTasksPrompt(changelog, '001-self', specsDir, changelog, { projectId: 'p1', tools: true });
expect(prompt).toContain(`- \`002-coding\`, session \`${taskSessionName('p1', '002-coding')}\`, In Progress`);
- expect(prompt).toContain('`list_parallel_tasks` (the changelog is the fallback)');
+ expect(prompt).toContain('`list_parallel_tasks` for the live picture');
+ expect(prompt).toContain('agree with that task via `message_task` on who changes what');
+ expect(prompt).toContain('sends a `[Workbench]` notice naming the file and lines when your changes actually conflict');
const plain = await buildParallelTasksPrompt(changelog, '001-self', specsDir);
expect(plain).not.toContain('session `');
expect(plain).not.toContain('list_parallel_tasks');
+ expect(plain).not.toContain('message_task');
+ // Shared files are fine: only edits to the same lines conflict
+ for (const text of [prompt, plain]) {
+ expect(text).toContain('Edit whatever files your task needs, including files other tasks change');
+ expect(text).not.toContain('leave those files alone');
+ }
});
it('says so when no other task has unmerged changes, also without a changelog yet', async () => {
diff --git a/src/main/__tests__/temp-folders.test.ts b/src/main/__tests__/temp-folders.test.ts
new file mode 100644
index 000000000..4838b7a93
--- /dev/null
+++ b/src/main/__tests__/temp-folders.test.ts
@@ -0,0 +1,65 @@
+import os, { hostname } from 'os';
+import path from 'path';
+import { existsSync } from 'fs';
+import { mkdir, mkdtemp, rm, utimes, writeFile } from 'fs/promises';
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
+
+vi.mock('../app-logger', () => ({ appLog: { warn: vi.fn(), info: vi.fn() } }));
+
+import { makeTempFolder, noteTempFolderRun, removeLeftoverTempFolders, removeTempFolder, TEMP_FOLDER_PREFIXES } from '../temp-folders';
+import { OWNER_FILE, processIdentity } from '../folder-owner';
+
+/** A process id nothing runs as */
+const DEAD_PID = 2 ** 22 + 12345;
+
+let parent: string;
+
+async function folder(name: string, owner?: object): Promise {
+ const dir = path.join(parent, name);
+ await mkdir(dir, { recursive: true });
+ if (owner) await writeFile(path.join(dir, OWNER_FILE), JSON.stringify(owner));
+ return dir;
+}
+
+describe('Workbench temp folders', () => {
+ beforeEach(async () => {
+ parent = await mkdtemp(path.join(os.tmpdir(), 'wb-temp-folders-'));
+ });
+ afterEach(async () => {
+ await rm(parent, { recursive: true, force: true });
+ });
+
+ it('makes a folder owned by this process and removes it', async () => {
+ const dir = await makeTempFolder(TEMP_FOLDER_PREFIXES.task, parent);
+ expect(path.basename(dir).startsWith('workbench-task-')).toBe(true);
+ expect(existsSync(path.join(dir, OWNER_FILE))).toBe(true);
+ await removeTempFolder(dir);
+ expect(existsSync(dir)).toBe(false);
+ });
+
+ it('removes only what no running Workbench or run holds', async () => {
+ const own = await makeTempFolder(TEMP_FOLDER_PREFIXES.chatTurn, parent);
+ const crashed = await folder('workbench-task-crashed', { pid: DEAD_PID, host: hostname() });
+ const otherWorkbench = await folder('workbench-insights-other', await processIdentity(process.ppid));
+ const runGoesOn = await folder('workbench-task-running', { pid: DEAD_PID, host: hostname() });
+ await noteTempFolderRun(runGoesOn, process.ppid);
+ const runEnded = await folder('workbench-insights-ended', { pid: DEAD_PID, host: hostname() });
+ await noteTempFolderRun(runEnded, DEAD_PID);
+ const unownedNew = await folder('workbench-mcp-probe-new');
+ const unownedOld = await folder('workbench-mcp-probe-old');
+ const twoHoursAgo = new Date(Date.now() - 2 * 60 * 60 * 1000);
+ await utimes(unownedOld, twoHoursAgo, twoHoursAgo);
+ const chatBrowser = await folder('workbench-chat-browser-x', { pid: DEAD_PID, host: hostname() });
+ const notOurs = await folder('something-else', { pid: DEAD_PID, host: hostname() });
+
+ const removed = await removeLeftoverTempFolders({ parent, skip: [TEMP_FOLDER_PREFIXES.chatBrowser] });
+
+ expect(removed.sort()).toEqual([crashed, runEnded, unownedOld].sort());
+ for (const dir of [own, otherWorkbench, runGoesOn, unownedNew, chatBrowser, notOurs]) expect(existsSync(dir)).toBe(true);
+ await removeTempFolder(own);
+ });
+
+ it('has nothing to do without the temp folder', async () => {
+ expect(await removeLeftoverTempFolders({ parent: path.join(parent, 'missing') })).toEqual([]);
+ });
+});
diff --git a/src/main/agent/agent-manager.test.ts b/src/main/agent/agent-manager.test.ts
index 904f29589..90e1da648 100644
--- a/src/main/agent/agent-manager.test.ts
+++ b/src/main/agent/agent-manager.test.ts
@@ -1,7 +1,7 @@
/**
* Tests for AgentManager: wiring of ClaudeTaskRun (Claude Code task runner) to manager events
*/
-import { describe, it, expect, vi, beforeEach } from 'vitest';
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import path from 'path';
import type { Project, Task } from '../../shared/types';
import type { TaskRunCallbacks, TaskRunConfig, TaskRunOutcome } from '../claude-code/task-runner';
@@ -15,8 +15,29 @@ interface MockRun {
const runs: MockRun[] = [];
-// Runs leave out MCP servers that can't start; tests don't start any
-vi.mock('../mcp-availability', () => ({ usableMcpConnectorIds: (ids: string[]) => ids }));
+// Runs leave out MCP servers that can't start; tests don't start any. `leftOut` connectors are
+// left out as if their browser were open
+const connectorMocks = vi.hoisted(() => ({
+ leftOut: new Set(),
+ /** The run's own Playwright browser each call was given (a task's choice) */
+ runBrowsers: [] as unknown[],
+}));
+vi.mock('../mcp-availability', () => ({
+ usableMcpConnectorIds: async (
+ ids: string[],
+ _settings: unknown,
+ onLeftOut?: (id: string, availability: unknown) => void,
+ runBrowser?: unknown
+ ) => {
+ connectorMocks.runBrowsers.push(runBrowser);
+ return ids.filter((id) => {
+ if (!connectorMocks.leftOut.has(id)) return true;
+ onLeftOut?.(id, { state: 'unavailable', browserOpen: true });
+ return false;
+ });
+ },
+ describeLeftOutConnector: (id: string) => `${id} connector left out of this run: the browser is open`,
+}));
vi.mock('../claude-code/task-runner', () => ({
ClaudeTaskRun: class {
private resolve!: (outcome: TaskRunOutcome) => void;
@@ -46,6 +67,21 @@ vi.mock('../settings-utils', () => ({
readSettingsFile: vi.fn(() => ({ claudeCodeTasks: { triage: 'fixed', fixedModel: 'opus' } })),
}));
+// The profiles still chosen (Settings and other tasks), which a copy's sweep keeps
+vi.mock('../browser-profiles/choices-in-use', () => ({
+ browserChoicesInUse: vi.fn(async (_projectPath: string, settingsChoice: unknown) => ({
+ project: settingsChoice ? [settingsChoice] : [],
+ all: settingsChoice ? [settingsChoice] : [],
+ })),
+}));
+
+// Copies of the Playwright connector's browser profile: a folder per run, nothing on disk
+vi.mock('../browser-profiles/profile-copy', () => ({
+ prepareBrowserProfileCopy: vi.fn(async (_projectPath: string, choice: { id: string }, slot: string) => `/copies/${choice.id}/${slot}`),
+ removeBrowserProfileCopy: vi.fn(async () => undefined),
+ removeStaleBrowserProfileCopies: vi.fn(async () => undefined),
+}));
+
vi.mock('../graphify', () => ({
getGraphifyPromptContext: vi.fn(async () => null),
isGraphifyEnabled: vi.fn(async () => false),
@@ -236,6 +272,109 @@ describe('AgentManager', () => {
}
});
+ it("says in the task's log when a chosen connector is left out of the run", async () => {
+ connectorMocks.leftOut.add('playwright');
+ try {
+ const logs: string[] = [];
+ manager.on('log', (_taskId: string, line: string) => logs.push(line));
+ const task = makeTask({ metadata: { mcpConnectors: ['context7', 'playwright'] } } as Partial);
+ await manager.startTask(task.id, { project, task, mode: 'start' });
+ const run = await nextRun(1);
+
+ expect(run.config.connectorIds).toEqual(['context7']);
+ expect(logs).toContain('playwright connector left out of this run: the browser is open\n');
+ // Handed to the run, whose own log writer saves it in task_logs.json
+ expect(run.config.startNotes).toEqual([{ phase: 'planning', line: 'playwright connector left out of this run: the browser is open' }]);
+ } finally {
+ connectorMocks.leftOut.clear();
+ }
+ });
+
+ it('logs a left-out connector under the step the run starts with', async () => {
+ const { loadClaudeRunInfo } = await import('../claude-code/task-runner');
+ // The last run stopped in validation
+ vi.mocked(loadClaudeRunInfo).mockReturnValue({ phases: [{ name: 'validate' }] } as unknown as ReturnType);
+ connectorMocks.leftOut.add('playwright');
+ const line = 'playwright connector left out of this run: the browser is open';
+ try {
+ const task = makeTask({ metadata: { mcpConnectors: ['playwright'] } } as Partial);
+ // A change request begins with coding
+ await manager.startTask(task.id, { project, task, mode: 'revise', feedback: 'Fix it' });
+ expect((await nextRun(1)).config.startNotes).toEqual([{ phase: 'coding', line }]);
+
+ // So does a resync (its merge is logged under coding)
+ pendingResync.value = { ref: 'develop', into: 'develop', via: 'local', merged: [], at: '2026-10-01T00:00:00Z' };
+ const other = makeTask({ id: '002-other', specId: '002-other', status: 'human_review', metadata: { mcpConnectors: ['playwright'] } } as Partial);
+ await manager.startTask(other.id, { project, task: other, mode: 'start' });
+ expect((await nextRun(2)).config.startNotes).toEqual([{ phase: 'coding', line }]);
+ pendingResync.value = undefined;
+
+ // A continued start goes on with validation
+ const third = makeTask({ id: '003-third', specId: '003-third', metadata: { mcpConnectors: ['playwright'] } } as Partial);
+ await manager.startTask(third.id, { project, task: third, mode: 'start' });
+ expect((await nextRun(3)).config.startNotes).toEqual([{ phase: 'validation', line }]);
+ } finally {
+ pendingResync.value = undefined;
+ connectorMocks.leftOut.clear();
+ vi.mocked(loadClaudeRunInfo).mockReturnValue(null);
+ }
+ });
+
+ describe("the Playwright connector's browser profile", () => {
+ const settingsBrowser = { id: 'chrome:Default', browser: 'chrome', engine: 'chromium', profileName: 'Person 1', executablePath: '/chrome', userDataDir: '/c', profilePath: '/c/Default' };
+ const taskBrowser = { id: 'firefox:work', browser: 'firefox', engine: 'firefox', profileName: 'work', executablePath: '/firefox', userDataDir: '/f', profilePath: '/f/work' };
+
+ beforeEach(async () => {
+ const { readSettingsFile } = await import('../settings-utils');
+ vi.mocked(readSettingsFile).mockReturnValue({
+ claudeCodeTasks: { triage: 'fixed', fixedModel: 'opus' },
+ mcpConnectors: { playwrightEnabled: true, playwrightBrowser: settingsBrowser },
+ });
+ connectorMocks.runBrowsers.length = 0;
+ });
+
+ afterEach(async () => {
+ const { readSettingsFile } = await import('../settings-utils');
+ vi.mocked(readSettingsFile).mockReturnValue({ claudeCodeTasks: { triage: 'fixed', fixedModel: 'opus' } });
+ });
+
+ it('follows Settings > Connectors when the task picked none', async () => {
+ const { prepareBrowserProfileCopy } = await import('../browser-profiles/profile-copy');
+ const task = makeTask({ metadata: { mcpConnectors: ['playwright'] } } as Partial);
+ await manager.startTask(task.id, { project, task, mode: 'start' });
+ const run = await nextRun(1);
+ expect(run.config.connectorSettings?.playwrightBrowser).toEqual(settingsBrowser);
+ expect(vi.mocked(prepareBrowserProfileCopy).mock.lastCall?.[1]).toEqual(settingsBrowser);
+ expect(connectorMocks.runBrowsers).toEqual([undefined]);
+ });
+
+ it("uses the task's own browser for the profile copy and the server", async () => {
+ const { prepareBrowserProfileCopy } = await import('../browser-profiles/profile-copy');
+ const task = makeTask({ metadata: { mcpConnectors: ['playwright'], playwrightBrowser: taskBrowser } } as unknown as Partial);
+ await manager.startTask(task.id, { project, task, mode: 'start' });
+ const run = await nextRun(1);
+ expect(run.config.connectorSettings?.playwrightBrowser).toEqual(taskBrowser);
+ expect(vi.mocked(prepareBrowserProfileCopy).mock.lastCall?.[1]).toEqual(taskBrowser);
+ expect(run.config.browserProfileDir).toMatch(/^\/copies\/firefox:work\//);
+ // Its sweep keeps the Settings profile's copies
+ expect(vi.mocked(prepareBrowserProfileCopy).mock.lastCall?.[3]).toEqual({ project: [settingsBrowser], all: [settingsBrowser] });
+ // Availability looks at the task's browser
+ expect(connectorMocks.runBrowsers).toEqual([taskBrowser]);
+ });
+
+ it("uses Playwright's own Chromium when the task picked it", async () => {
+ const { prepareBrowserProfileCopy } = await import('../browser-profiles/profile-copy');
+ vi.mocked(prepareBrowserProfileCopy).mockClear();
+ const task = makeTask({ metadata: { mcpConnectors: ['playwright'], playwrightBrowser: null } } as unknown as Partial);
+ await manager.startTask(task.id, { project, task, mode: 'start' });
+ const run = await nextRun(1);
+ expect(run.config.connectorSettings?.playwrightBrowser).toBeUndefined();
+ expect(run.config.browserProfileDir).toBeUndefined();
+ expect(prepareBrowserProfileCopy).not.toHaveBeenCalled();
+ expect(connectorMocks.runBrowsers).toEqual([null]);
+ });
+ });
+
it('runs in the project directory when worktrees are off', async () => {
const task = makeTask({ metadata: { useWorktree: false } } as Partial);
await manager.startTask(task.id, { project, task, mode: 'start' });
diff --git a/src/main/agent/agent-manager.ts b/src/main/agent/agent-manager.ts
index 26fec89df..27db44050 100644
--- a/src/main/agent/agent-manager.ts
+++ b/src/main/agent/agent-manager.ts
@@ -15,9 +15,12 @@ import { isClaudeRunFinished, loadClaudeRunInfo, resetClaudeRunInfo } from '../c
import { detectClaudeLimitMessage } from '../claude-code/limit';
import { createOrGetWorktree } from '../worktree';
import { addToWorktree } from '../live-agent/project-setup';
-import { usableMcpConnectorIds } from '../mcp-availability';
-import { getDefaultMcpConnectorIds } from '../../shared/utils/mcp-connectors';
-import { readSettingsFile } from '../settings-utils';
+import { describeLeftOutConnector, usableMcpConnectorIds } from '../mcp-availability';
+import type { TaskLogPhase } from '../../shared/types/task';
+import { prepareBrowserProfileCopy, removeBrowserProfileCopy, removeStaleBrowserProfileCopies } from '../browser-profiles/profile-copy';
+import { browserChoicesInUse } from '../browser-profiles/choices-in-use';
+import { getDefaultMcpConnectorIds, getTaskPlaywrightBrowser } from '../../shared/utils/mcp-connectors';
+import { readSettingsFile, readSettingsFileAsync } from '../settings-utils';
import { getGraphifyPromptContext, isGraphifyEnabled } from '../graphify';
import { isSelfImproveEnabled, SELF_IMPROVE_NUDGE } from '../self-improve';
import { getAugmentedEnvAsync } from '../env-utils';
@@ -28,7 +31,7 @@ import { getOperationRegistry } from '../claude-profile/operation-registry';
import { getAPIProfileEnv } from '../services/profile';
import { getSpecsDir } from '../../shared/constants';
import { getTaskWorktreeBranch } from '../../shared/utils/claude-run';
-import type { AppSettings } from '../../shared/types/settings';
+import type { AppSettings, McpConnectorSettings } from '../../shared/types/settings';
import { appLog } from '../app-logger';
import { resolveBaseBranch, resolveDefaultBaseBranch } from '../utils/base-branch';
import { taskHooks } from '../task-hooks';
@@ -212,6 +215,7 @@ export class AgentManager extends EventEmitter {
// Stopped while the worktree was being prepared
if (entry.killed) {
config.messaging?.dispose();
+ if (config.browserProfileDir) await removeBrowserProfileCopy(config.browserProfileDir);
resolveDone();
return;
}
@@ -264,9 +268,11 @@ export class AgentManager extends EventEmitter {
const message = error instanceof Error ? error.message : String(error);
this.handleRunFinished(taskId, entry, { status: 'failed', error: message });
})
- .finally(() => {
+ .finally(async () => {
// The run's Workbench tools stop working with it
config.messaging?.dispose();
+ // Removed before a restart of the task copies the profile again
+ if (config.browserProfileDir) await removeBrowserProfileCopy(config.browserProfileDir);
resolveDone();
});
}
@@ -505,6 +511,14 @@ export class AgentManager extends EventEmitter {
resetClaudeRunInfo(specDir);
}
+ // Connectors the run leaves out, for the start of its task log
+ const startNotes: { phase: TaskLogPhase; line: string }[] = [];
+ // The Playwright connector's browser: the task's own choice, else the one in Settings > Connectors
+ const taskBrowser = task.metadata?.playwrightBrowser;
+ const browser = getTaskPlaywrightBrowser(taskBrowser, settings.mcpConnectors);
+ const connectorSettings: McpConnectorSettings | undefined = taskBrowser === undefined
+ ? settings.mcpConnectors
+ : { ...settings.mcpConnectors, playwrightBrowser: browser };
const config: TaskRunConfig = {
taskId,
projectId: project.id,
@@ -518,12 +532,19 @@ export class AgentManager extends EventEmitter {
description: task.description?.trim() || task.title || task.specId,
attachments,
// The task's connectors (or the defaults), without servers that can't start
- connectorIds: usableMcpConnectorIds(
+ connectorIds: await usableMcpConnectorIds(
Array.isArray(task.metadata?.mcpConnectors) ? task.metadata.mcpConnectors : getDefaultMcpConnectorIds(settings.mcpConnectors),
- settings.mcpConnectors
+ settings.mcpConnectors,
+ (id, availability) => startNotes.push(this.noteLeftOutConnector(
+ taskId, options, specDir, describeLeftOutConnector(id, availability, connectorSettings), resync && mode !== 'revise' ? 'resync' : mode)),
+ taskBrowser === undefined ? undefined : browser ?? null
),
- connectorSettings: settings.mcpConnectors,
+ startNotes,
+ connectorSettings,
settings: taskSettings,
+ // Read again at each step, so switching Task messaging or messages from sessions off reaches a running task
+ readCurrentSettings: async () => resolveClaudeCodeTaskSettings(
+ ((await readSettingsFileAsync()) as Partial | undefined)?.claudeCodeTasks),
maxBudgetUsd: project.settings?.maxBudgetUsd,
changelogPath: project.autoBuildPath ? getTaskChangelogPath(project.path, project.autoBuildPath) : undefined,
mode,
@@ -538,8 +559,27 @@ export class AgentManager extends EventEmitter {
};
if (isSelfImproveEnabled(project.settings)) config.selfImprovePrompt = SELF_IMPROVE_NUDGE;
- // Parallel tasks message each other through Workbench (Settings > Agents)
- if (taskSettings.taskMessaging) config.messaging = createRunMessaging(project.id, task.specId);
+ // The Playwright connector's browser profile: a fresh copy per run (sign-ins as they are now),
+ // in the run's own slot so no two runs share a profile folder
+ if (browser && config.connectorIds?.includes('playwright')) {
+ try {
+ // A slot per run: a stopped run of the task may still be cleaning up its own copy
+ const slot = `task-${task.specId}-${randomUUID().slice(0, 8)}`;
+ // Copies of profiles still chosen (Settings, other tasks) are kept by its sweep
+ const inUse = await browserChoicesInUse(project.path, settings.mcpConnectors?.playwrightBrowser);
+ config.browserProfileDir = (await prepareBrowserProfileCopy(project.path, browser, slot, inUse)) ?? undefined;
+ // Copies earlier runs of the task left behind (a crash); not awaited, the run doesn't need it.
+ // Live runs' copies are kept, such as a newer launch's after this one was stopped mid-copy
+ void removeStaleBrowserProfileCopies(project.path, browser, `task-${task.specId}-`, slot);
+ } catch (error) {
+ appLog.warn(`[AgentManager] Could not copy the browser profile for ${taskId}:`, error);
+ }
+ }
+ // Parallel tasks message each other through Workbench (Settings > Agents). The link is made
+ // whatever the switch says now: the run reads Task messaging again at each step
+ // (`readCurrentSettings`), so switching it on reaches a running task at its next step. The link
+ // opens nothing until a step uses it
+ config.messaging = createRunMessaging(project.id, task.specId);
if (await isGraphifyEnabled(project.path)) {
try {
@@ -623,6 +663,29 @@ export class AgentManager extends EventEmitter {
return next;
}
+ /**
+ * A connector the task chose was left out of this run (its browser is open, its server can't
+ * start): shown in the task's live log now, and returned as a start note that the run writes to
+ * task_logs.json with its own log writer (`TaskRunConfig.startNotes`). The note's log step is the
+ * one the run starts with: a change request and a resync begin with coding (the resync's merge is
+ * logged there), a new run with planning (triage), and a continued one with the step it stopped in
+ */
+ private noteLeftOutConnector(
+ taskId: string, options: StartTaskOptions, specDir: string, line: string, start: 'start' | 'revise' | 'resync'
+ ): { phase: TaskLogPhase; line: string } {
+ this.emit('log', taskId, `${line}\n`, options.project.id);
+ let last: string | undefined;
+ try {
+ last = start === 'start' ? loadClaudeRunInfo(specDir)?.phases.at(-1)?.name : undefined;
+ } catch {
+ // No run state yet: a new run
+ }
+ const phase: TaskLogPhase = start !== 'start' ? 'coding'
+ : last === 'validate' ? 'validation'
+ : last === 'implement' || last === 'revise' || last === 'resync' ? 'coding' : 'planning';
+ return { phase, line };
+ }
+
private emitTaskEvent(taskId: string, options: StartTaskOptions, type: string, payload: Record): void {
const event: TaskEventPayload = {
...payload,
diff --git a/src/main/browser-drawer/__tests__/bridge-framing.test.ts b/src/main/browser-drawer/__tests__/bridge-framing.test.ts
new file mode 100644
index 000000000..8f4f50c3e
--- /dev/null
+++ b/src/main/browser-drawer/__tests__/bridge-framing.test.ts
@@ -0,0 +1,47 @@
+import { describe, it, expect } from 'vitest';
+import { createBridgeMessageReader, encodeBridgeMessage } from '../bridge-framing';
+
+describe('browser bridge framing', () => {
+ it('carries headers and raw bytes, whole or split across chunks', () => {
+ const got: Record[] = [];
+ const read = createBridgeMessageReader((message) => got.push(message));
+ const frame = encodeBridgeMessage({ type: 'frame', pageId: 'p#1', viewers: [3], data: new Uint8Array([255, 216, 0, 87, 66]), width: 800, height: 600 });
+ const pages = encodeBridgeMessage({ type: 'pages', pages: [{ id: 'p#1', title: 'Grüße' }] });
+ const all = Buffer.concat([frame, pages]);
+ // Byte by byte
+ for (let i = 0; i < all.length; i++) read(all.subarray(i, i + 1));
+ // Both at once
+ read(all);
+ expect(got).toHaveLength(4);
+ expect(got[0]).toEqual({ type: 'frame', pageId: 'p#1', viewers: [3], data: new Uint8Array([255, 216, 0, 87, 66]), width: 800, height: 600 });
+ expect(got[1]).toEqual({ type: 'pages', pages: [{ id: 'p#1', title: 'Grüße' }] });
+ expect(got[2]).toEqual(got[0]);
+ expect(got[0].data).toBeInstanceOf(Uint8Array);
+ });
+
+ it('reads a large frame that arrives in many chunks, with messages before and after it in the same chunks', () => {
+ const got: Record[] = [];
+ const read = createBridgeMessageReader((message) => got.push(message));
+ const data = new Uint8Array(1024 * 1024).map((_, i) => i % 251);
+ const all = Buffer.concat([
+ encodeBridgeMessage({ type: 'log', message: 'before' }),
+ encodeBridgeMessage({ type: 'frame', pageId: 'p#1', data, width: 800, height: 600 }),
+ encodeBridgeMessage({ type: 'log', message: 'after' }),
+ ]);
+ // Pipe-sized chunks that cut through every message
+ for (let i = 0; i < all.length; i += 65536) read(all.subarray(i, i + 65536));
+ expect(got.map((message) => message.type)).toEqual(['log', 'frame', 'log']);
+ // Compared as bytes (a deep compare of a megabyte, element by element, takes seconds)
+ expect(Buffer.from(got[1].data as Uint8Array).equals(Buffer.from(data))).toBe(true);
+ expect(got[2]).toEqual({ type: 'log', message: 'after' });
+ });
+
+ it('skips bytes that are not a message', () => {
+ const got: Record[] = [];
+ let noise = 0;
+ const read = createBridgeMessageReader((message) => got.push(message), (skipped) => { noise += skipped; });
+ read(Buffer.concat([Buffer.from('warning: something printed\n'), encodeBridgeMessage({ type: 'log', message: 'x' })]));
+ expect(got).toEqual([{ type: 'log', message: 'x' }]);
+ expect(noise).toBeGreaterThan(0);
+ });
+});
diff --git a/src/main/browser-drawer/__tests__/bridge-process.test.ts b/src/main/browser-drawer/__tests__/bridge-process.test.ts
new file mode 100644
index 000000000..71c1948de
--- /dev/null
+++ b/src/main/browser-drawer/__tests__/bridge-process.test.ts
@@ -0,0 +1,47 @@
+import { describe, it, expect, afterEach } from 'vitest';
+import { mkdtemp, rm } from 'fs/promises';
+import net from 'net';
+import os from 'os';
+import path from 'path';
+import { BrowserBridgeProcess } from '../bridge-process';
+
+describe('browser bridge process', () => {
+ let dir: string | undefined;
+ let bridge: BrowserBridgeProcess | undefined;
+ let server: net.Server | undefined;
+
+ afterEach(async () => {
+ await bridge?.stop();
+ await new Promise((resolve) => (server ? server.close(() => resolve()) : resolve()));
+ if (dir) await rm(dir, { recursive: true, force: true });
+ bridge = undefined;
+ server = undefined;
+ dir = undefined;
+ });
+
+ it('runs the real bridge over stdio: says which endpoints answer, and stops', async () => {
+ dir = await mkdtemp(path.join(os.tmpdir(), 'bridge-test-'));
+ const socket = process.platform === 'win32' ? `\\\\.\\pipe\\workbench-bridge-test-${process.pid}` : path.join(dir, 'live.sock');
+ server = net.createServer((connection) => connection.destroy());
+ await new Promise((resolve) => server!.listen(socket, resolve));
+
+ // The bridge script Workbench ships, run by this Node
+ bridge = new BrowserBridgeProcess({ execPath: process.execPath });
+ await Promise.all([bridge.start(), bridge.start()]);
+ expect(bridge.running).toBe(true);
+
+ const dead = path.join(dir, 'closed.sock');
+ const live = await bridge.probe([socket, dead]);
+ expect(live).toEqual(new Set([socket]));
+
+ const exited = new Promise((resolve) => bridge!.once('exit', resolve));
+ await bridge.stop();
+ expect(bridge.running).toBe(false);
+ await Promise.race([exited, new Promise((r) => setTimeout(r, 2000))]);
+ // Stopped (quitting): a probe doesn't start it again
+ await expect(bridge.probe([socket])).resolves.toBeNull();
+ expect(bridge.running).toBe(false);
+ // Nothing to start: nothing to ask
+ await expect(new BrowserBridgeProcess({ execPath: path.join(dir, 'no-such-node') }).probe([socket])).resolves.toBeNull();
+ }, 20_000);
+});
diff --git a/src/main/browser-drawer/__tests__/browser-bridge.test.ts b/src/main/browser-drawer/__tests__/browser-bridge.test.ts
new file mode 100644
index 000000000..544a962df
--- /dev/null
+++ b/src/main/browser-drawer/__tests__/browser-bridge.test.ts
@@ -0,0 +1,106 @@
+import { describe, it, expect, afterEach } from 'vitest';
+import { mkdtemp, readFile, rm, writeFile } from 'fs/promises';
+import os from 'os';
+import path from 'path';
+import { BrowserBridgeProcess, type BridgeMessage } from '../bridge-process';
+
+/**
+ * A stand-in for a browser's playwright-core, loaded by the real bridge script: one page whose
+ * screencast sends three frames at once (a browser has several on their way) and whose mouse
+ * moves are slow (a busy page), its calls written to calls.log
+ */
+const FAKE_PLAYWRIGHT = `
+const fs = require('fs');
+const path = require('path');
+const log = (entry) => fs.appendFileSync(path.join(__dirname, 'calls.log'), JSON.stringify(entry) + '\\n');
+const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
+let viewport = { width: 800, height: 600 };
+const page = {
+ on() {},
+ url: () => 'about:blank',
+ title: async () => 'Blank',
+ mainFrame: () => null,
+ emulateMedia: async () => {},
+ viewportSize: () => viewport,
+ setViewportSize: async (size) => { viewport = size; },
+ screencast: {
+ start: async ({ onFrame }) => {
+ setTimeout(() => {
+ for (const n of [1, 2, 3]) {
+ Promise.resolve(onFrame({ data: new Uint8Array([n]), viewportWidth: 0, viewportHeight: 0 })).then(() => log({ acked: n }));
+ }
+ }, 50);
+ },
+ stop: async () => {},
+ },
+ mouse: {
+ move: async (x) => { log({ move: x }); await sleep(200); },
+ down: async () => log({ down: true }),
+ up: async () => {},
+ wheel: async (dx, dy) => log({ wheel: dy }),
+ },
+ keyboard: { down: async () => {}, up: async () => {}, insertText: async () => {} },
+ close: async () => {},
+};
+const context = { pages: () => [page], on() {}, newPage: async () => page };
+module.exports = { chromium: { connect: async () => ({ contexts: () => [context], on() {}, close: async () => {} }) } };
+`;
+
+const until = async (check: () => boolean | Promise, ms = 5000) => {
+ const end = Date.now() + ms;
+ while (!(await check())) {
+ if (Date.now() > end) throw new Error('timed out');
+ await new Promise((resolve) => setTimeout(resolve, 20));
+ }
+};
+
+describe('browser bridge script', () => {
+ let dir: string | undefined;
+ let bridge: BrowserBridgeProcess | undefined;
+
+ afterEach(async () => {
+ await bridge?.stop();
+ if (dir) await rm(dir, { recursive: true, force: true });
+ bridge = undefined;
+ dir = undefined;
+ });
+
+ it('sends one frame at a time and merges mouse moves waiting behind a slow one', async () => {
+ dir = await mkdtemp(path.join(os.tmpdir(), 'bridge-script-test-'));
+ const lib = path.join(dir, 'fake-playwright.cjs');
+ await writeFile(lib, FAKE_PLAYWRIGHT);
+ const calls = async () =>
+ (await readFile(path.join(dir!, 'calls.log'), 'utf-8').catch(() => ''))
+ .split('\n')
+ .filter(Boolean)
+ .map((line) => JSON.parse(line) as Record);
+
+ bridge = new BrowserBridgeProcess({ execPath: process.execPath });
+ const frames: number[] = [];
+ let pageId: string | undefined;
+ bridge.on('message', (message: BridgeMessage) => {
+ if (message.type === 'pages' && message.pages[0]) pageId = message.pages[0].id;
+ if (message.type === 'frame') frames.push(message.data[0]);
+ });
+ await bridge.start();
+ bridge.send({ type: 'sessions', sessions: [{ id: 's1', endpoint: 'fake', browserName: 'chromium', playwrightLib: lib }] });
+ await until(() => !!pageId);
+
+ bridge.send({ type: 'view', viewerId: 1, pageId: pageId!, width: 700, height: 500, scale: 1 });
+ await until(() => frames.length === 1);
+ // The next frame waits for the drawer: the second is replaced by the third meanwhile
+ await new Promise((resolve) => setTimeout(resolve, 300));
+ expect(frames).toEqual([1]);
+ expect(await calls()).toContainEqual({ acked: 2 });
+ bridge.send({ type: 'frameAck', pageId: pageId! });
+ await until(() => frames.length === 2);
+ expect(frames).toEqual([1, 3]);
+
+ // Moves sent while the first is slow are merged into the newest; the click follows it
+ for (const x of [1, 2, 3, 4]) bridge.send({ type: 'input', pageId: pageId!, event: { kind: 'mousemove', x, y: 0 } });
+ bridge.send({ type: 'input', pageId: pageId!, event: { kind: 'mousedown', x: 5, y: 0, button: 'left', clickCount: 1 } });
+ await until(async () => (await calls()).some((call) => call.down));
+ const mouse = (await calls()).filter((call) => 'move' in call || 'down' in call);
+ expect(mouse).toEqual([{ move: 1 }, { move: 4 }, { move: 5 }, { down: true }]);
+ });
+});
diff --git a/src/main/browser-drawer/__tests__/browser-drawer-service.test.ts b/src/main/browser-drawer/__tests__/browser-drawer-service.test.ts
new file mode 100644
index 000000000..b5e87fc42
--- /dev/null
+++ b/src/main/browser-drawer/__tests__/browser-drawer-service.test.ts
@@ -0,0 +1,141 @@
+import { describe, it, expect } from 'vitest';
+import { EventEmitter } from 'events';
+import type { PlaywrightBrowserChoice } from '../../../shared/types/browser-profiles';
+import { BrowserDrawerService, bridgeSessions, frameScale, isDrawerInput, toDrawerSessions, viewportDimension } from '../browser-drawer-service';
+import type { BrowserBridgeProcess } from '../bridge-process';
+import type { WebContents } from 'electron';
+import type { RegistryDescriptor } from '../registry';
+
+const descriptors: RegistryDescriptor[] = [
+ { guid: 'task', title: 'claude-code', browserName: 'chromium', workspaceDir: '/work/app/.workbench/worktrees/tasks/001', endpoint: '/s/task.sock', playwrightLib: '/npx/a/playwright-core' },
+ { guid: 'chat', title: 'claude-code', browserName: 'firefox', workspaceDir: '/tmp/workbench-insights-x/playwright', endpoint: '/s/chat.sock', playwrightLib: '/npx/a/playwright-core' },
+ { guid: 'elsewhere', title: 'playwright-cli', browserName: 'chromium', workspaceDir: '/home/me', endpoint: '/s/cli.sock', playwrightLib: '/npx/b/playwright-core' },
+];
+
+describe('browser drawer service', () => {
+ it("matches WSL mode's Linux workspace folders to projects as Windows paths", () => {
+ const linux: RegistryDescriptor[] = [
+ { guid: 'task', title: 'claude-code', browserName: 'chromium', workspaceDir: '/mnt/c/work/app/.workbench/worktrees/tasks/001' },
+ { guid: 'chat', title: 'Workbench chat c1', browserName: 'chromium', workspaceDir: '/home/me/.cache/workbench/tmp/workbench-chat-browser-x' },
+ ];
+ const hostPath = (dir: string) => (dir.startsWith('/mnt/c/') ? `C:\\${dir.slice(7).replace(/\//g, '\\')}` : `\\\\wsl.localhost\\Ubuntu${dir.replace(/\//g, '\\')}`);
+ const chats = new Map([['\\\\wsl.localhost\\Ubuntu\\home\\me\\.cache\\workbench\\tmp\\workbench-chat-browser-x', 'C:\\work\\app']]);
+ const sessions = toDrawerSessions(linux, [{ id: 'app', path: 'C:\\work\\app' }], chats, true, () => ({ projectId: 'app', chatId: 'c1' }), hostPath);
+ expect(sessions.map((s) => [s.id, s.projectId, s.workspaceDir])).toEqual([
+ // A task run's browser stays headless: no project, so no drawer shows it
+ ['task', undefined, 'C:\\work\\app\\.workbench\\worktrees\\tasks\\001'],
+ ['chat', 'app', '\\\\wsl.localhost\\Ubuntu\\home\\me\\.cache\\workbench\\tmp\\workbench-chat-browser-x'],
+ ]);
+ expect(sessions[1].chatId).toBe('c1');
+ });
+
+ it("gives chats' browsers their project, and no other session", () => {
+ const sessions = toDrawerSessions(descriptors, [{ id: 'app', path: '/work/app' }], new Map([['/tmp/workbench-insights-x/playwright', '/work/app']]), false);
+ expect(sessions).toEqual([
+ { id: 'task', title: 'claude-code', browserName: 'chromium', workspaceDir: '/work/app/.workbench/worktrees/tasks/001' },
+ { id: 'chat', title: 'claude-code', browserName: 'firefox', workspaceDir: '/tmp/workbench-insights-x/playwright', projectId: 'app' },
+ { id: 'elsewhere', title: 'playwright-cli', browserName: 'chromium', workspaceDir: '/home/me' },
+ ]);
+ // The bridge connects to the chats' browsers only (never a task's or another tool's)
+ expect(bridgeSessions(descriptors, sessions)).toEqual([
+ { id: 'chat', endpoint: '/s/chat.sock', browserName: 'firefox', playwrightLib: '/npx/a/playwright-core' },
+ ]);
+ });
+
+ it("shows a chat browser's tabs with the browser the chat chose, not what the registry suggests", () => {
+ const chats = new Map([['/tmp/workbench-insights-x/playwright', '/work/app']]);
+ const projects = [{ id: 'app', path: '/work/app' }];
+ const tabsFor = (browser: PlaywrightBrowserChoice | null | undefined) =>
+ toDrawerSessions(descriptors, projects, chats, false, () => ({ projectId: 'app', chatId: 'c1', ...(browser !== undefined ? { browser } : {}) }))[1];
+ const edge = { id: 'windows-edge:Default', browser: 'edge', engine: 'chromium', profileName: 'Default', executablePath: 'C:\\edge.exe', userDataDir: 'C:\\ud', profilePath: 'C:\\ud\\Default' } as const;
+ // A Windows Edge attached over CDP has no executable in its entry, which reads as Playwright's own
+ expect(tabsFor(edge)).toMatchObject({ browserName: 'chromium', managed: false });
+ // Playwright's own Chromium
+ expect(tabsFor(null)).toMatchObject({ browserName: 'chromium', managed: true });
+ // Still starting: the registry's word
+ expect(tabsFor(undefined)).toMatchObject({ browserName: 'firefox' });
+ });
+
+ it('asks frames at the window\'s pixel density, 1 to 2', () => {
+ expect(frameScale(2)).toBe(2);
+ expect(frameScale(1.25)).toBe(1.25);
+ expect(frameScale(3)).toBe(2);
+ expect(frameScale(0.5)).toBe(1);
+ expect(frameScale('2')).toBe(1);
+ expect(frameScale(undefined)).toBe(1);
+ });
+
+ it('keeps viewport sizes within limits', () => {
+ expect(viewportDimension(640.4)).toBe(640);
+ expect(viewportDimension(99999)).toBe(4096);
+ expect(viewportDimension(-1)).toBe(0);
+ expect(viewportDimension('12')).toBe(0);
+ });
+
+ it('accepts only the input the bridge replays', () => {
+ expect(isDrawerInput({ kind: 'mousedown', x: 1, y: 2, button: 'left', clickCount: 1 })).toBe(true);
+ expect(isDrawerInput({ kind: 'mousedown', x: 1, y: 2, button: 'back', clickCount: 1 })).toBe(false);
+ expect(isDrawerInput({ kind: 'wheel', x: 1, y: 2, deltaX: 0, deltaY: 40 })).toBe(true);
+ expect(isDrawerInput({ kind: 'keydown', key: 'Enter' })).toBe(true);
+ expect(isDrawerInput({ kind: 'keydown', key: '' })).toBe(false);
+ expect(isDrawerInput({ kind: 'text', text: 'hello' })).toBe(true);
+ expect(isDrawerInput({ kind: 'evaluate', script: 'x' })).toBe(false);
+ expect(isDrawerInput(null)).toBe(false);
+ });
+});
+
+describe('browser drawer viewers', () => {
+ /** A bridge that records what it is sent */
+ function fakeBridge() {
+ const sent: unknown[] = [];
+ const bridge = Object.assign(new EventEmitter(), {
+ running: true,
+ start: async () => undefined,
+ stop: async () => undefined,
+ killNow: () => undefined,
+ send: (request: unknown) => { sent.push(request); },
+ });
+ return { bridge: bridge as unknown as BrowserBridgeProcess, emitter: bridge, sent };
+ }
+ const sender = (id: number) => ({ id, once: () => undefined, isDestroyed: () => false }) as unknown as WebContents;
+ const views = (sent: unknown[]) => sent.filter((r) => (r as { type: string }).type === 'view');
+
+ it("sends the page a reopened drawer asked for before it subscribed", async () => {
+ const { bridge, emitter, sent } = fakeBridge();
+ const service = new BrowserDrawerService({ getProjects: () => [], bridge });
+ emitter.emit('message', { type: 'pages', pages: [{ id: 's#1', sessionId: 's', title: '', url: 'about:blank' }], connected: ['s'] });
+ const window = sender(7);
+
+ // The page view asks first (child effects run before the drawer's)
+ service.view(window, 's#1', 800, 600, 2);
+ expect(views(sent)).toEqual([]);
+ await service.subscribe(window);
+ expect(views(sent)).toEqual([{ type: 'view', viewerId: 7, pageId: 's#1', width: 800, height: 600, scale: 2 }]);
+
+ // Closed: nothing is replayed when it opens again without asking
+ service.unsubscribe(7);
+ sent.length = 0;
+ await service.subscribe(window);
+ expect(views(sent)).toEqual([]);
+ });
+
+ it("gives the bridge Workbench's theme when it starts and whenever it changes", async () => {
+ const { bridge, sent } = fakeBridge();
+ (bridge as unknown as { running: boolean }).running = false;
+ const service = new BrowserDrawerService({ getProjects: () => [], bridge });
+ const schemes = () => sent.filter((r) => (r as { type: string }).type === 'colorScheme');
+
+ // Kept until the bridge runs (a drawer opened), then sent before the sessions
+ service.setColorScheme('dark');
+ expect(schemes()).toEqual([]);
+ (bridge as unknown as { running: boolean }).running = true;
+ await service.subscribe(sender(3));
+ expect(sent[0]).toEqual({ type: 'colorScheme', scheme: 'dark' });
+
+ // Changes are passed on once; repeats and anything else are dropped
+ service.setColorScheme('dark');
+ service.setColorScheme('light');
+ service.setColorScheme('sepia');
+ expect(schemes()).toEqual([{ type: 'colorScheme', scheme: 'dark' }, { type: 'colorScheme', scheme: 'light' }]);
+ });
+});
diff --git a/src/main/browser-drawer/__tests__/browser-drawer-wsl.test.ts b/src/main/browser-drawer/__tests__/browser-drawer-wsl.test.ts
new file mode 100644
index 000000000..b6f2da44e
--- /dev/null
+++ b/src/main/browser-drawer/__tests__/browser-drawer-wsl.test.ts
@@ -0,0 +1,102 @@
+/**
+ * The browser drawer in WSL mode (mocked runtime): the bridge runs with the distribution's node,
+ * the registry is the distribution's (through \\wsl.localhost) and asked through the bridge, and
+ * chat browsers' folders are made in the distribution
+ */
+import { describe, it, expect, vi, afterEach, afterAll } from 'vitest';
+import { EventEmitter } from 'events';
+import { PassThrough } from 'stream';
+import { mkdtempSync, rmSync, existsSync } from 'fs';
+import os from 'os';
+import path from 'path';
+
+const root = mkdtempSync(path.join(os.tmpdir(), 'drawer-wsl-test-'));
+const wsl = vi.hoisted(() => ({ home: '/home/me', distro: 'Ubuntu', mountRoot: '/mnt/' }));
+const spawned = vi.hoisted(() => [] as Array<{ tool: string; args: string[]; options: Record }>);
+
+vi.mock('../../platform/shell-runtime', () => ({
+ whenShellRuntimeReady: async () => ({}),
+ isWslRuntime: () => true,
+ getWslInfo: () => wsl,
+ getShellRuntimeStatus: () => ({ wsl: { version: 2 } }),
+ // The distribution's folders under the test's folder (standing in for \\wsl.localhost\Ubuntu)
+ toHostPath: (p: string) => path.join(root, 'wsl', p),
+ toRuntimePath: (p: string) => p,
+}));
+vi.mock('../../mcp-commands', () => ({
+ resolveCommand: async (command: string) => (command === 'node' ? '/usr/bin/node' : null),
+}));
+vi.mock('../../platform/runtime-exec', () => ({
+ spawnTool: (tool: string, args: string[], options: Record) => {
+ spawned.push({ tool, args, options });
+ const child = Object.assign(new EventEmitter(), {
+ stdin: new PassThrough(),
+ stdout: new PassThrough(),
+ stderr: new PassThrough(),
+ exitCode: null,
+ kill: () => true,
+ });
+ return child;
+ },
+ killRuntimeProcess: () => undefined,
+ killRuntimeProcessTree: () => undefined,
+}));
+
+import { BrowserBridgeProcess } from '../bridge-process';
+import { BrowserDrawerService } from '../browser-drawer-service';
+import { registryAccess, setRegistryAccess } from '../registry';
+import { runtimeTempParent, tempFolderParents } from '../../temp-folders';
+
+afterEach(() => {
+ setRegistryAccess(null);
+ spawned.length = 0;
+});
+afterAll(() => rmSync(root, { recursive: true, force: true }));
+
+describe('browser drawer in WSL mode', () => {
+ it("runs the bridge with the distribution's node, without Electron's variables", async () => {
+ const bridge = new BrowserBridgeProcess({ scriptPath: path.join(root, 'browser-bridge.cjs') });
+ await bridge.start();
+ expect(spawned).toHaveLength(1);
+ expect(spawned[0].tool).toBe('node');
+ expect(spawned[0].args).toEqual([path.join(root, 'browser-bridge.cjs')]);
+ expect(spawned[0].options.command).toBe('/usr/bin/node');
+ expect(spawned[0].options.env).toBeUndefined();
+ expect(spawned[0].options.stdio).toEqual(['pipe', 'pipe', 'pipe']);
+ bridge.killNow();
+ });
+
+ it("reads the distribution's registry and asks a running bridge which browsers answer", async () => {
+ const probes: string[][] = [];
+ const bridge = Object.assign(new EventEmitter(), {
+ running: false,
+ start: async () => undefined,
+ stop: async () => undefined,
+ killNow: () => undefined,
+ send: () => undefined,
+ probe: async (endpoints: string[]) => {
+ probes.push(endpoints);
+ return new Set(endpoints.filter((e) => e.includes('live')));
+ },
+ });
+ const service = new BrowserDrawerService({ getProjects: () => [], bridge: bridge as unknown as BrowserBridgeProcess });
+ await service.start();
+ const access = registryAccess('windows');
+ expect(access.dir).toBe(path.join(root, 'wsl', '/home/me/.cache/ms-playwright/b'));
+ // Before a drawer started the bridge, nothing is asked (a check never starts it)
+ expect(await access.connect('/tmp/pw-1/browser/live.sock')).toBeNull();
+ expect(probes).toEqual([]);
+ bridge.running = true;
+ expect(await access.connect('/tmp/pw-1/browser/live.sock')).toBe(true);
+ expect(await access.connect('/tmp/pw-1/browser/closed.sock')).toBe(false);
+ expect(probes).toEqual([['/tmp/pw-1/browser/live.sock'], ['/tmp/pw-1/browser/closed.sock']]);
+ await service.shutdown();
+ });
+
+ it("makes chat browsers' folders in the distribution, and sweeps both temp folders", async () => {
+ const parent = await runtimeTempParent();
+ expect(parent).toBe(path.join(root, 'wsl', '/home/me/.cache/workbench/tmp'));
+ expect(existsSync(parent)).toBe(true);
+ expect(await tempFolderParents()).toEqual([os.tmpdir(), parent]);
+ });
+});
diff --git a/src/main/browser-drawer/__tests__/chat-browser-restore.test.ts b/src/main/browser-drawer/__tests__/chat-browser-restore.test.ts
new file mode 100644
index 000000000..a794b687d
--- /dev/null
+++ b/src/main/browser-drawer/__tests__/chat-browser-restore.test.ts
@@ -0,0 +1,119 @@
+import os, { hostname } from 'os';
+import path from 'path';
+import { existsSync } from 'fs';
+import { mkdir, mkdtemp, readFile, rm, writeFile } from 'fs/promises';
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
+
+vi.mock('../../app-logger', () => ({ appLog: { warn: vi.fn(), info: vi.fn() } }));
+const copies = vi.hoisted(() => ({ root: '', kept: [] as string[], removed: [] as string[] }));
+vi.mock('../../browser-profiles/profile-copy', () => ({
+ isBrowserProfileCopyPath: (dir: string) => dir.startsWith(copies.root),
+ keepBrowserProfileCopy: async (dir: string) => {
+ copies.kept.push(dir);
+ return true;
+ },
+ removeBrowserProfileCopy: async (dir: string) => {
+ copies.removed.push(dir);
+ },
+}));
+
+import {
+ CHAT_BROWSER_RECORD,
+ RESTORE_MAX_AGE_MS,
+ discardRestorable,
+ keepsForChat,
+ parseChatBrowserRecord,
+ scanChatBrowserLeftovers,
+ tabsToRestore,
+ type ChatBrowserRecord,
+} from '../chat-browser-restore';
+import { OWNER_FILE, processIdentity } from '../../folder-owner';
+
+const DEAD_PID = 2 ** 22 + 12345;
+const NOW = Date.now();
+let parent: string;
+
+const record = (chatId: string, extra: Partial = {}): ChatBrowserRecord => ({
+ projectId: 'p1',
+ projectPath: '/old/path',
+ chatId,
+ browserId: 'chrome:Default',
+ profileCopyDir: path.join(copies.root, `copy-${chatId}`),
+ tabs: [{ url: 'https://example.com/', title: 'Example' }, { url: 'about:blank', title: '' }],
+ updatedAt: NOW - 1000,
+ ...extra,
+});
+
+async function leftover(name: string, value: ChatBrowserRecord | null, owner: object = { pid: DEAD_PID, host: hostname() }): Promise {
+ const dir = path.join(parent, `workbench-chat-browser-${name}`);
+ await mkdir(dir, { recursive: true });
+ await writeFile(path.join(dir, OWNER_FILE), JSON.stringify(owner));
+ if (value) await writeFile(path.join(dir, CHAT_BROWSER_RECORD), JSON.stringify(value));
+ return dir;
+}
+
+describe('chat browsers left by a crash', () => {
+ beforeEach(async () => {
+ parent = await mkdtemp(path.join(os.tmpdir(), 'wb-chat-restore-'));
+ copies.root = path.join(parent, 'copies');
+ copies.kept = [];
+ copies.removed = [];
+ });
+ afterEach(async () => {
+ await rm(parent, { recursive: true, force: true });
+ });
+
+ it('reads records and the tabs worth opening again', () => {
+ expect(parseChatBrowserRecord('{')).toBeNull();
+ expect(parseChatBrowserRecord(JSON.stringify({ projectId: 'p' }))).toBeNull();
+ const parsed = parseChatBrowserRecord(JSON.stringify({ ...record('session-1'), tabs: [{ url: 'x' }, { url: 'https://a.test', title: 'A' }] }));
+ expect(parsed?.tabs).toEqual([{ url: 'https://a.test', title: 'A' }]);
+ expect(tabsToRestore(record('session-1').tabs)).toEqual([{ url: 'https://example.com/', title: 'Example' }]);
+ });
+
+ it('keeps one for its chat while the chat exists and it is recent', () => {
+ const context = { now: NOW, projectPath: '/p', chatExists: true };
+ expect(keepsForChat(record('session-1'), context)).toBe(true);
+ expect(keepsForChat(record('session-1'), { ...context, chatExists: false })).toBe(false);
+ expect(keepsForChat(record('session-1'), { ...context, projectPath: undefined })).toBe(false);
+ expect(keepsForChat(record('session-1', { updatedAt: NOW - RESTORE_MAX_AGE_MS - 1 }), context)).toBe(false);
+ expect(keepsForChat(null, context)).toBe(false);
+ });
+
+ it('keeps the newest of each existing chat, removes the rest with their copies, and leaves running ones', async () => {
+ const kept = await leftover('kept', record('session-1'));
+ const older = await leftover('older', record('session-1', { updatedAt: NOW - 5000, profileCopyDir: path.join(copies.root, 'copy-older') }));
+ const deletedChat = await leftover('deleted', record('session-2'));
+ const expired = await leftover('expired', record('session-3', { updatedAt: NOW - RESTORE_MAX_AGE_MS - 1 }));
+ const otherProject = await leftover('project', record('session-1', { projectId: 'gone' }));
+ const noRecord = await leftover('none', null);
+ const outside = await leftover('outside', record('session-4', { profileCopyDir: path.join(os.homedir(), 'not-a-copy') }));
+ const running = await leftover('running', record('session-5'), await processIdentity(process.ppid));
+
+ const restorable = await scanChatBrowserLeftovers({
+ parent,
+ now: NOW,
+ projects: [{ id: 'p1', path: '/project' }],
+ chatExists: async (projectPath, chatId) => projectPath === '/project' && ['session-1', 'session-3', 'session-5'].includes(chatId),
+ });
+
+ expect(restorable).toEqual([{ dir: kept, record: { ...record('session-1'), projectPath: '/project' } }]);
+ expect(copies.kept).toEqual([path.join(copies.root, 'copy-session-1')]);
+ // This process holds it now
+ expect(JSON.parse(await readFile(path.join(kept, OWNER_FILE), 'utf-8'))).toMatchObject({ pid: process.pid });
+ for (const dir of [older, deletedChat, expired, otherProject, noRecord, outside]) expect(existsSync(dir)).toBe(false);
+ expect(existsSync(running)).toBe(true);
+ // A record naming a folder that isn't a profile copy never gets it removed
+ expect(copies.removed.sort()).toEqual([
+ path.join(copies.root, 'copy-older'),
+ path.join(copies.root, 'copy-session-1'),
+ path.join(copies.root, 'copy-session-2'),
+ path.join(copies.root, 'copy-session-3'),
+ ].sort());
+
+ copies.removed = [];
+ await discardRestorable(restorable[0]);
+ expect(existsSync(kept)).toBe(false);
+ expect(copies.removed).toEqual([path.join(copies.root, 'copy-session-1')]);
+ });
+});
diff --git a/src/main/browser-drawer/__tests__/chat-browsers.test.ts b/src/main/browser-drawer/__tests__/chat-browsers.test.ts
new file mode 100644
index 000000000..71cd7b1ef
--- /dev/null
+++ b/src/main/browser-drawer/__tests__/chat-browsers.test.ts
@@ -0,0 +1,195 @@
+import os from 'os';
+import { describe, it, expect, vi } from 'vitest';
+import path from 'path';
+import { ChatBrowsers, holderArgs, holderError, type ChatBrowserHolder, type StartChatBrowserHolder } from '../chat-browsers';
+import { toDrawerSessions } from '../browser-drawer-service';
+
+/** A holder that starts when `start()` is called and records closes */
+function fakeHolders() {
+ const started: Array<{ title: string; choice: unknown; restore: unknown; resolve: () => void; reject: (e: Error) => void; exit: () => void; closed: boolean }> = [];
+ const start: StartChatBrowserHolder = ({ title, choice, restore }) => new Promise((resolve, reject) => {
+ const listeners: Array<() => void> = [];
+ const entry = {
+ title, choice, restore, closed: false,
+ exit: () => listeners.forEach((l) => l()),
+ resolve: () => resolve({
+ close: async () => { entry.closed = true; entry.exit(); },
+ onExit: (l) => { listeners.push(l); },
+ }),
+ reject,
+ };
+ started.push(entry);
+ });
+ return { start, started };
+}
+
+describe('chat browsers left by a crash', () => {
+ const restorable = (chatId: string, dir = os.tmpdir()) => ({
+ dir,
+ record: {
+ projectId: 'p', projectPath: '/proj', chatId, browserId: null, profileCopyDir: null, updatedAt: Date.now(),
+ tabs: [{ url: 'https://a.test/', title: 'A' }, { url: 'about:blank', title: '' }, { url: 'https://b.test/', title: 'B' }],
+ },
+ });
+
+ it('lists them for their chats and starts the chat browser from them', async () => {
+ const { start, started } = fakeHolders();
+ const discard = vi.fn(async () => undefined);
+ const chats = new ChatBrowsers(start, discard);
+ const left = restorable('session-1');
+ chats.addRestorable(left);
+ expect(chats.list()).toEqual([{ projectId: 'p', chatId: 'session-1', status: 'restorable', tabs: 2 }]);
+ expect(chats.isOpen('p', 'session-1')).toBe(false);
+
+ const opening = chats.ensure('p', '/proj', 'session-1', undefined);
+ expect(started[0].restore).toBe(left);
+ expect(chats.list()).toEqual([{ projectId: 'p', chatId: 'session-1', status: 'starting' }]);
+ started[0].resolve();
+ await opening;
+ expect(chats.list()).toEqual([{ projectId: 'p', chatId: 'session-1', status: 'open' }]);
+ expect(discard).not.toHaveBeenCalled();
+ });
+
+ it('keeps one whose start failed, and removes those of deleted chats or chats that have a browser', async () => {
+ const { start, started } = fakeHolders();
+ const discard = vi.fn(async () => undefined);
+ const chats = new ChatBrowsers(start, discard);
+ const left = restorable('session-1');
+ chats.addRestorable(left);
+ const failing = chats.ensure('p', '/proj', 'session-1', undefined);
+ started[0].reject(new Error('Chromium is not installed'));
+ await expect(failing).rejects.toThrow('Chromium is not installed');
+ await vi.waitFor(() => expect(chats.list()).toEqual([{ projectId: 'p', chatId: 'session-1', status: 'restorable', tabs: 2 }]));
+
+ await chats.closeChats('p', ['session-1']);
+ expect(discard).toHaveBeenCalledWith(left);
+ expect(chats.list()).toEqual([]);
+
+ const opening = chats.ensure('p', '/proj', 'session-2', null);
+ const late = restorable('session-2');
+ chats.addRestorable(late);
+ expect(discard).toHaveBeenCalledWith(late);
+ started[1].resolve();
+ await opening;
+ expect(chats.list()).toEqual([{ projectId: 'p', chatId: 'session-2', status: 'open' }]);
+ });
+});
+
+describe('chat browsers', () => {
+ it('opens one browser per chat, once, with a title that names the chat', async () => {
+ const { start, started } = fakeHolders();
+ const chats = new ChatBrowsers(start);
+ const change = vi.fn();
+ chats.on('change', change);
+
+ const first = chats.ensure('p', '/proj', 'chat-1', null);
+ const second = chats.ensure('p', '/proj', 'chat-1', undefined);
+ expect(started).toHaveLength(1);
+ expect(chats.list()).toEqual([{ projectId: 'p', chatId: 'chat-1', status: 'starting' }]);
+ started[0].resolve();
+ await Promise.all([first, second]);
+ expect(chats.isOpen('p', 'chat-1')).toBe(true);
+ expect(started[0].choice).toBeNull();
+ expect(chats.chatOfTitle(started[0].title)).toEqual({ projectId: 'p', chatId: 'chat-1' });
+ expect(chats.titleFor('p', 'chat-1')).toBe(started[0].title);
+ expect(change).toHaveBeenCalled();
+
+ await chats.ensure('p', '/proj', 'chat-1', null);
+ expect(started).toHaveLength(1);
+ });
+
+ it('opens no second browser for a chat until the one closed while starting has closed', async () => {
+ const { start, started } = fakeHolders();
+ const chats = new ChatBrowsers(start);
+ const opening = chats.ensure('p', '/proj', 'a', null);
+ const closed = chats.close('p', 'a');
+ const reopening = chats.ensure('p', '/proj', 'a', null);
+ // The first is still starting: nothing else starts under its title
+ expect(started).toHaveLength(1);
+ started[0].resolve();
+ await expect(opening).rejects.toThrow('The browser was closed');
+ await closed;
+ expect(started[0].closed).toBe(true);
+ await vi.waitFor(() => expect(started).toHaveLength(2));
+ started[1].resolve();
+ await reopening;
+ expect(chats.isOpen('p', 'a')).toBe(true);
+ });
+
+ it('forgets a browser that failed to open, closed, or exited', async () => {
+ const { start, started } = fakeHolders();
+ const chats = new ChatBrowsers(start);
+ const failing = chats.ensure('p', '/proj', 'a', null);
+ started[0].reject(new Error('Chromium is not installed'));
+ await expect(failing).rejects.toThrow('Chromium is not installed');
+ expect(chats.list()).toEqual([]);
+
+ const opening = chats.ensure('p', '/proj', 'a', null);
+ started[1].resolve();
+ await opening;
+ await chats.close('p', 'a');
+ expect(started[1].closed).toBe(true);
+ expect(chats.list()).toEqual([]);
+
+ const again = chats.ensure('p', '/proj', 'a', null);
+ started[2].resolve();
+ await again;
+ started[2].exit();
+ expect(chats.isOpen('p', 'a')).toBe(false);
+ });
+
+ it("moves the New chat page's browser to its conversation", async () => {
+ const { start, started } = fakeHolders();
+ const chats = new ChatBrowsers(start);
+ const opening = chats.ensure('p', '/proj', 'new', null);
+ started[0].resolve();
+ await opening;
+ chats.adopt('p', 'session-1');
+ expect(chats.list()).toEqual([{ projectId: 'p', chatId: 'session-1', status: 'open' }]);
+ expect(chats.chatOfTitle(started[0].title)).toEqual({ projectId: 'p', chatId: 'session-1' });
+ expect(chats.titleFor('p', 'new')).not.toBe(started[0].title);
+ });
+
+ it('closes a browser that went away after it was seen live, and deleted chats', async () => {
+ const { start, started } = fakeHolders();
+ const chats = new ChatBrowsers(start);
+ const opening = chats.ensure('p', '/proj', 'a', null);
+ started[0].resolve();
+ await opening;
+ const title = started[0].title;
+ chats.syncLive(new Set());
+ expect(chats.isOpen('p', 'a')).toBe(true); // not seen live yet: still starting up
+ chats.syncLive(new Set([title]));
+ chats.syncLive(new Set());
+ await vi.waitFor(() => expect(started[0].closed).toBe(true));
+
+ const b = chats.ensure('p', '/proj', 'b', null);
+ started[1].resolve();
+ await b;
+ await chats.closeChats('p', ['b']);
+ expect(started[1].closed).toBe(true);
+ });
+
+ it("keeps the holder's browser open and on disk in its own folder", () => {
+ const dir = path.join('/tmp', 'holder');
+ expect(holderArgs(['-y', '@playwright/mcp@0.0.83', '--browser', 'chromium', '--isolated', '--sandbox', '--headless'], dir)).toEqual([
+ '-y', '@playwright/mcp@0.0.83', '--browser', 'chromium', '--user-data-dir', path.join(dir, 'profile'), '--sandbox', '--headless',
+ '--idle-timeout', '0', '--output-dir', dir,
+ ]);
+ expect(holderError('### Error\nError: Browser "chromium" is not installed. Run `npx playwright install`')).toBe('Browser "chromium" is not installed');
+ });
+
+ it("names a chat browser's session with its chat", () => {
+ const sessions = toDrawerSessions(
+ [
+ { guid: 'g1', title: 'Workbench chat x', browserName: 'chromium', workspaceDir: '/tmp/chat-x' },
+ { guid: 'g2', title: 'claude-code', browserName: 'chromium', workspaceDir: '/proj/.workbench/worktrees/tasks/1' },
+ ],
+ [{ id: 'p', path: '/proj' }],
+ new Map([['/tmp/chat-x', '/proj']]),
+ false,
+ (title) => (title === 'Workbench chat x' ? { projectId: 'p', chatId: 'session-1' } : undefined),
+ );
+ expect(sessions.map((s) => [s.id, s.projectId, s.chatId])).toEqual([['g1', 'p', 'session-1'], ['g2', undefined, undefined]]);
+ });
+});
diff --git a/src/main/browser-drawer/__tests__/display-scale.test.ts b/src/main/browser-drawer/__tests__/display-scale.test.ts
new file mode 100644
index 000000000..636ea65a2
--- /dev/null
+++ b/src/main/browser-drawer/__tests__/display-scale.test.ts
@@ -0,0 +1,17 @@
+import { describe, it, expect, vi } from 'vitest';
+
+vi.mock('electron', () => ({ app: { getPath: () => '/tmp' }, screen: { getAllDisplays: () => [], on: vi.fn() } }));
+vi.mock('../../app-logger', () => ({ appLog: { warn: vi.fn() } }));
+
+import { browserScaleFor } from '../display-scale';
+
+describe("browsers' display scale", () => {
+ it('follows the densest screen, from 1 to 2', () => {
+ expect(browserScaleFor([1])).toBe(1);
+ expect(browserScaleFor([1, 2])).toBe(2);
+ expect(browserScaleFor([1.25, 1.5])).toBe(1.5);
+ expect(browserScaleFor([3])).toBe(2);
+ expect(browserScaleFor([])).toBe(1);
+ expect(browserScaleFor([Number.NaN, 0.5])).toBe(1);
+ });
+});
diff --git a/src/main/browser-drawer/__tests__/project-match.test.ts b/src/main/browser-drawer/__tests__/project-match.test.ts
new file mode 100644
index 000000000..55dec7936
--- /dev/null
+++ b/src/main/browser-drawer/__tests__/project-match.test.ts
@@ -0,0 +1,45 @@
+import { describe, it, expect } from 'vitest';
+import { registerChatBrowserWorkspace, getChatBrowserWorkspaces, sessionProjectId } from '../project-match';
+
+const projects = [
+ { id: 'app', path: '/work/app' },
+ { id: 'inner', path: '/work/app/packages/inner' },
+ { id: 'other', path: '/work/other' },
+];
+
+describe('session -> project', () => {
+ it("leaves task runs' browsers out: they stay headless and unseen", () => {
+ expect(sessionProjectId('/work/app/.workbench/worktrees/tasks/001-login', projects, new Map())).toBeUndefined();
+ expect(sessionProjectId('/work/app', projects, new Map())).toBeUndefined();
+ expect(sessionProjectId('/work/app/packages/inner/.workbench/worktrees/tasks/003', projects, new Map())).toBeUndefined();
+ });
+
+ it('leaves other folders out', () => {
+ expect(sessionProjectId('/tmp/somewhere', projects, new Map())).toBeUndefined();
+ expect(sessionProjectId(undefined, projects, new Map())).toBeUndefined();
+ });
+
+ it("matches a chat browser's folder while it is registered", () => {
+ const unregister = registerChatBrowserWorkspace('/tmp/workbench-insights-abc/playwright', '/work/other');
+ expect(sessionProjectId('/tmp/workbench-insights-abc/playwright', projects, getChatBrowserWorkspaces())).toBe('other');
+ expect(sessionProjectId('/tmp/workbench-insights-abc/playwright/', projects, getChatBrowserWorkspaces())).toBe('other');
+ unregister();
+ expect(sessionProjectId('/tmp/workbench-insights-abc/playwright', projects, getChatBrowserWorkspaces())).toBeUndefined();
+ // Its project, not one inside or around it
+ const nested = new Map([['/tmp/chat-x', '/work/app/packages/inner']]);
+ expect(sessionProjectId('/tmp/chat-x', projects, nested)).toBe('inner');
+ });
+
+ it("matches a WSL distribution's folders by either of Windows' names for them", () => {
+ const wsl = [{ id: 'linux', path: '\\\\wsl$\\Ubuntu\\home\\me\\app' }];
+ const chats = new Map([['\\\\wsl.localhost\\Ubuntu\\home\\me\\.cache\\workbench\\tmp\\chat-1', '\\\\wsl.localhost\\Ubuntu\\home\\me\\app']]);
+ expect(sessionProjectId('\\\\wsl$\\Ubuntu\\home\\me\\.cache\\workbench\\tmp\\chat-1', wsl, chats, true)).toBe('linux');
+ });
+
+ it('ignores case on Windows and macOS', () => {
+ const windows = [{ id: 'win', path: 'C:\\Users\\Me\\App' }];
+ const chats = new Map([['C:\\Temp\\Chat-1', 'C:\\Users\\Me\\App']]);
+ expect(sessionProjectId('c:\\temp\\chat-1', windows, chats, true)).toBe('win');
+ expect(sessionProjectId('c:\\temp\\chat-1', windows, chats, false)).toBeUndefined();
+ });
+});
diff --git a/src/main/browser-drawer/__tests__/registry.test.ts b/src/main/browser-drawer/__tests__/registry.test.ts
new file mode 100644
index 000000000..cc4af4ad0
--- /dev/null
+++ b/src/main/browser-drawer/__tests__/registry.test.ts
@@ -0,0 +1,141 @@
+import { existsSync } from 'fs';
+import { describe, it, expect, afterEach } from 'vitest';
+import { mkdtemp, rm, writeFile, utimes } from 'fs/promises';
+import net from 'net';
+import os from 'os';
+import path from 'path';
+import { canConnect, parseDescriptor, readLiveSessions, registryDir, removeClosedSessions } from '../registry';
+
+const descriptor = (guid: string, extra: Record = {}) => JSON.stringify({
+ playwrightVersion: '1.64.0-alpha-1790635538000',
+ playwrightLib: '/home/me/.npm/_npx/abc/node_modules/playwright-core',
+ title: 'claude-code',
+ browser: { guid, browserName: 'chromium', launchOptions: {} },
+ endpoint: `/tmp/pw-1/browser/${guid}.sock`,
+ workspaceDir: '/work/project/.workbench/worktrees/tasks/001-x',
+ ...extra,
+});
+
+describe('Playwright registry folder', () => {
+ it('follows playwright-core per OS', () => {
+ expect(registryDir('linux', {}, '/home/me')).toBe('/home/me/.cache/ms-playwright/b');
+ expect(registryDir('linux', { XDG_CACHE_HOME: '/xdg' }, '/home/me')).toBe('/xdg/ms-playwright/b');
+ expect(registryDir('macos', {}, '/Users/me')).toBe('/Users/me/Library/Caches/ms-playwright/b');
+ expect(registryDir('windows', { LOCALAPPDATA: 'C:\\Users\\me\\AppData\\Local' }, 'C:\\Users\\me'))
+ .toBe('C:\\Users\\me\\AppData\\Local\\ms-playwright\\b');
+ expect(registryDir('windows', {}, 'C:\\Users\\me')).toBe('C:\\Users\\me\\AppData\\Local\\ms-playwright\\b');
+ expect(registryDir('linux', { PWTEST_SERVER_REGISTRY: '/custom' }, '/home/me')).toBe('/custom');
+ });
+});
+
+describe('registry descriptors', () => {
+ it('reads a bound browser', () => {
+ expect(parseDescriptor(descriptor('g1'))).toEqual({
+ guid: 'g1',
+ title: 'claude-code',
+ browserName: 'chromium',
+ workspaceDir: '/work/project/.workbench/worktrees/tasks/001-x',
+ endpoint: '/tmp/pw-1/browser/g1.sock',
+ playwrightVersion: '1.64.0-alpha-1790635538000',
+ playwrightLib: '/home/me/.npm/_npx/abc/node_modules/playwright-core',
+ managed: true,
+ });
+ });
+
+ it("tells Playwright's own browsers from the user's", () => {
+ const withExecutable = (executablePath: string) => {
+ const raw = JSON.parse(descriptor('g1'));
+ raw.browser.launchOptions = { executablePath };
+ return parseDescriptor(JSON.stringify(raw))?.managed;
+ };
+ expect(withExecutable('/snap/firefox/current/usr/lib/firefox/firefox')).toBe(false);
+ expect(withExecutable('/home/me/.cache/ms-playwright/chromium-1200/chrome-linux/chrome')).toBe(true);
+ expect(withExecutable('C:\\Users\\me\\AppData\\Local\\ms-playwright\\firefox-1500\\firefox.exe')).toBe(true);
+ });
+
+ it('leaves out what is not one', () => {
+ expect(parseDescriptor('{')).toBeNull();
+ expect(parseDescriptor('null')).toBeNull();
+ expect(parseDescriptor(JSON.stringify({ title: 'x' }))).toBeNull();
+ });
+});
+
+describe('live sessions', () => {
+ let dir: string;
+ afterEach(async () => {
+ if (dir) await rm(dir, { recursive: true, force: true });
+ });
+
+ it("removes a title's closed browsers only", async () => {
+ dir = await mkdtemp(path.join(os.tmpdir(), 'pw-registry-'));
+ await writeFile(path.join(dir, 'closed'), descriptor('closed', { title: 'Workbench chat 1' }));
+ await writeFile(path.join(dir, 'live'), descriptor('live', { title: 'Workbench chat 1' }));
+ await writeFile(path.join(dir, 'other'), descriptor('other', { title: 'claude-code' }));
+ await removeClosedSessions(dir, 'Workbench chat 1', async (endpoint) => endpoint.includes('/live.sock'));
+ expect(existsSync(path.join(dir, 'closed'))).toBe(false);
+ expect(existsSync(path.join(dir, 'live'))).toBe(true);
+ expect(existsSync(path.join(dir, 'other'))).toBe(true);
+ });
+
+ it('lists the browsers whose socket answers, without internal ones', async () => {
+ dir = await mkdtemp(path.join(os.tmpdir(), 'pw-registry-'));
+ await writeFile(path.join(dir, 'live'), descriptor('live'));
+ await writeFile(path.join(dir, 'closed'), descriptor('closed'));
+ await writeFile(path.join(dir, 'probe'), descriptor('probe', { title: '--playwright-internal-workbench-probe' }));
+ await writeFile(path.join(dir, 'broken'), '{');
+ const asked: string[] = [];
+ const connect = async (endpoint: string) => {
+ asked.push(endpoint);
+ return endpoint.includes('/live.sock');
+ };
+ const dead = new Map();
+ const sessions = await readLiveSessions(dir, dead, connect);
+ expect(sessions.map((s) => s.guid)).toEqual(['live']);
+ expect(asked.sort()).toEqual(['/tmp/pw-1/browser/closed.sock', '/tmp/pw-1/browser/live.sock']);
+
+ // A closed browser's file isn't read again until it changes
+ asked.length = 0;
+ await readLiveSessions(dir, dead, connect);
+ expect(asked).toEqual(['/tmp/pw-1/browser/live.sock']);
+ const later = new Date(Date.now() + 5000);
+ await utimes(path.join(dir, 'closed'), later, later);
+ asked.length = 0;
+ await readLiveSessions(dir, dead, connect);
+ expect(asked.sort()).toEqual(['/tmp/pw-1/browser/closed.sock', '/tmp/pw-1/browser/live.sock']);
+
+ // Browsers known to be live (the bridge's) aren't asked
+ asked.length = 0;
+ const known = await readLiveSessions(dir, dead, connect, (descriptor) => descriptor.guid === 'live');
+ expect(known.map((s) => s.guid)).toEqual(['live']);
+ expect(asked).toEqual([]);
+ });
+
+ it("leaves out, without forgetting, browsers whose liveness couldn't be asked (the bridge didn't answer)", async () => {
+ dir = await mkdtemp(path.join(os.tmpdir(), 'pw-registry-'));
+ await writeFile(path.join(dir, 'live'), descriptor('live'));
+ const dead = new Map();
+ expect(await readLiveSessions(dir, dead, async () => null)).toEqual([]);
+ expect(dead.size).toBe(0);
+ expect((await readLiveSessions(dir, dead, async () => true)).map((s) => s.guid)).toEqual(['live']);
+ // Nor removed as closed
+ await removeClosedSessions(dir, 'claude-code', async () => null);
+ expect(existsSync(path.join(dir, 'live'))).toBe(true);
+ });
+
+ it('has none without a registry folder', async () => {
+ expect(await readLiveSessions(path.join(os.tmpdir(), 'no-such-registry-folder'))).toEqual([]);
+ });
+
+ it('connects to a local socket', async () => {
+ dir = await mkdtemp(path.join(os.tmpdir(), 'pw-sock-'));
+ const socket = process.platform === 'win32' ? `\\\\.\\pipe\\workbench-test-${process.pid}` : path.join(dir, 's.sock');
+ const server = net.createServer((c) => c.destroy());
+ await new Promise((resolve) => server.listen(socket, resolve));
+ try {
+ expect(await canConnect(socket)).toBe(true);
+ } finally {
+ await new Promise((resolve) => server.close(resolve));
+ }
+ expect(await canConnect(socket)).toBe(false);
+ });
+});
diff --git a/src/main/browser-drawer/bridge-framing.ts b/src/main/browser-drawer/bridge-framing.ts
new file mode 100644
index 000000000..1110acf38
--- /dev/null
+++ b/src/main/browser-drawer/bridge-framing.ts
@@ -0,0 +1,104 @@
+/**
+ * The browser bridge's messages over stdio
+ * ========================================
+ *
+ * Each message is a JSON header, optionally with bytes (a frame's JPEG), so frames aren't
+ * inflated by base64: `WB` (two bytes), the header's length and the bytes' length (unsigned
+ * 32-bit, big endian), the header (UTF-8 JSON), the bytes. The header names the field the bytes
+ * belong in (`$bytes`). browser-bridge.cjs has the same codec in plain Node.
+ */
+
+const MAGIC_0 = 0x57; // W
+const MAGIC_1 = 0x42; // B
+const PREFIX_LENGTH = 10;
+/** A message larger than this is corrupt (a frame of a 4096x4096 viewport is far smaller) */
+const MAX_PART_LENGTH = 64 * 1024 * 1024;
+/** The header field that says which field the bytes go in */
+const BYTES_FIELD = '$bytes';
+
+/** One message as bytes: a field holding a Uint8Array (at most one) is sent as raw bytes */
+export function encodeBridgeMessage(message: Record): Buffer {
+ let bytes: Uint8Array | null = null;
+ const header: Record = {};
+ for (const [key, value] of Object.entries(message)) {
+ if (value instanceof Uint8Array && !bytes) {
+ bytes = value;
+ header[BYTES_FIELD] = key;
+ } else {
+ header[key] = value;
+ }
+ }
+ const json = Buffer.from(JSON.stringify(header), 'utf-8');
+ const prefix = Buffer.alloc(PREFIX_LENGTH);
+ prefix[0] = MAGIC_0;
+ prefix[1] = MAGIC_1;
+ prefix.writeUInt32BE(json.length, 2);
+ prefix.writeUInt32BE(bytes?.length ?? 0, 6);
+ return Buffer.concat(bytes ? [prefix, json, bytes] : [prefix, json]);
+}
+
+/**
+ * Reads messages from a byte stream. Bytes that aren't a message (a stray write to stdout) are
+ * skipped up to the next message's start, reported once per run through `onNoise`
+ */
+export function createBridgeMessageReader(
+ onMessage: (message: Record) => void,
+ onNoise: (skipped: number) => void = () => undefined,
+): (chunk: Buffer) => void {
+ let buffer: Buffer = Buffer.alloc(0);
+ // Chunks of a message still arriving, joined once all of it is there: joining each chunk as it
+ // came copied a multi-megabyte frame over again for every 64 KB of it
+ let waiting: Buffer[] = [];
+ let waitingLength = 0;
+ /** The length `buffer` needs for the message it starts (0: not known yet) */
+ let needed = 0;
+ return (chunk) => {
+ waiting.push(chunk);
+ waitingLength += chunk.length;
+ if (needed > 0 && buffer.length + waitingLength < needed) return;
+ const parts = buffer.length ? [buffer, ...waiting] : waiting;
+ buffer = parts.length === 1 ? parts[0] : Buffer.concat(parts);
+ waiting = [];
+ waitingLength = 0;
+ needed = 0;
+ for (;;) {
+ // Up to the next message's start
+ let start = 0;
+ while (start < buffer.length && !(buffer[start] === MAGIC_0 && (start + 1 >= buffer.length || buffer[start + 1] === MAGIC_1))) start++;
+ if (start > 0) {
+ onNoise(start);
+ buffer = buffer.subarray(start);
+ }
+ if (buffer.length < PREFIX_LENGTH) return;
+ const headerLength = buffer.readUInt32BE(2);
+ const bytesLength = buffer.readUInt32BE(6);
+ if (headerLength > MAX_PART_LENGTH || bytesLength > MAX_PART_LENGTH) {
+ // Not a real message start: look further
+ onNoise(1);
+ buffer = buffer.subarray(1);
+ continue;
+ }
+ const total = PREFIX_LENGTH + headerLength + bytesLength;
+ if (buffer.length < total) {
+ needed = total;
+ return;
+ }
+ const headerText = buffer.subarray(PREFIX_LENGTH, PREFIX_LENGTH + headerLength).toString('utf-8');
+ const bytes = buffer.subarray(PREFIX_LENGTH + headerLength, total);
+ buffer = buffer.subarray(total);
+ let header: Record;
+ try {
+ header = JSON.parse(headerText);
+ } catch {
+ onNoise(total);
+ continue;
+ }
+ if (!header || typeof header !== 'object') continue;
+ const field = header[BYTES_FIELD];
+ delete header[BYTES_FIELD];
+ // A copy: the buffer the bytes came in is reused for what follows
+ if (typeof field === 'string') header[field] = new Uint8Array(bytes);
+ onMessage(header);
+ }
+ };
+}
diff --git a/src/main/browser-drawer/bridge-process.ts b/src/main/browser-drawer/bridge-process.ts
new file mode 100644
index 000000000..2d8fe4101
--- /dev/null
+++ b/src/main/browser-drawer/bridge-process.ts
@@ -0,0 +1,228 @@
+/**
+ * The browser bridge process
+ * ==========================
+ *
+ * browser-bridge.cjs, started where the browsers run: natively with Workbench's executable as
+ * Node (ELECTRON_RUN_AS_NODE), in WSL mode with the distribution's node (spawnTool), since the
+ * browsers, their registry and their Unix sockets are inside the distribution. Messages go over
+ * its stdin/stdout as JSON headers with bytes (bridge-framing.ts), so JPEG frames arrive as
+ * bytes. It loads each browser's own playwright-core from the session's registry descriptor:
+ * nothing of Playwright ships with the app, and the client always matches the server that
+ * launched the browser. It runs apart from the main process so Playwright's client and the frames
+ * never weigh on it; it exits when its stdin closes, so it never outlives Workbench.
+ */
+
+import type { ChildProcess } from 'child_process';
+import { writeFile } from 'fs/promises';
+import { makeTempFolder, removeTempFolder, TEMP_FOLDER_PREFIXES } from '../temp-folders';
+import path from 'path';
+import { EventEmitter } from 'events';
+import { appLog } from '../app-logger';
+import { getWslInfo, whenShellRuntimeReady } from '../platform/shell-runtime';
+import { killRuntimeProcess, spawnTool } from '../platform/runtime-exec';
+import { resolveCommand } from '../mcp-commands';
+import type { BrowserDrawerInput, BrowserDrawerNavigation, BrowserDrawerPage } from '../../shared/types/browser-drawer';
+import { createBridgeMessageReader, encodeBridgeMessage } from './bridge-framing';
+import BRIDGE_SOURCE from './browser-bridge.cjs?raw';
+
+/** A browser the bridge connects to (from its registry descriptor) */
+export interface BridgeSession {
+ id: string;
+ endpoint: string;
+ browserName: string;
+ playwrightLib: string;
+}
+
+export type BridgeRequest =
+ | { type: 'sessions'; sessions: BridgeSession[] }
+ | { type: 'view'; viewerId: number; pageId: string | null; width: number; height: number; scale?: number }
+ | { type: 'input'; pageId: string; event: BrowserDrawerInput }
+ | { type: 'frameAck'; pageId: string }
+ | { type: 'navigate'; pageId: string; action: BrowserDrawerNavigation; url?: string }
+ | { type: 'closePage'; pageId: string }
+ | { type: 'newPage'; sessionId: string }
+ | { type: 'probe'; id: number; endpoints: string[] }
+ | { type: 'colorScheme'; scheme: 'light' | 'dark' };
+
+export type BridgeMessage =
+ | { type: 'pages'; pages: BrowserDrawerPage[]; connected?: string[] }
+ | { type: 'frame'; pageId: string; viewers: number[]; data: Uint8Array; width: number; height: number }
+ | { type: 'log'; message: string }
+ | { type: 'probed'; id: number; live: string[] };
+
+export interface BridgeProcessOptions {
+ /** The bridge script (written to a temporary folder when not given) */
+ scriptPath?: string;
+ /** The executable that runs it as Node natively (Workbench's own) */
+ execPath?: string;
+}
+
+/** How long a liveness probe may take (each endpoint is given a second) */
+const PROBE_TIMEOUT_MS = 10_000;
+
+/** Emits 'message' (BridgeMessage) and 'exit' */
+export class BrowserBridgeProcess extends EventEmitter {
+ private child: ChildProcess | null = null;
+ private starting: Promise | null = null;
+ private tempDir: string | null = null;
+ private nextProbeId = 1;
+ private readonly probes = new Map void>();
+ /** Stopped (the app is quitting): never started again, also not by a probe */
+ private stopped = false;
+
+ constructor(private readonly options: BridgeProcessOptions = {}) {
+ super();
+ }
+
+ get running(): boolean {
+ return this.child !== null;
+ }
+
+ /** Start the bridge (once) */
+ start(): Promise {
+ if (this.stopped) return Promise.reject(new Error('The browser bridge was stopped'));
+ if (this.child) return Promise.resolve();
+ this.starting ??= this.spawn().finally(() => {
+ this.starting = null;
+ });
+ return this.starting;
+ }
+
+ /**
+ * Which of these endpoints answer, asked from where the browsers run (WSL mode: the main
+ * process can't reach their sockets). Null when the bridge couldn't tell (not running, no answer)
+ */
+ async probe(endpoints: string[]): Promise | null> {
+ await this.start().catch(() => undefined);
+ if (!this.child) return null;
+ const id = this.nextProbeId++;
+ const live = await new Promise((resolve) => {
+ const timer = setTimeout(() => {
+ this.probes.delete(id);
+ resolve(null);
+ }, PROBE_TIMEOUT_MS);
+ this.probes.set(id, (result) => {
+ clearTimeout(timer);
+ this.probes.delete(id);
+ resolve(result);
+ });
+ if (!this.write({ type: 'probe', id, endpoints })) this.probes.get(id)?.(null);
+ });
+ return live ? new Set(live) : null;
+ }
+
+ private async spawn(): Promise {
+ await whenShellRuntimeReady();
+ // Looked up before the script's folder is made: without node in WSL every probe would make one
+ const wsl = getWslInfo();
+ const command = wsl ? await resolveCommand('node') : this.options.execPath ?? process.execPath;
+ if (!command) {
+ throw new Error(`Node.js was not found in WSL (${wsl?.distro ?? 'unknown'}), which the browser drawer needs`);
+ }
+ let script = this.options.scriptPath;
+ if (!script) {
+ // On the Windows side in WSL mode too: the distribution's node reads it through /mnt
+ this.tempDir = await makeTempFolder(TEMP_FOLDER_PREFIXES.browserBridge);
+ script = path.join(this.tempDir, 'browser-bridge.cjs');
+ await writeFile(script, BRIDGE_SOURCE, 'utf-8');
+ }
+ // Stopped while it was being set up (quitting): it must not start after stop() returned
+ if (this.stopped) {
+ await this.removeTempDir();
+ throw new Error('The browser bridge was stopped');
+ }
+ const child = spawnTool('node', [script], {
+ command,
+ stdio: ['pipe', 'pipe', 'pipe'],
+ ...(wsl ? {} : { env: { ...process.env, ELECTRON_RUN_AS_NODE: '1' } }),
+ windowsHide: true,
+ });
+ this.child = child;
+ const read = createBridgeMessageReader(
+ (message) => this.onMessage(message as BridgeMessage),
+ (skipped) => appLog.warn(`[BrowserDrawer] Skipped ${skipped} bytes from the bridge that weren't a message`),
+ );
+ child.stdout?.on('data', (data: Buffer) => read(data));
+ child.stdin?.on('error', () => undefined);
+ child.stderr?.on('data', (data: Buffer) => {
+ const text = data.toString('utf-8').trim();
+ if (text) appLog.warn(`[BrowserDrawer] Bridge: ${text}`);
+ });
+ // Gone: exited, or never started (no exit event follows a failed start)
+ const gone = () => {
+ if (this.child !== child) return;
+ this.child = null;
+ for (const settle of [...this.probes.values()]) settle(null);
+ void this.removeTempDir();
+ this.emit('exit');
+ };
+ child.on('error', (error) => {
+ appLog.warn('[BrowserDrawer] Bridge error:', error);
+ if (child.pid === undefined) gone();
+ });
+ child.on('exit', (code) => {
+ if (code && this.child === child) appLog.warn(`[BrowserDrawer] The browser bridge stopped (code ${code})`);
+ gone();
+ });
+ }
+
+ private onMessage(message: BridgeMessage): void {
+ if (message.type === 'probed') {
+ this.probes.get(message.id)?.(Array.isArray(message.live) ? message.live : []);
+ return;
+ }
+ this.emit('message', message);
+ }
+
+ send(request: BridgeRequest): void {
+ this.write(request);
+ }
+
+ private write(request: BridgeRequest): boolean {
+ const stdin = this.child?.stdin;
+ if (!stdin || stdin.destroyed || !stdin.writable) return false;
+ try {
+ stdin.write(encodeBridgeMessage(request as unknown as Record));
+ return true;
+ } catch (error) {
+ appLog.warn('[BrowserDrawer] Could not reach the bridge:', error);
+ return false;
+ }
+ }
+
+ /** Stop the bridge (it disconnects from the browsers, which keep running) */
+ stop(): Promise {
+ this.stopped = true;
+ const child = this.child;
+ this.child = null;
+ for (const settle of [...this.probes.values()]) settle(null);
+ if (!child || child.exitCode !== null) return this.removeTempDir();
+ return new Promise((resolve) => {
+ const timer = setTimeout(() => {
+ killRuntimeProcess(child, { timeoutMs: 1000 });
+ resolve();
+ }, 3000);
+ child.once('exit', () => {
+ clearTimeout(timer);
+ resolve();
+ });
+ // Its input ends: it disconnects and exits
+ child.stdin?.end();
+ }).then(() => this.removeTempDir());
+ }
+
+ /** Stop at once (the app is exiting) */
+ killNow(): void {
+ this.stopped = true;
+ const child = this.child;
+ this.child = null;
+ child?.stdin?.destroy();
+ child?.kill();
+ }
+
+ private async removeTempDir(): Promise {
+ const dir = this.tempDir;
+ this.tempDir = null;
+ if (dir) await removeTempFolder(dir);
+ }
+}
diff --git a/src/main/browser-drawer/browser-bridge.cjs b/src/main/browser-drawer/browser-bridge.cjs
new file mode 100644
index 000000000..2dca76746
--- /dev/null
+++ b/src/main/browser-drawer/browser-bridge.cjs
@@ -0,0 +1,519 @@
+// Workbench's browser bridge (the browser drawer's link to Playwright's headless browsers)
+//
+// Started by the main process (bridge-process.ts): natively with Workbench's executable as Node,
+// in WSL mode with the distribution's node (the browsers, their registry and sockets are there).
+// Messages go over stdin/stdout as length-prefixed JSON headers with optional bytes (a frame's
+// JPEG), the codec of bridge-framing.ts; stdout carries nothing else (console output goes to
+// stderr), and the bridge exits when stdin ends (Workbench is gone). It connects to the bound
+// browsers it is given (Playwright's registry endpoint) with each browser's own playwright-core (`require(playwrightLib)`, the npx cache of
+// the MCP server that launched it), the way Playwright's own dashboard does; disconnecting leaves
+// the browser running. It reports their pages, streams the viewed pages as JPEG frames
+// (`page.screencast`, one at a time: the next goes once the drawer drew the last), sizes a viewed page's viewport to the drawer, gives every page Workbench's
+// theme as its `prefers-color-scheme`, and replays the viewer's mouse, wheel and keys on it; it also says which registry endpoints answer (`probe`), for WSL
+// mode, where the main process can't reach the sockets. Plain Node, no packages of its own.
+'use strict';
+const net = require('net');
+
+/** session id -> { browser, key } */
+const sessions = new Map();
+/** page id -> { page, sessionId } */
+const pages = new Map();
+const pageIds = new WeakMap();
+let nextPageId = 1;
+/** How long connecting to a browser may take */
+const CONNECT_TIMEOUT_MS = 15000;
+/** How long a viewport change or a screencast's start or stop may hold up the commands after it */
+const COMMAND_TIMEOUT_MS = 5000;
+/** How long one input event may take before the page's next one goes (a page that never answers can't hold up its input) */
+const INPUT_TIMEOUT_MS = 5000;
+/** How long a frame may wait for the drawer to draw it before the next one goes anyway */
+const FRAME_ACK_TIMEOUT_MS = 1000;
+/**
+ * page id -> { viewers: Map, size: the frame size asked for | null, sending: the
+ * frame the drawer is drawing | null, next: the newest frame waiting for it | null }. Frames are
+ * asked at the viewport times the largest viewer's devicePixelRatio, so they are sharp on HiDPI
+ * screens (browsers render that many pixels only when launched for it: mcp-config.ts). One frame
+ * is on its way at a time and frames waiting meanwhile are replaced by newer ones; each frame's
+ * screencast acknowledgement waits for that, so the browser makes no more frames than the drawer
+ * draws (instead of flooding the main process and the window)
+ */
+const casts = new Map();
+/** viewer id -> page id */
+const viewers = new Map();
+/** Workbench's theme, which every page gets as its `prefers-color-scheme` (null: the browser's own) */
+let colorScheme = null;
+
+// stdout is the message channel: anything else printed goes to stderr
+const writeOut = process.stdout.write.bind(process.stdout);
+console.log = console.info = console.debug = (...args) => console.error(...args);
+process.stdout.write = (chunk, ...rest) => process.stderr.write(chunk, ...rest);
+
+/** One message as bytes (bridge-framing.ts's codec): a Uint8Array field travels as raw bytes */
+function encode(message) {
+ let bytes = null;
+ const header = {};
+ for (const [key, value] of Object.entries(message)) {
+ if (value instanceof Uint8Array && !bytes) {
+ bytes = value;
+ header.$bytes = key;
+ } else {
+ header[key] = value;
+ }
+ }
+ const json = Buffer.from(JSON.stringify(header), 'utf-8');
+ const prefix = Buffer.alloc(10);
+ prefix[0] = 0x57;
+ prefix[1] = 0x42;
+ prefix.writeUInt32BE(json.length, 2);
+ prefix.writeUInt32BE(bytes ? bytes.length : 0, 6);
+ return Buffer.concat(bytes ? [prefix, json, Buffer.from(bytes.buffer, bytes.byteOffset, bytes.length)] : [prefix, json]);
+}
+
+let outputClosed = false;
+process.stdout.on('error', () => {
+ outputClosed = true;
+});
+const send = (message) => {
+ if (outputClosed) return;
+ try {
+ writeOut(encode(message));
+ } catch {
+ // Workbench is gone
+ }
+};
+const log = (message) => send({ type: 'log', message: String(message && message.message ? message.message : message) });
+
+// Commands run one at a time (connects, screencasts, viewport changes); input has a queue per
+// page (inputQueues) so it stays in order without waiting behind a slow navigation or another page
+let queue = Promise.resolve();
+const enqueue = (fn) => (queue = queue.then(fn).catch(log));
+
+/** A promise's result, or `fallback` once it took `ms` (it may still settle later; a rejection passes through) */
+function bounded(promise, ms, fallback) {
+ return new Promise((resolve, reject) => {
+ const timer = setTimeout(() => resolve(fallback), ms);
+ promise.then(
+ (value) => {
+ clearTimeout(timer);
+ resolve(value);
+ },
+ (error) => {
+ clearTimeout(timer);
+ reject(error);
+ }
+ );
+ });
+}
+
+let pagesTimer = null;
+function pushPages() {
+ if (pagesTimer) return;
+ pagesTimer = setTimeout(async () => {
+ pagesTimer = null;
+ const list = await Promise.all([...pages].map(async ([id, entry]) => ({
+ id,
+ sessionId: entry.sessionId,
+ url: entry.page.url(),
+ title: await entry.page.title().catch(() => ''),
+ })));
+ send({ type: 'pages', pages: list, connected: [...sessions.keys()] });
+ }, 100);
+}
+
+/** Give a page Workbench's theme (some browsers can't emulate it: their pages keep their own) */
+function applyColorScheme(page) {
+ if (colorScheme) page.emulateMedia({ colorScheme }).catch(() => undefined);
+}
+
+function addPage(page, sessionId) {
+ if (pageIds.has(page)) return;
+ const id = `${sessionId}#${nextPageId++}`;
+ pageIds.set(page, id);
+ pages.set(id, { page, sessionId });
+ applyColorScheme(page);
+ page.on('close', () => {
+ pages.delete(id);
+ dropCast(id);
+ inputQueues.delete(id);
+ pushPages();
+ });
+ page.on('framenavigated', (frame) => {
+ if (frame === page.mainFrame()) pushPages();
+ });
+ page.on('load', pushPages);
+ pushPages();
+}
+
+function wireContext(context, sessionId) {
+ for (const page of context.pages()) addPage(page, sessionId);
+ context.on('page', (page) => addPage(page, sessionId));
+}
+
+async function connect(session) {
+ const key = `${session.endpoint}|${session.playwrightLib}`;
+ const previous = sessions.get(session.id);
+ if (previous?.key === key) return;
+ // The browser moved (another endpoint or playwright-core): the old link and its pages go first
+ if (previous) {
+ dropSession(session.id);
+ await previous.browser.close().catch(() => undefined);
+ }
+ const playwright = require(session.playwrightLib);
+ const browserType = playwright[session.browserName] || playwright.chromium;
+ // Bounded: commands run one at a time, so a browser that never answers must not hold up the rest
+ const browser = await browserType.connect(session.endpoint, { timeout: CONNECT_TIMEOUT_MS });
+ sessions.set(session.id, { browser, key });
+ for (const context of browser.contexts()) wireContext(context, session.id);
+ browser.on('context', (context) => wireContext(context, session.id));
+ browser.on('disconnected', () => {
+ if (sessions.get(session.id)?.browser === browser) dropSession(session.id);
+ });
+ pushPages();
+}
+
+/** A new tab in a session's browser (its first context: the one its MCP server uses) */
+async function newPage(sessionId) {
+ const entry = sessions.get(sessionId);
+ if (!entry) return;
+ const context = entry.browser.contexts()[0] || (await entry.browser.newContext());
+ const page = await context.newPage();
+ addPage(page, sessionId);
+}
+
+function dropSession(sessionId) {
+ sessions.delete(sessionId);
+ for (const [id, entry] of pages) {
+ if (entry.sessionId !== sessionId) continue;
+ pages.delete(id);
+ dropCast(id);
+ inputQueues.delete(id);
+ }
+ pushPages();
+}
+
+async function setSessions(list) {
+ const wanted = new Set(list.map((s) => s.id));
+ for (const [id, entry] of sessions) {
+ if (wanted.has(id)) continue;
+ dropSession(id);
+ // A connected client only disconnects; the browser keeps running
+ await entry.browser.close().catch(() => undefined);
+ }
+ for (const session of list) {
+ await connect(session).catch((error) => log(`Could not connect to ${session.id}: ${error.message}`));
+ }
+}
+
+/** Send a page's frame to its viewers; `done` acknowledges it to the browser once it is drawn */
+function sendFrame(pageId, cast, frame, done) {
+ send({ type: 'frame', pageId, viewers: [...cast.viewers.keys()], ...frame });
+ cast.sending = { done, timer: setTimeout(() => frameDrawn(pageId), FRAME_ACK_TIMEOUT_MS) };
+}
+
+/** A viewer drew the page's frame (or it took too long): the newest waiting frame goes next */
+function frameDrawn(pageId) {
+ const cast = casts.get(pageId);
+ if (!cast || !cast.sending) return;
+ clearTimeout(cast.sending.timer);
+ cast.sending.done();
+ cast.sending = null;
+ const next = cast.next;
+ cast.next = null;
+ if (!next) return;
+ if (cast.viewers.size > 0) sendFrame(pageId, cast, next.frame, next.done);
+ else next.done();
+}
+
+/** A cast ends: its frames on their way or waiting are acknowledged */
+function dropCast(pageId) {
+ const cast = casts.get(pageId);
+ if (!cast) return;
+ casts.delete(pageId);
+ if (cast.sending) {
+ clearTimeout(cast.sending.timer);
+ cast.sending.done();
+ }
+ cast.next?.done();
+ cast.sending = cast.next = null;
+}
+
+async function startCast(pageId) {
+ const entry = pages.get(pageId);
+ const cast = casts.get(pageId);
+ if (!entry || !cast) return;
+ const viewport = entry.page.viewportSize() || { width: 1280, height: 720 };
+ const scale = Math.max(1, ...cast.viewers.values());
+ const size = { width: Math.round(viewport.width * scale), height: Math.round(viewport.height * scale) };
+ if (cast.size && cast.size.width === size.width && cast.size.height === size.height) return;
+ if (cast.size) {
+ await bounded(entry.page.screencast.stop().catch(() => undefined), COMMAND_TIMEOUT_MS);
+ cast.size = null;
+ }
+ const started = await bounded(
+ entry.page.screencast
+ .start({
+ size,
+ // The best JPEG quality: lower ones blur small text (frames are local, so their size matters little)
+ quality: 100,
+ onFrame: ({ data, viewportWidth, viewportHeight }) => {
+ const current = casts.get(pageId);
+ if (!current || current.viewers.size === 0) return;
+ // The viewport in CSS pixels (Firefox reports the frame's device pixels as its viewport)
+ const css = entry.page.viewportSize() || { width: viewportWidth, height: viewportHeight };
+ const frame = { data, width: css.width, height: css.height };
+ // Acknowledged to the browser once drawn, or once a newer frame replaced it
+ return new Promise((done) => {
+ if (!current.sending) {
+ sendFrame(pageId, current, frame, done);
+ return;
+ }
+ current.next?.done();
+ current.next = { frame, done };
+ });
+ },
+ })
+ .then(() => true),
+ COMMAND_TIMEOUT_MS,
+ false
+ );
+ // Only a cast that started counts: one that failed (the page was navigating) is tried again
+ if (started) cast.size = size;
+}
+
+async function stopCast(pageId) {
+ const cast = casts.get(pageId);
+ if (!cast || cast.viewers.size > 0) return;
+ dropCast(pageId);
+ const entry = pages.get(pageId);
+ if (entry && cast.size) await bounded(entry.page.screencast.stop().catch(() => undefined), COMMAND_TIMEOUT_MS);
+}
+
+async function view(viewerId, pageId, width, height, scale) {
+ const previous = viewers.get(viewerId);
+ if (previous && previous !== pageId) {
+ casts.get(previous)?.viewers.delete(viewerId);
+ viewers.delete(viewerId);
+ await stopCast(previous);
+ }
+ const entry = pageId ? pages.get(pageId) : undefined;
+ if (!entry) {
+ viewers.delete(viewerId);
+ return;
+ }
+ viewers.set(viewerId, pageId);
+ // The page fills the drawer: its viewport is the drawer's page area (what the agent sees too)
+ if (width > 0 && height > 0) {
+ const current = entry.page.viewportSize();
+ if (!current || current.width !== width || current.height !== height) {
+ await bounded(entry.page.setViewportSize({ width, height }).catch((error) => log(error)), COMMAND_TIMEOUT_MS);
+ }
+ }
+ let cast = casts.get(pageId);
+ if (!cast) {
+ cast = { viewers: new Map(), size: null, sending: null, next: null };
+ casts.set(pageId, cast);
+ }
+ cast.viewers.set(viewerId, Number.isFinite(scale) && scale >= 1 ? Math.min(scale, 2) : 1);
+ await startCast(pageId);
+}
+
+/** page id -> { events: its input waiting to be replayed, in order; running } */
+const inputQueues = new Map();
+
+/**
+ * Queue a viewer's input for its page. Mouse moves and wheel steps waiting behind a slow one are
+ * merged into the newest (a busy page answers each event late: replaying every move of the
+ * pointer would hold a click up for seconds)
+ */
+function queueInput(pageId, event) {
+ if (!event || !pages.has(pageId)) return;
+ let queue = inputQueues.get(pageId);
+ if (!queue) {
+ queue = { events: [], running: false };
+ inputQueues.set(pageId, queue);
+ }
+ const last = queue.events[queue.events.length - 1];
+ if (last && last.kind === 'mousemove' && event.kind === 'mousemove') {
+ queue.events[queue.events.length - 1] = event;
+ } else if (last && last.kind === 'wheel' && event.kind === 'wheel') {
+ queue.events[queue.events.length - 1] = {
+ ...event,
+ deltaX: (last.deltaX || 0) + (event.deltaX || 0),
+ deltaY: (last.deltaY || 0) + (event.deltaY || 0),
+ };
+ } else {
+ queue.events.push(event);
+ }
+ if (!queue.running) void replayInput(pageId, queue);
+}
+
+async function replayInput(pageId, queue) {
+ queue.running = true;
+ while (queue.events.length > 0) {
+ const event = queue.events.shift();
+ await bounded(input(pageId, event).catch(() => undefined), INPUT_TIMEOUT_MS);
+ }
+ queue.running = false;
+}
+
+async function input(pageId, event) {
+ const page = pages.get(pageId)?.page;
+ if (!page) return;
+ const button = ['left', 'right', 'middle'].includes(event.button) ? event.button : 'left';
+ switch (event.kind) {
+ case 'mousemove':
+ await page.mouse.move(event.x, event.y);
+ break;
+ case 'mousedown':
+ await page.mouse.move(event.x, event.y);
+ await page.mouse.down({ button, clickCount: event.clickCount || 1 });
+ break;
+ case 'mouseup':
+ await page.mouse.move(event.x, event.y);
+ await page.mouse.up({ button, clickCount: event.clickCount || 1 });
+ break;
+ case 'wheel':
+ await page.mouse.move(event.x, event.y);
+ await page.mouse.wheel(event.deltaX || 0, event.deltaY || 0);
+ break;
+ case 'keydown':
+ try {
+ await page.keyboard.down(event.key);
+ } catch {
+ // A character Playwright has no key for (another layout): typed as text
+ if ([...event.key].length === 1) await page.keyboard.insertText(event.key);
+ }
+ break;
+ case 'keyup':
+ await page.keyboard.up(event.key).catch(() => undefined);
+ break;
+ case 'text':
+ await page.keyboard.insertText(String(event.text || ''));
+ break;
+ }
+}
+
+async function navigate(pageId, action, url) {
+ const page = pages.get(pageId)?.page;
+ if (!page) return;
+ const options = { timeout: 30000 };
+ if (action === 'back') await page.goBack(options);
+ else if (action === 'forward') await page.goForward(options);
+ else if (action === 'reload') await page.reload(options);
+ else if (action === 'goto' && url) await page.goto(url, options);
+}
+
+/** Whether a bound browser's socket (or ws:// endpoint) answers; a slow answer counts as live (registry.ts canConnect) */
+function canConnect(endpoint) {
+ return new Promise((resolve) => {
+ let socket;
+ try {
+ if (/^wss?:\/\//.test(endpoint)) {
+ const url = new URL(endpoint);
+ socket = net.createConnection(Number(url.port) || (url.protocol === 'wss:' ? 443 : 80), url.hostname);
+ } else {
+ socket = net.createConnection(endpoint);
+ }
+ } catch {
+ resolve(false);
+ return;
+ }
+ const done = (result) => {
+ clearTimeout(timer);
+ socket.destroy();
+ resolve(result);
+ };
+ const timer = setTimeout(() => done(true), 1000);
+ socket.once('connect', () => done(true));
+ socket.once('error', () => done(false));
+ });
+}
+
+/** Which of the endpoints answer (WSL mode: the main process can't reach the sockets) */
+async function probe(id, endpoints) {
+ const list = Array.isArray(endpoints) ? endpoints.filter((e) => typeof e === 'string') : [];
+ const answers = await Promise.all(list.map((endpoint) => canConnect(endpoint)));
+ send({ type: 'probed', id, live: list.filter((_, index) => answers[index]) });
+}
+
+function onMessage(message) {
+ if (!message || typeof message !== 'object') return;
+ switch (message.type) {
+ case 'sessions':
+ enqueue(() => setSessions(Array.isArray(message.sessions) ? message.sessions : []));
+ break;
+ case 'view':
+ enqueue(() => view(message.viewerId, message.pageId, Math.round(message.width), Math.round(message.height), Number(message.scale)));
+ break;
+ case 'input':
+ queueInput(message.pageId, message.event);
+ break;
+ case 'navigate':
+ // Not queued: a slow page must not hold up the other commands
+ navigate(message.pageId, message.action, message.url).catch(log);
+ break;
+ case 'frameAck':
+ frameDrawn(message.pageId);
+ break;
+ case 'closePage':
+ pages.get(message.pageId)?.page.close().catch(log);
+ break;
+ case 'newPage':
+ enqueue(() => newPage(message.sessionId));
+ break;
+ case 'probe':
+ // Not queued: answered while a slow connect runs
+ probe(message.id, message.endpoints).catch(log);
+ break;
+ case 'colorScheme':
+ colorScheme = message.scheme === 'dark' ? 'dark' : 'light';
+ for (const entry of pages.values()) applyColorScheme(entry.page);
+ break;
+ }
+}
+
+// Messages from the main process (bridge-framing.ts's codec)
+let received = Buffer.alloc(0);
+process.stdin.on('data', (chunk) => {
+ received = received.length ? Buffer.concat([received, chunk]) : chunk;
+ for (;;) {
+ let start = 0;
+ while (start < received.length && !(received[start] === 0x57 && (start + 1 >= received.length || received[start + 1] === 0x42))) start++;
+ if (start > 0) received = received.subarray(start);
+ if (received.length < 10) return;
+ const headerLength = received.readUInt32BE(2);
+ const bytesLength = received.readUInt32BE(6);
+ if (headerLength > 64 * 1024 * 1024 || bytesLength > 64 * 1024 * 1024) {
+ received = received.subarray(1);
+ continue;
+ }
+ const total = 10 + headerLength + bytesLength;
+ if (received.length < total) return;
+ let header = null;
+ try {
+ header = JSON.parse(received.subarray(10, 10 + headerLength).toString('utf-8'));
+ } catch {
+ // Skipped
+ }
+ if (header && typeof header.$bytes === 'string') header[header.$bytes] = new Uint8Array(received.subarray(10 + headerLength, total));
+ if (header) delete header.$bytes;
+ received = received.subarray(total);
+ try {
+ onMessage(header);
+ } catch (error) {
+ log(error);
+ }
+ }
+});
+
+// Gone with the main process (its end of stdin closed): disconnect (the browsers keep running)
+let exiting = false;
+function exitBridge() {
+ if (exiting) return;
+ exiting = true;
+ Promise.all([...sessions.values()].map((entry) => entry.browser.close().catch(() => undefined)))
+ .finally(() => process.exit(0));
+ setTimeout(() => process.exit(0), 2000).unref();
+}
+process.stdin.on('end', exitBridge);
+process.stdin.on('error', exitBridge);
diff --git a/src/main/browser-drawer/browser-drawer-service.ts b/src/main/browser-drawer/browser-drawer-service.ts
new file mode 100644
index 000000000..8758416d5
--- /dev/null
+++ b/src/main/browser-drawer/browser-drawer-service.ts
@@ -0,0 +1,406 @@
+/**
+ * The browser drawer
+ * ==================
+ *
+ * Playwright runs (task runs, Claude chats) launch their browsers headless; the user sees and
+ * drives Claude chats' browsers in the main window's browser drawer, Workbench's own UI. Task runs'
+ * browsers stay headless and unseen: no project is matched for them, so no window shows them and
+ * the bridge never connects to them. This service:
+ * - watches Playwright's registry (registry.ts) every few seconds and tells every window the
+ * live sessions, each chat's with the project it belongs to (project-match.ts), so a window can
+ * show that its project has browsers and open the drawer when one starts
+ * - once a drawer opens, runs the browser bridge (bridge-process.ts, until quit), which connects to the
+ * projects' browsers and reports their pages, streams the page a window views as JPEG frames
+ * (sent to that window only), sizes it to the window's drawer, replays the window's input and
+ * opens new tabs
+ * - opens and closes the chats' own browsers (chat-browsers.ts), which it tells by their title
+ *
+ * In WSL mode the browsers run inside the distribution, where their registry and sockets are: the
+ * registry is read through `\\wsl.localhost`, the bridge runs there (with the distribution's
+ * node) and also says which registered browsers answer, and workspace folders are matched to
+ * projects as Windows paths (toHostPath).
+ */
+
+import type { WebContents } from 'electron';
+import { IPC_CHANNELS } from '../../shared/constants';
+import type {
+ BrowserDrawerInput,
+ BrowserDrawerNavigation,
+ BrowserDrawerPage,
+ BrowserDrawerSession,
+ BrowserDrawerState,
+} from '../../shared/types/browser-drawer';
+import type { PlaywrightBrowserChoice } from '../../shared/types/browser-profiles';
+import { appLog } from '../app-logger';
+import { isMacOS, isWindows } from '../platform';
+import { getWslInfo, toHostPath, whenShellRuntimeReady } from '../platform/shell-runtime';
+import path from 'path';
+import { getAllWindows } from '../window-manager';
+import { clampPixelScale } from './pixel-scale';
+import { readLiveSessions, registryAccess, registryOs, setRegistryAccess, type RegistryDescriptor } from './registry';
+import { getChatBrowserWorkspaces, sessionProjectId, type ProjectLocation } from './project-match';
+import { BrowserBridgeProcess, type BridgeMessage, type BridgeSession } from './bridge-process';
+import { ChatBrowsers } from './chat-browsers';
+
+/** How often the registry is read */
+const POLL_INTERVAL_MS = 2000;
+/** The largest viewport the drawer may give a page */
+const MAX_VIEWPORT = 4096;
+
+/** The sessions as the renderer gets them, each with its project (and chat, for a chat's browser) */
+export function toDrawerSessions(
+ descriptors: readonly RegistryDescriptor[],
+ projects: readonly ProjectLocation[],
+ chats: ReadonlyMap,
+ caseInsensitive: boolean,
+ chatOfTitle: (title: string) => { projectId: string; chatId: string; browser?: PlaywrightBrowserChoice | null } | undefined = () => undefined,
+ /** A workspace folder as the app stores paths (WSL mode: the distribution's Linux paths as Windows ones) */
+ hostPath: (dir: string) => string = (dir) => dir,
+): BrowserDrawerSession[] {
+ return descriptors.map((descriptor) => {
+ const workspaceDir = descriptor.workspaceDir ? hostPath(descriptor.workspaceDir) : undefined;
+ const projectId = sessionProjectId(workspaceDir, projects, chats, caseInsensitive);
+ const chat = projectId ? chatOfTitle(descriptor.title) : undefined;
+ // A chat's browser shows the browser the chat chose: the registry can't tell, since a profile's
+ // browser may run on Playwright's own build (a Windows Firefox profile in WSL) or be attached
+ // over CDP with no executable recorded (a Windows Chromium browser in WSL)
+ const chosen = chat && chat.projectId === projectId ? chat.browser : undefined;
+ return {
+ id: descriptor.guid,
+ title: descriptor.title,
+ browserName: chosen === undefined ? descriptor.browserName : chosen?.engine ?? 'chromium',
+ managed: chosen === undefined ? descriptor.managed : chosen === null || !!chosen.managed,
+ ...(workspaceDir ? { workspaceDir } : {}),
+ ...(projectId ? { projectId } : {}),
+ ...(chat && chat.projectId === projectId ? { chatId: chat.chatId } : {}),
+ };
+ });
+}
+
+/** The sessions the bridge connects to: the projects' ones (never another tool's browsers) */
+export function bridgeSessions(descriptors: readonly RegistryDescriptor[], sessions: readonly BrowserDrawerSession[]): BridgeSession[] {
+ const withProject = new Set(sessions.filter((s) => s.projectId).map((s) => s.id));
+ return descriptors
+ .filter((d): d is RegistryDescriptor & { endpoint: string; playwrightLib: string } =>
+ withProject.has(d.guid) && !!d.endpoint && !!d.playwrightLib)
+ .map((d) => ({ id: d.guid, endpoint: d.endpoint, browserName: d.browserName, playwrightLib: d.playwrightLib }));
+}
+
+/** A viewport size the drawer may ask for (whole CSS pixels within limits), or 0 for none */
+export function viewportDimension(value: unknown): number {
+ const n = typeof value === 'number' && Number.isFinite(value) ? Math.round(value) : 0;
+ return n > 0 ? Math.min(n, MAX_VIEWPORT) : 0;
+}
+
+/** Device pixels per CSS pixel the drawer's frames are asked at: the window's devicePixelRatio, 1 to 2 */
+export function frameScale(value: unknown): number {
+ return clampPixelScale(value);
+}
+
+/** Whether a renderer's input event has the shape the bridge replays */
+export function isDrawerInput(event: unknown): event is BrowserDrawerInput {
+ if (!event || typeof event !== 'object') return false;
+ const e = event as Record;
+ const num = (v: unknown) => typeof v === 'number' && Number.isFinite(v);
+ switch (e.kind) {
+ case 'mousemove':
+ return num(e.x) && num(e.y);
+ case 'mousedown':
+ case 'mouseup':
+ return num(e.x) && num(e.y) && ['left', 'right', 'middle'].includes(e.button as string) && num(e.clickCount);
+ case 'wheel':
+ return num(e.x) && num(e.y) && num(e.deltaX) && num(e.deltaY);
+ case 'keydown':
+ case 'keyup':
+ return typeof e.key === 'string' && e.key.length > 0 && e.key.length <= 32;
+ case 'text':
+ return typeof e.text === 'string' && e.text.length <= 100_000;
+ default:
+ return false;
+ }
+}
+
+export interface BrowserDrawerServiceOptions {
+ getProjects: () => readonly ProjectLocation[];
+ registryDir?: string;
+ bridge?: BrowserBridgeProcess;
+ chatBrowsers?: ChatBrowsers;
+}
+
+export class BrowserDrawerService {
+ private descriptors: RegistryDescriptor[] = [];
+ private sessions: BrowserDrawerSession[] = [];
+ private pages: BrowserDrawerPage[] = [];
+ /** The sessions the bridge is connected to */
+ private connectedSessions: string[] = [];
+ private readonly dead = new Map();
+ private timer: ReturnType | null = null;
+ private pollInFlight: Promise | null = null;
+ private stopped = false;
+ private readonly bridge: BrowserBridgeProcess;
+ /** Windows whose drawer is open */
+ private readonly subscribers = new Map();
+ /**
+ * The page each window last asked to view. A reopened drawer's page asks before the drawer has
+ * subscribed (child effects run first), so the request is kept and sent once it subscribes
+ */
+ private readonly views = new Map();
+ private lastBridgeSessions = '';
+ /** Workbench's theme, which the chat browsers' pages get as their color scheme (null: not told yet) */
+ private colorScheme: 'light' | 'dark' | null = null;
+ readonly chatBrowsers: ChatBrowsers;
+
+ constructor(private readonly options: BrowserDrawerServiceOptions) {
+ this.bridge = options.bridge ?? new BrowserBridgeProcess();
+ this.chatBrowsers = options.chatBrowsers ?? new ChatBrowsers();
+ this.bridge.on('message', (message: BridgeMessage) => this.onBridgeMessage(message));
+ this.bridge.on('exit', () => {
+ this.lastBridgeSessions = '';
+ if (this.pages.length || this.connectedSessions.length) {
+ this.pages = [];
+ this.connectedSessions = [];
+ this.broadcast();
+ }
+ });
+ // A chat browser that opened shows up in the registry: read it now rather than in a while
+ this.chatBrowsers.on('change', () => {
+ this.broadcast();
+ if (this.timer) void this.poll();
+ });
+ }
+
+ /**
+ * Start watching the registry. In WSL mode the browsers run inside the distribution: its
+ * registry is read through `\\wsl.localhost`, and whether a browser runs is asked of the bridge,
+ * which runs there too (Windows can't reach the browsers' Unix sockets)
+ */
+ async start(): Promise {
+ await whenShellRuntimeReady();
+ if (this.stopped) return;
+ const wsl = getWslInfo();
+ if (wsl && !this.options.registryDir) {
+ setRegistryAccess({
+ dir: toHostPath(path.posix.join(wsl.home, '.cache', 'ms-playwright', 'b')),
+ // Only a running bridge is asked: a check never starts it (it runs once a drawer opens).
+ // Until then the chat browsers Workbench holds open count as live (knownLive below)
+ connect: (endpoint) => (this.bridge.running
+ ? this.bridge.probe([endpoint]).then((live) => (live ? live.has(endpoint) : null))
+ : Promise.resolve(null)),
+ });
+ }
+ void this.poll();
+ this.timer = setInterval(() => void this.poll(), POLL_INTERVAL_MS);
+ this.timer.unref?.();
+ }
+
+ getState(): BrowserDrawerState {
+ return {
+ available: true,
+ sessions: this.sessions,
+ pages: this.pages,
+ connectedSessions: this.connectedSessions,
+ chatBrowsers: this.chatBrowsers.list(),
+ };
+ }
+
+ /** A window's drawer opened: the bridge runs and tracks the projects' pages */
+ async subscribe(sender: WebContents): Promise {
+ if (this.stopped) return;
+ if (!this.subscribers.has(sender.id)) {
+ const id = sender.id;
+ this.subscribers.set(id, sender);
+ sender.once('destroyed', () => {
+ this.unsubscribe(id);
+ this.views.delete(id);
+ });
+ }
+ await this.bridge.start();
+ this.syncBridgeSessions(true);
+ // The view asked for before subscribing (unless the drawer closed again meanwhile)
+ const pending = this.views.get(sender.id);
+ if (pending && this.subscribers.has(sender.id) && !sender.isDestroyed()) {
+ this.view(sender, pending.pageId, pending.width, pending.height, pending.scale);
+ }
+ }
+
+ /** Workbench's theme changed (or a drawer opened): the chat browsers' pages follow it */
+ setColorScheme(scheme: unknown): void {
+ if (scheme !== 'light' && scheme !== 'dark') return;
+ if (scheme === this.colorScheme) return;
+ this.colorScheme = scheme;
+ if (this.bridge.running) this.bridge.send({ type: 'colorScheme', scheme });
+ }
+
+ /** A window's drawer closed: its page is no longer streamed */
+ unsubscribe(viewerId: number): void {
+ this.views.delete(viewerId);
+ if (!this.subscribers.delete(viewerId)) return;
+ this.bridge.send({ type: 'view', viewerId, pageId: null, width: 0, height: 0 });
+ }
+
+ view(sender: WebContents, pageId: string | null, width: unknown, height: unknown, scale?: unknown): void {
+ if (this.stopped) return;
+ this.views.set(sender.id, { pageId, width, height, scale });
+ if (!this.subscribers.has(sender.id)) return;
+ const known = pageId !== null && this.pages.some((page) => page.id === pageId);
+ this.bridge.send({
+ type: 'view',
+ viewerId: sender.id,
+ pageId: known ? pageId : null,
+ width: viewportDimension(width),
+ height: viewportDimension(height),
+ scale: frameScale(scale),
+ });
+ }
+
+ input(pageId: string, event: unknown): void {
+ if (!this.pages.some((page) => page.id === pageId) || !isDrawerInput(event)) return;
+ this.bridge.send({ type: 'input', pageId, event });
+ }
+
+ /** A window drew a frame of the page: the bridge sends its next one (one frame is on its way at a time) */
+ frameDrawn(pageId: string): void {
+ if (this.bridge.running) this.bridge.send({ type: 'frameAck', pageId });
+ }
+
+ navigate(pageId: string, action: BrowserDrawerNavigation, url?: string): void {
+ if (!this.pages.some((page) => page.id === pageId)) return;
+ if (action === 'goto') {
+ if (typeof url !== 'string' || !/^(https?|about|file):/i.test(url)) return;
+ this.bridge.send({ type: 'navigate', pageId, action, url });
+ } else if (action === 'back' || action === 'forward' || action === 'reload') {
+ this.bridge.send({ type: 'navigate', pageId, action });
+ }
+ }
+
+ closePage(pageId: string): void {
+ if (this.pages.some((page) => page.id === pageId)) this.bridge.send({ type: 'closePage', pageId });
+ }
+
+ /** Open a new tab in a session's browser */
+ newPage(sessionId: string): void {
+ if (this.sessions.some((session) => session.id === sessionId && session.projectId)) this.bridge.send({ type: 'newPage', sessionId });
+ }
+
+ /** Open a chat's own browser (the drawer's Open browser button, or a turn's first browser tool call) */
+ async openChatBrowser(projectId: string, chatId: string, choice: PlaywrightBrowserChoice | null | undefined): Promise {
+ const project = this.options.getProjects().find((p) => p.id === projectId);
+ if (!project) throw new Error('The project is not open');
+ await this.chatBrowsers.ensure(projectId, project.path, chatId, choice);
+ }
+
+ closeChatBrowser(projectId: string, chatId: string): Promise {
+ return this.chatBrowsers.close(projectId, chatId);
+ }
+
+ /** Stop watching and stop the bridge (the app is quitting; the browsers stop with their runs) */
+ async shutdown(): Promise {
+ this.stopped = true;
+ if (this.timer) clearInterval(this.timer);
+ this.timer = null;
+ await Promise.all([this.bridge.stop(), this.chatBrowsers.shutdown()]);
+ }
+
+ /** Stop the bridge at once (the app is exiting) */
+ killNow(): void {
+ this.bridge.killNow();
+ }
+
+ private onBridgeMessage(message: BridgeMessage): void {
+ if (message.type === 'pages') {
+ this.pages = message.pages;
+ this.connectedSessions = message.connected ?? [];
+ this.noteChatTabs();
+ this.broadcast();
+ } else if (message.type === 'frame') {
+ for (const viewerId of message.viewers) {
+ const target = this.subscribers.get(viewerId);
+ if (target && !target.isDestroyed()) {
+ target.send(IPC_CHANNELS.BROWSER_DRAWER_FRAME, {
+ pageId: message.pageId,
+ data: message.data,
+ width: message.width,
+ height: message.height,
+ });
+ }
+ }
+ } else if (message.type === 'log') {
+ appLog.warn(`[BrowserDrawer] ${message.message}`);
+ }
+ }
+
+ /** The chats' browsers' open tabs, kept in their records for a restart after a crash */
+ private noteChatTabs(): void {
+ const connected = new Set(this.connectedSessions);
+ for (const session of this.sessions) {
+ if (!session.chatId || !session.projectId || !connected.has(session.id)) continue;
+ const tabs = this.pages
+ .filter((page) => page.sessionId === session.id)
+ .map((page) => ({ url: page.url, title: page.title }));
+ this.chatBrowsers.noteTabs(session.projectId, session.chatId, tabs);
+ }
+ }
+
+ /** Tell the bridge the projects' live sessions (when they changed, or `force`) */
+ private syncBridgeSessions(force = false): void {
+ if (!this.bridge.running) return;
+ const sessions = bridgeSessions(this.descriptors, this.sessions);
+ const key = JSON.stringify(sessions);
+ if (!force && key === this.lastBridgeSessions) return;
+ // A bridge that just started (a drawer opened, or in WSL a liveness probe started it again
+ // after it stopped) knows no theme yet: sent before the sessions, so pages get it as they are found
+ if (this.lastBridgeSessions === '' && this.colorScheme) this.bridge.send({ type: 'colorScheme', scheme: this.colorScheme });
+ this.lastBridgeSessions = key;
+ this.bridge.send({ type: 'sessions', sessions });
+ }
+
+ /** Read the registry (once at a time: a call during a read waits for it) */
+ private poll(): Promise {
+ if (this.stopped) return Promise.resolve();
+ this.pollInFlight ??= this.readRegistry().finally(() => {
+ this.pollInFlight = null;
+ });
+ return this.pollInFlight;
+ }
+
+ private async readRegistry(): Promise {
+ try {
+ // The bridge's browsers aren't asked: its link reports when one goes away
+ const connected = new Set(this.connectedSessions);
+ const registry = this.options.registryDir
+ ? { dir: this.options.registryDir, connect: undefined }
+ : registryAccess(registryOs());
+ const wslBeforeBridge = !!getWslInfo() && !this.options.registryDir && !this.bridge.running;
+ this.descriptors = await readLiveSessions(registry.dir, this.dead, registry.connect, (descriptor) => {
+ if (connected.has(descriptor.guid)) return true;
+ if (!wslBeforeBridge) return false;
+ const chat = this.chatBrowsers.chatOfTitle(descriptor.title);
+ return !!chat && this.chatBrowsers.isOpen(chat.projectId, chat.chatId);
+ });
+ this.chatBrowsers.syncLive(new Set(this.descriptors.map((descriptor) => descriptor.title)));
+ const sessions = toDrawerSessions(
+ this.descriptors,
+ this.options.getProjects(),
+ getChatBrowserWorkspaces(),
+ isWindows() || isMacOS(),
+ (title) => this.chatBrowsers.chatOfTitle(title),
+ // WSL mode: the distribution's folders, as the app stores them (Windows paths)
+ getWslInfo() ? toHostPath : undefined,
+ );
+ if (JSON.stringify(sessions) !== JSON.stringify(this.sessions)) {
+ this.sessions = sessions;
+ this.broadcast();
+ }
+ this.syncBridgeSessions();
+ } catch (error) {
+ appLog.warn('[BrowserDrawer] Could not read Playwright\'s registry:', error);
+ }
+ }
+
+ private broadcast(): void {
+ const state = this.getState();
+ for (const window of getAllWindows()) {
+ if (!window.isDestroyed()) window.webContents.send(IPC_CHANNELS.BROWSER_DRAWER_STATE, state);
+ }
+ }
+}
diff --git a/src/main/browser-drawer/chat-browser-restore.ts b/src/main/browser-drawer/chat-browser-restore.ts
new file mode 100644
index 000000000..5945685a9
--- /dev/null
+++ b/src/main/browser-drawer/chat-browser-restore.ts
@@ -0,0 +1,199 @@
+/**
+ * Chat browsers after a crash
+ * ===========================
+ *
+ * A chat's browser (chat-browsers.ts) keeps a record in its folder in the system temp folder
+ * (CHAT_BROWSER_RECORD): its project and chat, the browser it opened, its profile copy and its
+ * open tabs, kept current while it runs. Closing it or quitting removes the folder, so a folder
+ * that is still there and whose Workbench process no longer runs was left by a crash or a kill.
+ *
+ * At startup, before profile copies are swept, scanChatBrowserLeftovers looks at those folders: one
+ * whose chat still exists (its conversation in the project's `.workbench/chats`) and that is
+ * younger than RESTORE_MAX_AGE_MS is kept for that chat (this process takes over its folder and its
+ * profile copy, so no sweep removes them, and quitting leaves them). The next time the chat's
+ * browser opens with the same browser, it starts from that profile (its sign-ins) and reopens the
+ * tabs. Everything else goes, with its profile copy. Only the newest folder of a chat is kept.
+ */
+
+import path from 'path';
+import { readdir, readFile, rm, stat } from 'fs/promises';
+import { appLog } from '../app-logger';
+import { claimFolder, folderClaim, releaseFolder, UNVERIFIED_OWNER_AGE_MS, writeOwner } from '../folder-owner';
+import { tempFolderParents, TEMP_FOLDER_PREFIXES } from '../temp-folders';
+import { isBrowserProfileCopyPath, keepBrowserProfileCopy, removeBrowserProfileCopy } from '../browser-profiles/profile-copy';
+import { InsightsPaths } from '../insights/paths';
+
+/** The record in a chat browser's folder */
+export const CHAT_BROWSER_RECORD = '.workbench-chat-browser.json';
+/** A chat browser left by a crash is kept for its chat this long (from its last change) */
+export const RESTORE_MAX_AGE_MS = 7 * 24 * 60 * 60 * 1000;
+
+export interface ChatBrowserTab {
+ url: string;
+ title: string;
+}
+
+/** What a chat browser's folder records about it */
+export interface ChatBrowserRecord {
+ projectId: string;
+ projectPath: string;
+ chatId: string;
+ /** The browser it opened (a profile id; null: Playwright's own Chromium) */
+ browserId: string | null;
+ /** Its profile copy (host path), or null (Playwright's own browsers keep their profile in the folder) */
+ profileCopyDir: string | null;
+ tabs: ChatBrowserTab[];
+ /** When it last changed (ms) */
+ updatedAt: number;
+}
+
+/** A chat browser left by a crash, kept for its chat */
+export interface RestorableChatBrowser {
+ /** Its folder (host path) */
+ dir: string;
+ record: ChatBrowserRecord;
+}
+
+/** A record read from its file, or null when it isn't one */
+export function parseChatBrowserRecord(text: string): ChatBrowserRecord | null {
+ let raw: unknown;
+ try {
+ raw = JSON.parse(text);
+ } catch {
+ return null;
+ }
+ const value = raw as Partial | null;
+ if (!value || typeof value !== 'object') return null;
+ if (typeof value.projectId !== 'string' || typeof value.projectPath !== 'string' || typeof value.chatId !== 'string') return null;
+ if (typeof value.updatedAt !== 'number' || !Number.isFinite(value.updatedAt)) return null;
+ const tabs = Array.isArray(value.tabs)
+ ? value.tabs.filter((tab): tab is ChatBrowserTab => !!tab && typeof tab.url === 'string' && typeof tab.title === 'string')
+ : [];
+ return {
+ projectId: value.projectId,
+ projectPath: value.projectPath,
+ chatId: value.chatId,
+ browserId: typeof value.browserId === 'string' ? value.browserId : null,
+ profileCopyDir: typeof value.profileCopyDir === 'string' ? value.profileCopyDir : null,
+ tabs,
+ updatedAt: value.updatedAt,
+ };
+}
+
+/** The tabs worth opening again (blank ones open as the browser starts anyway) */
+export function tabsToRestore(tabs: readonly ChatBrowserTab[]): ChatBrowserTab[] {
+ return tabs.filter((tab) => /^(https?|file):/i.test(tab.url));
+}
+
+/** Whether a left record's chat browser is kept for its chat */
+export function keepsForChat(
+ record: ChatBrowserRecord | null,
+ context: { now: number; projectPath: string | undefined; chatExists: boolean },
+): boolean {
+ if (!record || !context.projectPath || !context.chatExists) return false;
+ return context.now - record.updatedAt < RESTORE_MAX_AGE_MS;
+}
+
+/** Whether a chat's conversation is saved in its project */
+async function conversationExists(projectPath: string, chatId: string): Promise {
+ try {
+ return (await stat(new InsightsPaths().getSessionPath(projectPath, chatId))).isFile();
+ } catch {
+ // No such file, or not a conversation id (the New chat page's browser)
+ return false;
+ }
+}
+
+interface ChatBrowserScanOptions {
+ /** The app's projects */
+ projects: ReadonlyArray<{ id: string; path: string }>;
+ /** The temp folder (tests) */
+ parent?: string;
+ now?: number;
+ chatExists?: (projectPath: string, chatId: string) => Promise;
+}
+
+/** Remove a left chat browser's folder and its profile copy (unless another running Workbench holds the copy) */
+async function removeLeftover(dir: string, record: ChatBrowserRecord | null): Promise {
+ await rm(dir, { recursive: true, force: true, maxRetries: 3, retryDelay: 200 }).catch((error: unknown) => {
+ appLog.warn(`[BrowserDrawer] Could not remove ${dir}:`, error);
+ });
+ const copy = record?.profileCopyDir;
+ // Only a real profile copy's folder (the record could name any folder)
+ if (copy && isBrowserProfileCopyPath(copy) && (await folderClaim(copy)) === 'gone') await removeBrowserProfileCopy(copy);
+}
+
+/**
+ * At startup: keep the chat browsers left by a crash for their chats (taking over their folders
+ * and profile copies) and remove the other leftovers. Run before profile copies are swept. Best effort
+ */
+export async function scanChatBrowserLeftovers(options: ChatBrowserScanOptions): Promise {
+ const parents = options.parent ? [options.parent] : await tempFolderParents();
+ const now = options.now ?? Date.now();
+ const chatExists = options.chatExists ?? conversationExists;
+ // In each temp folder (WSL mode: also the distribution's, where chat browsers run)
+ const dirs: string[] = [];
+ for (const parent of parents) {
+ try {
+ const names = (await readdir(parent)).filter((name) => name.startsWith(TEMP_FOLDER_PREFIXES.chatBrowser));
+ dirs.push(...names.map((name) => path.join(parent, name)));
+ } catch {
+ // No such folder
+ }
+ }
+
+ // The left folders with their records, newest first
+ const left: Array<{ dir: string; record: ChatBrowserRecord | null }> = [];
+ for (const dir of dirs) {
+ try {
+ if (!(await stat(dir)).isDirectory()) continue;
+ // Another running Workbench's (or this one's, opened meanwhile), or one being set up
+ if ((await folderClaim(dir, UNVERIFIED_OWNER_AGE_MS)) !== 'gone') continue;
+ const text = await readFile(path.join(dir, CHAT_BROWSER_RECORD), 'utf-8').catch(() => '');
+ left.push({ dir, record: parseChatBrowserRecord(text) });
+ } catch {
+ // Gone meanwhile
+ }
+ }
+ left.sort((a, b) => (b.record?.updatedAt ?? 0) - (a.record?.updatedAt ?? 0));
+
+ const restorable: RestorableChatBrowser[] = [];
+ const chatsKept = new Set();
+ for (const { dir, record } of left) {
+ const project = record ? options.projects.find((p) => p.id === record.projectId) : undefined;
+ const chatKey = record ? `${record.projectId}\n${record.chatId}` : '';
+ const keep = !!record && !chatsKept.has(chatKey) && keepsForChat(record, {
+ now,
+ projectPath: project?.path,
+ chatExists: project ? await chatExists(project.path, record.chatId) : false,
+ });
+ if (!keep || !record || !project) {
+ await removeLeftover(dir, record);
+ continue;
+ }
+ try {
+ // This process's now: no sweep (of this or another Workbench) removes it
+ await writeOwner(dir);
+ claimFolder(dir);
+ } catch (error) {
+ appLog.warn(`[BrowserDrawer] Could not keep ${dir} for its chat:`, error);
+ continue;
+ }
+ // Its sign-ins; without the copy, the chat's browser starts from a new copy (the tabs still come back)
+ const copy = record.profileCopyDir && isBrowserProfileCopyPath(record.profileCopyDir) && (await keepBrowserProfileCopy(record.profileCopyDir))
+ ? record.profileCopyDir
+ : null;
+ chatsKept.add(chatKey);
+ restorable.push({ dir, record: { ...record, projectPath: project.path, profileCopyDir: copy } });
+ }
+ if (restorable.length > 0) appLog.info(`[BrowserDrawer] ${restorable.length} chat browser(s) left by a crash kept for their chats`);
+ return restorable;
+}
+
+/** Remove a kept chat browser that won't be opened again (its chat was deleted, or it opens anew) */
+export async function discardRestorable(restorable: RestorableChatBrowser): Promise {
+ releaseFolder(restorable.dir);
+ await rm(restorable.dir, { recursive: true, force: true, maxRetries: 3, retryDelay: 200 }).catch(() => undefined);
+ // Kept by this process (scanChatBrowserLeftovers checked it is a profile copy)
+ if (restorable.record.profileCopyDir) await removeBrowserProfileCopy(restorable.record.profileCopyDir);
+}
diff --git a/src/main/browser-drawer/chat-browsers.ts b/src/main/browser-drawer/chat-browsers.ts
new file mode 100644
index 000000000..e65cf02bd
--- /dev/null
+++ b/src/main/browser-drawer/chat-browsers.ts
@@ -0,0 +1,653 @@
+/**
+ * Chat browsers
+ * =============
+ *
+ * Each Claude chat has at most one browser, owned by Workbench rather than by a turn, so it stays
+ * open between turns, while the user is on other pages or chats, and lets the user and the chat
+ * work in the same pages (the user signs in by hand, then asks the chat to carry on).
+ *
+ * The browser is held by a long-lived Playwright MCP server Workbench starts itself (the
+ * "holder"): the same server and browser options a turn would get for the chat's browser choice
+ * (its profile copy, headless), with `--idle-timeout 0`. Its MCP client name is the chat's bind
+ * title, so the browser it launches is bound in Playwright's registry under that title, with the
+ * holder's own folder (outside the project) as its workspace, registered for the chat's project
+ * (project-match.ts). A turn's Playwright server gets `--endpoint ` and attaches to it
+ * (playwright-core's createRemoteBrowser: the registry entry with that title, `contexts()[0]`);
+ * attached servers leave it open when the turn ends (the chat's guard refuses `browser_close`,
+ * which could close the attached context).
+ *
+ * The browser opens when the user asks (the drawer's Open browser button) or on a turn's first
+ * browser tool call (the chat's Playwright guard asks through the turn's token,
+ * `insights-executor.ts`). It closes when the user closes its last tab, the chat is deleted, the
+ * browser goes away (it crashed: its registry entry stops answering) or the app quits.
+ *
+ * Chats are told apart by id within their project; the New chat page (no conversation yet) is
+ * NEW_CHAT_BROWSER_ID, and its browser moves to the conversation its first message creates.
+ *
+ * In WSL mode the holder runs inside the distribution (spawnTool, like every MCP server there),
+ * its folder in the distribution's own temp folder (runtimeTempParent), so the browser's profile
+ * isn't on a Windows drive.
+ */
+
+import { EventEmitter } from 'events';
+import { randomUUID } from 'crypto';
+import path from 'path';
+import { realpath, stat, writeFile } from 'fs/promises';
+import type { ChildProcess } from 'child_process';
+import type { AppSettings, McpConnectorSettings } from '../../shared/types/settings';
+import type { PlaywrightBrowserChoice } from '../../shared/types/browser-profiles';
+import { NEW_CHAT_BROWSER_ID, type ChatBrowserInfo } from '../../shared/types/browser-drawer';
+import { getTaskPlaywrightBrowser } from '../../shared/utils/mcp-connectors';
+import { appLog } from '../app-logger';
+import { buildMcpConfig, MCP_STARTUP_TIMEOUT_MS } from '../claude-code/mcp-config';
+import { readSettingsFileAsync } from '../settings-utils';
+import { resolveCommand } from '../mcp-commands';
+import { getToolEnvAsync } from '../cli-utils';
+import { isWindows } from '../platform';
+import { getWslInfo } from '../platform/shell-runtime';
+import { registryAccess, registryOs, removeClosedSessions } from './registry';
+import { killRuntimeProcessTree, spawnTool } from '../platform/runtime-exec';
+import { prepareBrowserProfileCopy, removeBrowserProfileCopy, useKeptBrowserProfileCopy } from '../browser-profiles/profile-copy';
+import { makeTempFolder, removeTempFolder, runtimeTempParent, TEMP_FOLDER_PREFIXES } from '../temp-folders';
+import {
+ CHAT_BROWSER_RECORD,
+ discardRestorable,
+ tabsToRestore,
+ type ChatBrowserRecord,
+ type ChatBrowserTab,
+ type RestorableChatBrowser,
+} from './chat-browser-restore';
+import { browserChoicesInUse } from '../browser-profiles/choices-in-use';
+import { registerChatBrowserWorkspace } from './project-match';
+
+/** The bind titles of chat browsers start with this */
+const CHAT_BROWSER_TITLE_PREFIX = 'Workbench chat ';
+
+/** How long a holder may take to start its browser (npx may download the server first) */
+const START_TIMEOUT_MS = MCP_STARTUP_TIMEOUT_MS;
+/** How long a holder may take to close its browser and exit before it is stopped */
+const CLOSE_TIMEOUT_MS = 5000;
+
+/** A running holder */
+export interface ChatBrowserHolder {
+ /** Close the browser and stop the holder */
+ close: () => Promise;
+ /** Called once when the holder exits (closed, crashed or stopped) */
+ onExit: (listener: () => void) => void;
+ /** Keep its record current (the chat it belongs to, its open tabs), for a restart after a crash */
+ updateRecord?: (patch: Partial>) => void;
+ /** The browser it opened (null: Playwright's own Chromium), whose icon the drawer's tabs show */
+ browser?: PlaywrightBrowserChoice | null;
+}
+
+/** Starts a holder whose browser is bound under `title` (rejects with a readable message) */
+export type StartChatBrowserHolder = (options: {
+ projectPath: string;
+ title: string;
+ /** The browser to open (undefined: Settings > Connectors) */
+ choice: PlaywrightBrowserChoice | null | undefined;
+ projectId?: string;
+ chatId?: string;
+ /** The chat's browser left by a crash: started from its profile and tabs when it is the same browser */
+ restore?: RestorableChatBrowser;
+}) => Promise;
+
+interface Entry {
+ projectId: string;
+ chatId: string;
+ title: string;
+ status: 'starting' | 'open';
+ starting?: Promise;
+ holder?: ChatBrowserHolder;
+ /** Its browser has been seen live in Playwright's registry */
+ seenLive: boolean;
+}
+
+const keyOf = (projectId: string, chatId: string) => `${projectId}\n${chatId}`;
+
+/** Emits 'change' when a chat browser starts, opens or closes */
+export class ChatBrowsers extends EventEmitter {
+ private readonly entries = new Map();
+ /** Bind titles by chat, kept while the app runs: a turn attaches by its chat's title */
+ private readonly titles = new Map();
+ /** Chats whose browser was closed while it started, until that start has ended */
+ private readonly closing = new Map>();
+ /** Chats' browsers left by a crash, opened again from their profile and tabs (chat-browser-restore.ts) */
+ private readonly restorables = new Map();
+ private stopped = false;
+
+ constructor(
+ private readonly startHolder: StartChatBrowserHolder = startPlaywrightHolder,
+ private readonly discard: (restorable: RestorableChatBrowser) => Promise = discardRestorable,
+ ) {
+ super();
+ }
+
+ /** The bind title of a chat's browser (the same for the chat while the app runs) */
+ titleFor(projectId: string, chatId: string): string {
+ const key = keyOf(projectId, chatId);
+ let title = this.titles.get(key);
+ if (!title) {
+ title = `${CHAT_BROWSER_TITLE_PREFIX}${randomUUID()}`;
+ this.titles.set(key, title);
+ }
+ return title;
+ }
+
+ /**
+ * The chat a bind title belongs to, with the browser its holder opened (undefined while it starts;
+ * null: Playwright's own Chromium)
+ */
+ chatOfTitle(title: string): { projectId: string; chatId: string; browser?: PlaywrightBrowserChoice | null } | undefined {
+ if (!title.startsWith(CHAT_BROWSER_TITLE_PREFIX)) return undefined;
+ for (const [key, value] of this.titles) {
+ if (value !== title) continue;
+ const [projectId, chatId] = key.split('\n');
+ const browser = this.entries.get(key)?.holder?.browser;
+ return { projectId, chatId, ...(browser !== undefined ? { browser } : {}) };
+ }
+ return undefined;
+ }
+
+ /** The chats' browsers being opened or open */
+ list(): ChatBrowserInfo[] {
+ const open = [...this.entries.values()].map(({ projectId, chatId, status }): ChatBrowserInfo => ({ projectId, chatId, status }));
+ const restorable = [...this.restorables.entries()]
+ .filter(([key]) => !this.entries.has(key))
+ .map(([, { record }]): ChatBrowserInfo => ({
+ projectId: record.projectId,
+ chatId: record.chatId,
+ status: 'restorable',
+ tabs: tabsToRestore(record.tabs).length,
+ }));
+ return [...open, ...restorable];
+ }
+
+ /**
+ * A chat's browser left by a crash: kept until the chat's browser opens again (or the chat is
+ * deleted). Removed at once when the chat has a browser already (opened while the leftovers were looked at)
+ */
+ addRestorable(restorable: RestorableChatBrowser): void {
+ const key = keyOf(restorable.record.projectId, restorable.record.chatId);
+ const previous = this.restorables.get(key);
+ if (this.stopped || this.entries.has(key) || (previous && previous.dir !== restorable.dir)) {
+ void this.discard(restorable);
+ return;
+ }
+ this.restorables.set(key, restorable);
+ this.emit('change');
+ }
+
+ /** A chat's open tabs (from the drawer's bridge), kept in its record */
+ noteTabs(projectId: string, chatId: string, tabs: ChatBrowserTab[]): void {
+ this.entries.get(keyOf(projectId, chatId))?.holder?.updateRecord?.({ tabs });
+ }
+
+ isOpen(projectId: string, chatId: string): boolean {
+ return this.entries.get(keyOf(projectId, chatId))?.status === 'open';
+ }
+
+ /**
+ * Open the chat's browser unless it is open or opening (then wait for that). `choice` is the
+ * chat's browser (undefined: Settings > Connectors); an open browser keeps the one it opened with
+ */
+ ensure(projectId: string, projectPath: string, chatId: string, choice: PlaywrightBrowserChoice | null | undefined): Promise {
+ if (this.stopped) return Promise.reject(new Error('Workbench is quitting'));
+ const key = keyOf(projectId, chatId);
+ // A browser closed while it started is still going: a new one waits for it (one per title)
+ const closing = this.closing.get(key);
+ if (closing) return closing.then(() => this.ensure(projectId, projectPath, chatId, choice));
+ const existing = this.entries.get(key);
+ if (existing?.status === 'open') return Promise.resolve();
+ if (existing?.starting) return existing.starting;
+
+ const entry: Entry = { projectId, chatId, title: this.titleFor(projectId, chatId), status: 'starting', seenLive: false };
+ this.entries.set(key, entry);
+ // Left by a crash: the holder starts from it, or removes it when the chat's browser changed
+ const restore = this.restorables.get(key);
+ this.restorables.delete(key);
+ entry.starting = this.startHolder({ projectPath, title: entry.title, choice, projectId, chatId, restore }).then(
+ async (holder) => {
+ entry.starting = undefined;
+ // Closed (or the chat deleted, or the app quitting) while it started
+ if (this.entries.get(keyOf(entry.projectId, entry.chatId)) !== entry) {
+ await holder.close().catch(() => undefined);
+ throw new Error('The browser was closed');
+ }
+ entry.holder = holder;
+ entry.status = 'open';
+ // The New chat page's browser may have moved to its conversation while it started
+ holder.updateRecord?.({ chatId: entry.chatId });
+ holder.onExit(() => this.forget(entry));
+ this.emit('change');
+ },
+ (error: unknown) => {
+ entry.starting = undefined;
+ // A failed start keeps what it was to open again (its folder is left as it was)
+ if (restore && !this.stopped && !this.restorables.has(key)) {
+ void stat(restore.dir).then(() => {
+ if (!this.restorables.has(key) && !this.entries.has(key)) {
+ this.restorables.set(key, restore);
+ this.emit('change');
+ }
+ }, () => undefined);
+ }
+ this.forget(entry);
+ throw error instanceof Error ? error : new Error(String(error));
+ },
+ );
+ this.emit('change');
+ return entry.starting;
+ }
+
+ /** Close a chat's browser (nothing when it has none) */
+ async close(projectId: string, chatId: string): Promise {
+ const key = keyOf(projectId, chatId);
+ const entry = this.entries.get(key);
+ if (!entry) return;
+ this.forget(entry);
+ if (entry.starting) {
+ // Still starting: it closes itself once started; until then the chat can't open another
+ const done = entry.starting.then(() => undefined, () => undefined).finally(() => {
+ if (this.closing.get(key) === done) this.closing.delete(key);
+ });
+ this.closing.set(key, done);
+ await done;
+ return;
+ }
+ await entry.holder?.close();
+ }
+
+ /** Close the browsers of chats that were deleted */
+ async closeChats(projectId: string, chatIds: readonly string[]): Promise {
+ for (const chatId of chatIds) {
+ const key = keyOf(projectId, chatId);
+ const restorable = this.restorables.get(key);
+ if (!restorable) continue;
+ this.restorables.delete(key);
+ void this.discard(restorable);
+ this.emit('change');
+ }
+ await Promise.all(chatIds.map((chatId) => this.close(projectId, chatId)));
+ for (const chatId of chatIds) this.titles.delete(keyOf(projectId, chatId));
+ }
+
+ /** The New chat page's browser belongs to the conversation its first message created */
+ adopt(projectId: string, toChatId: string, fromChatId = NEW_CHAT_BROWSER_ID): void {
+ if (toChatId === fromChatId) return;
+ const from = keyOf(projectId, fromChatId);
+ const to = keyOf(projectId, toChatId);
+ const title = this.titles.get(from);
+ if (!title || this.titles.has(to)) return;
+ this.titles.set(to, title);
+ this.titles.delete(from);
+ const entry = this.entries.get(from);
+ if (entry) {
+ this.entries.delete(from);
+ entry.chatId = toChatId;
+ this.entries.set(to, entry);
+ entry.holder?.updateRecord?.({ chatId: toChatId });
+ }
+ this.emit('change');
+ }
+
+ /**
+ * The titles live in Playwright's registry now: an open chat browser seen live before and gone
+ * now has crashed or was closed from outside, so its holder stops
+ */
+ syncLive(liveTitles: ReadonlySet): void {
+ for (const entry of [...this.entries.values()]) {
+ if (entry.status !== 'open') continue;
+ if (liveTitles.has(entry.title)) {
+ entry.seenLive = true;
+ } else if (entry.seenLive) {
+ appLog.info(`[BrowserDrawer] The browser of chat ${entry.chatId} went away; closing it`);
+ void this.close(entry.projectId, entry.chatId);
+ }
+ }
+ }
+
+ /** Close every chat browser (the app is quitting; browsers left by a crash stay for the next start) */
+ async shutdown(): Promise {
+ this.stopped = true;
+ const entries = [...this.entries.values()];
+ this.entries.clear();
+ await Promise.all(entries.map((entry) => entry.holder?.close()));
+ }
+
+ private forget(entry: Entry): void {
+ const key = keyOf(entry.projectId, entry.chatId);
+ if (this.entries.get(key) !== entry) return;
+ this.entries.delete(key);
+ this.emit('change');
+ }
+}
+
+// =============================================================================
+// The holder: a Playwright MCP server Workbench talks to over stdio
+// =============================================================================
+
+/** The first sentence of a Playwright tool error (its text starts with a `### Error` heading) */
+export function holderError(text: string): string {
+ const line = text.trim().split('\n').map((l) => l.trim()).find((l) => l && !/^#+\s/.test(l)) ?? '';
+ return line.replace(/^Error:\s*/, '').split(/\.\s+(?=[A-Z])/)[0].replace(/\.$/, '') || 'The browser could not be opened';
+}
+
+/**
+ * The holder's command line: the turn's Playwright server for this browser, kept open. A profile
+ * in memory (`--isolated`, without a profile copy) becomes one in the holder's folder instead
+ * (`/profile`, removed with it): a persistent context, which an attached turn's server
+ * never closes, and sign-ins made in it last while the browser is open
+ */
+export function holderArgs(args: readonly string[], dir: string): string[] {
+ const profile = path.join(dir, 'profile');
+ const own = args.flatMap((arg) => (arg === '--isolated' ? ['--user-data-dir', profile] : [arg]));
+ return [...own, '--idle-timeout', '0', '--output-dir', dir];
+}
+
+/** A JSON-RPC client over a holder's stdio (answers the server's own requests: ping, roots) */
+interface HolderClient {
+ request: (method: string, params: Record, timeoutMs: number) => Promise;
+ notify: (method: string) => void;
+ /** Rejects when the holder exits, with its last error line */
+ exited: Promise;
+}
+
+interface HolderReply {
+ result?: { isError?: boolean; content?: Array<{ text?: string }> };
+ error?: { message?: string };
+}
+
+function holderClient(proc: ChildProcess): HolderClient {
+ let buffer = '';
+ let stderr = '';
+ let nextId = 1;
+ const pending = new Map void>();
+ const write = (message: Record) => {
+ try {
+ proc.stdin?.write(JSON.stringify({ jsonrpc: '2.0', ...message }) + '\n');
+ } catch {
+ // The holder exited; its exit settles
+ }
+ };
+ proc.stdin?.on('error', () => undefined);
+ proc.stdout?.on('data', (data: Buffer) => {
+ buffer += data.toString('utf-8');
+ let end: number;
+ while ((end = buffer.indexOf('\n')) >= 0) {
+ const line = buffer.slice(0, end).trim();
+ buffer = buffer.slice(end + 1);
+ if (!line) continue;
+ let message: HolderReply & { id?: unknown; method?: string };
+ try {
+ message = JSON.parse(line);
+ } catch {
+ continue;
+ }
+ // The server's own requests (ping, roots) get an empty answer
+ if (message.method && message.id !== undefined) {
+ write({ id: message.id, result: message.method === 'roots/list' ? { roots: [] } : {} });
+ continue;
+ }
+ if (typeof message.id === 'number') {
+ pending.get(message.id)?.(message);
+ pending.delete(message.id);
+ }
+ }
+ });
+ proc.stderr?.on('data', (data: Buffer) => {
+ stderr = (stderr + data.toString('utf-8')).slice(-2000);
+ });
+ const exited = new Promise((_, reject) => {
+ const fail = (error: Error) => reject(error);
+ proc.once('error', fail);
+ proc.once('exit', (code) => {
+ const lastLine = stderr.trim().split('\n').filter(Boolean).at(-1);
+ fail(new Error(lastLine || `The browser stopped (code ${code ?? 'unknown'})`));
+ });
+ });
+ exited.catch(() => undefined);
+ return {
+ request: (method, params, timeoutMs) => {
+ const id = nextId++;
+ let timer: ReturnType | undefined;
+ const reply = new Promise((resolve, reject) => {
+ pending.set(id, resolve);
+ timer = setTimeout(() => {
+ pending.delete(id);
+ reject(new Error('The browser did not start in time'));
+ }, timeoutMs);
+ write({ id, method, params });
+ });
+ return Promise.race([reply, exited]).finally(() => clearTimeout(timer));
+ },
+ notify: (method) => write({ method }),
+ exited,
+ };
+}
+
+/** A tool call's failure, as text (undefined: it worked) */
+function replyFailure(reply: HolderReply): string | undefined {
+ return reply.error?.message ?? (reply.result?.isError ? reply.result.content?.map((part) => part.text ?? '').join(' ') : undefined);
+}
+
+/**
+ * Talk MCP to a started holder: initialize as `title`, then open about:blank so the browser
+ * launches (and binds). Resolves once it has
+ */
+async function initializeHolder(client: HolderClient, title: string, timeoutMs = START_TIMEOUT_MS): Promise {
+ // One deadline for the whole start, not one per request
+ const deadline = Date.now() + timeoutMs;
+ const init = await client.request('initialize', {
+ protocolVersion: '2025-06-18',
+ capabilities: {},
+ clientInfo: { name: title, version: '1.0.0' },
+ }, timeoutMs);
+ if (init.error) throw new Error(init.error.message ?? 'The browser could not be opened');
+ client.notify('notifications/initialized');
+ const opened = await client.request(
+ 'tools/call',
+ { name: 'browser_navigate', arguments: { url: 'about:blank' } },
+ Math.max(0, deadline - Date.now()),
+ );
+ const failure = replyFailure(opened);
+ if (failure !== undefined) throw new Error(holderError(failure));
+}
+
+/** How long reopening one saved tab may take */
+const RESTORE_TAB_TIMEOUT_MS = 30_000;
+
+/** Open a crashed chat browser's tabs again: the first in the tab the browser opened with (best effort) */
+async function restoreTabs(client: HolderClient, tabs: readonly ChatBrowserTab[]): Promise {
+ // Gone (closed or crashed): nothing more to open. Told by its exit, not its error's text (the
+ // holder's last stderr line, which can say anything)
+ let gone = false;
+ client.exited.catch(() => {
+ gone = true;
+ });
+ for (const [index, tab] of tabs.entries()) {
+ if (gone) return;
+ const call = index === 0
+ ? { name: 'browser_navigate', arguments: { url: tab.url } }
+ : { name: 'browser_tabs', arguments: { action: 'new', url: tab.url } };
+ try {
+ const failure = replyFailure(await client.request('tools/call', call, RESTORE_TAB_TIMEOUT_MS));
+ if (failure !== undefined) appLog.info(`[BrowserDrawer] Could not reopen ${tab.url}: ${holderError(failure)}`);
+ } catch (error) {
+ if (gone) return;
+ appLog.info(`[BrowserDrawer] Could not reopen ${tab.url}:`, error);
+ }
+ }
+}
+
+/** Ask a holder to close its browser (its input ends), and stop it when it doesn't exit in time */
+function closeHolderProcess(proc: ChildProcess): Promise {
+ if (proc.exitCode !== null || proc.signalCode !== null) return Promise.resolve();
+ return new Promise((resolve) => {
+ const timer = setTimeout(() => {
+ killRuntimeProcessTree(proc);
+ resolve();
+ }, CLOSE_TIMEOUT_MS);
+ proc.once('exit', () => {
+ clearTimeout(timer);
+ resolve();
+ });
+ try {
+ proc.stdin?.end();
+ } catch {
+ killRuntimeProcessTree(proc);
+ }
+ });
+}
+
+/** The chosen browser for a chat (undefined: Settings), with the settings a run would use */
+function chatRunSettings(settings: McpConnectorSettings | undefined, choice: PlaywrightBrowserChoice | null | undefined): McpConnectorSettings {
+ return { ...settings, playwrightBrowser: getTaskPlaywrightBrowser(choice, settings) } as McpConnectorSettings;
+}
+
+/** How long a record change waits before it is written (tabs change in bursts while pages load) */
+const RECORD_WRITE_DELAY_MS = 1000;
+
+/** Keeps a chat browser's record file current (debounced writes; the last one before close wins) */
+function recordWriter(dir: string, initial: ChatBrowserRecord) {
+ let record = initial;
+ let timer: ReturnType | undefined;
+ let closed = false;
+ const write = () => {
+ timer = undefined;
+ if (closed) return;
+ void writeFile(path.join(dir, CHAT_BROWSER_RECORD), JSON.stringify(record), { mode: 0o600 }).catch(() => undefined);
+ };
+ return {
+ writeNow: write,
+ update: (patch: Partial>) => {
+ const next = { ...record, ...patch };
+ if (JSON.stringify({ ...next, updatedAt: 0 }) === JSON.stringify({ ...record, updatedAt: 0 })) return;
+ record = { ...next, updatedAt: Date.now() };
+ if (!timer && !closed) timer = setTimeout(write, RECORD_WRITE_DELAY_MS);
+ },
+ close: () => {
+ closed = true;
+ clearTimeout(timer);
+ },
+ };
+}
+
+/**
+ * Start a holder for a chat: copy the chosen profile, start the server, open the browser. With a
+ * browser left by a crash (`restore`) for the same browser, its folder and profile copy are used
+ * again and its tabs reopened; for another browser it is removed and the chat's browser starts anew
+ */
+const startPlaywrightHolder: StartChatBrowserHolder = async ({ projectPath, title, choice, projectId, chatId, restore }) => {
+ const settings = ((await readSettingsFileAsync()) as Partial | undefined)?.mcpConnectors;
+ const runSettings = chatRunSettings(settings, choice);
+ const browser = runSettings.playwrightBrowser;
+ const browserId = browser?.id ?? null;
+ const reuse = restore && restore.record.browserId === browserId ? restore : undefined;
+ if (restore && !reuse) await discardRestorable(restore);
+
+ const cleanups: Array<() => Promise | void> = [];
+ const cleanup = async () => {
+ for (const fn of cleanups.splice(0).reverse()) await Promise.resolve(fn()).catch(() => undefined);
+ };
+ // What is removed when the browser closes: at once for a new one; for a reused one only once it
+ // started (a failed start leaves it to open again)
+ const removals: Array<() => Promise | void> = [];
+ try {
+ // The holder's own folder: its workspace and output folder, registered for the project
+ // Where the browser runs (in WSL inside the distribution: a profile on /mnt/c is slow for it)
+ const dir = reuse ? reuse.dir : await makeTempFolder(TEMP_FOLDER_PREFIXES.chatBrowser, await runtimeTempParent());
+ removals.push(() => removeTempFolder(dir));
+ for (const folder of new Set([dir, await realpath(dir).catch(() => dir)])) {
+ cleanups.push(registerChatBrowserWorkspace(folder, projectPath));
+ }
+
+ let browserProfileDir: string | undefined;
+ // The crashed browser's copy stays kept (never swept, left on quit) until this start worked, so
+ // a failed start leaves it, sign-ins and all, to open again
+ let keptCopy: string | undefined;
+ if (browser && !browser.managed) {
+ if (reuse?.record.profileCopyDir) {
+ const copy = reuse.record.profileCopyDir;
+ browserProfileDir = keptCopy = copy;
+ removals.push(() => removeBrowserProfileCopy(copy));
+ } else {
+ const inUse = await browserChoicesInUse(projectPath, settings?.playwrightBrowser).catch(() => undefined);
+ browserProfileDir = (await prepareBrowserProfileCopy(projectPath, browser, `chat-${randomUUID().slice(0, 8)}`, inUse).catch((error) => {
+ appLog.warn('[BrowserDrawer] Could not copy the browser profile for a chat:', error);
+ return null;
+ })) ?? undefined;
+ // A copy made now goes with a failed start too (the next try makes another)
+ if (browserProfileDir) {
+ const copy = browserProfileDir;
+ cleanups.push(() => removeBrowserProfileCopy(copy));
+ }
+ }
+ }
+ if (!reuse) cleanups.push(...removals.splice(0));
+
+ // Its record, for a restart after a crash (a close or quit removes it with the folder)
+ const record = recordWriter(dir, {
+ projectId: projectId ?? reuse?.record.projectId ?? '',
+ projectPath,
+ chatId: chatId ?? reuse?.record.chatId ?? '',
+ browserId,
+ profileCopyDir: browserProfileDir ?? null,
+ tabs: reuse?.record.tabs ?? [],
+ updatedAt: Date.now(),
+ });
+ record.writeNow();
+ cleanups.push(() => record.close());
+
+ const entry = buildMcpConfig(['playwright'], runSettings, { browserProfileDir }).mcpServers.playwright;
+ if (entry?.type !== 'stdio') throw new Error('Playwright is not available');
+ const command = await resolveCommand(entry.command);
+ if (!command) throw new Error(`${entry.command} was not found`);
+ const proc = spawnTool('python', holderArgs(entry.args ?? [], dir), {
+ command,
+ cwd: dir,
+ stdio: ['pipe', 'pipe', 'pipe'],
+ // In WSL the distribution's login environment applies (only changed variables are passed in)
+ env: { ...(getWslInfo() ? process.env : await getToolEnvAsync()), ...entry.env },
+ windowsHide: true,
+ // Its own process group, so the server npx starts (and its browser) can be stopped with it
+ detached: !isWindows(),
+ });
+ const exited = new Promise((resolve) => proc.once('exit', () => resolve()));
+ const client = holderClient(proc);
+ try {
+ await initializeHolder(client, title);
+ } catch (error) {
+ await closeHolderProcess(proc);
+ throw error;
+ }
+ // Started: a reused folder and copy go when it closes (or on quit), like a new one's
+ if (keptCopy) useKeptBrowserProfileCopy(keptCopy);
+ cleanups.push(...removals.splice(0));
+ if (reuse) void restoreTabs(client, tabsToRestore(reuse.record.tabs));
+
+ const listeners: Array<() => void> = [];
+ // Gone (closed, crashed or stopped): its folder, profile copy and registration go too
+ const done = exited.then(async () => {
+ await cleanup();
+ // Its closed browser's entry in Playwright's registry (kept there because it had a profile folder)
+ const registry = registryAccess(registryOs());
+ await removeClosedSessions(registry.dir, title, registry.connect);
+ for (const listener of listeners) listener();
+ });
+ return {
+ browser: browser ?? null,
+ close: async () => {
+ await closeHolderProcess(proc);
+ await done;
+ },
+ onExit: (listener) => {
+ listeners.push(listener);
+ },
+ updateRecord: (patch) => record.update(patch),
+ };
+ } catch (error) {
+ await cleanup();
+ throw error;
+ }
+};
diff --git a/src/main/browser-drawer/display-scale.ts b/src/main/browser-drawer/display-scale.ts
new file mode 100644
index 000000000..cc91325bc
--- /dev/null
+++ b/src/main/browser-drawer/display-scale.ts
@@ -0,0 +1,59 @@
+/**
+ * The pixel density Playwright's browsers render at: the largest devicePixelRatio of the screens
+ * (at most 2), so the browser drawer shows their pages as sharp as the rest of the window. Runs
+ * started after a screen change use the new density; running browsers keep theirs (Playwright
+ * fixes it when it launches one). Screenshots for agents stay in CSS pixels (Playwright's default).
+ */
+
+import { app, screen } from 'electron';
+import { mkdir, writeFile } from 'fs/promises';
+import path from 'path';
+import { appLog } from '../app-logger';
+import { clampPixelScale } from './pixel-scale';
+import { playwrightScaleConfig, setPlaywrightDisplayScale } from '../claude-code/mcp-config';
+
+/** The density for screens of these scale factors: the largest, within 1..MAX_PIXEL_SCALE */
+export function browserScaleFor(scaleFactors: readonly number[]): number {
+ return clampPixelScale(Math.max(1, ...scaleFactors.filter((f) => Number.isFinite(f))));
+}
+
+let applied = 1;
+
+async function apply(): Promise {
+ const scale = browserScaleFor(screen.getAllDisplays().map((display) => display.scaleFactor));
+ if (scale === applied) return;
+ if (scale <= 1) {
+ applied = 1;
+ setPlaywrightDisplayScale(null);
+ return;
+ }
+ try {
+ const dir = path.join(app.getPath('userData'), 'playwright');
+ await mkdir(dir, { recursive: true });
+ const configFiles = {
+ chromium: path.join(dir, 'display-scale-chromium.json'),
+ other: path.join(dir, 'display-scale.json'),
+ };
+ await writeFile(configFiles.chromium, JSON.stringify(playwrightScaleConfig('chromium', scale), null, 2));
+ await writeFile(configFiles.other, JSON.stringify(playwrightScaleConfig('other', scale), null, 2));
+ // Only once the files are there: a run naming a missing config wouldn't start its browser
+ applied = scale;
+ setPlaywrightDisplayScale({ scale, configFiles });
+ } catch (error) {
+ appLog.warn('[BrowserDrawer] Could not write the browsers\' display scale:', error);
+ }
+}
+
+let queue = Promise.resolve();
+/** One update at a time, in order */
+const schedule = () => {
+ queue = queue.then(apply, apply);
+};
+
+/** Follow the screens' density (after app ready) */
+export function watchBrowserDisplayScale(): void {
+ schedule();
+ screen.on('display-added', schedule);
+ screen.on('display-removed', schedule);
+ screen.on('display-metrics-changed', schedule);
+}
diff --git a/src/main/browser-drawer/index.ts b/src/main/browser-drawer/index.ts
new file mode 100644
index 000000000..0a60a5a4a
--- /dev/null
+++ b/src/main/browser-drawer/index.ts
@@ -0,0 +1,11 @@
+/**
+ * The browser drawer's service (browser-drawer-service.ts), for the app's projects
+ */
+
+import { projectStore } from '../project-store';
+import { BrowserDrawerService } from './browser-drawer-service';
+
+export const browserDrawer = new BrowserDrawerService({
+ getProjects: () => projectStore.getProjects().map((project) => ({ id: project.id, path: project.path })),
+});
+
diff --git a/src/main/browser-drawer/pixel-scale.ts b/src/main/browser-drawer/pixel-scale.ts
new file mode 100644
index 000000000..6778b847a
--- /dev/null
+++ b/src/main/browser-drawer/pixel-scale.ts
@@ -0,0 +1,14 @@
+/**
+ * Device pixels per CSS pixel for the browser drawer: what the browsers render at
+ * (display-scale.ts) and what the drawer's frames are asked at (browser-drawer-service.ts). Pure, so
+ * both use one rule without the service loading Electron's screen module
+ */
+
+/** At most this many device pixels per CSS pixel (4x the pixels at 1, like a Retina screen) */
+export const MAX_PIXEL_SCALE = 2;
+
+/** A scale within 1..MAX_PIXEL_SCALE, to two decimals (anything that isn't a number: 1) */
+export function clampPixelScale(value: unknown): number {
+ const n = typeof value === 'number' && Number.isFinite(value) ? value : 1;
+ return Math.round(Math.min(Math.max(n, 1), MAX_PIXEL_SCALE) * 100) / 100;
+}
diff --git a/src/main/browser-drawer/project-match.ts b/src/main/browser-drawer/project-match.ts
new file mode 100644
index 000000000..9cceda027
--- /dev/null
+++ b/src/main/browser-drawer/project-match.ts
@@ -0,0 +1,66 @@
+/**
+ * Which project a Playwright browser session belongs to
+ * =====================================================
+ *
+ * Only Claude chats' browsers belong to a project here: the drawer shows nothing else. A chat's
+ * browser works in a folder of its own (the chat browser's holder folder, or a turn's temporary
+ * folder, insights/playwright-guard.cjs), registered here for its project while it runs. Task runs'
+ * browsers (their workspace is the task's worktree or the project) stay headless and unseen, as
+ * does any other tool's Playwright. In WSL mode the folders are the distribution's Linux paths, compared as the Windows paths
+ * the app stores (toHostPath: `/mnt/c/x` as `C:\x`, `/home/x` as `\\wsl.localhost\\home\x`).
+ */
+
+import path from 'path';
+
+export interface ProjectLocation {
+ id: string;
+ path: string;
+}
+
+/** Chat turns' Playwright folders -> their project's folder */
+const chatWorkspaces = new Map();
+
+/** A chat turn's Playwright folder belongs to its project until the returned function is called */
+export function registerChatBrowserWorkspace(dir: string, projectPath: string): () => void {
+ chatWorkspaces.set(dir, projectPath);
+ return () => {
+ if (chatWorkspaces.get(dir) === projectPath) chatWorkspaces.delete(dir);
+ };
+}
+
+/** The chat folders registered now (folder -> project folder) */
+export function getChatBrowserWorkspaces(): ReadonlyMap {
+ return chatWorkspaces;
+}
+
+/** A folder for comparison: resolved, without a trailing separator, lower case where case doesn't count */
+function normalize(dir: string, caseInsensitive: boolean): string {
+ const p = /^[A-Za-z]:[\\/]|^\\\\/.test(dir) ? path.win32 : path.posix;
+ // A WSL distribution's folders by either of Windows' names for them (\\wsl$ is the older)
+ const resolved = p.resolve(dir).replace(/[\\/]+$/, '').replace(/^\\\\wsl\$\\/i, '\\\\wsl.localhost\\');
+ return caseInsensitive ? resolved.toLowerCase() : resolved;
+}
+
+
+/**
+ * The project of a chat's browser, by its registered workspace folder; undefined for every other
+ * session (task runs, another tool's Playwright, the availability probe)
+ */
+export function sessionProjectId(
+ workspaceDir: string | undefined,
+ projects: readonly ProjectLocation[],
+ chats: ReadonlyMap = chatWorkspaces,
+ caseInsensitive = false,
+): string | undefined {
+ if (!workspaceDir) return undefined;
+ const dir = normalize(workspaceDir, caseInsensitive);
+ let projectDir: string | undefined;
+ for (const [chatDir, chatProject] of chats) {
+ if (normalize(chatDir, caseInsensitive) === dir) {
+ projectDir = normalize(chatProject, caseInsensitive);
+ break;
+ }
+ }
+ if (projectDir === undefined) return undefined;
+ return projects.find((project) => project.path && normalize(project.path, caseInsensitive) === projectDir)?.id;
+}
diff --git a/src/main/browser-drawer/registry.ts b/src/main/browser-drawer/registry.ts
new file mode 100644
index 000000000..6b2010f4c
--- /dev/null
+++ b/src/main/browser-drawer/registry.ts
@@ -0,0 +1,221 @@
+/**
+ * Playwright's browser registry
+ * =============================
+ *
+ * Every browser @playwright/mcp launches is "bound" (playwright-core's `browser.bind()`): it
+ * listens on a local socket (a named pipe on Windows) and writes a descriptor, one JSON file per
+ * browser named by its guid, into a registry folder shared by every Playwright on the machine:
+ * `/ms-playwright/b` (`$XDG_CACHE_HOME` or `~/.cache` on Linux, `~/Library/Caches` on
+ * macOS, `%LOCALAPPDATA%` on Windows; `PWTEST_SERVER_REGISTRY` overrides it). The descriptor
+ * holds the session's title (the MCP client's name, `claude-code` for Claude Code), its workspace
+ * folder (the client's first root, else the server's working folder), the socket and the
+ * playwright-core it runs. A browser with a profile folder keeps its file after it closes, so a
+ * session counts as live only while its socket answers (as Playwright's own dashboard does).
+ * Titles starting with `--playwright-internal` are Playwright's (and Workbench's availability
+ * probe's) own and never shown.
+ */
+
+import { readdir, readFile, stat, unlink } from 'fs/promises';
+import net from 'net';
+import os from 'os';
+import path from 'path';
+import { isMacOS, isWindows } from '../platform';
+
+export interface RegistryDescriptor {
+ guid: string;
+ title: string;
+ browserName: string;
+ workspaceDir?: string;
+ /** The socket path (or ws:// URL) the bound browser listens on */
+ endpoint?: string;
+ playwrightVersion?: string;
+ /** The playwright-core package folder that launched the browser */
+ playwrightLib?: string;
+ /** Playwright's own browser build (no executable of the user's, or one in Playwright's cache) */
+ managed?: boolean;
+}
+
+/** Sessions with this title prefix are Playwright's own (its dashboard leaves them out too) */
+export const INTERNAL_TITLE_PREFIX = '--playwright-internal';
+
+export type RegistryOs = 'linux' | 'macos' | 'windows';
+
+/** This machine's OS, which says where its registry folder is */
+export function registryOs(): RegistryOs {
+ return isWindows() ? 'windows' : isMacOS() ? 'macos' : 'linux';
+}
+
+/** The registry folder playwright-core uses (serverRegistry.ts `registryDirectory`) */
+export function registryDir(platform: RegistryOs, env: Record, home: string): string {
+ if (env.PWTEST_SERVER_REGISTRY) return env.PWTEST_SERVER_REGISTRY;
+ const p = platform === 'windows' ? path.win32 : path.posix;
+ const cache = platform === 'linux'
+ ? env.XDG_CACHE_HOME || p.join(home, '.cache')
+ : platform === 'macos'
+ ? p.join(home, 'Library', 'Caches')
+ : env.LOCALAPPDATA || p.join(home, 'AppData', 'Local');
+ return p.join(cache, 'ms-playwright', 'b');
+}
+
+/** This machine's registry folder */
+export function defaultRegistryDir(platform: RegistryOs): string {
+ return registryDir(platform, process.env, os.homedir());
+}
+
+/** Whether a browser's endpoint answers; null when that couldn't be asked (the file is read again next time) */
+export type EndpointCheck = (endpoint: string) => Promise;
+
+/**
+ * Where the registry is and how its browsers are asked whether they run: natively this
+ * machine's folder and its sockets; in WSL mode the distribution's folder (read through
+ * `\\wsl.localhost`) and the bridge, which runs there (set by the browser drawer service)
+ */
+export interface RegistryAccess {
+ dir: string;
+ connect: EndpointCheck;
+}
+
+let registryAccessOverride: RegistryAccess | null = null;
+
+/** Use another registry (WSL mode), or this machine's again (null) */
+export function setRegistryAccess(access: RegistryAccess | null): void {
+ registryAccessOverride = access;
+}
+
+/** The registry the browsers are in */
+export function registryAccess(platform: RegistryOs): RegistryAccess {
+ return registryAccessOverride ?? { dir: defaultRegistryDir(platform), connect: canConnect };
+}
+
+/** A descriptor file's content, or null when it isn't one */
+export function parseDescriptor(text: string): RegistryDescriptor | null {
+ let raw: unknown;
+ try {
+ raw = JSON.parse(text);
+ } catch {
+ return null;
+ }
+ if (!raw || typeof raw !== 'object') return null;
+ const value = raw as Record;
+ const browser = value.browser as Record | undefined;
+ if (!browser || typeof browser.guid !== 'string' || typeof value.title !== 'string') return null;
+ const launchOptions = browser.launchOptions as Record | undefined;
+ const executablePath = typeof launchOptions?.executablePath === 'string' ? launchOptions.executablePath : '';
+ const endpoint = typeof value.endpoint === 'string' ? value.endpoint : typeof value.pipeName === 'string' ? value.pipeName : undefined;
+ return {
+ guid: browser.guid,
+ title: value.title,
+ browserName: typeof browser.browserName === 'string' ? browser.browserName : 'chromium',
+ ...(typeof value.workspaceDir === 'string' ? { workspaceDir: value.workspaceDir } : {}),
+ ...(endpoint ? { endpoint } : {}),
+ ...(typeof value.playwrightVersion === 'string' ? { playwrightVersion: value.playwrightVersion } : {}),
+ ...(typeof value.playwrightLib === 'string' ? { playwrightLib: value.playwrightLib } : {}),
+ managed: !executablePath || /[\\/]ms-playwright[\\/]/.test(executablePath),
+ };
+}
+
+/** Whether a bound browser's socket (or ws:// endpoint) answers */
+export function canConnect(endpoint: string, timeoutMs = 1000): Promise {
+ return new Promise((resolve) => {
+ let socket: net.Socket;
+ try {
+ if (/^wss?:\/\//.test(endpoint)) {
+ const url = new URL(endpoint);
+ socket = net.createConnection(Number(url.port) || (url.protocol === 'wss:' ? 443 : 80), url.hostname);
+ } else {
+ socket = net.createConnection(endpoint);
+ }
+ } catch {
+ resolve(false);
+ return;
+ }
+ const done = (result: boolean) => {
+ clearTimeout(timer);
+ socket.destroy();
+ resolve(result);
+ };
+ // A socket that neither accepts nor refuses in time is a busy browser, not a closed one (a
+ // closed one refuses at once): counted as live, so one slow answer never hides it for good
+ const timer = setTimeout(() => done(true), timeoutMs);
+ socket.once('connect', () => done(true));
+ socket.once('error', () => done(false));
+ });
+}
+
+/** Descriptors whose socket didn't answer, by file, with the file's mtime then */
+type DeadCache = Map;
+
+/**
+ * The live sessions in a registry folder (none when it doesn't exist). Files whose browser
+ * didn't answer are skipped until they change (`dead`, kept by the caller between reads)
+ */
+export async function readLiveSessions(
+ dir: string,
+ dead: DeadCache = new Map(),
+ connect: EndpointCheck = canConnect,
+ /**
+ * Browsers known to be live without asking: the bridge is connected to them and hears when they
+ * go, or (WSL mode, before a drawer started the bridge) Workbench holds them open
+ */
+ knownLive: (descriptor: RegistryDescriptor) => boolean = () => false,
+): Promise {
+ let names: string[];
+ try {
+ names = await readdir(dir);
+ } catch {
+ dead.clear();
+ return [];
+ }
+ const present = new Set(names);
+ for (const name of dead.keys()) if (!present.has(name)) dead.delete(name);
+ const results = await Promise.all(names.map(async (name): Promise => {
+ const file = path.join(dir, name);
+ try {
+ const { mtimeMs, isFile } = await stat(file).then((s) => ({ mtimeMs: s.mtimeMs, isFile: s.isFile() }));
+ if (!isFile || dead.get(name) === mtimeMs) return null;
+ const descriptor = parseDescriptor(await readFile(file, 'utf-8'));
+ if (!descriptor || descriptor.title.startsWith(INTERNAL_TITLE_PREFIX)) return null;
+ if (!descriptor.endpoint) {
+ dead.set(name, mtimeMs);
+ return null;
+ }
+ if (knownLive(descriptor)) return descriptor;
+ const live = await connect(descriptor.endpoint);
+ // Not asked (the bridge didn't answer): left out now, asked again next time
+ if (live === null) return null;
+ if (!live) {
+ dead.set(name, mtimeMs);
+ return null;
+ }
+ return descriptor;
+ } catch {
+ return null;
+ }
+ }));
+ return results.filter((d): d is RegistryDescriptor => d !== null);
+}
+
+/**
+ * Remove the files of closed browsers bound under `title` (a browser with a profile folder keeps
+ * its file after it closes, and each chat browser has a title of its own). Best effort
+ */
+export async function removeClosedSessions(dir: string, title: string, connect: EndpointCheck = canConnect): Promise {
+ let names: string[];
+ try {
+ names = await readdir(dir);
+ } catch {
+ return;
+ }
+ await Promise.all(names.map(async (name) => {
+ const file = path.join(dir, name);
+ try {
+ const descriptor = parseDescriptor(await readFile(file, 'utf-8'));
+ if (!descriptor || descriptor.title !== title) return;
+ // Kept while it answers, or when that couldn't be asked
+ if (descriptor.endpoint && (await connect(descriptor.endpoint)) !== false) return;
+ await unlink(file);
+ } catch {
+ // Gone meanwhile
+ }
+ }));
+}
diff --git a/src/main/browser-profiles/__tests__/app-alias.test.ts b/src/main/browser-profiles/__tests__/app-alias.test.ts
new file mode 100644
index 000000000..f8f619e4a
--- /dev/null
+++ b/src/main/browser-profiles/__tests__/app-alias.test.ts
@@ -0,0 +1,37 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+
+const readlinkSync = vi.fn();
+const isWindows = vi.fn(() => true);
+vi.mock('fs', () => ({ readlinkSync: (p: string) => readlinkSync(p) }));
+vi.mock('../../platform', () => ({ isWindows: () => isWindows() }));
+
+import { appAliasTarget } from '../app-alias';
+
+const ALIAS = 'C:\\Users\\me\\AppData\\Local\\Microsoft\\WindowsApps\\Mozilla.Firefox_n80bbvh6b1yt2\\firefox.exe';
+const TARGET = 'C:\\Program Files\\WindowsApps\\Mozilla.Firefox_158.0.1.0_x64__n80bbvh6b1yt2\\VFS\\ProgramFiles\\Firefox Package Root\\firefox.exe';
+
+describe('appAliasTarget', () => {
+ beforeEach(() => {
+ readlinkSync.mockReset();
+ isWindows.mockReturnValue(true);
+ });
+
+ it("runs a Store app's alias as the package executable it points at", () => {
+ readlinkSync.mockReturnValue(TARGET);
+ expect(appAliasTarget(ALIAS)).toBe(TARGET);
+ });
+
+ it('keeps the alias when it cannot be read', () => {
+ readlinkSync.mockImplementation(() => {
+ throw new Error('EINVAL');
+ });
+ expect(appAliasTarget(ALIAS)).toBe(ALIAS);
+ });
+
+ it('leaves other executables alone', () => {
+ expect(appAliasTarget('C:\\Program Files\\Mozilla Firefox\\firefox.exe')).toBe('C:\\Program Files\\Mozilla Firefox\\firefox.exe');
+ isWindows.mockReturnValue(false);
+ expect(appAliasTarget('/usr/lib/firefox/firefox')).toBe('/usr/lib/firefox/firefox');
+ expect(readlinkSync).not.toHaveBeenCalled();
+ });
+});
diff --git a/src/main/browser-profiles/__tests__/choices-in-use.test.ts b/src/main/browser-profiles/__tests__/choices-in-use.test.ts
new file mode 100644
index 000000000..f81b1bcbb
--- /dev/null
+++ b/src/main/browser-profiles/__tests__/choices-in-use.test.ts
@@ -0,0 +1,55 @@
+/**
+ * The profiles still chosen: Settings plus the tasks' own picks that aren't archived, per project
+ * and across projects
+ */
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
+import path from 'path';
+import os from 'os';
+import { mkdtemp, mkdir, rm, writeFile } from 'fs/promises';
+
+const projects = vi.hoisted(() => ({ list: [] as { path: string; autoBuildPath?: string }[] }));
+vi.mock('../../project-store', () => ({ projectStore: { getProjects: () => projects.list } }));
+
+import { browserChoicesInUse } from '../choices-in-use';
+
+const choice = (id: string) => ({ id, browser: 'chrome', engine: 'chromium', profileName: id, executablePath: '/c', userDataDir: '/c', profilePath: `/c/${id}` });
+
+describe('browserChoicesInUse', () => {
+ let root: string;
+
+ async function task(project: string, name: string, metadata: unknown): Promise {
+ const dir = path.join(project, '.workbench', 'tasks', name);
+ await mkdir(dir, { recursive: true });
+ await writeFile(path.join(dir, 'task_metadata.json'), JSON.stringify(metadata));
+ }
+
+ beforeEach(async () => {
+ root = await mkdtemp(path.join(os.tmpdir(), 'choices-in-use-'));
+ projects.list = [{ path: path.join(root, 'a'), autoBuildPath: '.workbench' }, { path: path.join(root, 'b') }];
+ });
+
+ afterEach(async () => {
+ await rm(root, { recursive: true, force: true });
+ });
+
+ it("lists Settings' choice and the tasks' own picks, leaving out archived tasks and Playwright's Chromium", async () => {
+ const [a, b] = projects.list.map((project) => project.path);
+ await task(a, '001-own', { playwrightBrowser: choice('chrome:A') });
+ await task(a, '002-archived', { playwrightBrowser: choice('chrome:Old'), archivedAt: '2026-10-01T00:00:00Z' });
+ await task(a, '003-default-chrome', { playwrightBrowser: null });
+ await task(a, '004-follows-settings', {});
+ await task(b, '001-other', { playwrightBrowser: choice('chrome:B') });
+ // A pick saved before the connector moved to Playwright
+ await task(b, '002-older', { puppeteerBrowser: choice('chrome:Older') });
+ await mkdir(path.join(a, '.workbench', 'tasks', '005-broken'), { recursive: true });
+ await writeFile(path.join(a, '.workbench', 'tasks', '005-broken', 'task_metadata.json'), '{');
+
+ const inUse = await browserChoicesInUse(a, choice('chrome:Settings') as never);
+ expect(inUse.project.map((c) => c.id)).toEqual(['chrome:Settings', 'chrome:A']);
+ expect(inUse.all.map((c) => c.id).sort()).toEqual(['chrome:A', 'chrome:B', 'chrome:Older', 'chrome:Settings']);
+ });
+
+ it('chooses nothing for a project without tasks', async () => {
+ expect(await browserChoicesInUse(path.join(root, 'a'), undefined)).toEqual({ project: [], all: [] });
+ });
+});
diff --git a/src/main/browser-profiles/__tests__/detect-watch.test.ts b/src/main/browser-profiles/__tests__/detect-watch.test.ts
new file mode 100644
index 000000000..7cebb42a6
--- /dev/null
+++ b/src/main/browser-profiles/__tests__/detect-watch.test.ts
@@ -0,0 +1,68 @@
+/**
+ * waitForManagedBrowser: a later download of the same browser shares the running watch and moves
+ * its deadline, so a download that finishes after the first click's 15 minutes still updates the list
+ */
+import { describe, it, expect, vi, afterEach } from 'vitest';
+
+const mocks = vi.hoisted(() => ({ downloaded: new Set() }));
+
+vi.mock('../managed', () => ({
+ findManagedBrowser: vi.fn(async (browser: string) => (mocks.downloaded.has(browser) ? `/home/me/.cache/ms-playwright/${browser}` : undefined)),
+ scanManagedBrowsers: vi.fn(async () => []),
+}));
+vi.mock('../../mcp-commands', () => ({ resolveCommand: async () => null }));
+vi.mock('../../platform/runtime-exec', () => ({ runTool: vi.fn() }));
+vi.mock('../../app-logger', () => ({ appLog: { warn: vi.fn() } }));
+vi.mock('../../platform', () => ({ isWindows: () => false, isMacOS: () => false }));
+vi.mock('../../platform/shell-runtime', () => ({
+ whenShellRuntimeReady: async () => undefined,
+ getWslInfo: () => null,
+ toHostPath: (p: string) => p,
+}));
+vi.mock('os', async (importOriginal) => {
+ const actual = await importOriginal();
+ // No real browser profiles are scanned
+ const homedir = () => '/nonexistent-home-for-test';
+ return { ...actual, default: { ...actual, homedir }, homedir };
+});
+
+import { waitForManagedBrowser } from '../detect';
+
+afterEach(() => {
+ vi.useRealTimers();
+ mocks.downloaded.clear();
+});
+
+describe('waitForManagedBrowser', () => {
+ it("extends the shared watch's deadline on each call", async () => {
+ vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'Date'] });
+ const first = waitForManagedBrowser('firefox');
+ await vi.advanceTimersByTimeAsync(10 * 60 * 1000);
+ const second = waitForManagedBrowser('firefox');
+ expect(second).toBe(first);
+ // Past the first call's deadline, before the second's
+ await vi.advanceTimersByTimeAsync(10 * 60 * 1000);
+ mocks.downloaded.add('firefox');
+ await vi.advanceTimersByTimeAsync(5_000);
+ expect(await first).not.toBeNull();
+ });
+
+ it('watches each browser on its own', async () => {
+ vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'Date'] });
+ const firefox = waitForManagedBrowser('firefox');
+ const webkit = waitForManagedBrowser('webkit');
+ expect(webkit).not.toBe(firefox);
+ mocks.downloaded.add('webkit');
+ await vi.advanceTimersByTimeAsync(5_000);
+ expect(await webkit).not.toBeNull();
+ await vi.advanceTimersByTimeAsync(15 * 60 * 1000 + 5_000);
+ expect(await firefox).toBeNull();
+ });
+
+ it('gives up 15 minutes after the latest call', async () => {
+ vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'Date'] });
+ const watch = waitForManagedBrowser('firefox');
+ await vi.advanceTimersByTimeAsync(15 * 60 * 1000 + 5_000);
+ expect(await watch).toBeNull();
+ });
+});
diff --git a/src/main/browser-profiles/__tests__/detect.test.ts b/src/main/browser-profiles/__tests__/detect.test.ts
new file mode 100644
index 000000000..8eedd76c2
--- /dev/null
+++ b/src/main/browser-profiles/__tests__/detect.test.ts
@@ -0,0 +1,347 @@
+import os from 'os';
+import path from 'path';
+import { mkdtemp, mkdir, rm, utimes, writeFile } from 'fs/promises';
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
+
+const mocks = vi.hoisted(() => ({
+ commands: new Map(),
+ wslHome: null as string | null,
+ toHost: (p: string) => p,
+ runTool: vi.fn(async () => ({ stdout: 'Mozilla Firefox 150.0', stderr: '' })),
+}));
+
+vi.mock('../../mcp-commands', () => ({ resolveCommand: async (command: string) => mocks.commands.get(command) ?? null }));
+vi.mock('../../platform/runtime-exec', () => ({ runTool: mocks.runTool }));
+vi.mock('../../app-logger', () => ({ appLog: { warn: vi.fn() } }));
+vi.mock('../../platform', () => ({ isWindows: () => mocks.wslHome !== null, isMacOS: () => false }));
+vi.mock('../../platform/shell-runtime', () => ({
+ whenShellRuntimeReady: async () => undefined,
+ getWslInfo: () => (mocks.wslHome ? { distro: 'Ubuntu', home: mocks.wslHome } : null),
+ toHostPath: (p: string) => mocks.toHost(p),
+}));
+
+import { STALE_PROFILE_MS, UNOPENED_PROFILE_MS, detectBrowserProfiles, isStaleProfile, majorVersion, pickWslFirefox, scanBrowserProfiles } from '../detect';
+import { findManagedBrowser, playwrightCacheDir } from '../managed';
+
+let root: string;
+
+/** The browsers' own profiles (Playwright's downloads are tested apart) */
+async function scanUserProfiles(context: Parameters[0]) {
+ return (await scanBrowserProfiles(context)).filter((profile) => !profile.managed);
+}
+
+/** A path from an OS's table -> where the fixture keeps it */
+function fixturePath(p: string): string {
+ return path.join(root, p.replace(/^[A-Za-z]:/, '').replace(/\\/g, '/'));
+}
+
+async function put(p: string, content = ''): Promise {
+ const file = fixturePath(p);
+ await mkdir(path.dirname(file), { recursive: true });
+ await writeFile(file, content);
+}
+
+async function folder(p: string): Promise {
+ await mkdir(fixturePath(p), { recursive: true });
+}
+
+const localState = (cache: Record) => JSON.stringify({ profile: { info_cache: cache } });
+
+describe('browser profile detection', () => {
+ beforeEach(async () => {
+ root = await mkdtemp(path.join(os.tmpdir(), 'browser-profiles-'));
+ mocks.commands.clear();
+ mocks.wslHome = null;
+ mocks.toHost = fixturePath;
+ mocks.runTool.mockClear();
+ });
+
+ afterEach(async () => {
+ await rm(root, { recursive: true, force: true });
+ });
+
+ it('finds Windows Chromium and Firefox profiles and marks missing executables', async () => {
+ const local = 'C:\\Users\\me\\AppData\\Local';
+ await put(`${local}\\Google\\Chrome\\User Data\\Local State`, localState({ Default: { name: 'Me', user_name: 'me@example.com' }, 'Profile 1': { name: 'Work' } }));
+ await folder(`${local}\\Google\\Chrome\\User Data\\Default`);
+ await folder(`${local}\\Google\\Chrome\\User Data\\Profile 1`);
+ await put('C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe');
+ // Edge's profiles are there, its executable isn't
+ await put(`${local}\\Microsoft\\Edge\\User Data\\Local State`, localState({ Default: { name: 'Edge me' } }));
+ await folder(`${local}\\Microsoft\\Edge\\User Data\\Default`);
+ const roaming = 'C:\\Users\\me\\AppData\\Roaming\\Mozilla\\Firefox';
+ await put(`${roaming}\\profiles.ini`, '[Profile0]\r\nName=default-release\r\nIsRelative=1\r\nPath=Profiles/x.default-release\r\n');
+ await folder(`${roaming}\\Profiles\\x.default-release`);
+ await put('C:\\Program Files\\Mozilla Firefox\\firefox.exe');
+
+ const profiles = await scanUserProfiles({
+ os: 'windows',
+ home: 'C:\\Users\\me',
+ env: { LOCALAPPDATA: local, APPDATA: 'C:\\Users\\me\\AppData\\Roaming', ProgramFiles: 'C:\\Program Files' },
+ toHost: fixturePath,
+ lookUpCommands: false,
+ });
+
+ expect(profiles.map((p) => [p.id, p.usable, p.disabledReason])).toEqual([
+ ['chrome:Default', true, undefined],
+ ['chrome:Profile 1', true, undefined],
+ ['edge:Default', false, 'executable-missing'],
+ ['firefox:x.default-release', true, undefined],
+ ]);
+ expect(profiles[0]).toMatchObject({
+ browser: 'chrome',
+ engine: 'chromium',
+ profileName: 'Me',
+ email: 'me@example.com',
+ userDataDir: `${local}\\Google\\Chrome\\User Data`,
+ profileDirectory: 'Default',
+ profilePath: `${local}\\Google\\Chrome\\User Data\\Default`,
+ executablePath: 'C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe',
+ });
+ expect(profiles[3]).toMatchObject({
+ engine: 'firefox',
+ profilePath: `${roaming}\\Profiles\\x.default-release`,
+ executablePath: 'C:\\Program Files\\Mozilla Firefox\\firefox.exe',
+ });
+ });
+
+ it('finds Microsoft Store Firefox by the profiles its package keeps, whatever the package is called', async () => {
+ const local = 'C:\\Users\\me\\AppData\\Local';
+ const store = `${local}\\Packages\\Some.Firefox_xyz\\LocalCache\\Roaming\\Mozilla\\Firefox`;
+ await put(`${store}\\profiles.ini`, '[Profile0]\r\nName=default-release\r\nIsRelative=1\r\nPath=Profiles/s.default-release\r\n');
+ await folder(`${store}\\Profiles\\s.default-release`);
+ await put(`${local}\\Microsoft\\WindowsApps\\Some.Firefox_xyz\\firefox.exe`);
+ // Another app's package, without Firefox profiles
+ await folder(`${local}\\Packages\\Microsoft.WindowsCalculator_8wekyb3d8bbwe\\LocalCache`);
+
+ const profiles = await scanUserProfiles({ os: 'windows', home: 'C:\\Users\\me', env: { LOCALAPPDATA: local }, toHost: fixturePath, lookUpCommands: false });
+
+ expect(profiles).toEqual([
+ expect.objectContaining({
+ id: 'firefox-store:s.default-release',
+ variant: 'store',
+ usable: true,
+ profilePath: `${store}\\Profiles\\s.default-release`,
+ executablePath: `${local}\\Microsoft\\WindowsApps\\Some.Firefox_xyz\\firefox.exe`,
+ }),
+ ]);
+ });
+
+ it('lists Safari on macOS as unsupported and skips profiles whose folder is gone', async () => {
+ const support = '/Users/me/Library/Application Support';
+ await put(`${support}/BraveSoftware/Brave-Browser/Local State`, localState({ Default: { name: 'Brave me' }, 'Profile 3': { name: 'Deleted' } }));
+ await folder(`${support}/BraveSoftware/Brave-Browser/Default`);
+ await put('/Applications/Brave Browser.app/Contents/MacOS/Brave Browser');
+ await put('/Applications/Safari.app/Contents/MacOS/Safari');
+
+ const profiles = await scanUserProfiles({ os: 'macos', home: '/Users/me', env: {}, toHost: fixturePath, lookUpCommands: false });
+
+ expect(profiles.map((p) => [p.id, p.usable, p.disabledReason])).toEqual([
+ ['brave:Default', true, undefined],
+ ['safari:default', false, 'unsupported-engine'],
+ ]);
+ });
+
+ it('finds Linux browsers through PATH, snaps, and lists Flatpaks as unusable', async () => {
+ await put('/home/me/.config/google-chrome/Local State', localState({ Default: { name: 'Me' } }));
+ await folder('/home/me/.config/google-chrome/Default');
+ mocks.commands.set('google-chrome', '/usr/bin/google-chrome');
+ await put('/home/me/snap/firefox/common/.mozilla/firefox/profiles.ini', '[Profile0]\nName=snappy\nIsRelative=1\nPath=s.default\n');
+ await folder('/home/me/snap/firefox/common/.mozilla/firefox/s.default');
+ await put('/snap/bin/firefox');
+ await put('/snap/firefox/current/usr/lib/firefox/firefox');
+ await put('/home/me/.var/app/org.chromium.Chromium/config/chromium/Local State', localState({ Default: { name: 'Flat' } }));
+ await folder('/home/me/.var/app/org.chromium.Chromium/config/chromium/Default');
+ // Unreadable Local State: that browser is skipped, the others are listed
+ await put('/home/me/.config/microsoft-edge/Local State', '{broken');
+
+ const profiles = await scanUserProfiles({ os: 'linux', home: '/home/me', env: {}, toHost: fixturePath, lookUpCommands: true });
+
+ expect(profiles.map((p) => [p.id, p.usable, p.executablePath, p.disabledReason])).toEqual([
+ ['chrome:Default', true, '/usr/bin/google-chrome', undefined],
+ ['chromium-flatpak:Default', false, undefined, 'sandboxed-package'],
+ ['firefox-snap:s.default', true, '/snap/bin/firefox', undefined],
+ ]);
+ // Profiles with the same name in different installs can be told apart
+ expect(profiles.map((p) => p.variant)).toEqual([undefined, 'flatpak', 'snap']);
+ });
+
+ it("treats Ubuntu's /usr/bin/firefox script as the snap and checks the snap's binary runs once", async () => {
+ await put('/home/me/.mozilla/firefox/profiles.ini', '[Profile0]\nName=deb\nIsRelative=1\nPath=d.default\n');
+ await folder('/home/me/.mozilla/firefox/d.default');
+ await put('/home/me/snap/firefox/common/.mozilla/firefox/profiles.ini', '[Profile0]\nName=snappy\nIsRelative=1\nPath=s.default\n');
+ await folder('/home/me/snap/firefox/common/.mozilla/firefox/s.default');
+ await put('/usr/bin/firefox', '#!/bin/sh\nexec /snap/bin/firefox "$@"\n');
+ mocks.commands.set('firefox', '/usr/bin/firefox');
+ await put('/snap/bin/firefox');
+ await put('/snap/firefox/current/usr/lib/firefox/firefox');
+ const context = { os: 'linux' as const, home: '/home/me', env: {}, toHost: fixturePath, lookUpCommands: true };
+
+ const profiles = await scanUserProfiles(context);
+ expect(profiles.map((p) => [p.id, p.usable, p.executablePath])).toEqual([
+ ['firefox:d.default', true, '/snap/bin/firefox'],
+ ['firefox-snap:s.default', true, '/snap/bin/firefox'],
+ ]);
+ expect(mocks.runTool).toHaveBeenCalledTimes(1);
+ expect(mocks.runTool).toHaveBeenCalledWith('node', ['--version'], expect.objectContaining({ command: '/snap/firefox/current/usr/lib/firefox/firefox' }));
+
+ // On a system older than the snap's base the binary can't load
+ mocks.runTool.mockRejectedValueOnce(Object.assign(new Error('failed'), {
+ stderr: "firefox: /lib/x86_64-linux-gnu/libc.so.6: version `GLIBC_2.38' not found (required by firefox)",
+ }));
+ const old = await scanUserProfiles({ ...context });
+ expect(old.map((p) => [p.usable, p.disabledReason])).toEqual([
+ [false, 'snap-needs-newer-glibc'],
+ [false, 'snap-needs-newer-glibc'],
+ ]);
+ });
+
+ it('keeps a real Firefox launcher script as it is', async () => {
+ await put('/home/me/.mozilla/firefox/profiles.ini', '[Profile0]\nName=deb\nIsRelative=1\nPath=d.default\n');
+ await folder('/home/me/.mozilla/firefox/d.default');
+ await put('/usr/bin/firefox', '#!/bin/sh\nexec /usr/lib64/firefox/firefox "$@"\n');
+ mocks.commands.set('firefox', '/usr/bin/firefox');
+
+ const profiles = await scanUserProfiles({ os: 'linux', home: '/home/me', env: {}, toHost: fixturePath, lookUpCommands: true });
+ expect(profiles.map((p) => [p.usable, p.executablePath])).toEqual([[true, '/usr/bin/firefox']]);
+ expect(mocks.runTool).not.toHaveBeenCalled();
+ });
+
+ it('leaves out profiles nothing has written to for a year', async () => {
+ const dir = '/home/me/.mozilla/firefox';
+ await put(`${dir}/profiles.ini`, [
+ '[Profile0]', 'Name=old', 'IsRelative=1', 'Path=a.old', '',
+ '[Profile1]', 'Name=in-use', 'IsRelative=1', 'Path=b.in-use', '',
+ '[Profile2]', 'Name=never-opened', 'IsRelative=1', 'Path=c.fresh', '',
+ // Firefox's placeholder: made on its first run, never opened since
+ '[Profile3]', 'Name=default', 'IsRelative=1', 'Path=d.default',
+ ].join('\n'));
+ await put(`${dir}/a.old/prefs.js`);
+ await put(`${dir}/b.in-use/prefs.js`);
+ await folder(`${dir}/c.fresh`);
+ await put(`${dir}/d.default/times.json`);
+ const longAgo = new Date(Date.now() - 2 * STALE_PROFILE_MS);
+ await utimes(fixturePath(`${dir}/a.old/prefs.js`), longAgo, longAgo);
+ const weeksAgo = new Date(Date.now() - 2 * UNOPENED_PROFILE_MS);
+ await utimes(fixturePath(`${dir}/d.default`), weeksAgo, weeksAgo);
+ await put('/usr/lib/firefox/firefox');
+
+ const profiles = await scanUserProfiles({ os: 'linux', home: '/home/me', env: {}, toHost: fixturePath, lookUpCommands: false });
+
+ expect(profiles.map((p) => p.profileName)).toEqual(['in-use', 'never-opened']);
+ });
+
+ it('judges a profile by its activity files, not its folder date', async () => {
+ const folderPath = fixturePath('/p/profile');
+ await put('/p/profile/prefs.js');
+ const longAgo = new Date(Date.now() - 2 * STALE_PROFILE_MS);
+ await utimes(`${folderPath}/prefs.js`, longAgo, longAgo);
+ // The folder itself was touched just now
+ expect(await isStaleProfile(folderPath)).toBe(true);
+ // Without activity files it was never opened: its folder date counts, with a shorter limit
+ await folder('/p/empty');
+ expect(await isStaleProfile(fixturePath('/p/empty'))).toBe(false);
+ const weeksAgo = new Date(Date.now() - 2 * UNOPENED_PROFILE_MS);
+ await utimes(fixturePath('/p/empty'), weeksAgo, weeksAgo);
+ expect(await isStaleProfile(fixturePath('/p/empty'))).toBe(true);
+ expect(await isStaleProfile(fixturePath('/p/missing'))).toBe(false);
+ });
+
+ it("lists Playwright's Firefox and WebKit as downloadable until their builds are in the cache, then as usable", async () => {
+ const context = { os: 'linux' as const, home: '/home/me', env: {}, toHost: fixturePath, lookUpCommands: false };
+ const managed = async () => (await scanBrowserProfiles(context)).filter((p) => p.managed);
+
+ expect(await managed()).toEqual([
+ expect.objectContaining({ id: 'playwright:firefox', engine: 'firefox', usable: false, disabledReason: 'not-downloaded', downloadable: 'firefox' }),
+ expect.objectContaining({ id: 'playwright:webkit', engine: 'webkit', usable: false, disabledReason: 'not-downloaded', downloadable: 'webkit' }),
+ ]);
+
+ // Another version's build doesn't count: the pinned server needs its own
+ await put('/home/me/.cache/ms-playwright/firefox-1495/INSTALLATION_COMPLETE');
+ await put('/home/me/.cache/ms-playwright/firefox-1495/firefox/firefox');
+ await put('/home/me/.cache/ms-playwright/firefox-1553/INSTALLATION_COMPLETE');
+ await put('/home/me/.cache/ms-playwright/firefox-1553/firefox/firefox');
+ const [firefox, webkit] = await managed();
+ expect(firefox).toMatchObject({ usable: true, executablePath: '/home/me/.cache/ms-playwright/firefox-1553/firefox/firefox' });
+ expect(firefox.downloadable).toBeUndefined();
+ expect(webkit.usable).toBe(false);
+ });
+
+ it('skips a Playwright build that is still being unpacked (no INSTALLATION_COMPLETE yet)', async () => {
+ const context = { os: 'linux' as const, home: '/home/me', env: {}, toHost: fixturePath, lookUpCommands: false };
+ await put('/home/me/.cache/ms-playwright/webkit-2368/pw_run.sh');
+ expect(await findManagedBrowser('webkit', context)).toBeUndefined();
+ await put('/home/me/.cache/ms-playwright/webkit-2368/INSTALLATION_COMPLETE');
+ expect(await findManagedBrowser('webkit', context)).toBe('/home/me/.cache/ms-playwright/webkit-2368/pw_run.sh');
+ });
+
+ it("finds the builds in the cache folder each OS uses", async () => {
+ await put('/Users/me/Library/Caches/ms-playwright/chromium-1247/INSTALLATION_COMPLETE');
+ await put('/Users/me/Library/Caches/ms-playwright/chromium-1247/chrome-mac-arm64/Google Chrome for Testing.app/Contents/MacOS/Google Chrome for Testing');
+ // macOS 14 gets an older WebKit build
+ await put('/Users/me/Library/Caches/ms-playwright/webkit_mac14_arm64_special-2251/INSTALLATION_COMPLETE');
+ await put('/Users/me/Library/Caches/ms-playwright/webkit_mac14_arm64_special-2251/pw_run.sh');
+ const mac = { os: 'macos' as const, home: '/Users/me', env: {}, toHost: fixturePath };
+ expect(await findManagedBrowser('chromium', mac))
+ .toBe('/Users/me/Library/Caches/ms-playwright/chromium-1247/chrome-mac-arm64/Google Chrome for Testing.app/Contents/MacOS/Google Chrome for Testing');
+ expect(await findManagedBrowser('webkit', mac)).toBe('/Users/me/Library/Caches/ms-playwright/webkit_mac14_arm64_special-2251/pw_run.sh');
+
+ await put('C:\\Users\\me\\AppData\\Local\\ms-playwright\\firefox-1553\\INSTALLATION_COMPLETE');
+ await put('C:\\Users\\me\\AppData\\Local\\ms-playwright\\firefox-1553\\firefox\\firefox.exe');
+ const windows = await scanBrowserProfiles({ os: 'windows', home: 'C:\\Users\\me', env: {}, toHost: fixturePath, lookUpCommands: false });
+ expect(windows.find((p) => p.id === 'playwright:firefox')?.executablePath).toBe('C:\\Users\\me\\AppData\\Local\\ms-playwright\\firefox-1553\\firefox\\firefox.exe');
+
+ // PLAYWRIGHT_BROWSERS_PATH, then XDG_CACHE_HOME on Linux
+ const linux = { os: 'linux' as const, home: '/home/me', toHost: fixturePath };
+ expect(playwrightCacheDir({ ...linux, env: { PLAYWRIGHT_BROWSERS_PATH: '/opt/pw' } })).toBe('/opt/pw');
+ expect(playwrightCacheDir({ ...linux, env: { XDG_CACHE_HOME: '/xdg' } })).toBe('/xdg/ms-playwright');
+ expect(playwrightCacheDir({ ...linux, env: { PLAYWRIGHT_BROWSERS_PATH: '0' } })).toBe('/home/me/.cache/ms-playwright');
+ });
+
+ it("doesn't list Playwright's downloads for Windows browsers while tools run in WSL", async () => {
+ mocks.wslHome = '/home/wsl';
+ const profiles = await detectBrowserProfiles({ refresh: true });
+ expect(profiles.filter((p) => p.managed).map((p) => p.id)).toEqual(['playwright:firefox', 'playwright:webkit']);
+ });
+
+ it("reads the WSL distribution's browsers through host paths, with Linux paths", async () => {
+ mocks.wslHome = '/home/wsl';
+ await put('/home/wsl/.config/chromium/Local State', localState({ Default: { name: 'In WSL' } }));
+ await folder('/home/wsl/.config/chromium/Default');
+ await put('/usr/lib/chromium/chromium');
+
+ const profiles = (await detectBrowserProfiles({ refresh: true })).filter((p) => !p.id.startsWith('windows-') && !p.managed);
+
+ expect(profiles).toEqual([
+ expect.objectContaining({
+ id: 'chromium:Default',
+ usable: true,
+ executablePath: '/usr/lib/chromium/chromium',
+ profilePath: '/home/wsl/.config/chromium/Default',
+ }),
+ ]);
+ });
+});
+
+describe('the Firefox in WSL that runs a Windows Firefox profile', () => {
+ const installed = { executablePath: '/usr/lib/firefox/firefox', major: 158 };
+ const playwright = '/home/me/.cache/ms-playwright/firefox-1553/firefox/firefox';
+
+ it('reads major versions from `--version` and compatibility.ini', () => {
+ expect(majorVersion('Mozilla Firefox 156.0')).toBe(156);
+ expect(majorVersion('158.0.1_20261019185856/20261019185856')).toBe(158);
+ expect(majorVersion('')).toBeUndefined();
+ });
+
+ it('takes the installed Firefox when it is at least the profile\'s version', () => {
+ expect(pickWslFirefox(158, { installed, playwright })).toBe(installed.executablePath);
+ expect(pickWslFirefox(undefined, { installed, playwright })).toBe(installed.executablePath);
+ });
+
+ it("takes Playwright's Firefox for a profile a newer Firefox wrote, else the older installed one", () => {
+ expect(pickWslFirefox(159, { installed, playwright })).toBe(playwright);
+ expect(pickWslFirefox(159, { installed })).toBe(installed.executablePath);
+ expect(pickWslFirefox(158, { playwright })).toBe(playwright);
+ expect(pickWslFirefox(158, {})).toBeUndefined();
+ });
+});
diff --git a/src/main/browser-profiles/__tests__/in-use.test.ts b/src/main/browser-profiles/__tests__/in-use.test.ts
new file mode 100644
index 000000000..7c2cd219d
--- /dev/null
+++ b/src/main/browser-profiles/__tests__/in-use.test.ts
@@ -0,0 +1,185 @@
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
+import { lutimes, mkdtemp, readFile, rm, symlink } from 'fs/promises';
+import { existsSync } from 'fs';
+import { execFile, spawn, type ChildProcess } from 'child_process';
+import { promisify } from 'util';
+import { hostname, tmpdir } from 'os';
+import path from 'path';
+import type { PlaywrightBrowserChoice } from '../../../shared/types/browser-profiles';
+
+const mocks = vi.hoisted(() => ({ windows: false, linux: false, mac: false }));
+
+vi.mock('../../platform', () => ({ isWindows: () => mocks.windows, isLinux: () => mocks.linux, isMacOS: () => mocks.mac }));
+vi.mock('fs/promises', async (importOriginal) => {
+ const actual = await importOriginal();
+ return { ...actual, open: vi.fn(actual.open) };
+});
+
+import { open } from 'fs/promises';
+import { isBrowserProfileInUse } from '../in-use';
+
+/** A process id nothing runs as */
+const DEAD_PID = 2 ** 22 + 12345;
+const isRoot = typeof process.getuid === 'function' && process.getuid() === 0;
+
+describe.skipIf(process.platform === 'win32')('isBrowserProfileInUse', () => {
+ let dir: string;
+ beforeEach(async () => {
+ dir = await mkdtemp(path.join(tmpdir(), 'browser-lock-'));
+ mocks.windows = false;
+ mocks.linux = false;
+ mocks.mac = false;
+ });
+ afterEach(async () => {
+ await rm(dir, { recursive: true, force: true });
+ });
+
+ const firefox = (executablePath = '/usr/lib/firefox/firefox'): PlaywrightBrowserChoice => ({
+ id: 'firefox:x', browser: 'firefox', engine: 'firefox', profileName: 'default',
+ executablePath, userDataDir: path.dirname(dir), profilePath: dir,
+ });
+ const chrome = (): PlaywrightBrowserChoice => ({
+ id: 'chrome:Default', browser: 'chrome', engine: 'chromium', profileName: 'Default', profileDirectory: 'Default',
+ executablePath: '/opt/google/chrome/chrome', userDataDir: dir, profilePath: path.join(dir, 'Default'),
+ });
+
+ it('reads Firefox as open while the process its lock names runs', async () => {
+ await symlink(`127.0.1.1:+${process.pid}`, path.join(dir, 'lock'));
+ expect(await isBrowserProfileInUse(firefox())).toBe(true);
+ });
+
+ it("reads Firefox's NFS-style lock without the plus sign", async () => {
+ await symlink(`127.0.1.1:${process.pid}`, path.join(dir, 'lock'));
+ expect(await isBrowserProfileInUse(firefox())).toBe(true);
+ });
+
+ it('reads a lock a crashed browser left behind as closed', async () => {
+ await symlink(`127.0.1.1:+${DEAD_PID}`, path.join(dir, 'lock'));
+ expect(await isBrowserProfileInUse(firefox())).toBe(false);
+ });
+
+ it.skipIf(isRoot)("reads a lock whose process id now belongs to another user's process as closed", async () => {
+ // pid 1 runs as root
+ await symlink(`127.0.1.1:+1`, path.join(dir, 'lock'));
+ expect(await isBrowserProfileInUse(firefox())).toBe(false);
+ mocks.linux = process.platform === 'linux';
+ expect(await isBrowserProfileInUse(firefox())).toBe(false);
+ });
+
+ it.skipIf(process.platform !== 'linux')('on Linux, counts the process only when it is a browser', async () => {
+ mocks.linux = true;
+ await symlink(`127.0.1.1:+${process.pid}`, path.join(dir, 'lock'));
+ // This test's process is node, not Firefox: a pid reused since the browser crashed
+ expect(await isBrowserProfileInUse(firefox())).toBe(false);
+ const name = (await readFile(`/proc/${process.pid}/comm`, 'utf-8')).trim();
+ expect(await isBrowserProfileInUse(firefox(`/opt/browser/${name}`))).toBe(true);
+ });
+
+ it.skipIf(process.platform !== 'linux')('on Linux, reads a lock written before the process started as open (clock steps move lock times)', async () => {
+ mocks.linux = true;
+ const name = (await readFile(`/proc/${process.pid}/comm`, 'utf-8')).trim();
+ const link = path.join(dir, 'SingletonLock');
+ await symlink(`${hostname()}-${process.pid}`, link);
+ const choice = { ...chrome(), executablePath: `/opt/browser/${name}` };
+ expect(await isBrowserProfileInUse(choice)).toBe(true);
+ // As after the clock stepped back: the lock looks older than the browser holding it
+ const before = new Date(Date.now() - process.uptime() * 1000 - 60 * 60 * 1000);
+ await lutimes(link, before, before);
+ expect(await isBrowserProfileInUse(choice)).toBe(true);
+ });
+
+ it.skipIf(!existsSync('/bin/ps') || isRoot)('on macOS, names the process with ps and counts it only when it is a browser', async () => {
+ mocks.mac = true;
+ await symlink(`127.0.1.1:+${process.pid}`, path.join(dir, 'lock'));
+ // This test's process is node, not Firefox: a pid reused since the browser crashed
+ expect(await isBrowserProfileInUse(firefox())).toBe(false);
+ const { stdout } = await promisify(execFile)('/bin/ps', ['-p', String(process.pid), '-o', 'comm=']);
+ const name = path.basename(stdout.trim()).slice(0, 15);
+ expect(await isBrowserProfileInUse(firefox(`/opt/browser/${name}`))).toBe(true);
+ });
+
+ it("reads Chromium's SingletonLock in its user data folder; another host's only for a browser here", async () => {
+ expect(await isBrowserProfileInUse(chrome())).toBe(false);
+ await symlink(`other-host-${process.pid}`, path.join(dir, 'SingletonLock'));
+ expect(await isBrowserProfileInUse(chrome())).toBe(false);
+ await rm(path.join(dir, 'SingletonLock'));
+ await symlink(`${hostname()}-${process.pid}`, path.join(dir, 'SingletonLock'));
+ expect(await isBrowserProfileInUse(chrome())).toBe(true);
+ });
+
+ describe.skipIf(process.platform !== 'linux' || !existsSync('/bin/sleep'))('on Linux, with processes named like browsers', () => {
+ const children: ChildProcess[] = [];
+ /** A process whose name (comm) is `name`: sleep started through a link with that name */
+ async function processNamed(name: string): Promise {
+ const link = path.join(dir, name);
+ await symlink('/bin/sleep', link);
+ const child = spawn(link, ['30'], { stdio: 'ignore' });
+ children.push(child);
+ // Until exec has replaced the forked node's name
+ for (let i = 0; i < 100; i++) {
+ const comm = await readFile(`/proc/${child.pid}/comm`, 'utf-8').catch(() => '');
+ if (comm.trim() === name.slice(0, 15)) break;
+ await new Promise((resolve) => setTimeout(resolve, 10));
+ }
+ return child.pid!;
+ }
+ afterEach(() => {
+ for (const child of children.splice(0)) child.kill();
+ });
+
+ it("counts only the lock's own engine: a Firefox lock taken over by a Chrome process reads as closed", async () => {
+ mocks.linux = true;
+ const chromePid = await processNamed('chrome');
+ await symlink(`127.0.1.1:+${chromePid}`, path.join(dir, 'lock'));
+ expect(await isBrowserProfileInUse(firefox('/usr/lib/firefox-esr/firefox-esr'))).toBe(false);
+ await symlink(`${hostname()}-${chromePid}`, path.join(dir, 'SingletonLock'));
+ expect(await isBrowserProfileInUse(chrome())).toBe(true);
+ await rm(path.join(dir, 'lock'));
+ const firefoxPid = await processNamed('firefox');
+ await symlink(`127.0.1.1:+${firefoxPid}`, path.join(dir, 'lock'));
+ expect(await isBrowserProfileInUse(firefox('/usr/lib/firefox-esr/firefox-esr'))).toBe(true);
+ });
+
+ it("never counts Chromium's crash handler", async () => {
+ mocks.linux = true;
+ const crashpad = await processNamed('chrome_crashpad_handler');
+ await symlink(`127.0.1.1:+${crashpad}`, path.join(dir, 'lock'));
+ expect(await isBrowserProfileInUse(firefox())).toBe(false);
+ await symlink(`${hostname()}-${crashpad}`, path.join(dir, 'SingletonLock'));
+ expect(await isBrowserProfileInUse(chrome())).toBe(false);
+ });
+
+ it('reads a lock naming another host as open while its pid is a Chromium browser here (the host was renamed)', async () => {
+ mocks.linux = true;
+ const chromePid = await processNamed('chrome');
+ await symlink(`old-dhcp-name.local-${chromePid}`, path.join(dir, 'SingletonLock'));
+ expect(await isBrowserProfileInUse(chrome())).toBe(true);
+ await rm(path.join(dir, 'SingletonLock'));
+ // Another host's lock whose pid is something else here, or nothing: closed
+ await symlink(`old-dhcp-name.local-${process.pid}`, path.join(dir, 'SingletonLock'));
+ expect(await isBrowserProfileInUse(chrome())).toBe(false);
+ await rm(path.join(dir, 'SingletonLock'));
+ await symlink(`old-dhcp-name.local-${DEAD_PID}`, path.join(dir, 'SingletonLock'));
+ expect(await isBrowserProfileInUse(chrome())).toBe(false);
+ });
+ });
+
+ it("never reads Playwright's own browsers as open", async () => {
+ await symlink(`127.0.1.1:+${process.pid}`, path.join(dir, 'lock'));
+ expect(await isBrowserProfileInUse({ ...firefox(), managed: true })).toBe(false);
+ });
+
+ it('on Windows, checks profiles on network shares but not in WSL', async () => {
+ mocks.windows = true;
+ const openMock = vi.mocked(open);
+ openMock.mockClear();
+ const wsl = { ...firefox(), profilePath: '\\\\wsl.localhost\\Ubuntu\\home\\me\\.mozilla\\firefox\\x' };
+ expect(await isBrowserProfileInUse(wsl)).toBe(false);
+ expect(await isBrowserProfileInUse({ ...wsl, profilePath: '\\\\wsl$\\Ubuntu\\home\\me\\x' })).toBe(false);
+ // In WSL mode its browsers are stored with their Linux paths
+ expect(await isBrowserProfileInUse({ ...wsl, profilePath: '/home/me/.mozilla/firefox/x' })).toBe(false);
+ expect(openMock).not.toHaveBeenCalled();
+ await isBrowserProfileInUse({ ...firefox(), profilePath: '\\\\server\\home\\me\\Firefox\\x' });
+ expect(openMock).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/src/main/browser-profiles/__tests__/locations.test.ts b/src/main/browser-profiles/__tests__/locations.test.ts
new file mode 100644
index 000000000..f673423bc
--- /dev/null
+++ b/src/main/browser-profiles/__tests__/locations.test.ts
@@ -0,0 +1,116 @@
+import { describe, it, expect } from 'vitest';
+import { browserLocations, confinedSnapName } from '../locations';
+
+const find = (locations: ReturnType, browser: string, variant?: string) =>
+ locations.find((l) => l.browser === browser && l.variant === variant);
+
+describe('browserLocations', () => {
+ it('uses LOCALAPPDATA, APPDATA and Program Files on Windows', () => {
+ const locations = browserLocations('windows', {
+ home: 'C:\\Users\\me',
+ env: { LOCALAPPDATA: 'C:\\Users\\me\\AppData\\Local', APPDATA: 'C:\\Users\\me\\AppData\\Roaming', ProgramFiles: 'C:\\Program Files' },
+ });
+ expect(find(locations, 'chrome')).toMatchObject({
+ engine: 'chromium',
+ dataDirs: ['C:\\Users\\me\\AppData\\Local\\Google\\Chrome\\User Data'],
+ executables: [
+ 'C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe',
+ 'C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe',
+ 'C:\\Users\\me\\AppData\\Local\\Google\\Chrome\\Application\\chrome.exe',
+ ],
+ });
+ expect(find(locations, 'edge')?.dataDirs).toEqual(['C:\\Users\\me\\AppData\\Local\\Microsoft\\Edge\\User Data']);
+ expect(find(locations, 'brave')?.executables[0]).toBe('C:\\Program Files\\BraveSoftware\\Brave-Browser\\Application\\brave.exe');
+ expect(find(locations, 'firefox')).toMatchObject({
+ engine: 'firefox',
+ dataDirs: ['C:\\Users\\me\\AppData\\Roaming\\Mozilla\\Firefox'],
+ executables: [
+ 'C:\\Program Files\\Mozilla Firefox\\firefox.exe',
+ 'C:\\Program Files (x86)\\Mozilla Firefox\\firefox.exe',
+ 'C:\\Users\\me\\AppData\\Local\\Mozilla Firefox\\firefox.exe',
+ ],
+ });
+ // Store installs only when detection found their packages
+ expect(find(locations, 'firefox', 'store')).toBeUndefined();
+ expect(find(locations, 'safari')).toBeUndefined();
+ });
+
+ it('adds a Firefox for each Microsoft Store package detection found', () => {
+ const locations = browserLocations('windows', {
+ home: 'C:\\Users\\me',
+ env: { LOCALAPPDATA: 'C:\\Users\\me\\AppData\\Local' },
+ storePackages: ['Mozilla.Firefox_abc', 'Mozilla.FirefoxNightly_abc'],
+ });
+ expect(locations.filter((l) => l.variant === 'store')).toEqual([
+ {
+ browser: 'firefox', engine: 'firefox', variant: 'store',
+ dataDirs: ['C:\\Users\\me\\AppData\\Local\\Packages\\Mozilla.Firefox_abc\\LocalCache\\Roaming\\Mozilla\\Firefox'],
+ executables: ['C:\\Users\\me\\AppData\\Local\\Microsoft\\WindowsApps\\Mozilla.Firefox_abc\\firefox.exe'],
+ },
+ {
+ browser: 'firefox', engine: 'firefox', variant: 'store',
+ dataDirs: ['C:\\Users\\me\\AppData\\Local\\Packages\\Mozilla.FirefoxNightly_abc\\LocalCache\\Roaming\\Mozilla\\Firefox'],
+ executables: ['C:\\Users\\me\\AppData\\Local\\Microsoft\\WindowsApps\\Mozilla.FirefoxNightly_abc\\firefox.exe'],
+ },
+ ]);
+ });
+
+ it('falls back to the home folder when the environment has no folders (Windows)', () => {
+ const locations = browserLocations('windows', { home: 'C:\\Users\\me', env: {} });
+ expect(find(locations, 'chromium')?.dataDirs).toEqual(['C:\\Users\\me\\AppData\\Local\\Chromium\\User Data']);
+ });
+
+ it('uses Application Support and app bundles on macOS, with Safari unsupported', () => {
+ const locations = browserLocations('macos', { home: '/Users/me', env: {} });
+ expect(find(locations, 'chrome')).toMatchObject({
+ dataDirs: ['/Users/me/Library/Application Support/Google/Chrome'],
+ executables: [
+ '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',
+ '/Users/me/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',
+ ],
+ });
+ expect(find(locations, 'firefox')?.dataDirs).toEqual(['/Users/me/Library/Application Support/Firefox']);
+ expect(find(locations, 'safari')).toMatchObject({ engine: 'webkit', disabledReason: 'unsupported-engine' });
+ });
+
+ it('covers distribution packages, snaps and Flatpaks on Linux', () => {
+ const locations = browserLocations('linux', { home: '/home/me', env: {} });
+ expect(find(locations, 'chrome')).toMatchObject({
+ dataDirs: ['/home/me/.config/google-chrome'],
+ executables: ['/opt/google/chrome/chrome'],
+ commands: ['google-chrome-stable', 'google-chrome'],
+ });
+ expect(find(locations, 'chromium', 'snap')).toMatchObject({
+ dataDirs: ['/home/me/snap/chromium/common/chromium'],
+ executables: ['/snap/bin/chromium'],
+ });
+ expect(find(locations, 'firefox')).toMatchObject({
+ dataDirs: ['/home/me/.mozilla/firefox', '/home/me/.config/mozilla/firefox'],
+ commands: ['firefox', 'firefox-esr'],
+ });
+ expect(find(locations, 'firefox')?.executables).toContain('/usr/lib/firefox-esr/firefox-esr');
+ expect(find(locations, 'firefox', 'snap')?.dataDirs).toEqual(['/home/me/snap/firefox/common/.mozilla/firefox']);
+ expect(find(locations, 'chrome', 'flatpak')).toMatchObject({
+ dataDirs: ['/home/me/.var/app/com.google.Chrome/config/google-chrome'],
+ disabledReason: 'sandboxed-package',
+ });
+ expect(find(locations, 'safari')).toBeUndefined();
+ });
+
+ it('honors an absolute XDG_CONFIG_HOME on Linux', () => {
+ const locations = browserLocations('linux', { home: '/home/me', env: { XDG_CONFIG_HOME: '/data/config' } });
+ expect(find(locations, 'chrome')?.dataDirs).toEqual(['/data/config/google-chrome']);
+ expect(find(locations, 'brave')?.dataDirs).toEqual(['/data/config/BraveSoftware/Brave-Browser']);
+ expect(find(locations, 'firefox')?.dataDirs).toEqual(['/home/me/.mozilla/firefox', '/data/config/mozilla/firefox']);
+ // Relative: invalid, ignored
+ const relative = browserLocations('linux', { home: '/home/me', env: { XDG_CONFIG_HOME: 'config' } });
+ expect(find(relative, 'chrome')?.dataDirs).toEqual(['/home/me/.config/google-chrome']);
+ });
+
+ it('tells which snap launchers run their browser confined', () => {
+ expect(confinedSnapName('/snap/bin/chromium')).toBe('chromium');
+ // Runs map it to the snap's own binary, outside the sandbox
+ expect(confinedSnapName('/snap/bin/firefox')).toBeUndefined();
+ expect(confinedSnapName('/usr/lib/chromium/chromium')).toBeUndefined();
+ });
+});
diff --git a/src/main/browser-profiles/__tests__/parsing.test.ts b/src/main/browser-profiles/__tests__/parsing.test.ts
new file mode 100644
index 000000000..2af6e3721
--- /dev/null
+++ b/src/main/browser-profiles/__tests__/parsing.test.ts
@@ -0,0 +1,103 @@
+import path from 'path';
+import { describe, it, expect } from 'vitest';
+import { parseChromiumLocalState, parseFirefoxProfilesIni } from '../parsing';
+
+describe('parseChromiumLocalState', () => {
+ it("lists profiles in the browser's order with their names and accounts", () => {
+ const localState = JSON.stringify({
+ profile: {
+ info_cache: {
+ Default: { name: 'Person 1', user_name: '' },
+ 'Profile 2': { name: 'Work', user_name: 'me@work.example' },
+ 'Profile 1': { name: 'Home' },
+ },
+ profiles_order: ['Profile 2', 'Default', 'Gone'],
+ },
+ });
+ expect(parseChromiumLocalState(localState)).toEqual([
+ { directory: 'Profile 2', name: 'Work', email: 'me@work.example' },
+ { directory: 'Default', name: 'Person 1' },
+ { directory: 'Profile 1', name: 'Home' },
+ ]);
+ });
+
+ it('sorts by folder without an order and names unnamed profiles after their folder', () => {
+ const localState = JSON.stringify({ profile: { info_cache: { 'Profile 1': {}, Default: { name: ' ' } } } });
+ expect(parseChromiumLocalState(localState)).toEqual([
+ { directory: 'Default', name: 'Default' },
+ { directory: 'Profile 1', name: 'Profile 1' },
+ ]);
+ });
+
+ it('gives no profiles for invalid JSON or a missing info_cache', () => {
+ expect(parseChromiumLocalState('{not json')).toEqual([]);
+ expect(parseChromiumLocalState('{}')).toEqual([]);
+ expect(parseChromiumLocalState('null')).toEqual([]);
+ expect(parseChromiumLocalState(JSON.stringify({ profile: { info_cache: [] } }))).toEqual([]);
+ });
+});
+
+describe('parseFirefoxProfilesIni', () => {
+ it('reads Linux profiles, with the install default first', () => {
+ const ini = [
+ '[Profile1]',
+ 'Name=default',
+ 'IsRelative=1',
+ 'Path=abcd.default',
+ 'Default=1',
+ '',
+ '[Profile0]',
+ 'Name=default-release',
+ 'IsRelative=1',
+ 'Path=efgh.default-release',
+ '',
+ '[Install4F96D1932A9F858E]',
+ 'Default=efgh.default-release',
+ 'Locked=1',
+ '',
+ '[General]',
+ 'StartWithLastProfile=1',
+ 'Version=2',
+ ].join('\n');
+ expect(parseFirefoxProfilesIni(ini, '/home/me/.mozilla/firefox', path.posix)).toEqual([
+ { name: 'default-release', path: '/home/me/.mozilla/firefox/efgh.default-release', folder: 'efgh.default-release', isDefault: true },
+ { name: 'default', path: '/home/me/.mozilla/firefox/abcd.default', folder: 'abcd.default', isDefault: false },
+ ]);
+ });
+
+ it('reads Windows profiles with CRLF, comments, relative and absolute paths', () => {
+ const ini = [
+ '\uFEFF; written by Firefox',
+ '[Profile0]',
+ 'Name=Main',
+ 'IsRelative=1',
+ 'Path=Profiles/xyz.default-release',
+ 'Default=1',
+ '',
+ '[Profile1]',
+ 'Name=Elsewhere',
+ 'IsRelative=0',
+ 'Path=D:\\Firefox\\other',
+ '',
+ '[Profile2]',
+ 'Name=No path',
+ ].join('\r\n');
+ const appData = 'C:\\Users\\me\\AppData\\Roaming\\Mozilla\\Firefox';
+ expect(parseFirefoxProfilesIni(ini, appData, path.win32)).toEqual([
+ { name: 'Main', path: `${appData}\\Profiles\\xyz.default-release`, folder: 'xyz.default-release', isDefault: true },
+ { name: 'Elsewhere', path: 'D:\\Firefox\\other', folder: 'other', isDefault: false },
+ ]);
+ });
+
+ it('reads macOS profiles and names unnamed ones after their folder', () => {
+ const ini = '[Profile0]\nIsRelative=1\nPath=Profiles/q1.default\n';
+ const dir = '/Users/me/Library/Application Support/Firefox';
+ expect(parseFirefoxProfilesIni(ini, dir, path.posix)).toEqual([
+ { name: 'q1.default', path: `${dir}/Profiles/q1.default`, folder: 'q1.default', isDefault: false },
+ ]);
+ });
+
+ it('gives no profiles for an empty file', () => {
+ expect(parseFirefoxProfilesIni('', '/x', path.posix)).toEqual([]);
+ });
+});
diff --git a/src/main/browser-profiles/__tests__/profile-copy.test.ts b/src/main/browser-profiles/__tests__/profile-copy.test.ts
new file mode 100644
index 000000000..8327c9bd3
--- /dev/null
+++ b/src/main/browser-profiles/__tests__/profile-copy.test.ts
@@ -0,0 +1,674 @@
+import os from 'os';
+import path from 'path';
+import { existsSync } from 'fs';
+import { hostname } from 'os';
+import { mkdtemp, mkdir, readFile, rm, stat, utimes, writeFile } from 'fs/promises';
+import * as fsPromises from 'fs/promises';
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
+import type { PlaywrightBrowserChoice } from '../../../shared/types/browser-profiles';
+
+vi.mock('fs/promises', async (importOriginal) => {
+ const actual = await importOriginal();
+ return { ...actual, copyFile: vi.fn(actual.copyFile), chmod: vi.fn(actual.chmod) };
+});
+vi.mock('../../app-logger', () => ({ appLog: { warn: vi.fn(), info: vi.fn() } }));
+const mocks = vi.hoisted(() => ({
+ userData: '',
+ windows: false,
+ wslRoot: '',
+ wslDistros: [] as string[],
+ wslRunning: '',
+ // Whether the chosen browser is open: open by default, so runs copy the live profile and save nothing
+ inUse: true,
+}));
+vi.mock('../in-use', () => ({ isBrowserProfileInUse: async () => mocks.inUse }));
+vi.mock('electron', () => ({ app: { getPath: () => mocks.userData } }));
+vi.mock('../../platform/shell-runtime', () => ({
+ toHostPath: (p: string) => p,
+ toRuntimePath: (p: string) => p,
+ getWslInfo: () => null,
+ whenShellRuntimeReady: async () => ({}),
+}));
+vi.mock('../../platform', async (importOriginal) => {
+ const actual = await importOriginal();
+ return { ...actual, isWindows: () => mocks.windows || actual.isWindows() };
+});
+// A distribution's files under the test folder instead of \\wsl.localhost
+vi.mock('../../platform/wsl-paths', async (importOriginal) => {
+ const actual = await importOriginal();
+ return { ...actual, wslToWindows: (p: string, options: { distro: string }) => path.join(mocks.wslRoot, options.distro, p) };
+});
+vi.mock('../../platform/wsl-detect', async (importOriginal) => {
+ const actual = await importOriginal();
+ return {
+ ...actual,
+ checkWslAvailable: async () => ({ available: mocks.wslDistros.length > 0, distros: mocks.wslDistros, checkedAt: 0 }),
+ };
+});
+vi.mock('child_process', async (importOriginal) => {
+ const actual = await importOriginal();
+ return {
+ ...actual,
+ // `wsl.exe -l --running -q`
+ execFile: vi.fn((_file: string, _args: string[], _options: unknown, callback: (error: Error | null, stdout: Buffer) => void) => {
+ callback(null, Buffer.from(mocks.wslRunning));
+ }),
+ };
+});
+vi.mock('../../platform/runtime-exec', () => ({ runTool: vi.fn(async () => ({ stdout: '', stderr: '' })) }));
+
+import {
+ browserProfileCopiesRoot,
+ browserProfileCopyBlocked,
+ refreshSavedBrowserProfileCopy,
+ browserProfileCopyDir,
+ isBrowserProfileCopyPath,
+ keepBrowserProfileCopy,
+ prepareBrowserProfileCopy,
+ removeBrowserProfileCopy,
+ removeLeftoverBrowserProfileCopies,
+ removeLiveBrowserProfileCopies,
+ removeOldBrowserProfileCopies,
+ removeStaleBrowserProfileCopies,
+} from '../profile-copy';
+
+const isPosix = process.platform !== 'win32';
+
+let root: string;
+
+async function put(file: string, content = 'x'): Promise {
+ await mkdir(path.dirname(file), { recursive: true });
+ await writeFile(file, content);
+}
+
+/** A process id nothing runs as */
+const DEAD_PID = 2 ** 22 + 12345;
+const OWNER_FILE = '.workbench-copy-owner.json';
+
+/** A copy owned by a Workbench process that is gone (a crash) */
+async function leftover(dir: string, file: string): Promise {
+ await put(path.join(dir, file));
+ await put(path.join(dir, OWNER_FILE), JSON.stringify({ pid: DEAD_PID, host: hostname() }));
+}
+
+describe('browser profile copies', () => {
+ const realHome = process.env.HOME;
+ beforeEach(async () => {
+ root = await mkdtemp(path.join(os.tmpdir(), 'profile-copy-'));
+ mocks.userData = path.join(root, 'userData');
+ mocks.windows = false;
+ mocks.wslRoot = path.join(root, 'wsl');
+ mocks.wslDistros = [];
+ mocks.wslRunning = '';
+ mocks.inUse = true;
+ // Snap copies go to the home's ~/snap: the test's own home instead of the user's
+ process.env.HOME = path.join(root, 'home');
+ });
+
+ afterEach(async () => {
+ process.env.HOME = realHome;
+ vi.useRealTimers();
+ await rm(root, { recursive: true, force: true });
+ });
+
+ it("keeps a crashed chat browser's copy for its chat through every sweep, and quitting leaves it", async () => {
+ const project = path.join(root, 'project');
+ const choice: PlaywrightBrowserChoice = {
+ id: 'chrome:Default', browser: 'chrome', engine: 'chromium', profileName: 'Default',
+ executablePath: '/opt/google/chrome/chrome', userDataDir: path.join(root, 'chrome'), profileDirectory: 'Default',
+ profilePath: path.join(root, 'chrome', 'Default'),
+ };
+ const kept = browserProfileCopyDir(project, choice, 'chat-kept');
+ const other = browserProfileCopyDir(project, choice, 'chat-other');
+ await leftover(kept, 'Cookies');
+ await leftover(other, 'Cookies');
+ expect(isBrowserProfileCopyPath(kept)).toBe(true);
+ expect(isBrowserProfileCopyPath(path.join(root, 'home'))).toBe(false);
+ expect(isBrowserProfileCopyPath(path.dirname(kept))).toBe(false);
+
+ expect(await keepBrowserProfileCopy(kept)).toBe(true);
+ // This process holds it now
+ expect(JSON.parse(await readFile(path.join(kept, OWNER_FILE), 'utf-8'))).toMatchObject({ pid: process.pid });
+ await removeLeftoverBrowserProfileCopies([project]);
+ await removeOldBrowserProfileCopies(project, { force: true, keep: [] });
+ await removeLiveBrowserProfileCopies();
+ expect(existsSync(path.join(kept, 'Cookies'))).toBe(true);
+ expect(existsSync(other)).toBe(false);
+ // Nothing to keep where there is no copy
+ expect(await keepBrowserProfileCopy(other)).toBe(false);
+ await removeBrowserProfileCopy(kept);
+ });
+
+ it('copies a Chromium profile with Local State, leaving out caches and locks', async () => {
+ const userData = path.join(root, 'chrome');
+ const profile = path.join(userData, 'Profile 1');
+ await put(path.join(userData, 'Local State'), '{"os_crypt":{}}');
+ await put(path.join(userData, 'SingletonLock'));
+ await put(path.join(profile, 'Cookies'), 'cookies');
+ await put(path.join(profile, 'Network', 'Cookies'), 'network cookies');
+ await put(path.join(profile, 'Cache', 'data_0'));
+ await put(path.join(profile, 'Service Worker', 'CacheStorage', 'blob'));
+ await put(path.join(profile, 'Service Worker', 'Database', 'db'));
+ await put(path.join(profile, 'lockfile'));
+ const choice: PlaywrightBrowserChoice = {
+ id: 'chrome:Profile 1',
+ browser: 'chrome',
+ engine: 'chromium',
+ profileName: 'Work',
+ executablePath: '/opt/google/chrome/chrome',
+ userDataDir: userData,
+ profileDirectory: 'Profile 1',
+ profilePath: profile,
+ };
+ const project = path.join(root, 'project');
+
+ const copy = await prepareBrowserProfileCopy(project, choice, 'task-001-x');
+
+ // In the app's data folder, never in the project (Claude sessions read the project)
+ expect(path.dirname(path.dirname(path.dirname(copy!)))).toBe(path.join(mocks.userData, 'browser-profiles'));
+ expect(copy!.startsWith(project)).toBe(false);
+ expect(copy).toBe(path.join(browserProfileCopiesRoot(project), 'chrome_Profile_1', 'task-001-x'));
+ expect(path.basename(browserProfileCopiesRoot(project))).toMatch(/^project-[0-9a-f]{16}$/);
+ expect(browserProfileCopiesRoot(path.join(root, 'other', 'project'))).not.toBe(browserProfileCopiesRoot(project));
+ expect(JSON.parse(await readFile(path.join(copy!, OWNER_FILE), 'utf-8'))).toMatchObject({ pid: process.pid, host: hostname() });
+ expect(copy).toBe(browserProfileCopyDir(project, choice, 'task-001-x'));
+ const copied = (...parts: string[]) => path.join(copy!, ...parts);
+ expect(await readFile(copied('Local State'), 'utf-8')).toBe('{"os_crypt":{}}');
+ expect(existsSync(copied('First Run'))).toBe(true);
+ expect(await readFile(copied('Profile 1', 'Cookies'), 'utf-8')).toBe('cookies');
+ expect(await readFile(copied('Profile 1', 'Network', 'Cookies'), 'utf-8')).toBe('network cookies');
+ expect(existsSync(copied('Profile 1', 'Service Worker', 'Database', 'db'))).toBe(true);
+ expect(existsSync(copied('Profile 1', 'Cache'))).toBe(false);
+ expect(existsSync(copied('Profile 1', 'Service Worker', 'CacheStorage'))).toBe(false);
+ expect(existsSync(copied('Profile 1', 'lockfile'))).toBe(false);
+ expect(existsSync(copied('SingletonLock'))).toBe(false);
+ // The run's Playwright config: the browser's executable with this copy as its profile
+ expect(JSON.parse(await readFile(copied('.workbench-playwright.json'), 'utf-8'))).toMatchObject({
+ browser: {
+ browserName: 'chromium',
+ userDataDir: copy,
+ launchOptions: { executablePath: '/opt/google/chrome/chrome', args: ['--profile-directory=Profile 1'] },
+ },
+ });
+
+ // A new run starts from a fresh copy
+ await put(copied('Profile 1', 'stale'));
+ await prepareBrowserProfileCopy(project, choice, 'task-001-x');
+ expect(existsSync(copied('Profile 1', 'stale'))).toBe(false);
+
+ await removeBrowserProfileCopy(copy!);
+ expect(existsSync(copy!)).toBe(false);
+ });
+
+ it('copies a Firefox profile folder as the user data folder, without its lock and caches', async () => {
+ const profile = path.join(root, 'firefox', 'x.default-release');
+ await put(path.join(profile, 'cookies.sqlite'), 'jar');
+ await put(path.join(profile, 'parent.lock'));
+ await put(path.join(profile, 'cache2', 'entries', 'a'));
+ const choice: PlaywrightBrowserChoice = {
+ id: 'firefox:x.default-release',
+ browser: 'firefox',
+ engine: 'firefox',
+ profileName: 'default-release',
+ executablePath: '/usr/lib/firefox/firefox',
+ userDataDir: path.join(root, 'firefox'),
+ profilePath: profile,
+ };
+
+ const copy = await prepareBrowserProfileCopy(path.join(root, 'project'), choice, 'chat');
+
+ expect(await readFile(path.join(copy!, 'cookies.sqlite'), 'utf-8')).toBe('jar');
+ expect(existsSync(path.join(copy!, 'parent.lock'))).toBe(false);
+ expect(existsSync(path.join(copy!, 'cache2'))).toBe(false);
+ });
+
+ it("removes a task's older copies, keeping the current run's and other tasks'", async () => {
+ const profile = path.join(root, 'chrome', 'Default');
+ await put(path.join(profile, 'Cookies'));
+ const choice: PlaywrightBrowserChoice = {
+ id: 'chrome:Default', browser: 'chrome', engine: 'chromium', profileName: 'Me',
+ executablePath: '/opt/google/chrome/chrome', userDataDir: path.join(root, 'chrome'), profileDirectory: 'Default', profilePath: profile,
+ };
+ const project = path.join(root, 'project');
+ // Left by a crash: no live run uses it
+ const old = browserProfileCopyDir(project, choice, 'task-001-a-aaaa');
+ await leftover(old, 'Default/Cookies');
+ // A newer launch of the task, still copying or running
+ const live = await prepareBrowserProfileCopy(project, choice, 'task-001-a-dddd');
+ const other = await prepareBrowserProfileCopy(project, choice, 'task-002-b-bbbb');
+ const current = await prepareBrowserProfileCopy(project, choice, 'task-001-a-cccc');
+
+ await removeStaleBrowserProfileCopies(project, choice, 'task-001-a-', 'task-001-a-cccc');
+
+ expect(existsSync(old)).toBe(false);
+ expect(existsSync(live!)).toBe(true);
+ expect(existsSync(other!)).toBe(true);
+ expect(existsSync(current!)).toBe(true);
+ });
+
+ it('keeps the copy private and leaves out the session to restore and nested caches', async () => {
+ const userData = path.join(root, 'chrome');
+ const profile = path.join(userData, 'Default');
+ await put(path.join(profile, 'Cookies'));
+ await put(path.join(profile, 'Sessions', 'Session_1'));
+ await put(path.join(profile, 'Current Session'));
+ await put(path.join(profile, 'Last Tabs'));
+ await put(path.join(profile, 'Storage', 'ext', 'abc', 'def', 'Code Cache', 'js'));
+ await put(path.join(profile, 'Preferences'), JSON.stringify({ session: { restore_on_startup: 1, startup_urls: ['https://mail'] }, other: 1 }));
+ const choice: PlaywrightBrowserChoice = {
+ id: 'chrome:Default', browser: 'chrome', engine: 'chromium', profileName: 'Me',
+ executablePath: '/opt/google/chrome/chrome', userDataDir: userData, profileDirectory: 'Default', profilePath: profile,
+ };
+ const project = path.join(root, 'project');
+ // Made before copies were private
+ await mkdir(browserProfileCopiesRoot(project), { recursive: true, mode: 0o755 });
+
+ const copy = (await prepareBrowserProfileCopy(project, choice, 'chat-1'))!;
+
+ expect(existsSync(path.join(copy, 'Default', 'Cookies'))).toBe(true);
+ for (const left of ['Sessions', 'Current Session', 'Last Tabs', 'Storage/ext/abc/def/Code Cache']) {
+ expect(existsSync(path.join(copy, 'Default', left))).toBe(false);
+ }
+ const prefs = JSON.parse(await readFile(path.join(copy, 'Default', 'Preferences'), 'utf-8'));
+ expect(prefs).toEqual({ session: { restore_on_startup: 5, startup_urls: [] }, other: 1 });
+ if (isPosix) {
+ const projectRoot = browserProfileCopiesRoot(project);
+ for (const dir of [path.dirname(projectRoot), projectRoot, path.dirname(copy), copy, path.join(copy, 'Default')]) {
+ expect((await stat(dir)).mode & 0o777).toBe(0o700);
+ }
+ }
+ });
+
+ it("leaves out Firefox's session, Sync account and per-site caches", async () => {
+ const profile = path.join(root, 'firefox', 'x.default-release');
+ await put(path.join(profile, 'cookies.sqlite'));
+ await put(path.join(profile, 'sessionstore.jsonlz4'));
+ await put(path.join(profile, 'sessionstore-backups', 'recovery.jsonlz4'));
+ await put(path.join(profile, 'signedInUser.json'));
+ await put(path.join(profile, 'weave', 'bookmarks.sqlite'));
+ await put(path.join(profile, 'storage', 'default', 'https+++a.com', 'cache', 'caches.sqlite'));
+ await put(path.join(profile, 'storage', 'default', 'https+++a.com', 'idb', 'db.sqlite'));
+ const choice: PlaywrightBrowserChoice = {
+ id: 'firefox:x', browser: 'firefox', engine: 'firefox', profileName: 'x',
+ executablePath: '/usr/lib/firefox/firefox', userDataDir: path.join(root, 'firefox'), profilePath: profile,
+ };
+
+ const copy = (await prepareBrowserProfileCopy(path.join(root, 'project'), choice, 'chat-1'))!;
+
+ expect(existsSync(path.join(copy, 'cookies.sqlite'))).toBe(true);
+ expect(existsSync(path.join(copy, 'storage', 'default', 'https+++a.com', 'idb', 'db.sqlite'))).toBe(true);
+ for (const left of ['sessionstore.jsonlz4', 'sessionstore-backups', 'signedInUser.json', 'weave', 'storage/default/https+++a.com/cache']) {
+ expect(existsSync(path.join(copy, left))).toBe(false);
+ }
+ });
+
+ it('removes a partial copy when the disk is full', async () => {
+ const profile = path.join(root, 'firefox', 'x');
+ await put(path.join(profile, 'cookies.sqlite'));
+ const choice: PlaywrightBrowserChoice = {
+ id: 'firefox:x', browser: 'firefox', engine: 'firefox', profileName: 'x',
+ executablePath: '/usr/lib/firefox/firefox', userDataDir: path.join(root, 'firefox'), profilePath: profile,
+ };
+ const project = path.join(root, 'project');
+ vi.mocked(fsPromises.copyFile).mockRejectedValueOnce(Object.assign(new Error('no space'), { code: 'ENOSPC' }));
+
+ await expect(prepareBrowserProfileCopy(project, choice, 'task-001-x')).rejects.toThrow('no space');
+
+ expect(existsSync(browserProfileCopyDir(project, choice, 'task-001-x'))).toBe(false);
+ });
+
+ it("removes a project's copies older than a day that no live run uses, for any profile", async () => {
+ const project = path.join(root, 'project');
+ const copies = browserProfileCopiesRoot(project);
+ const dayAgo = new Date(Date.now() - 2 * 24 * 60 * 60 * 1000);
+ const oldOther = path.join(copies, 'firefox_y', 'chat');
+ const recent = path.join(copies, 'firefox_y', 'task-003-c-1234');
+ await leftover(oldOther, 'cookies.sqlite');
+ await leftover(recent, 'cookies.sqlite');
+ await utimes(oldOther, dayAgo, dayAgo);
+
+ await removeOldBrowserProfileCopies(project, { force: true });
+
+ expect(existsSync(oldOther)).toBe(false);
+ expect(existsSync(recent)).toBe(true);
+ });
+
+ it("removes an earlier choice's copies at once, keeping the current profile's recent ones and live runs'", async () => {
+ const profile = path.join(root, 'chrome', 'Default');
+ await put(path.join(profile, 'Cookies'));
+ const choice: PlaywrightBrowserChoice = {
+ id: 'chrome:Default', browser: 'chrome', engine: 'chromium', profileName: 'Me',
+ executablePath: '/opt/google/chrome/chrome', userDataDir: path.join(root, 'chrome'), profileDirectory: 'Default', profilePath: profile,
+ };
+ const project = path.join(root, 'project');
+ const copies = browserProfileCopiesRoot(project);
+ const dayAgo = new Date(Date.now() - 2 * 24 * 60 * 60 * 1000);
+ const otherProfile = path.join(copies, 'firefox_y', 'task-003-c-1234');
+ const oldSame = path.join(copies, 'chrome_Default', 'chat-old');
+ const recentSame = path.join(copies, 'chrome_Default', 'chat-recent');
+ await leftover(otherProfile, 'cookies.sqlite');
+ await leftover(oldSame, 'Default/Cookies');
+ await leftover(recentSame, 'Default/Cookies');
+ await utimes(oldSame, dayAgo, dayAgo);
+ const live = (await prepareBrowserProfileCopy(project, choice, 'task-004-d-5678'))!;
+ await utimes(live, dayAgo, dayAgo);
+
+ await removeOldBrowserProfileCopies(project, { force: true, keep: [choice] });
+
+ expect(existsSync(otherProfile)).toBe(false);
+ expect(existsSync(oldSame)).toBe(false);
+ expect(existsSync(recentSame)).toBe(true);
+ expect(existsSync(live)).toBe(true);
+ await removeBrowserProfileCopy(live);
+ });
+
+ it("removes a project's copies when runs use Playwright's own browser", async () => {
+ const project = path.join(root, 'project');
+ const recent = path.join(browserProfileCopiesRoot(project), 'chrome_Default', 'chat-1');
+ await leftover(recent, 'Default/Cookies');
+ const managed: PlaywrightBrowserChoice = {
+ id: 'playwright:firefox', browser: 'firefox', engine: 'firefox', managed: true, profileName: 'Firefox',
+ executablePath: '/c/firefox', userDataDir: '', profilePath: '',
+ };
+ expect(await prepareBrowserProfileCopy(project, managed, 'chat-2')).toBeNull();
+ await vi.waitFor(() => expect(existsSync(recent)).toBe(false));
+ });
+
+ it('removes every leftover copy at startup, of every project, and the copies earlier versions kept in projects', async () => {
+ const a = path.join(browserProfileCopiesRoot(path.join(root, 'a')), 'chrome_Default', 'chat-1');
+ const b = path.join(browserProfileCopiesRoot(path.join(root, 'b')), 'firefox_x', 'task-001-x-1');
+ // A project since removed from the app
+ const gone = path.join(browserProfileCopiesRoot(path.join(root, 'gone')), 'firefox_x', 'chat-2');
+ await leftover(a, 'Default/Cookies');
+ await leftover(b, 'cookies.sqlite');
+ await leftover(gone, 'cookies.sqlite');
+ // Kept inside the project by an earlier version (no owner file), from a while ago
+ const legacyRoot = path.join(root, 'a', '.workbench', 'browser-profiles');
+ const legacy = path.join(legacyRoot, 'chrome_Default', 'chat-1');
+ await put(path.join(legacy, 'Default', 'Cookies'));
+ const hourAgo = new Date(Date.now() - 60 * 60 * 1000);
+ await utimes(legacy, hourAgo, hourAgo);
+
+ await removeLeftoverBrowserProfileCopies([path.join(root, 'a'), path.join(root, 'b'), path.join(root, 'none')]);
+
+ expect(existsSync(a)).toBe(false);
+ expect(existsSync(b)).toBe(false);
+ expect(existsSync(gone)).toBe(false);
+ expect(existsSync(legacyRoot)).toBe(false);
+ expect(existsSync(path.join(root, 'a', '.workbench'))).toBe(true);
+ });
+
+ it("never sweeps a copy another running Workbench process owns, at startup or for another choice", async () => {
+ const project = path.join(root, 'project');
+ const copies = browserProfileCopiesRoot(project);
+ // Owned by a process that runs (this test's parent), as by `npm run dev` next to the installed app
+ const others = path.join(copies, 'firefox_y', 'task-003-c-1234');
+ await put(path.join(others, 'cookies.sqlite'));
+ await put(path.join(others, OWNER_FILE), JSON.stringify({ pid: process.ppid, host: hostname() }));
+ // Being set up by another process: no owner file yet
+ const settingUp = path.join(copies, 'firefox_y', 'chat-9');
+ await put(path.join(settingUp, 'cookies.sqlite'));
+ // Kept in the project by an earlier version that may still run (no owner file, recent)
+ const legacyRoot = path.join(project, '.workbench', 'browser-profiles');
+ const legacyFresh = path.join(legacyRoot, 'chrome_Default', 'chat-1');
+ await put(path.join(legacyFresh, 'Default', 'Cookies'));
+
+ await removeLeftoverBrowserProfileCopies([project]);
+ await removeOldBrowserProfileCopies(project, { force: true, keep: [] });
+
+ expect(existsSync(others)).toBe(true);
+ expect(existsSync(settingUp)).toBe(true);
+ expect(existsSync(legacyFresh)).toBe(true);
+
+ // Once its owner is gone, it goes
+ await put(path.join(others, OWNER_FILE), JSON.stringify({ pid: DEAD_PID, host: hostname() }));
+ await removeOldBrowserProfileCopies(project, { force: true, keep: [] });
+ expect(existsSync(others)).toBe(false);
+ });
+
+ it.skipIf(process.platform !== 'linux')('on Linux, tells an owner from a process that took its id after a reboot', async () => {
+ const project = path.join(root, 'project');
+ const copy = path.join(browserProfileCopiesRoot(project), 'firefox_y', 'chat-1');
+ await put(path.join(copy, 'cookies.sqlite'));
+ // The parent process's id, but another boot: a process that took the id of a Workbench gone since
+ await put(path.join(copy, OWNER_FILE), JSON.stringify({ pid: process.ppid, host: hostname(), boot: 'another-boot', start: '1' }));
+
+ await removeOldBrowserProfileCopies(project, { force: true, keep: [] });
+
+ expect(existsSync(copy)).toBe(false);
+ });
+
+ it('removes the copies of runs still going on quit', async () => {
+ const profile = path.join(root, 'firefox', 'x');
+ await put(path.join(profile, 'cookies.sqlite'));
+ const choice: PlaywrightBrowserChoice = {
+ id: 'firefox:x', browser: 'firefox', engine: 'firefox', profileName: 'x',
+ executablePath: '/usr/lib/firefox/firefox', userDataDir: path.join(root, 'firefox'), profilePath: profile,
+ };
+ const copy = (await prepareBrowserProfileCopy(path.join(root, 'project'), choice, 'chat-1'))!;
+ expect(existsSync(copy)).toBe(true);
+
+ await removeLiveBrowserProfileCopies();
+
+ expect(existsSync(copy)).toBe(false);
+ });
+
+ it("still copies where the filesystem can't hold modes (chmod fails)", async () => {
+ const profile = path.join(root, 'firefox', 'x');
+ await put(path.join(profile, 'cookies.sqlite'), 'jar');
+ const choice: PlaywrightBrowserChoice = {
+ id: 'firefox:x', browser: 'firefox', engine: 'firefox', profileName: 'x',
+ executablePath: '/usr/lib/firefox/firefox', userDataDir: path.join(root, 'firefox'), profilePath: profile,
+ };
+ vi.mocked(fsPromises.chmod).mockRejectedValue(Object.assign(new Error('not permitted'), { code: 'EPERM' }));
+ try {
+ const copy = await prepareBrowserProfileCopy(path.join(root, 'project'), choice, 'chat-1');
+ expect(await readFile(path.join(copy!, 'cookies.sqlite'), 'utf-8')).toBe('jar');
+ // Other errors still fail the copy
+ vi.mocked(fsPromises.chmod).mockRejectedValue(Object.assign(new Error('io'), { code: 'EIO' }));
+ await expect(prepareBrowserProfileCopy(path.join(root, 'project'), choice, 'chat-2')).rejects.toThrow('io');
+ } finally {
+ vi.mocked(fsPromises.chmod).mockReset();
+ const actual = await vi.importActual('fs/promises');
+ vi.mocked(fsPromises.chmod).mockImplementation(actual.chmod);
+ }
+ });
+
+ it.skipIf(process.platform !== 'linux')('puts confined snap Chromium copies in the snap\'s own folder, private, and sweeps them', async () => {
+ const userData = path.join(root, 'home', 'snap', 'chromium', 'common', 'chromium');
+ const profile = path.join(userData, 'Default');
+ await put(path.join(userData, 'Local State'), '{}');
+ await put(path.join(profile, 'Cookies'), 'cookies');
+ const choice: PlaywrightBrowserChoice = {
+ id: 'chromium-snap:Default', browser: 'chromium', engine: 'chromium', profileName: 'Me',
+ executablePath: '/snap/bin/chromium', userDataDir: userData, profileDirectory: 'Default', profilePath: profile,
+ };
+ const project = path.join(root, 'project');
+ const snapBase = path.join(root, 'home', 'snap', 'chromium', 'common', 'workbench-profiles');
+
+ const copy = (await prepareBrowserProfileCopy(project, choice, 'chat-1'))!;
+
+ // Not under a hidden folder, which the snap's home interface denies
+ expect(copy.startsWith(snapBase + path.sep)).toBe(true);
+ expect(copy).toBe(path.join(browserProfileCopiesRoot(project, choice), 'chromium-snap_Default', 'chat-1'));
+ expect(await readFile(path.join(copy, 'Default', 'Cookies'), 'utf-8')).toBe('cookies');
+ const projectRoot = browserProfileCopiesRoot(project, choice);
+ for (const dir of [snapBase, projectRoot, path.dirname(copy), copy]) {
+ expect((await stat(dir)).mode & 0o777).toBe(0o700);
+ }
+ // Snap Firefox runs its own binary outside the sandbox: its copies stay in the app's folder
+ const firefox = { ...choice, id: 'firefox-snap:x', engine: 'firefox' as const, executablePath: '/snap/bin/firefox' };
+ expect(browserProfileCopiesRoot(project, firefox)).toBe(browserProfileCopiesRoot(project));
+
+ // Another choice sweeps the snap's copies too
+ await removeBrowserProfileCopy(copy);
+ await leftover(copy, 'Default/Cookies');
+ await removeOldBrowserProfileCopies(project, { force: true, keep: [] });
+ expect(existsSync(copy)).toBe(false);
+
+ // And so does startup
+ await leftover(copy, 'Default/Cookies');
+ await removeLeftoverBrowserProfileCopies([]);
+ expect(existsSync(copy)).toBe(false);
+ });
+
+ it("on Windows, sweeps the copies a WSL session left in a running distribution's home", async () => {
+ mocks.windows = true;
+ mocks.wslDistros = ['Ubuntu', 'Debian'];
+ mocks.wslRunning = 'Ubuntu\r\n';
+ const inDistro = (distro: string, ...parts: string[]) => path.join(mocks.wslRoot, distro, ...parts);
+ const crashed = inDistro('Ubuntu', 'home', 'me', '.cache', 'workbench', 'browser-profiles', 'project-0123456789abcdef', 'chrome_Default', 'chat-1');
+ await leftover(crashed, 'Default/Cookies');
+ const snapCrashed = inDistro('Ubuntu', 'home', 'me', 'snap', 'chromium', 'common', 'workbench-profiles', 'project-0123456789abcdef', 'chromium-snap_Default', 'chat-2');
+ await leftover(snapCrashed, 'Default/Cookies');
+ // Owned by a Workbench that still runs (in WSL mode, it is a Windows process too)
+ const owned = inDistro('Ubuntu', 'home', 'me', '.cache', 'workbench', 'browser-profiles', 'project-0123456789abcdef', 'chrome_Default', 'chat-3');
+ await put(path.join(owned, 'Default', 'Cookies'));
+ await put(path.join(owned, OWNER_FILE), JSON.stringify({ pid: process.ppid, host: hostname() }));
+ // A stopped distribution isn't started to look
+ const stopped = inDistro('Debian', 'home', 'me', '.cache', 'workbench', 'browser-profiles', 'project-0123456789abcdef', 'chrome_Default', 'chat-1');
+ await leftover(stopped, 'Default/Cookies');
+
+ await removeLeftoverBrowserProfileCopies([]);
+
+ expect(existsSync(crashed)).toBe(false);
+ expect(existsSync(snapCrashed)).toBe(false);
+ expect(existsSync(owned)).toBe(true);
+ expect(existsSync(stopped)).toBe(true);
+ });
+
+ it("refreshes its owner files while copies are in use; an owner that stopped refreshing is gone", async () => {
+ const profile = path.join(root, 'firefox', 'x');
+ await put(path.join(profile, 'cookies.sqlite'));
+ const choice: PlaywrightBrowserChoice = {
+ id: 'firefox:x', browser: 'firefox', engine: 'firefox', profileName: 'x',
+ executablePath: '/usr/lib/firefox/firefox', userDataDir: path.join(root, 'firefox'), profilePath: profile,
+ };
+ const project = path.join(root, 'project');
+ // Earlier tests' copies end, and with them the heartbeat on real timers
+ await removeLiveBrowserProfileCopies();
+ vi.useFakeTimers({ toFake: ['setInterval', 'clearInterval'] });
+ const copy = (await prepareBrowserProfileCopy(project, choice, 'chat-1'))!;
+ const owner = path.join(copy, OWNER_FILE);
+ const twoHoursAgo = new Date(Date.now() - 2 * 60 * 60 * 1000);
+ await utimes(owner, twoHoursAgo, twoHoursAgo);
+ vi.advanceTimersByTime(10 * 60 * 1000);
+ await vi.waitFor(async () => expect(Date.now() - (await stat(owner)).mtimeMs).toBeLessThan(60_000));
+ await removeLiveBrowserProfileCopies();
+
+ // A live process whose identity can't be checked (no boot and start, as off Linux): its claim lasts while refreshed
+ const other = path.join(browserProfileCopiesRoot(project), 'firefox_y', 'chat-2');
+ await put(path.join(other, 'cookies.sqlite'));
+ await put(path.join(other, OWNER_FILE), JSON.stringify({ pid: process.ppid, host: hostname() }));
+ await removeOldBrowserProfileCopies(project, { force: true, keep: [] });
+ expect(existsSync(other)).toBe(true);
+ await utimes(path.join(other, OWNER_FILE), twoHoursAgo, twoHoursAgo);
+ await removeOldBrowserProfileCopies(project, { force: true, keep: [] });
+ expect(existsSync(other)).toBe(false);
+ });
+
+ it("makes no copy for Playwright's own download", async () => {
+ const choice: PlaywrightBrowserChoice = {
+ id: 'playwright:firefox', browser: 'firefox', engine: 'firefox', managed: true, profileName: 'Firefox',
+ executablePath: '/c/firefox', userDataDir: '', profilePath: '',
+ };
+ expect(await prepareBrowserProfileCopy(path.join(root, 'project'), choice, 'chat')).toBeNull();
+ expect(existsSync(path.join(root, 'project'))).toBe(false);
+ });
+
+ it('gives no copy when the profile is gone', async () => {
+ const choice: PlaywrightBrowserChoice = {
+ id: 'chrome:Default',
+ browser: 'chrome',
+ engine: 'chromium',
+ profileName: 'Me',
+ executablePath: '/opt/google/chrome/chrome',
+ userDataDir: path.join(root, 'missing'),
+ profileDirectory: 'Default',
+ profilePath: path.join(root, 'missing', 'Default'),
+ };
+ expect(await prepareBrowserProfileCopy(path.join(root, 'project'), choice, 'chat')).toBeNull();
+ });
+ describe('saved copies', () => {
+ const firefox = (id = 'firefox:x.default'): PlaywrightBrowserChoice => ({
+ id, browser: 'firefox', engine: 'firefox', profileName: 'default', executablePath: '/usr/lib/firefox/firefox',
+ userDataDir: path.join(root, 'firefox'), profilePath: path.join(root, 'firefox', id.split(':')[1]),
+ });
+ const savedRoot = () => path.join(mocks.userData, 'browser-profiles', '_saved');
+
+ it('saves a closed browser\'s profile and copies the saved one while the browser is open', async () => {
+ const choice = firefox();
+ await put(path.join(choice.profilePath, 'cookies.sqlite'), 'signed in');
+ const project = path.join(root, 'project');
+ mocks.inUse = false;
+
+ // Closed: the run copies the live profile, and a saved copy is made meanwhile
+ const first = await prepareBrowserProfileCopy(project, choice, 'chat-a');
+ expect(await readFile(path.join(first!, 'cookies.sqlite'), 'utf-8')).toBe('signed in');
+ await refreshSavedBrowserProfileCopy(choice);
+ expect(await browserProfileCopyBlocked(choice)).toBe(false);
+
+ // Open: the live profile changes under the browser, the run gets the saved copy
+ mocks.inUse = true;
+ await put(path.join(choice.profilePath, 'cookies.sqlite'), 'half written');
+ expect(await browserProfileCopyBlocked(choice)).toBe(false);
+ const second = await prepareBrowserProfileCopy(project, choice, 'chat-b');
+ expect(await readFile(path.join(second!, 'cookies.sqlite'), 'utf-8')).toBe('signed in');
+ expect(existsSync(path.join(second!, '.workbench-saved-complete'))).toBe(false);
+ expect(JSON.parse(await readFile(path.join(second!, OWNER_FILE), 'utf-8'))).toMatchObject({ pid: process.pid });
+ });
+
+ it('blocks runs only while the browser is open with no saved copy', async () => {
+ const choice = firefox();
+ await put(path.join(choice.profilePath, 'cookies.sqlite'));
+ expect(await browserProfileCopyBlocked(choice)).toBe(true);
+ expect(existsSync(savedRoot())).toBe(false);
+ expect(await browserProfileCopyBlocked({ ...choice, managed: true })).toBe(false);
+ });
+
+ it("keeps saved copies at startup, and removes them when another profile is chosen", async () => {
+ const choice = firefox();
+ await put(path.join(choice.profilePath, 'cookies.sqlite'));
+ const project = path.join(root, 'project');
+ mocks.inUse = false;
+ await refreshSavedBrowserProfileCopy(choice);
+ const saved = path.join(savedRoot(), 'firefox_x_default');
+ expect(existsSync(saved)).toBe(true);
+
+ await removeLeftoverBrowserProfileCopies([project]);
+ expect(existsSync(saved)).toBe(true);
+
+ await removeOldBrowserProfileCopies(project, { force: true, keep: [firefox('firefox:y.default')] });
+ expect(existsSync(saved)).toBe(false);
+ });
+
+ it('keeps the copies of every profile still chosen when a run uses another one', async () => {
+ const settingsChoice = firefox();
+ const taskChoice = firefox('firefox:y.default');
+ const dropped = firefox('firefox:z.default');
+ for (const choice of [settingsChoice, taskChoice, dropped]) await put(path.join(choice.profilePath, 'cookies.sqlite'));
+ const project = path.join(root, 'project');
+ mocks.inUse = false;
+ for (const choice of [settingsChoice, taskChoice, dropped]) await refreshSavedBrowserProfileCopy(choice);
+ const copies = browserProfileCopiesRoot(project);
+ const settingsCopy = path.join(copies, 'firefox_x_default', 'chat-old');
+ const droppedCopy = path.join(copies, 'firefox_z_default', 'task-002-b-1234');
+ await leftover(settingsCopy, 'cookies.sqlite');
+ await leftover(droppedCopy, 'cookies.sqlite');
+
+ // A task's run on its own profile, while Settings still chooses another one
+ const run = (await prepareBrowserProfileCopy(project, taskChoice, 'task-001-a-1234', { project: [settingsChoice], all: [settingsChoice] }))!;
+ await vi.waitFor(() => expect(existsSync(droppedCopy)).toBe(false));
+ await vi.waitFor(() => expect(existsSync(path.join(savedRoot(), 'firefox_z_default'))).toBe(false));
+ expect(existsSync(settingsCopy)).toBe(true);
+ expect(existsSync(path.join(savedRoot(), 'firefox_x_default'))).toBe(true);
+ expect(existsSync(path.join(savedRoot(), 'firefox_y_default'))).toBe(true);
+
+ // Playwright's own browser for a run: profiles chosen elsewhere keep their copies
+ await removeOldBrowserProfileCopies(project, { force: true, keep: [settingsChoice], keepSaved: [settingsChoice, taskChoice] });
+ expect(existsSync(settingsCopy)).toBe(true);
+ expect(existsSync(path.join(savedRoot(), 'firefox_y_default'))).toBe(true);
+ await removeBrowserProfileCopy(run);
+ });
+ });
+});
diff --git a/src/main/browser-profiles/__tests__/windows-browser-launcher.test.ts b/src/main/browser-profiles/__tests__/windows-browser-launcher.test.ts
new file mode 100644
index 000000000..ff935515c
--- /dev/null
+++ b/src/main/browser-profiles/__tests__/windows-browser-launcher.test.ts
@@ -0,0 +1,89 @@
+/**
+ * The launcher and the relay for Windows browsers in WSL, run for real with a fake browser and a
+ * fake Playwright server: Node stands in for Workbench's executable (the relay's Node) and the
+ * browser is a script that serves DevTools' /json/version and exits when a DevTools client
+ * connects (as Browser.close would close it)
+ */
+import { spawn } from 'child_process';
+import { chmod, mkdir, mkdtemp, readdir, readFile, rm, writeFile } from 'fs/promises';
+import os from 'os';
+import path from 'path';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+import { isWindows } from '../../platform';
+
+const LAUNCHER = path.join(__dirname, '..', 'windows-browser-launcher.cjs');
+const RELAY = path.join(__dirname, '..', 'windows-cdp-relay.cjs');
+
+const FAKE_BROWSER = `#!/usr/bin/env node
+const fs = require('fs'); const http = require('http'); const path = require('path');
+const dir = process.argv.find((a) => a.startsWith('--user-data-dir=')).slice('--user-data-dir='.length);
+fs.writeFileSync(process.env.FAKE_ARGS_FILE, JSON.stringify(process.argv.slice(2)));
+const server = http.createServer((req, res) => {
+ const port = server.address().port;
+ res.setHeader('content-type', 'application/json');
+ res.end(JSON.stringify({ Browser: 'Fake/1.0', webSocketDebuggerUrl: 'ws://127.0.0.1:' + port + '/devtools/browser/fake' }));
+});
+server.on('upgrade', (req, socket) => { socket.destroy(); process.exit(0); });
+server.listen(0, '127.0.0.1', () => fs.writeFileSync(path.join(dir, 'DevToolsActivePort'), server.address().port + '\\n/devtools/browser/fake'));
+process.on('SIGTERM', () => process.exit(0));
+`;
+
+const FAKE_SERVER = `
+const endpoint = process.argv[process.argv.indexOf('--cdp-endpoint') + 1];
+fetch(endpoint + '/json/version').then((r) => r.json()).then((v) => { process.stdout.write('VERSION ' + JSON.stringify(v) + '\\n'); process.exit(0); },
+ (e) => { process.stdout.write('FAILED ' + e.message + '\\n'); process.exit(1); });
+`;
+
+let dir: string;
+
+beforeEach(async () => {
+ dir = await mkdtemp(path.join(os.tmpdir(), 'windows-browser-launcher-'));
+});
+
+afterEach(async () => {
+ await rm(dir, { recursive: true, force: true });
+});
+
+function run(args: string[], env: NodeJS.ProcessEnv): Promise<{ code: number | null; stdout: string }> {
+ return new Promise((resolve) => {
+ const child = spawn(process.execPath, args, { env, stdio: ['pipe', 'pipe', 'ignore'] });
+ let stdout = '';
+ child.stdout.on('data', (data: Buffer) => {
+ stdout += data.toString();
+ });
+ child.on('exit', (code) => resolve({ code, stdout }));
+ });
+}
+
+describe('windows-browser-launcher', () => {
+ it.skipIf(isWindows())('starts the browser, relays its DevTools port to the server and cleans up after it', async () => {
+ const browser = path.join(dir, 'fake-browser.cjs');
+ await writeFile(browser, FAKE_BROWSER);
+ await chmod(browser, 0o755);
+ const fakeServer = path.join(dir, 'fake-server.cjs');
+ await writeFile(fakeServer, FAKE_SERVER);
+ const tempDir = path.join(dir, 'tmp');
+ await mkdir(tempDir);
+ const argsFile = path.join(dir, 'browser-args.json');
+ const config = {
+ executable: browser,
+ args: ['--profile-directory=Default'],
+ tempDir: { windows: tempDir, runtime: tempDir },
+ relay: { command: process.execPath, script: RELAY },
+ };
+
+ const { code, stdout } = await run([LAUNCHER, JSON.stringify(config), process.execPath, fakeServer], { ...process.env, FAKE_ARGS_FILE: argsFile });
+
+ // The server reached the browser's DevTools through the listener and the relay
+ expect(stdout).toContain('VERSION');
+ expect(JSON.parse(stdout.slice(stdout.indexOf('{'))).Browser).toBe('Fake/1.0');
+ expect(code).toBe(0);
+ const browserArgs = JSON.parse(await readFile(argsFile, 'utf-8')) as string[];
+ expect(browserArgs).toEqual(expect.arrayContaining([
+ '--profile-directory=Default', '--remote-debugging-port=0', '--headless', '--no-startup-window',
+ ]));
+ expect(browserArgs.find((a) => a.startsWith('--user-data-dir='))).toMatch(/workbench-windows-browser-/);
+ // The keeper closed the browser and removed its temporary profile
+ expect(await readdir(tempDir)).toEqual([]);
+ }, 30_000);
+});
diff --git a/src/main/browser-profiles/__tests__/windows-browser.test.ts b/src/main/browser-profiles/__tests__/windows-browser.test.ts
new file mode 100644
index 000000000..e14b30012
--- /dev/null
+++ b/src/main/browser-profiles/__tests__/windows-browser.test.ts
@@ -0,0 +1,37 @@
+import { describe, it, expect, vi } from 'vitest';
+
+const wsl = vi.hoisted(() => ({ info: null as null | { distro: string } }));
+vi.mock('../../platform/shell-runtime', () => ({ getWslInfo: () => wsl.info }));
+vi.mock('electron', () => ({ app: { getPath: () => '/data' } }));
+
+import { isWindowsBrowserInWsl } from '../windows-browser';
+import type { PlaywrightBrowserChoice } from '../../../shared/types/browser-profiles';
+
+const choice = (patch: Partial): PlaywrightBrowserChoice => ({
+ id: 'windows-edge:Default',
+ browser: 'edge',
+ engine: 'chromium',
+ profileName: 'Default',
+ executablePath: 'C:\\Program Files (x86)\\Microsoft\\Edge\\Application\\msedge.exe',
+ userDataDir: 'C:\\Users\\me\\AppData\\Local\\Microsoft\\Edge\\User Data',
+ profilePath: 'C:\\Users\\me\\AppData\\Local\\Microsoft\\Edge\\User Data\\Default',
+ ...patch,
+});
+
+describe('isWindowsBrowserInWsl', () => {
+ it('takes Windows Chromium browsers while tools run in WSL', () => {
+ wsl.info = { distro: 'Ubuntu' };
+ expect(isWindowsBrowserInWsl(choice({}))).toBe(true);
+ });
+
+ it("leaves out native runs, WSL's own browsers, Firefox and Playwright's downloads", () => {
+ wsl.info = null;
+ expect(isWindowsBrowserInWsl(choice({}))).toBe(false);
+ wsl.info = { distro: 'Ubuntu' };
+ expect(isWindowsBrowserInWsl(choice({ executablePath: '/usr/bin/microsoft-edge' }))).toBe(false);
+ // A Windows Firefox profile runs on a Firefox in WSL (its Linux executable)
+ expect(isWindowsBrowserInWsl(choice({ engine: 'firefox', browser: 'firefox', executablePath: '/home/me/.cache/ms-playwright/firefox-1553/firefox/firefox' }))).toBe(false);
+ expect(isWindowsBrowserInWsl(choice({ managed: true }))).toBe(false);
+ expect(isWindowsBrowserInWsl(undefined)).toBe(false);
+ });
+});
diff --git a/src/main/browser-profiles/app-alias.ts b/src/main/browser-profiles/app-alias.ts
new file mode 100644
index 000000000..fa1a52ada
--- /dev/null
+++ b/src/main/browser-profiles/app-alias.ts
@@ -0,0 +1,22 @@
+/**
+ * Microsoft Store apps (Firefox's MSIX package) start through an app execution alias in
+ * `%LOCALAPPDATA%\Microsoft\WindowsApps`. Playwright checks a browser's executable with stat,
+ * which fails on an alias (EACCES), so runs launch the alias's target: the package's own
+ * executable, whose path names the version. The alias is what's stored, so a chosen profile keeps
+ * working after the Store updates the browser.
+ */
+import { readlinkSync } from 'fs';
+import { isWindows } from '../platform';
+
+const APP_ALIAS_FOLDER = /[\\/]Microsoft[\\/]WindowsApps[\\/]/i;
+
+/** The executable an app execution alias points at; any other path is returned as it is */
+export function appAliasTarget(executablePath: string): string {
+ if (!isWindows() || !APP_ALIAS_FOLDER.test(executablePath)) return executablePath;
+ try {
+ // A reparse point read, no process: cheap enough for the sync run-config builders
+ return readlinkSync(executablePath);
+ } catch {
+ return executablePath;
+ }
+}
diff --git a/src/main/browser-profiles/choices-in-use.ts b/src/main/browser-profiles/choices-in-use.ts
new file mode 100644
index 000000000..95667ff2a
--- /dev/null
+++ b/src/main/browser-profiles/choices-in-use.ts
@@ -0,0 +1,61 @@
+/**
+ * The Playwright browser profiles still chosen, so sweeps of profile copies (profile-copy.ts) keep
+ * theirs: the one in Settings > Connectors and every task's own pick (TaskMetadata.playwrightBrowser)
+ * that isn't archived. Read from the tasks' task_metadata.json files without blocking (the
+ * project store's task scan is synchronous)
+ */
+
+import path from 'path';
+import { readdir, readFile } from 'fs/promises';
+import { projectStore } from '../project-store';
+import { getSpecsDir } from '../../shared/constants';
+import type { PlaywrightBrowserChoice } from '../../shared/types/browser-profiles';
+import type { BrowserChoicesInUse } from './profile-copy';
+import { migrateTaskConnectorFields } from '../../shared/utils/mcp-connectors';
+
+/** The profiles a project's tasks picked for themselves (archived tasks don't count) */
+async function projectTaskChoices(projectPath: string, autoBuildPath: string | undefined): Promise {
+ const specsDir = path.join(projectPath, getSpecsDir(autoBuildPath));
+ let names: string[];
+ try {
+ names = await readdir(specsDir);
+ } catch {
+ return [];
+ }
+ const choices = await Promise.all(names.map(async (name) => {
+ try {
+ const metadata = JSON.parse(await readFile(path.join(specsDir, name, 'task_metadata.json'), 'utf-8')) as {
+ playwrightBrowser?: PlaywrightBrowserChoice | null;
+ archivedAt?: string;
+ } | null;
+ // A pick stored before the connector moved to Playwright (puppeteerBrowser)
+ migrateTaskConnectorFields(metadata as Record | null);
+ const choice = metadata?.playwrightBrowser;
+ return choice && typeof choice.id === 'string' && !metadata?.archivedAt ? choice : null;
+ } catch {
+ return null;
+ }
+ }));
+ return choices.filter((choice): choice is PlaywrightBrowserChoice => choice !== null);
+}
+
+/**
+ * The profiles chosen for runs in `projectPath` (Settings and its tasks) and anywhere (Settings and
+ * every project's tasks). Best effort: a folder that can't be read counts as choosing nothing
+ */
+export async function browserChoicesInUse(
+ projectPath: string,
+ settingsChoice: PlaywrightBrowserChoice | undefined
+): Promise {
+ const projects = projectStore.getProjects();
+ const settings = settingsChoice ? [settingsChoice] : [];
+ const perProject = await Promise.all(projects.map(async (project) => ({
+ path: project.path,
+ choices: await projectTaskChoices(project.path, project.autoBuildPath),
+ })));
+ const own = perProject.filter((entry) => entry.path === projectPath).flatMap((entry) => entry.choices);
+ return {
+ project: [...settings, ...own],
+ all: [...settings, ...perProject.flatMap((entry) => entry.choices)],
+ };
+}
diff --git a/src/main/browser-profiles/detect.ts b/src/main/browser-profiles/detect.ts
new file mode 100644
index 000000000..bdad8403f
--- /dev/null
+++ b/src/main/browser-profiles/detect.ts
@@ -0,0 +1,427 @@
+/**
+ * Browser profile detection
+ * =========================
+ *
+ * Finds the installed Chromium-family browsers (Chrome, Edge, Brave, Chromium) and Firefox and
+ * lists their profiles for the Playwright connector (Settings > Connectors). A profile is usable
+ * when Playwright can drive the browser and its executable exists where tools run.
+ *
+ * When tools run in WSL, Playwright starts inside the distribution: its browsers are read through
+ * `\\wsl.localhost` paths and stored with their Linux paths, and Windows browsers are listed but
+ * can't be used. Only async file reads; command lookups go through mcp-commands (async, cached).
+ * Runs once at startup; `refresh` looks again.
+ */
+
+import os from 'os';
+import path from 'path';
+import { access, readFile, readdir, stat } from 'fs/promises';
+import type { BrowserProfile, BrowserProfileDisabledReason, DownloadableBrowser } from '../../shared/types/browser-profiles';
+import { isMacOS, isWindows } from '../platform';
+import { getWslInfo, toHostPath, whenShellRuntimeReady } from '../platform/shell-runtime';
+import { resolveCommand } from '../mcp-commands';
+import { runTool } from '../platform/runtime-exec';
+import { appLog } from '../app-logger';
+import {
+ SNAP_FIREFOX_BINARY,
+ SNAP_FIREFOX_LAUNCHER,
+ browserLocations,
+ pathApi,
+ storeFirefoxPaths,
+ windowsLocalAppData,
+ type BrowserLocation,
+ type BrowserOs,
+} from './locations';
+import { parseChromiumLocalState, parseFirefoxProfilesIni } from './parsing';
+import { findManagedBrowser, scanManagedBrowsers } from './managed';
+import { ensureWindowsBrowserScripts } from './windows-browser';
+
+/** Profiles with no sign of use for this long are left out (leftovers of old or removed installs) */
+export const STALE_PROFILE_MS = 365 * 24 * 60 * 60 * 1000;
+/**
+ * Profiles no browser ever opened (none of the activity files) are left out once made this long
+ * ago: Firefox's placeholder `default` profile, made on its first run next to the
+ * `default-release` one it uses. A profile just made (about:profiles) is still listed
+ */
+export const UNOPENED_PROFILE_MS = 7 * 24 * 60 * 60 * 1000;
+/** Files a browser writes while a profile is in use, relative to the profile's folder */
+const ACTIVITY_FILES = [
+ 'Preferences', 'Cookies', 'Network/Cookies', 'History', 'Login Data',
+ 'prefs.js', 'cookies.sqlite', 'places.sqlite', 'sessionstore.jsonlz4',
+];
+
+/** How often, and for how long, a started download is looked for */
+const WATCH_INTERVAL_MS = 3000;
+const WATCH_LIMIT_MS = 15 * 60 * 1000;
+
+const BROWSER_ORDER = ['chrome', 'edge', 'brave', 'chromium', 'firefox', 'safari', 'webkit'];
+
+interface ScanContext {
+ os: BrowserOs;
+ home: string;
+ env: Record;
+ /** A path from the table -> the path this process reads it with */
+ toHost: (p: string) => string;
+ /** Whether PATH lookups apply (they look where tools run) */
+ lookUpCommands: boolean;
+ /** Look commands up again instead of taking the cached answer */
+ refresh?: boolean;
+ /** Leave out the browsers Playwright downloads itself */
+ skipManaged?: boolean;
+}
+
+async function exists(p: string): Promise {
+ try {
+ await access(p);
+ return true;
+ } catch {
+ return false;
+ }
+}
+
+/**
+ * Whether nothing in a profile's folder changed for STALE_PROFILE_MS. Judged by the files a
+ * browser writes in use (a folder's own date moves when anything is added to it); a profile
+ * without any of them was never opened, and counts by its folder's date with UNOPENED_PROFILE_MS
+ */
+export async function isStaleProfile(profileFolder: string, now = Date.now()): Promise {
+ let newest = 0;
+ for (const file of ACTIVITY_FILES) {
+ try {
+ newest = Math.max(newest, (await stat(`${profileFolder}/${file}`)).mtimeMs);
+ } catch {
+ // Not written by this browser
+ }
+ }
+ if (newest === 0) {
+ try {
+ return now - (await stat(profileFolder)).mtimeMs > UNOPENED_PROFILE_MS;
+ } catch {
+ return false;
+ }
+ }
+ return now - newest > STALE_PROFILE_MS;
+}
+
+async function readText(p: string): Promise {
+ try {
+ return await readFile(p, 'utf-8');
+ } catch {
+ return null;
+ }
+}
+
+async function findExecutable(location: BrowserLocation, context: ScanContext): Promise {
+ for (const candidate of location.executables) {
+ if (await exists(context.toHost(candidate))) return candidate;
+ }
+ if (!context.lookUpCommands) return undefined;
+ for (const command of location.commands ?? []) {
+ const found = await resolveCommand(command, { refresh: context.refresh });
+ if (found) return found;
+ }
+ return undefined;
+}
+
+/** Ubuntu's `/usr/bin/firefox` is a small script that starts the snap */
+async function startsSnapFirefox(executable: string, context: ScanContext): Promise {
+ if (executable === SNAP_FIREFOX_LAUNCHER) return true;
+ try {
+ const host = context.toHost(executable);
+ if ((await stat(host)).size > 64 * 1024) return false;
+ const text = await readFile(host, 'utf-8');
+ return text.startsWith('#!') && text.includes(SNAP_FIREFOX_LAUNCHER);
+ } catch {
+ return false;
+ }
+}
+
+/** One check per scan: the deb and snap locations can both lead to the snap */
+const snapChecks = new WeakMap>();
+
+/**
+ * Why snap Firefox's own binary (the one runs launch, see mcp-config.ts) can't run outside the
+ * snap. It is built on the snap's base (core24: glibc 2.38 or newer) and has no bundled libc, so
+ * on an older system the loader refuses it
+ */
+function snapFirefoxProblem(context: ScanContext): Promise {
+ let check = snapChecks.get(context);
+ if (!check) {
+ check = (async () => {
+ if (!(await exists(context.toHost(SNAP_FIREFOX_BINARY)))) return 'executable-missing' as const;
+ try {
+ // Tool name aside, this runs the given binary where tools run
+ await runTool('node', ['--version'], { command: SNAP_FIREFOX_BINARY, timeout: 15_000 });
+ return undefined;
+ } catch (error) {
+ // `version `GLIBC_2.38' not found (required by ...)`; other failures are left to the connector check
+ const stderr = String((error as { stderr?: unknown }).stderr ?? '');
+ return /GLIBC(?:XX)?_[\d.]+' not found/.test(stderr) ? 'snap-needs-newer-glibc' as const : undefined;
+ }
+ })();
+ snapChecks.set(context, check);
+ }
+ return check;
+}
+
+/** The executable a location's profiles launch with, or why there is none that works */
+async function resolveLaunch(
+ location: BrowserLocation,
+ context: ScanContext
+): Promise<{ executablePath?: string; disabledReason?: BrowserProfileDisabledReason }> {
+ if (location.disabledReason) return { disabledReason: location.disabledReason };
+ const executablePath = await findExecutable(location, context);
+ if (!executablePath) return { disabledReason: 'executable-missing' };
+ if (context.os === 'linux' && location.engine === 'firefox' && (await startsSnapFirefox(executablePath, context))) {
+ // Stored as the snap's launcher, which runs map to the snap's own binary
+ const disabledReason = await snapFirefoxProblem(context);
+ return { executablePath: SNAP_FIREFOX_LAUNCHER, ...(disabledReason ? { disabledReason } : {}) };
+ }
+ return { executablePath };
+}
+
+function profileId(location: BrowserLocation, folder: string): string {
+ return `${location.browser}${location.variant ? `-${location.variant}` : ''}:${folder}`;
+}
+
+async function scanLocation(location: BrowserLocation, context: ScanContext): Promise {
+ const p = pathApi(context.os);
+ const found: Omit[] = [];
+
+ if (location.engine === 'webkit') {
+ // Safari: one entry when it is installed, never usable
+ const app = location.executables[0];
+ if (app && (await exists(context.toHost(app)))) {
+ found.push({ id: `${location.browser}:default`, browser: location.browser, engine: location.engine, profileName: 'Safari', userDataDir: '', profilePath: '' });
+ }
+ }
+
+ for (const dataDir of location.dataDirs) {
+ if (location.engine === 'chromium') {
+ const text = await readText(context.toHost(p.join(dataDir, 'Local State')));
+ if (text === null) continue;
+ for (const entry of parseChromiumLocalState(text)) {
+ const profilePath = p.join(dataDir, entry.directory);
+ // Listed in Local State but deleted since
+ if (!(await exists(context.toHost(profilePath)))) continue;
+ if (await isStaleProfile(context.toHost(profilePath))) continue;
+ found.push({
+ id: profileId(location, entry.directory),
+ browser: location.browser,
+ engine: location.engine,
+ ...(location.variant ? { variant: location.variant } : {}),
+ profileName: entry.name,
+ ...(entry.email ? { email: entry.email } : {}),
+ userDataDir: dataDir,
+ profileDirectory: entry.directory,
+ profilePath,
+ });
+ }
+ } else if (location.engine === 'firefox') {
+ const text = await readText(context.toHost(p.join(dataDir, 'profiles.ini')));
+ if (text === null) continue;
+ for (const entry of parseFirefoxProfilesIni(text, dataDir, p)) {
+ if (!(await exists(context.toHost(entry.path)))) continue;
+ if (await isStaleProfile(context.toHost(entry.path))) continue;
+ found.push({
+ id: profileId(location, entry.folder),
+ browser: location.browser,
+ engine: location.engine,
+ ...(location.variant ? { variant: location.variant } : {}),
+ profileName: entry.name,
+ userDataDir: dataDir,
+ profilePath: entry.path,
+ });
+ }
+ }
+ }
+ if (found.length === 0) return [];
+
+ const { executablePath, disabledReason } = await resolveLaunch(location, context);
+ return found.map((profile) => ({
+ ...profile,
+ ...(executablePath ? { executablePath } : {}),
+ usable: !disabledReason,
+ ...(disabledReason ? { disabledReason } : {}),
+ }));
+}
+
+/**
+ * The Microsoft Store packages that hold Firefox profiles, found by what they keep on disk rather
+ * than by name, so any Firefox the Store installs is covered
+ */
+async function findStoreFirefoxPackages(context: ScanContext): Promise {
+ if (context.os !== 'windows') return [];
+ const localAppData = windowsLocalAppData(context);
+ let families: string[];
+ try {
+ families = await readdir(context.toHost(path.win32.join(localAppData, 'Packages')));
+ } catch {
+ return [];
+ }
+ const hasProfiles = await Promise.all(
+ families.map((family) => exists(context.toHost(path.win32.join(storeFirefoxPaths(localAppData, family).dataDir, 'profiles.ini'))))
+ );
+ return families.filter((_, index) => hasProfiles[index]);
+}
+
+/** Every profile of the browsers in one OS's table; a browser that can't be read is skipped */
+export async function scanBrowserProfiles(context: ScanContext): Promise {
+ const profiles: BrowserProfile[] = [];
+ const seen = new Set();
+ const storePackages = await findStoreFirefoxPackages(context);
+ for (const location of browserLocations(context.os, { ...context, storePackages })) {
+ try {
+ for (const profile of await scanLocation(location, context)) {
+ if (seen.has(profile.id)) continue;
+ seen.add(profile.id);
+ profiles.push(profile);
+ }
+ } catch (error) {
+ appLog.warn(`[BrowserProfiles] Could not read ${location.browser} profiles:`, error);
+ }
+ }
+ // Grouped by browser in a fixed order; profiles keep the browser's own order
+ const sorted = profiles
+ .map((profile, index) => ({ profile, index }))
+ .sort((a, b) => BROWSER_ORDER.indexOf(a.profile.browser) - BROWSER_ORDER.indexOf(b.profile.browser) || a.index - b.index)
+ .map(({ profile }) => profile);
+ // Playwright's own downloads come last
+ return context.skipManaged ? sorted : [...sorted, ...(await scanManagedBrowsers(context).catch(() => []))];
+}
+
+function nativeOs(): BrowserOs {
+ if (isWindows()) return 'windows';
+ if (isMacOS()) return 'macos';
+ return 'linux';
+}
+
+async function detect(refresh: boolean): Promise {
+ await whenShellRuntimeReady();
+ const wsl = getWslInfo();
+ const native: ScanContext = { os: nativeOs(), home: os.homedir(), env: process.env, toHost: (p) => p, lookUpCommands: !isWindows(), refresh };
+ if (!wsl) return scanBrowserProfiles(native);
+
+ // Tools (and so Playwright) run in the distribution: its own browsers can be used; Windows Firefox
+ // profiles with a Firefox there (runs copy them in, profile-copy.ts); Windows Chromium browsers
+ // through the launcher (windows-browser.ts, which needs interop), signed out: their cookies are
+ // encrypted with an app-bound key that only opens in the browser's own profile folder
+ const linuxContext: ScanContext = { os: 'linux', home: wsl.home, env: {}, toHost: toHostPath, lookUpCommands: true, refresh };
+ const linux = await scanBrowserProfiles(linuxContext);
+ void ensureWindowsBrowserScripts().catch((error: unknown) => appLog.warn('[BrowserProfiles] Could not write the Windows browser launcher:', error));
+ const windowsProfiles = await scanBrowserProfiles({ ...native, lookUpCommands: false, skipManaged: true });
+ const firefoxes = windowsProfiles.some((profile) => profile.engine === 'firefox') ? await wslFirefoxes(linuxContext) : null;
+ const windows = await Promise.all(windowsProfiles.map(async (profile): Promise => {
+ const id = `windows-${profile.id}`;
+ if (profile.engine === 'chromium') {
+ if (!profile.usable) return { ...profile, id };
+ return wsl.interop === false
+ ? { ...profile, id, usable: false, disabledReason: 'windows-browser-in-wsl' }
+ : { ...profile, id, signedOut: true };
+ }
+ if (profile.engine !== 'firefox' || !firefoxes) return { ...profile, id, usable: false, disabledReason: 'windows-browser-in-wsl' };
+ const { disabledReason: _disabledReason, ...rest } = profile;
+ const executablePath = pickWslFirefox(await windowsProfileFirefoxMajor(profile.profilePath), firefoxes);
+ return executablePath
+ ? { ...rest, id, executablePath, usable: true }
+ : { ...rest, id, executablePath: undefined, usable: false, disabledReason: 'needs-firefox-in-wsl', downloadable: 'firefox' };
+ }));
+ return [...linux, ...windows];
+}
+
+/** The Firefoxes in the distribution that can run a Windows Firefox profile's copy */
+export interface WslFirefoxes {
+ /** An installed Firefox (not the snap's: it may only read non-hidden folders), with its major version */
+ installed?: { executablePath: string; major: number };
+ /** Playwright's own Firefox build */
+ playwright?: string;
+}
+
+/** A version's major number (`Mozilla Firefox 156.0`, `158.0.1_20261019185856/...`), or undefined */
+export function majorVersion(text: string): number | undefined {
+ const major = Number(/(\d+)\.\d/.exec(text)?.[1]);
+ return major > 0 ? major : undefined;
+}
+
+async function wslFirefoxes(context: ScanContext): Promise {
+ const found: WslFirefoxes = {};
+ const playwright = await findManagedBrowser('firefox', context).catch(() => undefined);
+ if (playwright) found.playwright = playwright;
+ for (const location of browserLocations('linux', context)) {
+ if (location.engine !== 'firefox' || location.variant) continue;
+ const executablePath = await findExecutable(location, context);
+ if (!executablePath || (await startsSnapFirefox(executablePath, context))) continue;
+ try {
+ // Tool name aside, this runs the given executable where tools run
+ const { stdout } = await runTool('node', ['--version'], { command: executablePath, timeout: 15_000 });
+ const major = majorVersion(String(stdout));
+ if (major) found.installed = { executablePath, major };
+ } catch {
+ // Doesn't start: Playwright's Firefox, if any, runs the profiles
+ }
+ break;
+ }
+ return found;
+}
+
+/** The major version of the Firefox that last wrote a profile (its `compatibility.ini`), or undefined */
+async function windowsProfileFirefoxMajor(profilePath: string): Promise {
+ const compatibility = await readText(pathApi('windows').join(profilePath, 'compatibility.ini'));
+ return compatibility ? majorVersion(/^LastVersion=(.*)$/m.exec(compatibility)?.[1] ?? '') : undefined;
+}
+
+/**
+ * The Firefox in the distribution that runs a Windows profile's copy: the installed one when it is
+ * at least the version that last wrote the profile (Firefox refuses a profile a newer version
+ * wrote), else Playwright's own build, which runs the copy with `--allow-downgrade` (mcp-config.ts)
+ */
+export function pickWslFirefox(profileMajor: number | undefined, firefoxes: WslFirefoxes): string | undefined {
+ if (firefoxes.installed && (profileMajor === undefined || firefoxes.installed.major >= profileMajor)) return firefoxes.installed.executablePath;
+ return firefoxes.playwright ?? firefoxes.installed?.executablePath;
+}
+
+let detection: Promise | null = null;
+
+/** The detected browser profiles (looked for once; `refresh` looks again) */
+export function detectBrowserProfiles(options: { refresh?: boolean } = {}): Promise {
+ if (!detection || options.refresh) {
+ detection = detect(options.refresh === true).catch((error: unknown) => {
+ appLog.warn('[BrowserProfiles] Detection failed:', error);
+ return [];
+ });
+ }
+ return detection;
+}
+
+/** Running watches by browser, with when each gives up (each new download moves it to WATCH_LIMIT_MS from then) */
+const watches = new Map }>();
+
+/**
+ * After a download button opened a terminal: wait (up to WATCH_LIMIT_MS after the latest call) for
+ * the browser's build to show up in Playwright's cache folder, then detect again and return the new
+ * list (null when it never did). One watch per browser; a later call shares it and extends its deadline
+ */
+export function waitForManagedBrowser(browser: DownloadableBrowser): Promise {
+ const deadline = Date.now() + WATCH_LIMIT_MS;
+ const running = watches.get(browser);
+ if (running) {
+ running.deadline = Math.max(running.deadline, deadline);
+ return running.promise;
+ }
+ const watch: { deadline: number; promise: Promise } = { deadline, promise: Promise.resolve(null) };
+ watch.promise = (async () => {
+ await whenShellRuntimeReady();
+ const wsl = getWslInfo();
+ const context = wsl
+ ? { os: 'linux' as const, home: wsl.home, env: {}, toHost: toHostPath }
+ : { os: nativeOs(), home: os.homedir(), env: process.env, toHost: (p: string) => p };
+ while (Date.now() < watch.deadline) {
+ if (await findManagedBrowser(browser, context)) return detectBrowserProfiles({ refresh: true });
+ await new Promise((resolve) => setTimeout(resolve, WATCH_INTERVAL_MS));
+ }
+ return null;
+ })().finally(() => {
+ watches.delete(browser);
+ });
+ watches.set(browser, watch);
+ return watch.promise;
+}
diff --git a/src/main/browser-profiles/in-use.ts b/src/main/browser-profiles/in-use.ts
new file mode 100644
index 000000000..1c5aaed33
--- /dev/null
+++ b/src/main/browser-profiles/in-use.ts
@@ -0,0 +1,167 @@
+/**
+ * Whether the browser chosen for the Playwright connector is open with its profile. Runs copy the
+ * profile, which an open browser keeps locked and half written, so the connector waits until it
+ * is closed (mcp-availability.ts).
+ *
+ * Read from the lock the browser holds, not from the process list: only the chosen profile
+ * counts, never Playwright's own browsers (they run on new profiles). On Linux and macOS the lock is a
+ * link naming the browser's process (Firefox's `lock` -> `127.0.1.1:+`, Chromium's
+ * `SingletonLock` -> `-`), checked to be alive since a crash leaves it behind: a
+ * process of another user, or a process that isn't the lock's browser (by its name: /proc on
+ * Linux, `ps` on macOS; a Firefox lock needs a Firefox process, a Chromium lock a Chromium one)
+ * reads as closed. A Chromium lock naming another host still counts when its pid is a live
+ * Chromium browser here, as Chromium's own check does (macOS renames the host on a network
+ * change); otherwise it reads as closed (a shared home folder). On Windows the browser keeps the lock file open
+ * (`parent.lock`, `lockfile`), so it can't be opened. A Chromium browser that keeps running
+ * without windows (Edge's Startup boost, Chrome's "Continue running background apps") holds it
+ * too, and its profile's files with it, so it counts as open: the tip says to quit it from the
+ * system tray or turn that setting off.
+ * macOS Firefox keeps only `.parentlock` (an fcntl lock Node can't test), so it reads as closed.
+ */
+
+import { execFile } from 'child_process';
+import { open, readFile, readlink } from 'fs/promises';
+import { hostname } from 'os';
+import path from 'path';
+import { promisify } from 'util';
+import type { PlaywrightBrowserChoice } from '../../shared/types/browser-profiles';
+import { isLinux, isMacOS, isWindows } from '../platform';
+import { isWslUncPath } from '../platform/wsl-paths';
+
+/**
+ * Main process names (Linux `comm` or the macOS executable's name, at most 15 characters) of the
+ * browsers that write each engine's lock. Whole names, so helpers such as `chrome_crashpad`
+ * (Chromium's and Electron's crash handler) and Firefox's content processes never count
+ */
+const BROWSER_PROCESS: Record<'firefox' | 'chromium', RegExp> = {
+ firefox: /^(?:firefox|firefox-bin|firefox-esr|firefox\.real|librewolf|waterfox|floorp|zen)$/i,
+ chromium:
+ /^(?:chrome|google chrome|chromium|chromium-browse|chromium-browser|msedge|microsoft edge|brave|brave browser|vivaldi|vivaldi-bin|opera|yandex_browser|yandex)$/i,
+};
+
+const execFileAsync = promisify(execFile);
+/** How long `ps` may take on macOS */
+const PS_TIMEOUT_MS = 3000;
+
+/**
+ * The process's name: `comm` from /proc on Linux, `ps -o comm=` on macOS (the executable's path,
+ * cut to its file name and to Linux's 15 characters so one check fits both), or null when it can't
+ * be read
+ */
+async function processName(pid: number): Promise {
+ if (isLinux()) {
+ try {
+ return (await readFile(`/proc/${pid}/comm`, 'utf-8')).trim();
+ } catch {
+ return null;
+ }
+ }
+ if (isMacOS()) {
+ try {
+ // A system tool, not a detected one: /bin/ps on every macOS, run natively
+ const { stdout } = await execFileAsync('/bin/ps', ['-p', String(pid), '-o', 'comm='], { timeout: PS_TIMEOUT_MS });
+ const name = path.basename(stdout.trim()).slice(0, 15);
+ return name || null;
+ } catch {
+ return null;
+ }
+ }
+ return null;
+}
+
+/**
+ * Whether the browser that wrote a lock still runs as this process. After a crash and a reboot
+ * its id can belong to anything, so a name that isn't a browser's doesn't count (Linux and macOS
+ * read the name), and without a name neither does another user's process (the user's browser runs
+ * as the user).
+ *
+ * The process's start isn't compared with the lock's time: the lock's mtime is wall-clock time,
+ * so a clock step (NTP, a VM resumed) between writing it and now moves it against any start time,
+ * and an open browser would read as closed, letting a run copy a half-written profile. A pid
+ * reused by another browser after a crash reads as open instead, which only makes the connector
+ * wait (the browser fixes its stale lock when it next starts)
+ */
+async function browserRunning(
+ pid: number,
+ executablePath: string,
+ engine: 'firefox' | 'chromium',
+ options: { needName?: boolean } = {}
+): Promise {
+ let ours: boolean;
+ try {
+ process.kill(pid, 0);
+ ours = true;
+ } catch (error) {
+ // EPERM: it runs, as another user
+ if ((error as NodeJS.ErrnoException).code !== 'EPERM') return false;
+ ours = false;
+ }
+ const name = await processName(pid);
+ if (name === null) return ours && !options.needName;
+ // The chosen executable's own name first (a browser not in the list), then the engine's browsers
+ const executable = path.basename(executablePath).slice(0, 15);
+ return (executable !== '' && name === executable) || BROWSER_PROCESS[engine].test(name);
+}
+
+/** A Windows lock file the browser holds open */
+async function fileHeld(file: string): Promise {
+ try {
+ const handle = await open(file, 'r+');
+ await handle.close();
+ return false;
+ } catch (error) {
+ const code = (error as NodeJS.ErrnoException).code;
+ return code === 'EBUSY' || code === 'EPERM';
+ }
+}
+
+/** Firefox's lock link: `:+`, or `:` where it fell back from fcntl locks (NFS) */
+function parseFirefoxLock(target: string): number | undefined {
+ const pid = Number(/:\+?(\d+)$/.exec(target)?.[1]);
+ return pid > 0 ? pid : undefined;
+}
+
+/** Chromium's SingletonLock link: `-` (the host may contain dashes) */
+function parseChromiumLock(target: string): { host: string; pid: number } | undefined {
+ const match = /^(.*)-(\d+)$/.exec(target);
+ const pid = Number(match?.[2]);
+ return match && pid > 0 ? { host: match[1], pid } : undefined;
+}
+
+async function readLock(link: string): Promise {
+ try {
+ return await readlink(link);
+ } catch {
+ // No lock: the browser is closed
+ return null;
+ }
+}
+
+export async function isBrowserProfileInUse(choice: PlaywrightBrowserChoice): Promise {
+ // Playwright's own browsers start on a new profile each time
+ if (choice.managed) return false;
+ const firefox = choice.engine === 'firefox';
+ // Firefox locks the profile; Chromium the user data folder, shared by its profiles
+ const dir = firefox ? choice.profilePath : choice.userDataDir;
+ if (isWindows()) {
+ // A WSL browser (stored with its Linux path, or a WSL UNC path): its process can't be seen from
+ // Windows. Other UNC paths are network shares
+ if (dir.startsWith('/') || isWslUncPath(dir)) return false;
+ return fileHeld(path.join(dir, firefox ? 'parent.lock' : 'lockfile'));
+ }
+ if (firefox) {
+ const link = path.join(dir, 'lock');
+ const target = await readLock(link);
+ const pid = target === null ? undefined : parseFirefoxLock(target);
+ return pid !== undefined && browserRunning(pid, choice.executablePath, 'firefox');
+ }
+ const link = path.join(dir, 'SingletonLock');
+ const target = await readLock(link);
+ const lock = target === null ? undefined : parseChromiumLock(target);
+ if (lock === undefined) return false;
+ // Another host's lock: the host was renamed (macOS on a network change) while the browser runs
+ // here, or a shared home folder. Like Chromium's own check, a live Chromium browser with its pid
+ // counts; its name must be readable then, since a pid alone may be anything here
+ const otherHost = lock.host !== hostname();
+ return browserRunning(lock.pid, choice.executablePath, 'chromium', { needName: otherHost });
+}
diff --git a/src/main/browser-profiles/locations.ts b/src/main/browser-profiles/locations.ts
new file mode 100644
index 000000000..9c9da449f
--- /dev/null
+++ b/src/main/browser-profiles/locations.ts
@@ -0,0 +1,223 @@
+/**
+ * Where each browser keeps its profiles and its executable, per OS. Pure: the OS, home folder and
+ * environment are passed in, so every OS's table can be tested anywhere. Paths are the ones tools
+ * see where they run (Linux paths in WSL); detect.ts reads them through host paths.
+ */
+
+import path from 'path';
+
+/** Node's path functions for one OS (path.posix or path.win32) */
+export type PathApi = typeof path.posix;
+import type { BrowserEngine, BrowserKind, BrowserProfileDisabledReason } from '../../shared/types/browser-profiles';
+
+export type BrowserOs = 'windows' | 'macos' | 'linux';
+
+/** Snap Firefox's launcher (runs it in the snap's sandbox) and its own binary (runs outside it) */
+export const SNAP_FIREFOX_LAUNCHER = '/snap/bin/firefox';
+export const SNAP_FIREFOX_BINARY = '/snap/firefox/current/usr/lib/firefox/firefox';
+/** Snap Chromium's launcher: runs Chromium confined by the snap's AppArmor profile */
+export const SNAP_CHROMIUM_LAUNCHER = '/snap/bin/chromium';
+
+/**
+ * Snap launchers runs replace with the snap's own binary, which runs outside the sandbox
+ * (mcp-config.ts; detect.ts checks the binary runs on this system)
+ */
+export const SNAP_UNCONFINED_BINARIES: Readonly> = {
+ [SNAP_FIREFOX_LAUNCHER]: SNAP_FIREFOX_BINARY,
+};
+
+/**
+ * Snaps whose browser runs confined: the snap's `home` interface lets it write only non-hidden
+ * folders of the home (`owner @{HOME}/[^s.]**`) and the snap's own `~/snap/`, so a run's
+ * profile copy goes to `~/snap//common` (profile-copy.ts). Snap Chromium's inner binary
+ * isn't run directly like Firefox's: it needs the libraries of the GNOME content snap, mounted
+ * only inside the snap's namespace
+ */
+export const CONFINED_SNAPS = ['chromium'] as const;
+
+/** The snap a browser runs confined in, from its executable (`/snap/bin/`), or undefined */
+export function confinedSnapName(executablePath: string): string | undefined {
+ if (executablePath in SNAP_UNCONFINED_BINARIES) return undefined;
+ const name = /^\/snap\/bin\/([a-z0-9][a-z0-9-]*)$/.exec(executablePath)?.[1];
+ return name;
+}
+
+export interface BrowserLocation {
+ browser: BrowserKind;
+ engine: BrowserEngine;
+ /** Tells installs of the same browser apart in profile ids (`snap`, `flatpak`) */
+ variant?: string;
+ /** Chromium: user data folders (holding `Local State`); Firefox: folders holding profiles.ini */
+ dataDirs: string[];
+ /** Executables to try, in order */
+ executables: string[];
+ /** Command names looked up on PATH when no executable above exists (Linux) */
+ commands?: string[];
+ /** Listed, but never usable */
+ disabledReason?: BrowserProfileDisabledReason;
+}
+
+export interface BrowserLocationContext {
+ home: string;
+ env: Record;
+ /** Windows: Microsoft Store packages holding Firefox profiles, by package family name (detect.ts finds them) */
+ storePackages?: string[];
+}
+
+/** The path functions for an OS's paths */
+export function pathApi(os: BrowserOs): PathApi {
+ return os === 'windows' ? path.win32 : path.posix;
+}
+
+/** `%LOCALAPPDATA%`, or its default under the home folder */
+export function windowsLocalAppData({ home, env }: Pick): string {
+ return env.LOCALAPPDATA || path.win32.join(home, 'AppData', 'Local');
+}
+
+/**
+ * A Microsoft Store (MSIX) package's Firefox folders, from its package family name (a folder
+ * name in `%LOCALAPPDATA%\Packages`): the package keeps what it writes to AppData in its own
+ * `LocalCache`, and starts through an app execution alias in `WindowsApps\`
+ */
+export function storeFirefoxPaths(localAppData: string, packageFamily: string): { dataDir: string; executable: string } {
+ const p = path.win32;
+ return {
+ dataDir: p.join(localAppData, 'Packages', packageFamily, 'LocalCache', 'Roaming', 'Mozilla', 'Firefox'),
+ executable: p.join(localAppData, 'Microsoft', 'WindowsApps', packageFamily, 'firefox.exe'),
+ };
+}
+
+function windowsLocations({ home, env, storePackages = [] }: BrowserLocationContext): BrowserLocation[] {
+ const p = path.win32;
+ const localAppData = windowsLocalAppData({ home, env });
+ const appData = env.APPDATA || p.join(home, 'AppData', 'Roaming');
+ const programFiles = env.ProgramFiles || env.PROGRAMFILES || 'C:\\Program Files';
+ const programFilesX86 = env['ProgramFiles(x86)'] || env['PROGRAMFILES(X86)'] || 'C:\\Program Files (x86)';
+ const installRoots = [programFiles, programFilesX86, localAppData];
+ const installed = (...parts: string[]) => installRoots.map((root) => p.join(root, ...parts));
+ return [
+ {
+ browser: 'chrome', engine: 'chromium',
+ dataDirs: [p.join(localAppData, 'Google', 'Chrome', 'User Data')],
+ executables: installed('Google', 'Chrome', 'Application', 'chrome.exe'),
+ },
+ {
+ browser: 'edge', engine: 'chromium',
+ dataDirs: [p.join(localAppData, 'Microsoft', 'Edge', 'User Data')],
+ executables: installed('Microsoft', 'Edge', 'Application', 'msedge.exe'),
+ },
+ {
+ browser: 'brave', engine: 'chromium',
+ dataDirs: [p.join(localAppData, 'BraveSoftware', 'Brave-Browser', 'User Data')],
+ executables: installed('BraveSoftware', 'Brave-Browser', 'Application', 'brave.exe'),
+ },
+ {
+ browser: 'chromium', engine: 'chromium',
+ dataDirs: [p.join(localAppData, 'Chromium', 'User Data')],
+ executables: installed('Chromium', 'Application', 'chrome.exe'),
+ },
+ {
+ browser: 'firefox', engine: 'firefox',
+ dataDirs: [p.join(appData, 'Mozilla', 'Firefox')],
+ // Machine-wide (release and ESR install to the same folder), then a per-user install
+ executables: installed('Mozilla Firefox', 'firefox.exe'),
+ },
+ // Microsoft Store installs (mcp-config.ts runs the alias's target)
+ ...storePackages.map((family): BrowserLocation => {
+ const { dataDir, executable } = storeFirefoxPaths(localAppData, family);
+ return { browser: 'firefox', engine: 'firefox', variant: 'store', dataDirs: [dataDir], executables: [executable] };
+ }),
+ ];
+}
+
+function macLocations({ home }: BrowserLocationContext): BrowserLocation[] {
+ const p = path.posix;
+ const support = p.join(home, 'Library', 'Application Support');
+ const app = (bundle: string, binary: string) =>
+ ['/Applications', p.join(home, 'Applications')].map((root) => p.join(root, `${bundle}.app`, 'Contents', 'MacOS', binary));
+ return [
+ { browser: 'chrome', engine: 'chromium', dataDirs: [p.join(support, 'Google', 'Chrome')], executables: app('Google Chrome', 'Google Chrome') },
+ { browser: 'edge', engine: 'chromium', dataDirs: [p.join(support, 'Microsoft Edge')], executables: app('Microsoft Edge', 'Microsoft Edge') },
+ { browser: 'brave', engine: 'chromium', dataDirs: [p.join(support, 'BraveSoftware', 'Brave-Browser')], executables: app('Brave Browser', 'Brave Browser') },
+ { browser: 'chromium', engine: 'chromium', dataDirs: [p.join(support, 'Chromium')], executables: app('Chromium', 'Chromium') },
+ { browser: 'firefox', engine: 'firefox', dataDirs: [p.join(support, 'Firefox')], executables: app('Firefox', 'firefox') },
+ // Listed so the user sees why it can't be picked; Playwright can't drive Safari (its own WebKit build is offered instead, managed.ts)
+ {
+ browser: 'safari', engine: 'webkit', dataDirs: [],
+ executables: ['/Applications/Safari.app/Contents/MacOS/Safari'],
+ disabledReason: 'unsupported-engine',
+ },
+ ];
+}
+
+function linuxLocations({ home, env }: BrowserLocationContext): BrowserLocation[] {
+ const p = path.posix;
+ // Chromium browsers (and Firefox from 147 for new profiles) follow XDG_CONFIG_HOME; a relative
+ // value is invalid by the spec and ignored, as the browsers do
+ const config = env.XDG_CONFIG_HOME && p.isAbsolute(env.XDG_CONFIG_HOME) ? env.XDG_CONFIG_HOME : p.join(home, '.config');
+ const flatpak = (appId: string, ...parts: string[]) => p.join(home, '.var', 'app', appId, ...parts);
+ const sandboxed = { variant: 'flatpak', executables: [], disabledReason: 'sandboxed-package' as const };
+ return [
+ {
+ browser: 'chrome', engine: 'chromium',
+ dataDirs: [p.join(config, 'google-chrome')],
+ executables: ['/opt/google/chrome/chrome'],
+ commands: ['google-chrome-stable', 'google-chrome'],
+ },
+ {
+ browser: 'edge', engine: 'chromium',
+ dataDirs: [p.join(config, 'microsoft-edge')],
+ executables: ['/opt/microsoft/msedge/msedge'],
+ commands: ['microsoft-edge-stable', 'microsoft-edge'],
+ },
+ {
+ browser: 'brave', engine: 'chromium',
+ dataDirs: [p.join(config, 'BraveSoftware', 'Brave-Browser')],
+ executables: ['/opt/brave.com/brave/brave'],
+ commands: ['brave-browser', 'brave'],
+ },
+ {
+ browser: 'chromium', engine: 'chromium',
+ dataDirs: [p.join(config, 'chromium')],
+ executables: ['/usr/lib/chromium/chromium', '/usr/lib/chromium-browser/chromium-browser'],
+ commands: ['chromium', 'chromium-browser'],
+ },
+ {
+ browser: 'chromium', engine: 'chromium', variant: 'snap',
+ dataDirs: [p.join(home, 'snap', 'chromium', 'common', 'chromium')],
+ executables: [SNAP_CHROMIUM_LAUNCHER],
+ },
+ {
+ browser: 'firefox', engine: 'firefox',
+ dataDirs: [p.join(home, '.mozilla', 'firefox'), p.join(config, 'mozilla', 'firefox')],
+ // Distribution packages, Mozilla's tarball in /opt, then Debian's default ESR
+ executables: [
+ '/usr/lib/firefox/firefox', '/usr/lib64/firefox/firefox', '/opt/firefox/firefox',
+ '/usr/lib/firefox-esr/firefox-esr', '/usr/lib64/firefox-esr/firefox-esr',
+ ],
+ commands: ['firefox', 'firefox-esr'],
+ },
+ {
+ browser: 'firefox', engine: 'firefox', variant: 'snap',
+ dataDirs: [p.join(home, 'snap', 'firefox', 'common', '.mozilla', 'firefox')],
+ executables: [SNAP_FIREFOX_LAUNCHER],
+ },
+ { browser: 'chrome', engine: 'chromium', dataDirs: [flatpak('com.google.Chrome', 'config', 'google-chrome')], ...sandboxed },
+ { browser: 'edge', engine: 'chromium', dataDirs: [flatpak('com.microsoft.Edge', 'config', 'microsoft-edge')], ...sandboxed },
+ { browser: 'brave', engine: 'chromium', dataDirs: [flatpak('com.brave.Browser', 'config', 'BraveSoftware', 'Brave-Browser')], ...sandboxed },
+ { browser: 'chromium', engine: 'chromium', dataDirs: [flatpak('org.chromium.Chromium', 'config', 'chromium')], ...sandboxed },
+ { browser: 'firefox', engine: 'firefox', dataDirs: [flatpak('org.mozilla.firefox', '.mozilla', 'firefox')], ...sandboxed },
+ ];
+}
+
+/** Every browser's profile and executable locations on an OS */
+export function browserLocations(os: BrowserOs, context: BrowserLocationContext): BrowserLocation[] {
+ switch (os) {
+ case 'windows':
+ return windowsLocations(context);
+ case 'macos':
+ return macLocations(context);
+ default:
+ return linuxLocations(context);
+ }
+}
diff --git a/src/main/browser-profiles/managed.ts b/src/main/browser-profiles/managed.ts
new file mode 100644
index 000000000..86fee63d8
--- /dev/null
+++ b/src/main/browser-profiles/managed.ts
@@ -0,0 +1,153 @@
+/**
+ * Browsers Playwright downloads itself
+ * ====================================
+ *
+ * The Playwright connector runs a pinned @playwright/mcp (PLAYWRIGHT_MCP_PACKAGE), whose
+ * playwright-core needs one build of each browser (its browsers.json: PLAYWRIGHT_BUILDS).
+ * `npx -y @playwright/mcp@ install-browser ` puts a build in Playwright's cache
+ * (`PLAYWRIGHT_BROWSERS_PATH`, else `~/.cache/ms-playwright` on Linux (`$XDG_CACHE_HOME`),
+ * `~/Library/Caches/ms-playwright` on macOS, `%LOCALAPPDATA%\ms-playwright` on Windows), one folder
+ * per build (`firefox-1553`) holding `INSTALLATION_COMPLETE` once unpacked. The picker lists
+ * Firefox and WebKit as "Playwright's Firefox" / "Playwright's WebKit": usable once their build is
+ * in the cache, otherwise disabled with a download button. Playwright's Chromium is the picker's
+ * default entry, so it isn't listed here.
+ */
+
+import { readdir, access } from 'fs/promises';
+import type { BrowserProfile, DownloadableBrowser } from '../../shared/types/browser-profiles';
+import { pathApi, type BrowserOs } from './locations';
+
+/** The Playwright MCP server's version: bump it together with PLAYWRIGHT_BUILDS */
+export const PLAYWRIGHT_MCP_VERSION = '0.0.83';
+/** What npx runs for the Playwright connector */
+export const PLAYWRIGHT_MCP_PACKAGE = `@playwright/mcp@${PLAYWRIGHT_MCP_VERSION}`;
+
+/** A build Playwright downloads: its cache folder (`-`) and where its executable sits, per OS */
+interface PlaywrightBuild {
+ /** Cache folders of the build, the first one that holds a finished download counts */
+ folders: Partial> & { default: string[] };
+ executables: Record;
+}
+
+/**
+ * The builds @playwright/mcp@0.0.83 needs (playwright-core's browsers.json: chromium 1247 is
+ * Chrome for Testing 155, firefox 1553 is Firefox 156, webkit 2368 is WebKit 26.6, 2251 on macOS 14,
+ * in its own folder)
+ */
+export const PLAYWRIGHT_BUILDS: Readonly> = {
+ chromium: {
+ folders: { default: ['chromium-1247'] },
+ executables: {
+ linux: [['chrome-linux64', 'chrome'], ['chrome-linux-arm64', 'chrome']],
+ macos: [
+ ['chrome-mac-arm64', 'Google Chrome for Testing.app', 'Contents', 'MacOS', 'Google Chrome for Testing'],
+ ['chrome-mac-x64', 'Google Chrome for Testing.app', 'Contents', 'MacOS', 'Google Chrome for Testing'],
+ ],
+ windows: [['chrome-win64', 'chrome.exe']],
+ },
+ },
+ firefox: {
+ folders: { default: ['firefox-1553'] },
+ executables: {
+ linux: [['firefox', 'firefox']],
+ macos: [['firefox', 'Nightly.app', 'Contents', 'MacOS', 'firefox']],
+ windows: [['firefox', 'firefox.exe']],
+ },
+ },
+ webkit: {
+ // macOS 14's override goes to `__special-` (dashes as `_`)
+ folders: { default: ['webkit-2368'], macos: ['webkit-2368', 'webkit_mac14_arm64_special-2251', 'webkit_mac14_special-2251'] },
+ executables: {
+ linux: [['pw_run.sh']],
+ macos: [['pw_run.sh']],
+ windows: [['Playwright.exe']],
+ },
+ },
+};
+
+/** Written into a build's folder once it is unpacked */
+const INSTALLATION_COMPLETE = 'INSTALLATION_COMPLETE';
+
+/** The command a download button runs (opened in a terminal by the main process) */
+export function playwrightInstallCommand(browser: DownloadableBrowser): string {
+ return `npx -y ${PLAYWRIGHT_MCP_PACKAGE} install-browser ${browser}`;
+}
+
+export interface ManagedScanContext {
+ os: BrowserOs;
+ home: string;
+ env: Record;
+ /** A path of the OS's table -> the path this process reads it with */
+ toHost: (p: string) => string;
+}
+
+/** Playwright's cache folder where tools run (`PLAYWRIGHT_BROWSERS_PATH=0`, a folder inside the package, can't be known here) */
+export function playwrightCacheDir({ os, home, env }: ManagedScanContext): string {
+ const p = pathApi(os);
+ const custom = env.PLAYWRIGHT_BROWSERS_PATH;
+ if (custom && custom !== '0' && p.isAbsolute(custom)) return custom;
+ if (os === 'windows') return p.join(env.LOCALAPPDATA || p.join(home, 'AppData', 'Local'), 'ms-playwright');
+ if (os === 'macos') return p.join(home, 'Library', 'Caches', 'ms-playwright');
+ const cache = env.XDG_CACHE_HOME && p.isAbsolute(env.XDG_CACHE_HOME) ? env.XDG_CACHE_HOME : p.join(home, '.cache');
+ return p.join(cache, 'ms-playwright');
+}
+
+async function exists(p: string): Promise {
+ try {
+ await access(p);
+ return true;
+ } catch {
+ return false;
+ }
+}
+
+/** Whether an executable is one of Playwright's own builds (in its cache folder, `ms-playwright`) */
+export function isPlaywrightBuild(executablePath: string): boolean {
+ return /[\\/]ms-playwright[\\/]/.test(executablePath);
+}
+
+/** The executable of a downloaded build the pinned server needs (a path where tools run), or undefined */
+export async function findManagedBrowser(browser: DownloadableBrowser, context: ManagedScanContext): Promise {
+ const p = pathApi(context.os);
+ const root = playwrightCacheDir(context);
+ const build = PLAYWRIGHT_BUILDS[browser];
+ let entries: string[];
+ try {
+ entries = await readdir(context.toHost(root));
+ } catch {
+ return undefined;
+ }
+ for (const folder of build.folders[context.os] ?? build.folders.default) {
+ if (!entries.includes(folder)) continue;
+ const dir = p.join(root, folder);
+ // Still being unpacked (or an interrupted download)
+ if (!(await exists(context.toHost(p.join(dir, INSTALLATION_COMPLETE))))) continue;
+ for (const parts of build.executables[context.os]) {
+ const executable = p.join(dir, ...parts);
+ if (await exists(context.toHost(executable))) return executable;
+ }
+ }
+ return undefined;
+}
+
+const MANAGED_LISTED: { browser: DownloadableBrowser; name: string }[] = [
+ { browser: 'firefox', name: 'Firefox' },
+ { browser: 'webkit', name: 'WebKit' },
+];
+
+/** "Playwright's Firefox" and "Playwright's WebKit" for the picker: usable when downloaded, else downloadable */
+export async function scanManagedBrowsers(context: ManagedScanContext): Promise {
+ return Promise.all(MANAGED_LISTED.map(async ({ browser, name }) => {
+ const executablePath = await findManagedBrowser(browser, context);
+ return {
+ id: `playwright:${browser}`,
+ browser,
+ engine: browser,
+ managed: true,
+ profileName: name,
+ userDataDir: '',
+ profilePath: '',
+ ...(executablePath ? { executablePath, usable: true } : { usable: false, disabledReason: 'not-downloaded' as const, downloadable: browser }),
+ };
+ }));
+}
diff --git a/src/main/browser-profiles/parsing.ts b/src/main/browser-profiles/parsing.ts
new file mode 100644
index 000000000..2ba586525
--- /dev/null
+++ b/src/main/browser-profiles/parsing.ts
@@ -0,0 +1,94 @@
+/**
+ * Reading browsers' profile lists: Chromium's `Local State` (profile.info_cache) and Firefox's
+ * profiles.ini. Pure; unreadable input gives no profiles.
+ */
+
+import path from 'path';
+
+type PathApi = typeof path.posix;
+
+export interface ChromiumProfileEntry {
+ /** The profile's folder inside the user data folder (`Default`, `Profile 1`) */
+ directory: string;
+ name: string;
+ email?: string;
+}
+
+/** Profiles in a Chromium `Local State` file, in the browser's own order */
+export function parseChromiumLocalState(json: string): ChromiumProfileEntry[] {
+ let state: unknown;
+ try {
+ state = JSON.parse(json);
+ } catch {
+ return [];
+ }
+ const profile = (state as { profile?: { info_cache?: unknown; profiles_order?: unknown } } | null)?.profile;
+ const cache = profile?.info_cache;
+ if (!cache || typeof cache !== 'object' || Array.isArray(cache)) return [];
+ const entries = cache as Record;
+ const order = Array.isArray(profile.profiles_order)
+ ? profile.profiles_order.filter((dir): dir is string => typeof dir === 'string' && dir in entries)
+ : [];
+ const rest = Object.keys(entries).filter((dir) => !order.includes(dir)).sort((a, b) => a.localeCompare(b));
+ return [...order, ...rest].map((directory) => {
+ const info = entries[directory] ?? {};
+ const name = typeof info.name === 'string' && info.name.trim() ? info.name.trim() : directory;
+ const email = typeof info.user_name === 'string' && info.user_name.trim() ? info.user_name.trim() : undefined;
+ return { directory, name, ...(email ? { email } : {}) };
+ });
+}
+
+export interface FirefoxProfileEntry {
+ name: string;
+ /** The profile's folder */
+ path: string;
+ /** The folder's own name, which tells profiles apart */
+ folder: string;
+ /** The profile Firefox opens by default */
+ isDefault: boolean;
+}
+
+/** INI sections: name -> key/value pairs */
+function parseIni(text: string): Map> {
+ const sections = new Map>();
+ let current: Record | null = null;
+ for (const raw of text.replace(/^\uFEFF/, '').split(/\r?\n/)) {
+ const line = raw.trim();
+ if (!line || line.startsWith(';') || line.startsWith('#')) continue;
+ const header = /^\[(.+)\]$/.exec(line);
+ if (header) {
+ current = {};
+ sections.set(header[1].trim(), current);
+ continue;
+ }
+ const eq = line.indexOf('=');
+ if (current && eq > 0) current[line.slice(0, eq).trim()] = line.slice(eq + 1).trim();
+ }
+ return sections;
+}
+
+/**
+ * Profiles in a Firefox profiles.ini. Relative paths (always written with `/`) are resolved
+ * against `iniDir` with `pathApi` (the paths of the OS the file belongs to)
+ */
+export function parseFirefoxProfilesIni(text: string, iniDir: string, pathApi: PathApi = path): FirefoxProfileEntry[] {
+ const sections = parseIni(text);
+ // Newer Firefox records each install's default in an [Install] section
+ const installDefaults = new Set(
+ [...sections].filter(([name]) => name.startsWith('Install')).map(([, values]) => values.Default).filter(Boolean)
+ );
+ const profiles: FirefoxProfileEntry[] = [];
+ for (const [name, values] of sections) {
+ if (!/^Profile\d+$/.test(name) || !values.Path) continue;
+ const relative = values.IsRelative !== '0';
+ const profilePath = relative ? pathApi.join(iniDir, ...values.Path.split('/')) : values.Path;
+ const folder = pathApi.basename(profilePath);
+ profiles.push({
+ name: values.Name || folder,
+ path: profilePath,
+ folder,
+ isDefault: installDefaults.size > 0 ? installDefaults.has(values.Path) : values.Default === '1',
+ });
+ }
+ return profiles.sort((a, b) => Number(b.isDefault) - Number(a.isDefault) || a.name.localeCompare(b.name));
+}
diff --git a/src/main/browser-profiles/profile-copy.ts b/src/main/browser-profiles/profile-copy.ts
new file mode 100644
index 000000000..4a8ef911e
--- /dev/null
+++ b/src/main/browser-profiles/profile-copy.ts
@@ -0,0 +1,751 @@
+/**
+ * Copies of browser profiles for Playwright runs
+ * ==============================================
+ *
+ * A run never drives the user's real profile folder: Chrome 136+ refuses remote debugging on its
+ * default user data folder, and a browser that is open holds a lock on it. Each run gets a copy in
+ * the app's own data folder, `/browser-profiles///` (a slot per
+ * task run or chat turn), so parallel runs never share a folder. Copies stay out of the project:
+ * they hold cookies and sign-ins, and the project is what Claude Code sessions (the read-only
+ * Claude chat too) can read. In WSL the browsers are Linux ones, so the copies live in the
+ * distribution's home (`~/.cache/workbench/browser-profiles`), where the browser reads them
+ * natively. A browser that runs confined in its snap (snap Chromium, locations.ts) may write only
+ * its own `~/snap/`, so its copies live in `~/snap//common/workbench-profiles`. Caches,
+ * locks, the session to restore and Firefox's Sync account are left out; files a running browser
+ * keeps locked (Windows) are skipped, so closing the browser first copies every sign-in. The folders
+ * are private (0700) where the filesystem keeps modes; in WSL they are made private from inside
+ * the distribution, since modes set over `\\wsl.localhost` don't apply.
+ *
+ * Each copy names the Workbench process that made it (folder-owner.ts's OWNER_FILE: pid, plus the process's start
+ * on Linux), since two Workbench processes can share the data folder (`npm run dev` next to the
+ * installed app). The owner refreshes the file's time while the copy is in use, so where a
+ * process can't be told from one that later took its id (off Linux), a claim not refreshed for an
+ * hour has ended. Copies no live run uses are removed: at startup (all of them, in every place
+ * above, and on Windows also in a running WSL distribution's home after a switch back from WSL,
+ * except copies another running Workbench owns), on quit (those of runs still going, such as
+ * chat turns), at once when no one chooses their profile any more, and after a day
+ * otherwise; a copy whose owner is another live Workbench process is never swept.
+ *
+ * Each profile also has one saved copy (`/_saved//