Beautiful, AI-native markdown IDE and LLM wiki
TypeScript 2nd-brainagent-skillsclaudecodexcompany-braindocsknowledge-knowledge-baseknowledge-managementllmllm-wikillm-wiki-karpathymarkdownmarkdown-editormdmdxnotespkmsecond-brainskills
Install the agent browser outside the chat's tree (PRD-9332) (#6190)
Andrew Mikofalvy7e09fbb5acd3
diff --git a/.changeset/prd-9332-browser-install-step.md b/.changeset/prd-9332-browser-install-step.mdnew file mode 100644index 000000000..70b152493--- /dev/null+++ b/.changeset/prd-9332-browser-install-step.md@@ -0,0 +1,5 @@+---+"@inkeep/open-knowledge": patch+---++Closing an agent chat while its browser was still installing no longer leaves a broken copy that keeps later chats from getting a browser.diff --git a/docs/content/features/editor.mdx b/docs/content/features/editor.mdxindex bba5b8142..2eea07f3a 100644--- a/docs/content/features/editor.mdx+++ b/docs/content/features/editor.mdx@@ -299,7 +299,7 @@ In-app agent chats in the Agents panel follow the same rule and the same settingShell commands in an in-app chat still prompt one at a time. When the command an agent asks to run is read-only (listing, reading, and searching files, `git status`, `log`, `diff` and other read-only git subcommands, and plain `curl` GET probes), the prompt adds **Allow read-only commands while this chat is open**. Choosing it approves that command and every later read-only command in the same chat without a prompt. A pipeline or compound command counts as read-only only when every stage does, and output can go only to `/dev/null` or into another stream (`2>&1`). Globs and variables are fine in the arguments of commands that cannot change anything, such as `cat`, `ls`, `grep` and `echo`, but `git`, `curl`, `find`, `sort` and the other commands whose options the classifier checks prompt when handed one. Command substitution, and anything else the classifier cannot prove read-only, keeps prompting. The grant shows as **Read-only allowed** on the agent settings trigger, lasts while the chat stays open (a restarted server prompts again), and **Ask again before read-only commands** in that menu revokes it.-In-app Claude Code and Codex chats can also get a browser they can drive. Turn on **Settings → Preferences → “Let agent chats use a browser”** ([`agents.browserTools`](../reference/configuration.mdx), off by default) and each Claude Code or Codex chat you start afterwards gets the [Playwright MCP](https://github.com/microsoft/playwright-mcp) server, so the agent can open pages, click, type, and take screenshots, for example to check a site it just built. Other agents' chats don't get it, because OpenKnowledge can't tell their browser actions apart from their other tools. It needs Google Chrome and Node.js installed. OpenKnowledge starts the server with the `npx` on the agent's own PATH, from a folder of its own outside the project, so npm never uses the project's `package.json`, `node_modules`, or `.npmrc`; if it can't find a usable `npx`, or the browser can't be set up, the chat starts without the browser and says so in the conversation, and the server log has the details. Without Chrome, the agent's browser actions fail with a message that Chrome is missing. The browser opens in its own window (headless on Linux with no display) with a fresh profile kept in memory, so it starts signed out of everything, and pages cannot add tools of their own. Every browser action asks for your approval, with no option to always allow it, unless the agent skips approvals itself: through its mode (the **Agent mode** item in the chat's agent settings menu) or its own permission settings, such as a Claude Code rule that allows the browser's tools. Everything the browser saves, whether or not the agent names the file, goes to a folder OpenKnowledge keeps for the chat under `~/.ok/agent-browser/` (Beta: `~/.ok-beta/agent-browser/`), outside the project, and is removed when you delete the chat. Pages can also carry instructions aimed at the agent, and OpenKnowledge's own read and write tools still run without asking; turn off **Let agents use OpenKnowledge without asking** ([`agents.autoApproveOkTools`](../reference/configuration.mdx)) to approve those too.+In-app Claude Code and Codex chats can also get a browser they can drive. Turn on **Settings → Preferences → “Let agent chats use a browser”** ([`agents.browserTools`](../reference/configuration.mdx), off by default) and each Claude Code or Codex chat you start afterwards gets the [Playwright MCP](https://github.com/microsoft/playwright-mcp) server, so the agent can open pages, click, type, and take screenshots, for example to check a site it just built. Other agents' chats don't get it, because OpenKnowledge can't tell their browser actions apart from their other tools. It needs Google Chrome and Node.js installed. OpenKnowledge starts the server with the `npx` on the agent's own PATH, from a folder of its own outside the project, so npm never uses the project's `package.json`, `node_modules`, or `.npmrc`. It installs the server before the chat starts, so closing the chat during that install can't leave a broken copy in npm's cache. If that install takes longer than two minutes (45 seconds when you resume or retry a chat, change its context window, or finish signing in to its agent), the chat starts without the browser while the install carries on, and chats you start once it finishes get the browser. If it can't find a usable `npx`, or the browser can't be set up, the chat starts without the browser and says so in the conversation, and the server log has the details. Without Chrome, the agent's browser actions fail with a message that Chrome is missing. The browser opens in its own window (headless on Linux with no display) with a fresh profile kept in memory, so it starts signed out of everything, and pages cannot add tools of their own. Every browser action asks for your approval, with no option to always allow it, unless the agent skips approvals itself: through its mode (the **Agent mode** item in the chat's agent settings menu) or its own permission settings, such as a Claude Code rule that allows the browser's tools. Everything the browser saves, whether or not the agent names the file, goes to a folder OpenKnowledge keeps for the chat under `~/.ok/agent-browser/` (Beta: `~/.ok-beta/agent-browser/`), outside the project, and is removed when you delete the chat. Pages can also carry instructions aimed at the agent, and OpenKnowledge's own read and write tools still run without asking; turn off **Let agents use OpenKnowledge without asking** ([`agents.autoApproveOkTools`](../reference/configuration.mdx)) to approve those too.## Tabs and split panesdiff --git a/docs/content/reference/what-open-knowledge-writes.mdx b/docs/content/reference/what-open-knowledge-writes.mdxindex f7588b55f..7a8ec70f4 100644--- a/docs/content/reference/what-open-knowledge-writes.mdx+++ b/docs/content/reference/what-open-knowledge-writes.mdx@@ -195,7 +195,7 @@ Beta writes the `~/.ok/` entries below under `~/.ok-beta/` instead, except the s| `~/.ok/local/installed-skills.json`, `~/.ok/local/skill-placements.json`, `~/.ok/local/skill-move-retained.json`, `~/.ok/skills-lock.json` | The same skill-install markers, placement records, unfinished-scope-move bookkeeping, and import provenance that a project keeps under its own `.ok/`, written under your home directory for Global-scope skills instead. Shared by every product: Beta writes these to `~/.ok/` too | No || `~/.ok/stats.jsonl` | Local "open with AI" handoff stats — local-only, no phone-home | No || `~/.ok/agent-browser/<chat>/` | Only while **Let agent chats use a browser** is on: `npm/`, the folder that chat's browser server starts from, rebuilt each time it launches, and `files/`, everything the browser saves. Removed when you delete the chat in OpenKnowledge; turning the setting off keeps it, and nothing else clears it, so delete the folder yourself to remove every chat's saved files at once | No |-| `_npx/<hash>/` in the npm cache that launch uses: your own npm cache (`~/.npm` unless your `npm_config_cache` says otherwise) when the agent runs through your system npx, or OpenKnowledge's managed Node.js runtime cache at `~/.ok/runtimes/cache/node` when no usable system Node.js was found and the agent runs on that runtime | Deleted, not written: when a catalog-managed in-app agent that OpenKnowledge launched through npx fails because npm reports that entry is missing its `package.json`, OpenKnowledge removes that one directory so npx rebuilds it on the single relaunch that follows. Never for custom agent commands or uv-managed adapters | No |+| `_npx/<hash>/` in the npm cache that launch uses: your own npm cache (`~/.npm` unless your `npm_config_cache` says otherwise) when the agent runs through your system npx, or OpenKnowledge's managed Node.js runtime cache at `~/.ok/runtimes/cache/node` when no usable system Node.js was found and the agent runs on that runtime | Deleted, not written: when a catalog-managed in-app agent that OpenKnowledge launched through npx fails because npm reports that entry is missing its `package.json`, OpenKnowledge removes that one directory so npx rebuilds it on the single relaunch that follows. The same applies, with one reinstall, to the entry of the browser server a Claude Code or Codex chat starts while **Let agent chats use a browser** is on. Never for custom agent commands or uv-managed adapters | No || `~/.ok/themes/` | Your saved color themes from the [Themes plugin](../plugins/themes.mdx), one Tinted Theming base16 YAML file per theme, written when you create or edit a theme | No || `~/.ok/mcp-status.json` | First-launch MCP consent record | No || `~/.ok/logs/`, `~/.ok/bug-reports/` | Desktop and CLI logs, and bug-report bundles from `ok bug-report` and the app's **Help → Report a bug…** dialog (`ok diagnose bundle` writes into the project, under `.ok/local/diagnostics/`). Each report from the dialog also gets a small YAML record holding its send state and a secret-redacted copy of the note you wrote, so report history can still show what a report was about. The zip is deleted once the report is sent; the record is kept, and both go when you delete the report from report history. If that record ever can't be read back, OpenKnowledge leaves it exactly as it is rather than overwriting your note, and writes a second tiny `.sent.yaml` file beside it when a report does send, so history still shows it as sent instead of offering to send it again | No |@@ -335,7 +335,7 @@ Beta writes the `~/.ok/` entries below under `~/.ok-beta/` instead, except the s| `~/.ok/local/installed-skills.json`, `~/.ok/local/skill-placements.json`, `~/.ok/local/skill-move-retained.json`, `~/.ok/skills-lock.json` | The same skill-install markers, placement records, unfinished-scope-move bookkeeping, and import provenance that a project keeps under its own `.ok/`, written under your home directory for Global-scope skills instead. Shared by every product: Beta writes these to `~/.ok/` too | No || `~/.ok/stats.jsonl` | Local "open with AI" handoff stats — local-only, no phone-home | No || `~/.ok/agent-browser/<chat>/` | Only while **Let agent chats use a browser** is on: `npm/`, the folder that chat's browser server starts from, rebuilt each time it launches, and `files/`, everything the browser saves. Removed when you delete the chat in OpenKnowledge; turning the setting off keeps it, and nothing else clears it, so delete the folder yourself to remove every chat's saved files at once | No |-| `_npx/<hash>/` in the npm cache that launch uses: your own npm cache (`~/.npm` unless your `npm_config_cache` says otherwise) when the agent runs through your system npx, or OpenKnowledge's managed Node.js runtime cache at `~/.ok/runtimes/cache/node` when no usable system Node.js was found and the agent runs on that runtime | Deleted, not written: when a catalog-managed in-app agent that OpenKnowledge launched through npx fails because npm reports that entry is missing its `package.json`, OpenKnowledge removes that one directory so npx rebuilds it on the single relaunch that follows. Never for custom agent commands or uv-managed adapters | No |+| `_npx/<hash>/` in the npm cache that launch uses: your own npm cache (`~/.npm` unless your `npm_config_cache` says otherwise) when the agent runs through your system npx, or OpenKnowledge's managed Node.js runtime cache at `~/.ok/runtimes/cache/node` when no usable system Node.js was found and the agent runs on that runtime | Deleted, not written: when a catalog-managed in-app agent that OpenKnowledge launched through npx fails because npm reports that entry is missing its `package.json`, OpenKnowledge removes that one directory so npx rebuilds it on the single relaunch that follows. The same applies, with one reinstall, to the entry of the browser server a Claude Code or Codex chat starts while **Let agent chats use a browser** is on. Never for custom agent commands or uv-managed adapters | No || `~/.ok/themes/` | Your saved color themes from the [Themes plugin](../plugins/themes.mdx), one Tinted Theming base16 YAML file per theme, written when you create or edit a theme | No || `~/.ok/logs/` | CLI logs (`cli.<date>.log`), size- and age-capped | No || `~/.ok/bug-reports/` | Bug-report bundles from `ok bug-report` — the desktop app's **Help → Report a bug…** dialog writes here too (`ok diagnose bundle` writes into the project, under `.ok/local/diagnostics/`). A report filed from the dialog also leaves a small YAML record beside its bundle, holding the report's send state and a secret-redacted copy of the note you wrote so report history can name it. That record outlives the bundle: the zip is deleted once the report is sent, and the record is kept until you delete the report from report history. If the record ever can't be read back, OpenKnowledge leaves it exactly as it is rather than overwriting your note, and writes a second tiny `.sent.yaml` file beside it when a report does send. That marker holds only the send time and the report's reference, never your note, and it is removed with the rest of the report | No |diff --git a/knip.config.ts b/knip.config.tsindex 0004a763a..69344114d 100644--- a/knip.config.ts+++ b/knip.config.ts@@ -149,15 +149,11 @@ export default {'packages/server': {entry: ['src/**/*.test.ts', 'src/parse-worker.ts'],project: 'src/**',- ignoreDependencies: [- '@types/shell-quote',- ],+ ignoreDependencies: ['@types/shell-quote'],},'packages/cli': {entry: ['src/**/*.test.ts', 'scripts/*.ts', 'tests/**/*.ts', 'src/parse-worker.ts'],- ignoreDependencies: [- 'yjs',- ],+ ignoreDependencies: ['yjs'],},'packages/desktop': {entry: [diff --git a/packages/app/tests/integration/bug3-source-mode-writeback.test.ts b/packages/app/tests/integration/bug3-source-mode-writeback.test.tsindex 4549c74b3..a50b00123 100644--- a/packages/app/tests/integration/bug3-source-mode-writeback.test.ts+++ b/packages/app/tests/integration/bug3-source-mode-writeback.test.ts@@ -1,4 +1,3 @@-import { readFileSync } from 'node:fs';import { join } from 'node:path';import { setTimeout as wait } from 'node:timers/promises';diff --git a/packages/app/tests/integration/indented-jsx-byte-sacred.test.ts b/packages/app/tests/integration/indented-jsx-byte-sacred.test.tsindex 4fc2c11f9..6fcdc23f2 100644--- a/packages/app/tests/integration/indented-jsx-byte-sacred.test.ts+++ b/packages/app/tests/integration/indented-jsx-byte-sacred.test.ts@@ -1,4 +1,3 @@-import { setTimeout as wait } from 'node:timers/promises';import { normalizeBridge } from '@inkeep/open-knowledge-core';import { updateYFragment } from '@tiptap/y-tiptap';diff --git a/packages/app/tests/integration/interior-edit-freshness.test.ts b/packages/app/tests/integration/interior-edit-freshness.test.tsindex 9f2f6feb6..40b5cdfd6 100644--- a/packages/app/tests/integration/interior-edit-freshness.test.ts+++ b/packages/app/tests/integration/interior-edit-freshness.test.ts@@ -1,4 +1,3 @@-import { setTimeout as wait } from 'node:timers/promises';import { updateYFragment, yXmlFragmentToProseMirrorRootNode } from '@tiptap/y-tiptap';import { afterAll, beforeAll, describe, expect, test } from 'vitest';diff --git a/packages/app/tests/integration/keystroke-cadence-danger-space.test.ts b/packages/app/tests/integration/keystroke-cadence-danger-space.test.tsindex 2a085742b..93666af70 100644--- a/packages/app/tests/integration/keystroke-cadence-danger-space.test.ts+++ b/packages/app/tests/integration/keystroke-cadence-danger-space.test.ts@@ -1,4 +1,3 @@-import { setTimeout as wait } from 'node:timers/promises';import { updateYFragment, yXmlFragmentToProseMirrorRootNode } from '@tiptap/y-tiptap';import { afterAll, beforeAll, describe, expect, test } from 'vitest';diff --git a/packages/app/tests/integration/producer-guard-wiring.test.ts b/packages/app/tests/integration/producer-guard-wiring.test.tsindex 878d5196b..867598d34 100644--- a/packages/app/tests/integration/producer-guard-wiring.test.ts+++ b/packages/app/tests/integration/producer-guard-wiring.test.ts@@ -1,4 +1,3 @@-import { setTimeout as wait } from 'node:timers/promises';import { updateYFragment, yXmlFragmentToProseMirrorRootNode } from '@tiptap/y-tiptap';import { afterAll, beforeAll, describe, expect, test } from 'vitest';diff --git a/packages/app/tests/integration/qa-039-reconciliation-counters-http.test.ts b/packages/app/tests/integration/qa-039-reconciliation-counters-http.test.tsindex 4ada3cf26..0970ac12f 100644--- a/packages/app/tests/integration/qa-039-reconciliation-counters-http.test.ts+++ b/packages/app/tests/integration/qa-039-reconciliation-counters-http.test.ts@@ -1,4 +1,3 @@-import { randomUUID } from 'node:crypto';import { afterEach, describe, expect, test } from 'vitest';import { agentWriteMd, createTestServer, type TestServer } from './test-harness';diff --git a/packages/app/tests/integration/qa-045-restore-after-gc.test.ts b/packages/app/tests/integration/qa-045-restore-after-gc.test.tsindex cbe2b705f..b632185e1 100644--- a/packages/app/tests/integration/qa-045-restore-after-gc.test.ts+++ b/packages/app/tests/integration/qa-045-restore-after-gc.test.ts@@ -1,4 +1,3 @@-import { execFileSync } from 'node:child_process';import { randomUUID } from 'node:crypto';import { join } from 'node:path';diff --git a/packages/app/tests/integration/qa-050-rollback-undo-shipped-path.test.ts b/packages/app/tests/integration/qa-050-rollback-undo-shipped-path.test.tsindex 89bc9b4d9..c530ce4ba 100644--- a/packages/app/tests/integration/qa-050-rollback-undo-shipped-path.test.ts+++ b/packages/app/tests/integration/qa-050-rollback-undo-shipped-path.test.ts@@ -1,4 +1,3 @@-import { randomUUID } from 'node:crypto';import { afterAll, afterEach, beforeAll, describe, expect, test } from 'vitest';import type * as Y from 'yjs';diff --git a/packages/app/tests/integration/undo-after-rollback.test.ts b/packages/app/tests/integration/undo-after-rollback.test.tsindex a78aeb0e4..d3767adc9 100644--- a/packages/app/tests/integration/undo-after-rollback.test.ts+++ b/packages/app/tests/integration/undo-after-rollback.test.ts@@ -1,4 +1,3 @@-import { ROLLBACK_ORIGIN } from '@inkeep/open-knowledge-server';import { afterAll, beforeAll, describe, expect, test } from 'vitest';import * as Y from 'yjs';diff --git a/packages/app/tests/integration/undo-recycle-reset.test.ts b/packages/app/tests/integration/undo-recycle-reset.test.tsindex e7cc69c3f..b076f955c 100644--- a/packages/app/tests/integration/undo-recycle-reset.test.ts+++ b/packages/app/tests/integration/undo-recycle-reset.test.ts@@ -1,4 +1,3 @@-import { writeFileSync } from 'node:fs';import { join } from 'node:path';import { setTimeout as wait } from 'node:timers/promises';diff --git a/packages/app/tests/integration/undo-rederive-survival.test.ts b/packages/app/tests/integration/undo-rederive-survival.test.tsindex 9ddcd0730..7935e35f8 100644--- a/packages/app/tests/integration/undo-rederive-survival.test.ts+++ b/packages/app/tests/integration/undo-rederive-survival.test.ts@@ -1,4 +1,3 @@-import { prependFrontmatter } from '@inkeep/open-knowledge-core';import { Plugin, PluginKey } from '@tiptap/pm/state';import { updateYFragment, yXmlFragmentToProseMirrorRootNode } from '@tiptap/y-tiptap';diff --git a/packages/core/src/bridge/compose.ts b/packages/core/src/bridge/compose.tsindex 2a597ec3d..f4cc8a286 100644--- a/packages/core/src/bridge/compose.ts+++ b/packages/core/src/bridge/compose.ts@@ -1,4 +1,3 @@-import { prependFrontmatter, stripFrontmatter } from '../extensions/frontmatter.ts';export type ComposeAdjustment = 'none' | 'body' | 'frontmatter' | 'unresolved';diff --git a/packages/core/src/bridge/doc-boundary-space.ts b/packages/core/src/bridge/doc-boundary-space.tsindex ffd8fce06..e7e63f43d 100644--- a/packages/core/src/bridge/doc-boundary-space.ts+++ b/packages/core/src/bridge/doc-boundary-space.ts@@ -1,4 +1,3 @@-import { FRONTMATTER_RE, stripFrontmatter } from '../extensions/frontmatter.ts';import { carriedEdgeEmpties, type DocEdgeEmpties } from '../markdown/doc-edge-blank-runs.ts';diff --git a/packages/core/src/markdown/comment-promoter.ts b/packages/core/src/markdown/comment-promoter.tsindex fb0ba5a7c..fc267cbea 100644--- a/packages/core/src/markdown/comment-promoter.ts+++ b/packages/core/src/markdown/comment-promoter.ts@@ -1,4 +1,3 @@-import type { Nodes, Paragraph, PhrasingContent, Root, RootContent, Text } from 'mdast';import { SKIP, visit } from 'unist-util-visit';import type { VFile } from 'vfile';diff --git a/packages/core/src/markdown/merged-walker.ts b/packages/core/src/markdown/merged-walker.tsindex fa3cfcd86..bfd7e3109 100644--- a/packages/core/src/markdown/merged-walker.ts+++ b/packages/core/src/markdown/merged-walker.ts@@ -1,4 +1,3 @@-import type { Nodes, Parent, Root } from 'mdast';import { SKIP, visit } from 'unist-util-visit';import type { VFile } from 'vfile';diff --git a/packages/core/src/markdown/safe-url.ts b/packages/core/src/markdown/safe-url.tsindex 8be632ba4..4d3250d3a 100644--- a/packages/core/src/markdown/safe-url.ts+++ b/packages/core/src/markdown/safe-url.ts@@ -1,4 +1,3 @@-export const SAFE_URL_SCHEMES = ['https', 'http', 'mailto', 'tel', 'ftp', 'sms'] as const;const SCHEME_ALT = SAFE_URL_SCHEMES.map((s) => `${s}:`).join('|');diff --git a/packages/server/src/acp/browser-install-teardown.integration.test.ts b/packages/server/src/acp/browser-install-teardown.integration.test.tsnew file mode 100644index 000000000..df99bfaa0--- /dev/null+++ b/packages/server/src/acp/browser-install-teardown.integration.test.ts@@ -0,0 +1,359 @@+import { spawnSync } from 'node:child_process';+import { existsSync, mkdtempSync, readdirSync, readFileSync, rmSync } from 'node:fs';+import { join } from 'node:path';+import type {+ ThreadEvent,+ ThreadServerFrame,+} from '@inkeep/open-knowledge-core/acp/thread-protocol';+import { describe, expect, test } from 'vitest';+import type { AgentSessionManager } from '../agent-sessions.ts';+import { getLogger } from '../logger.ts';+import { readProcessState } from '../process-scan.ts';+import { waitWithinTestBudget } from '../wait-within-test-budget.test-helper.ts';+import { AGENT_BROWSER_MCP_PACKAGE } from './browser-mcp.ts';+import {+ type HeldInstallRegistry,+ withHeldInstallRegistry,+} from './held-install-registry.test-helper.ts';+import { resetAcquisitionCache } from './launch.ts';+import { AcpPermissionStore } from './permissions.ts';+import { AcpRegistry, type RegistryAgent } from './registry.ts';+import { AcpThreadManager } from './thread-manager.ts';++const log = getLogger('browser-install-teardown-test');++const WAIT = { timeoutMs: 60_000 };+const TARBALL_ARRIVES_AFTER_MS = 10_000;+const BROWSER_NAME = AGENT_BROWSER_MCP_PACKAGE.slice(0, AGENT_BROWSER_MCP_PACKAGE.lastIndexOf('@'));++const sessionManager = {+ getSession: async () => {+ throw new Error('the held agent never uses client fs');+ },+ closeAllForAgent: async () => {},+} as unknown as AgentSessionManager;++function browserManager(held: HeldInstallRegistry): AcpThreadManager {+ const localDir = mkdtempSync(join(held.home, 'local-'));+ const contentDir = mkdtempSync(join(held.home, 'content-'));+ const agent: RegistryAgent = {+ id: 'claude-acp',+ name: 'Claude Code',+ version: '1.0.0',+ distribution: { npx: { package: held.npmPackage } },+ };+ return new AcpThreadManager({+ contentDir,+ localDir,+ globalDir: mkdtempSync(join(held.home, 'global-')),+ registry: new AcpRegistry({+ localDir,+ log,+ fetchImpl: (async () => new Response(JSON.stringify({ agents: [agent] }))) as typeof fetch,+ }),+ permissions: new AcpPermissionStore(localDir, log),+ sessionManager,+ isExcludedPath: () => false,+ isIgnoredPath: () => false,+ log,+ resolveLoginShellPath: async () => null,+ projectSkillSourceDir: null,+ agentBrowserTools: () => true,+ });+}++function descendantsOf(root: number): number[] {+ const ps = spawnSync('ps', ['-A', '-o', 'pid=,ppid='], { encoding: 'utf8' });+ if (ps.error !== undefined) throw ps.error;+ const children = new Map<number, number[]>();+ for (const line of ps.stdout.split('\n')) {+ const [pid, ppid] = line.trim().split(/\s+/).map(Number);+ if (pid === undefined || ppid === undefined || !Number.isInteger(pid) || pid === ps.pid) {+ continue;+ }+ children.set(ppid, [...(children.get(ppid) ?? []), pid]);+ }+ const found: number[] = [];+ const queue = [root];+ for (let next = queue.shift(); next !== undefined; next = queue.shift()) {+ for (const kid of children.get(next) ?? []) {+ found.push(kid);+ queue.push(kid);+ }+ }+ return found;+}++function processEnded(pid: number): boolean {+ const state = readProcessState(pid, {+ onProbeFailure: ({ reason }) => {+ throw new Error(`could not read the state of process ${pid}: ${reason}`);+ },+ });+ return state.status === 'gone' || state.status === 'defunct';+}++function npxEntries(home: string): string[] {+ const npxCache = join(home, 'npm-cache', '_npx');+ return existsSync(npxCache) ? readdirSync(npxCache).map((name) => join(npxCache, name)) : [];+}++function hasManifest(dir: string): boolean {+ return existsSync(join(dir, 'package.json'));+}++function browserEntry(home: string): string | undefined {+ return npxEntries(home).find((entry) => {+ const manifest = join(entry, 'package.json');+ if (!existsSync(manifest)) return false;+ try {+ const { dependencies = {} } = JSON.parse(readFileSync(manifest, 'utf8')) as {+ dependencies?: Record<string, string>;+ };+ return BROWSER_NAME in dependencies;+ } catch {+ return false;+ }+ });+}++function entryOutcome(entry: string) {+ const modules = join(entry, 'node_modules');+ const packages = existsSync(modules)+ ? readdirSync(modules)+ .filter((name) => !name.startsWith('.'))+ .flatMap((name) =>+ name.startsWith('@')+ ? readdirSync(join(modules, name)).map((scoped) => `${name}/${scoped}`)+ : [name],+ )+ : [];+ const snapshot = {+ rootManifest: hasManifest(entry),+ lock: existsSync(join(entry, 'concurrency.lock')),+ packages,+ withoutManifest: packages.filter((name) => !hasManifest(join(modules, name))),+ };+ const complete =+ snapshot.rootManifest &&+ !snapshot.lock &&+ packages.includes(BROWSER_NAME) &&+ snapshot.withoutManifest.length === 0;+ const rolledBack = !snapshot.rootManifest && !snapshot.lock && packages.length === 0;+ return {+ state: complete ? 'complete' : rolledBack ? 'rolled-back' : 'partial',+ ...snapshot,+ };+}++function relayStartedFrom(entry: string): boolean {+ return existsSync(join(entry, 'node_modules', BROWSER_NAME, 'started'));+}++function collect(into: ThreadEvent[]) {+ return (frame: ThreadServerFrame): void => {+ if (frame.op === 'event') into.push(frame.event);+ if (frame.op === 'events') into.push(...frame.events);+ };+}++const TEARDOWNS = [+ {+ teardown: 'the chat is closed',+ run: (manager: AcpThreadManager, threadId: string) => manager.closeThread(threadId),+ },+ {+ teardown: 'the server shuts its chats down',+ run: (manager: AcpThreadManager) => manager.destroy(),+ },+] as const;++describe.skipIf(process.platform === 'win32')(+ "the agent browser's npx package and chat teardown",+ () => {+ test.each(TEARDOWNS)(+ 'the browser npx cache entry ends complete or rolled back when $teardown mid-install',+ async ({ run }) => {+ await withHeldInstallRegistry(async (held) => {+ held.release('npm-dependency');+ const preexisting = new Set(descendantsOf(process.pid));+ const started = new Set<number>();+ const liveSinceStart = (): number[] => {+ const live = descendantsOf(process.pid).filter((pid) => !preexisting.has(pid));+ for (const pid of live) started.add(pid);+ return live;+ };+ const everyStartedProcessEnded = (): boolean =>+ liveSinceStart().length === 0 && [...started].every(processEnded);+ resetAcquisitionCache();+ const manager = browserManager(held);+ try {+ const { threadId } = await manager.createThread({+ agent: { source: 'registry', id: 'claude-acp' },+ });+ await waitWithinTestBudget(+ "npm to request the browser package's held dependency mid-install",+ () => {+ liveSinceStart();+ const status = manager.getInfo(threadId)?.status;+ if (status === 'error' || status === 'exited') {+ throw new Error(`the chat settled as ${status} before npm reached the tarball`);+ }+ return held.requested('browser-dependency') === 1;+ },+ WAIT,+ );+ const installing = npxEntries(held.home).filter((entry) => !hasManifest(entry));+ expect(+ installing,+ 'npm is installing the browser when the teardown begins',+ ).toHaveLength(1);+ const entry = String(installing[0]);++ let teardownSettled = false;+ const teardownStartedAt = Date.now();+ const teardown = run(manager, threadId).finally(() => {+ teardownSettled = true;+ });+ await waitWithinTestBudget(+ 'the teardown to settle or the held tarball to outlast every teardown grace',+ () => {+ liveSinceStart();+ return (+ teardownSettled || Date.now() - teardownStartedAt >= TARBALL_ARRIVES_AFTER_MS+ );+ },+ { timeoutMs: TARBALL_ARRIVES_AFTER_MS + 5_000 },+ );+ held.release('browser-dependency');+ await teardown;+ await waitWithinTestBudget(+ 'every process the chat started to exit',+ everyStartedProcessEnded,+ WAIT,+ );++ const outcome = entryOutcome(entry);+ expect(['complete', 'rolled-back'], JSON.stringify(outcome)).toContain(outcome.state);+ } finally {+ held.release('browser-dependency');+ await manager.destroy();+ await waitWithinTestBudget(+ 'every process the test started to exit',+ everyStartedProcessEnded,+ WAIT,+ );+ }+ });+ },+ 150_000,+ );++ test('a chat repairs a browser entry an earlier teardown left without its manifest', async () => {+ await withHeldInstallRegistry(async (held) => {+ held.release('npm-dependency');+ held.release('browser-dependency');+ resetAcquisitionCache();+ let manager = browserManager(held);+ try {+ const first = await manager.createThread({+ agent: { source: 'registry', id: 'claude-acp' },+ });+ await waitWithinTestBudget(+ 'the first chat to start with its browser installed',+ () => {+ const entry = browserEntry(held.home);+ return (+ manager.getInfo(first.threadId)?.status === 'ready' &&+ entry !== undefined &&+ entryOutcome(entry).state === 'complete' &&+ relayStartedFrom(entry)+ );+ },+ WAIT,+ );+ await manager.destroy();+ const entry = browserEntry(held.home);+ if (entry === undefined) throw new Error('the first chat installed no browser entry');+ rmSync(join(entry, 'node_modules', BROWSER_NAME, 'started'));+ rmSync(join(entry, 'package.json'));+ rmSync(join(entry, 'node_modules', 'ok-held-install-browser-dependency', 'package.json'));++ manager = browserManager(held);+ const second = await manager.createThread({+ agent: { source: 'registry', id: 'claude-acp' },+ });+ const events: ThreadEvent[] = [];+ await manager.subscribe(second.threadId, 0, collect(events));+ await waitWithinTestBudget(+ 'the second chat to start and its browser to run from the repaired entry',+ () => manager.getInfo(second.threadId)?.status === 'ready' && relayStartedFrom(entry),+ WAIT,+ );+ expect(entryOutcome(entry).state).toBe('complete');+ expect(events.filter((event) => event.kind === 'browser_unavailable')).toEqual([]);++ rmSync(entry, { recursive: true, force: true });+ const third = await manager.createThread({+ agent: { source: 'registry', id: 'claude-acp' },+ });+ await waitWithinTestBudget(+ 'a chat started after the whole browser entry was deleted, with its browser running from the rebuilt entry',+ () => manager.getInfo(third.threadId)?.status === 'ready' && relayStartedFrom(entry),+ WAIT,+ );+ expect(entryOutcome(entry).state).toBe('complete');+ } finally {+ await manager.destroy();+ }+ });+ }, 150_000);++ test("a chat installs the browser when npm's cached package data predates the pinned version", async () => {+ await withHeldInstallRegistry(async (held) => {+ held.release('npm-dependency');+ held.release('browser-dependency');+ held.publishBrowser(false);+ resetAcquisitionCache();+ const manager = browserManager(held);+ try {+ const stale = await manager.createThread({+ agent: { source: 'registry', id: 'claude-acp' },+ });+ const staleEvents: ThreadEvent[] = [];+ await manager.subscribe(stale.threadId, 0, collect(staleEvents));+ await waitWithinTestBudget(+ 'a chat to start without the browser while the pinned version is unpublished',+ () =>+ manager.getInfo(stale.threadId)?.status === 'ready' &&+ staleEvents.some((event) => event.kind === 'browser_unavailable'),+ WAIT,+ );++ held.publishBrowser(true);+ const fresh = await manager.createThread({+ agent: { source: 'registry', id: 'claude-acp' },+ });+ const events: ThreadEvent[] = [];+ await manager.subscribe(fresh.threadId, 0, collect(events));+ await waitWithinTestBudget(+ 'a chat to start with the browser once the pinned version is published',+ () => {+ const entry = browserEntry(held.home);+ return (+ manager.getInfo(fresh.threadId)?.status === 'ready' &&+ entry !== undefined &&+ entryOutcome(entry).state === 'complete' &&+ relayStartedFrom(entry)+ );+ },+ WAIT,+ );+ expect(events.filter((event) => event.kind === 'browser_unavailable')).toEqual([]);+ } finally {+ await manager.destroy();+ }+ });+ }, 150_000);+ },+);diff --git a/packages/server/src/acp/browser-mcp.test.ts b/packages/server/src/acp/browser-mcp.test.tsindex 751d085af..4bfe10706 100644--- a/packages/server/src/acp/browser-mcp.test.ts+++ b/packages/server/src/acp/browser-mcp.test.ts@@ -18,12 +18,14 @@ import { afterEach, describe, expect, test } from 'vitest';import { resolveOnPath } from '../git-preflight.ts';import {AGENT_BROWSER_MCP_PACKAGE,+ agentBrowserInstallLaunch,agentBrowserMcpServer,agentGetsBrowser,type BrowserCallEvidence,browserNpxRunnable,identifyBrowserCall,needsReportedToolCall,+ npmCacheOf,prepareAgentBrowserFolders,removeAgentBrowserFolders,resolveBrowserNpx,@@ -310,7 +312,7 @@ describe('agentBrowserMcpServer', () => {'/opt/node/bin/npx','--prefix',FOLDERS.npm,- '-y',+ '--yes=false',AGENT_BROWSER_MCP_PACKAGE,'--isolated','--no-webmcp',@@ -319,7 +321,10 @@ describe('agentBrowserMcpServer', () => {'--file-paths','absolute',],- env: [{ name: 'PATH', value: '/opt/node/bin:/usr/bin' }],+ env: [+ { name: 'PATH', value: '/opt/node/bin:/usr/bin' },+ { name: 'npm_config_prefer_offline', value: 'true' },+ ],});expect(agentBrowserMcpServer({@@ -332,6 +337,22 @@ describe('agentBrowserMcpServer', () => {).toBeNull();});+ test("reads npm's cache from the agent's own npm cache setting", () => {+ const server = agentBrowserMcpServer({+ npx: NPX,+ folders: FOLDERS,+ npmCache: '/runtime/npm-cache',+ platform: 'darwin',+ env: {},+ exists: () => true,+ });+ expect(server?.env).toEqual([+ { name: 'PATH', value: '/opt/node/bin:/usr/bin' },+ { name: 'npm_config_prefer_offline', value: 'true' },+ { name: 'npm_config_cache', value: '/runtime/npm-cache' },+ ]);+ });+test('runs headless only on Linux with no display', () => {const headless = (platform: NodeJS.Platform, env: NodeJS.ProcessEnv) =>agentBrowserMcpServer({@@ -356,21 +377,24 @@ describe('agentBrowserMcpServer', () => {env: processEnv,exists: () => true,})?.env;- const path = { name: 'PATH', value: NPX.path };+ const npm = [+ { name: 'PATH', value: NPX.path },+ { name: 'npm_config_prefer_offline', value: 'true' },+ ];expect(env('linux', { DISPLAY: ':0', XAUTHORITY: '/home/me/.Xauthority', HOME: '/h' })).toEqual([- path,+ ...npm,{ name: 'DISPLAY', value: ':0' },{ name: 'XAUTHORITY', value: '/home/me/.Xauthority' },],);expect(env('linux', { WAYLAND_DISPLAY: 'wayland-0', XDG_RUNTIME_DIR: '/run/user/1' })).toEqual([- path,+ ...npm,{ name: 'WAYLAND_DISPLAY', value: 'wayland-0' },{ name: 'XDG_RUNTIME_DIR', value: '/run/user/1' },]);- expect(env('linux', { XAUTHORITY: '/home/me/.Xauthority' })).toEqual([path]);- expect(env('darwin', { DISPLAY: ':0' })).toEqual([path]);+ expect(env('linux', { XAUTHORITY: '/home/me/.Xauthority' })).toEqual(npm);+ expect(env('darwin', { DISPLAY: ':0' })).toEqual(npm);});test('on Windows runs npm through the node that ships beside npx, or not at all', () => {@@ -393,7 +417,7 @@ describe('agentBrowserMcpServer', () => {npxCli,'--prefix',FOLDERS.npm,- '-y',+ '--yes=false',AGENT_BROWSER_MCP_PACKAGE,]);expect(@@ -812,6 +836,43 @@ describe.skipIf(process.platform === 'win32')('the browser server launch, run fo}, 90_000);});+describe('agentBrowserInstallLaunch', () => {+ test("installs through the browser's npx and PATH, into the cache the browser reads", () => {+ const base = {+ Path: '/elsewhere',+ NPM_CONFIG_CACHE: '/server/cache',+ NPM_CONFIG_PREFER_OFFLINE: 'false',+ HOME: '/home/me',+ };+ expect(agentBrowserInstallLaunch(NPX, '/runtime/npm-cache', 'cached', base)).toEqual({+ cmd: '/opt/node/bin/npx',+ args: [],+ env: {+ HOME: '/home/me',+ PATH: NPX.path,+ npm_config_prefer_offline: 'true',+ npm_config_cache: '/runtime/npm-cache',+ },+ kind: 'npx',+ pathFromOverlay: true,+ });+ expect(agentBrowserInstallLaunch(NPX, null, 'fresh', base).env).toEqual({+ NPM_CONFIG_CACHE: '/server/cache',+ HOME: '/home/me',+ PATH: NPX.path,+ npm_config_prefer_offline: 'false',+ });+ });+});++describe('npmCacheOf', () => {+ test('reads the npm cache setting in any spelling and ignores an empty one', () => {+ expect(npmCacheOf({ NPM_CONFIG_CACHE: '/a' })).toBe('/a');+ expect(npmCacheOf({ npm_config_cache: '' })).toBeNull();+ expect(npmCacheOf({ PATH: '/bin' })).toBeNull();+ });+});+describe('resolveBrowserNpx', () => {test('takes the first PATH whose npx is accepted and skips empty candidates', () => {const seen: string[] = [];diff --git a/packages/server/src/acp/browser-mcp.ts b/packages/server/src/acp/browser-mcp.tsindex 46697dfbf..5804ecb8a 100644--- a/packages/server/src/acp/browser-mcp.ts+++ b/packages/server/src/acp/browser-mcp.ts@@ -5,6 +5,7 @@ import { asRecord, stringField } from '@inkeep/open-knowledge-core/acp/tool-callimport { tracedMkdir, tracedRm, tracedWriteFile } from '../fs-traced.ts';import { resolveOnPath } from '../git-preflight.ts';import { runBrowserRelay } from './browser-relay.ts';+import { mergedEnv, type ResolvedLaunch } from './launch.ts';import { isMintedThreadId } from './thread-persistence.ts';export const AGENT_BROWSER_MCP_PACKAGE = '@playwright/[email protected]';@@ -29,6 +30,9 @@ const DISPLAY_ENV = ['DISPLAY', 'WAYLAND_DISPLAY', 'XAUTHORITY', 'XDG_RUNTIME_DIconst AGENT_BROWSER_DIR = 'agent-browser';+const NPM_CACHE_KEY = 'npm_config_cache';+const NPM_PREFER_OFFLINE_KEY = 'npm_config_prefer_offline';+export function agentGetsBrowser(agentRef: {readonly source: 'registry' | 'custom';readonly id: string;@@ -149,6 +153,34 @@ export function resolveBrowserNpx(return null;}+export function npmCacheOf(env: Readonly<Record<string, string>>): string | null {+ for (const [key, value] of Object.entries(env)) {+ if (key.toLowerCase() === NPM_CACHE_KEY && value !== '') return value;+ }+ return null;+}++export type BrowserPackageData = 'cached' | 'fresh';++export function agentBrowserInstallLaunch(+ npx: ResolvedBrowserNpx,+ npmCache: string | null,+ packageData: BrowserPackageData,+ baseEnv: Readonly<Record<string, string>> = mergedEnv(),+): ResolvedLaunch & { kind: 'npx' } {+ const env: Record<string, string> = {};+ for (const [key, value] of Object.entries(baseEnv)) {+ const lower = key.toLowerCase();+ if (lower === 'path' || lower === NPM_PREFER_OFFLINE_KEY) continue;+ if (npmCache !== null && lower === NPM_CACHE_KEY) continue;+ env[key] = value;+ }+ env.PATH = npx.path;+ env[NPM_PREFER_OFFLINE_KEY] = packageData === 'cached' ? 'true' : 'false';+ if (npmCache !== null) env[NPM_CACHE_KEY] = npmCache;+ return { cmd: npx.npx, args: [], env, kind: 'npx', pathFromOverlay: true };+}+function isFile(path: string): boolean {try {return statSync(path).isFile();@@ -194,6 +226,7 @@ export interface AgentBrowserFolders {export function agentBrowserMcpServer(opts: {npx: ResolvedBrowserNpx;folders: AgentBrowserFolders;+ npmCache?: string | null;platform?: NodeJS.Platform;env?: NodeJS.ProcessEnv;exists?: (path: string) => boolean;@@ -222,7 +255,7 @@ export function agentBrowserMcpServer(opts: {...runtime.npx,'--prefix',opts.folders.npm,- '-y',+ '--yes=false',AGENT_BROWSER_MCP_PACKAGE,'--isolated','--no-webmcp',@@ -232,7 +265,12 @@ export function agentBrowserMcpServer(opts: {'absolute',...(noDisplay ? ['--headless'] : []),],- env: [{ name: 'PATH', value: opts.npx.path }, ...displayEnv],+ env: [+ { name: 'PATH', value: opts.npx.path },+ { name: NPM_PREFER_OFFLINE_KEY, value: 'true' },+ ...(opts.npmCache == null ? [] : [{ name: NPM_CACHE_KEY, value: opts.npmCache }]),+ ...displayEnv,+ ],};}diff --git a/packages/server/src/acp/held-install-registry.test-helper.ts b/packages/server/src/acp/held-install-registry.test-helper.tsindex d85f4a7a6..8683bd19b 100644--- a/packages/server/src/acp/held-install-registry.test-helper.ts+++ b/packages/server/src/acp/held-install-registry.test-helper.ts@@ -5,10 +5,16 @@ import { mkdirSync, readFileSync, writeFileSync } from 'node:fs';import { createServer } from 'node:http';import { join } from 'node:path';import { ZipFile } from 'yazl';+import { AGENT_BROWSER_MCP_PACKAGE } from './browser-mcp.ts';import { withAcquisitionHome } from './package-acquisition.test-helper.ts';import type { RegistryBinaryTarget } from './registry.ts';-type HeldArtifact = 'npm-package' | 'npm-dependency' | 'wheel' | 'binary-archive';+type HeldArtifact =+ | 'npm-package'+ | 'npm-dependency'+ | 'browser-dependency'+ | 'wheel'+ | 'binary-archive';export type HeldInstallRegistry = {home: string;@@ -19,15 +25,20 @@ export type HeldInstallRegistry = {release: (artifact: HeldArtifact) => void;rearm: (artifact: HeldArtifact) => void;answerNotFound: (artifact: HeldArtifact) => void;+ publishBrowser: (published: boolean) => void;};const AGENT_NAME = 'ok-held-install-agent';const DEPENDENCY_NAME = 'ok-held-install-dependency';+const BROWSER_DEPENDENCY_NAME = 'ok-held-install-browser-dependency';const VERSION = '1.0.0';+const UNPINNED_BROWSER_VERSION = '0.0.1';const PUBLISHED = '2020-01-01T00:00:00.000Z';const WHEEL_FILE = `ok_held_install_agent-${VERSION}-py3-none-any.whl`;const NODE_ACP_AGENT = `+const { spawn } = require('node:child_process');+const mcpServers = [];const write = (msg) => process.stdout.write(JSON.stringify(msg) + '\\n');let buffer = '';process.stdin.setEncoding('utf8');@@ -43,6 +54,12 @@ process.stdin.on('data', (chunk) => {if (msg.method === 'initialize') {write({ jsonrpc: '2.0', id: msg.id, result: { protocolVersion: 1, agentCapabilities: {} } });} else if (msg.method === 'session/new') {+ for (const server of msg.params.mcpServers ?? []) {+ if (typeof server.command !== 'string') continue;+ const env = { ...process.env };+ for (const entry of server.env ?? []) env[entry.name] = entry.value;+ mcpServers.push(spawn(server.command, server.args ?? [], { env, stdio: ['pipe', 'ignore', 'ignore'] }));+ }write({ jsonrpc: '2.0', id: msg.id, result: { sessionId: 'held-install-session' } });} else if (msg.id !== undefined && msg.method !== undefined) {write({ jsonrpc: '2.0', id: msg.id, result: {} });@@ -109,29 +126,34 @@ async function wheel(): Promise<Buffer> {return Buffer.concat(chunks);}+function tarballPath(name: string, version: string): string {+ return `/${name}/-/${name.slice(name.lastIndexOf('/') + 1)}-${version}.tgz`;+}+function packument(host: string,name: string,bytes: Buffer,manifest: Record<string, unknown>,published: string,+ version: string = VERSION,): string {return JSON.stringify({name,- 'dist-tags': { latest: VERSION },+ 'dist-tags': { latest: version },versions: {- [VERSION]: {+ [version]: {name,- version: VERSION,+ version,...manifest,dist: {- tarball: `http://${host}/${name}/-/${name}-${VERSION}.tgz`,+ tarball: `http://${host}${tarballPath(name, version)}`,shasum: createHash('sha1').update(bytes).digest('hex'),integrity: `sha512-${createHash('sha512').update(bytes).digest('base64')}`,},},},- time: { [VERSION]: published },+ time: { [version]: published },});}@@ -166,6 +188,37 @@ export async function withHeldInstallRegistry(},'package',);+ const browserAt = AGENT_BROWSER_MCP_PACKAGE.lastIndexOf('@');+ const browserName = AGENT_BROWSER_MCP_PACKAGE.slice(0, browserAt);+ const browserVersion = AGENT_BROWSER_MCP_PACKAGE.slice(browserAt + 1);+ let browserPublished = true;+ const browserManifest = {+ bin: { [browserName.slice(browserName.lastIndexOf('/') + 1)]: 'browser.js' },+ dependencies: { [BROWSER_DEPENDENCY_NAME]: VERSION },+ };+ const browserTarball = tarball(+ sources,+ 'npm-browser',+ {+ 'package.json': JSON.stringify({+ name: browserName,+ version: browserVersion,+ ...browserManifest,+ }),+ 'browser.js':+ "#!/usr/bin/env node\nrequire('node:fs').writeFileSync(require('node:path').join(__dirname, 'started'), '');\nprocess.stdin.resume();\n",+ },+ 'package',+ );+ const browserDependencyTarball = tarball(+ sources,+ 'npm-browser-dependency',+ {+ 'package.json': JSON.stringify({ name: BROWSER_DEPENDENCY_NAME, version: VERSION }),+ 'index.js': 'module.exports = 1;\n',+ },+ 'package',+ );const binaryArchive = tarball(sources,'binary',@@ -193,7 +246,13 @@ export async function withHeldInstallRegistry(opened: Promise<void>;}>();- for (const artifact of ['npm-package', 'npm-dependency', 'wheel', 'binary-archive'] as const) {+ for (const artifact of [+ 'npm-package',+ 'npm-dependency',+ 'browser-dependency',+ 'wheel',+ 'binary-archive',+ ] as const) {holds.set(artifact, { count: 0, released: false, notFound: false, ...gate() });}const heldEntry = (artifact: HeldArtifact) => {@@ -243,6 +302,31 @@ export async function withHeldInstallRegistry(),'application/json',);+ } else if (path === `/${browserName}`) {+ send(+ Buffer.from(+ packument(+ host,+ browserName,+ browserTarball,+ browserManifest,+ PUBLISHED,+ browserPublished ? browserVersion : UNPINNED_BROWSER_VERSION,+ ),+ ),+ 'application/json',+ );+ } else if (path === `/${BROWSER_DEPENDENCY_NAME}`) {+ send(+ Buffer.from(+ packument(host, BROWSER_DEPENDENCY_NAME, browserDependencyTarball, {}, PUBLISHED),+ ),+ 'application/json',+ );+ } else if (path === tarballPath(browserName, browserVersion)) {+ send(browserTarball, 'application/octet-stream');+ } else if (path === tarballPath(BROWSER_DEPENDENCY_NAME, VERSION)) {+ sendHeld('browser-dependency', browserDependencyTarball, 'application/octet-stream');} else if (path === `/${AGENT_NAME}/-/${AGENT_NAME}-${VERSION}.tgz`) {sendHeld('npm-package', agentTarball, 'application/octet-stream');} else if (path === `/${DEPENDENCY_NAME}/-/${DEPENDENCY_NAME}-${VERSION}.tgz`) {@@ -307,6 +391,9 @@ export async function withHeldInstallRegistry(answerNotFound: (artifact) => {heldEntry(artifact).notFound = true;},+ publishBrowser: (published) => {+ browserPublished = published;+ },});} finally {for (const open of openers) open();diff --git a/packages/server/src/acp/launch.ts b/packages/server/src/acp/launch.tsindex ee9879c27..57f06e78a 100644--- a/packages/server/src/acp/launch.ts+++ b/packages/server/src/acp/launch.ts@@ -409,7 +409,7 @@ function acquisitionKey(launch: ResolvedLaunch, name: string, ceiling: string):return JSON.stringify([launch.cmd, sortedLaunchEnv(launch), name, ceiling]);}-function ensureNpmPackageInstalled(+export function ensureNpmPackageInstalled(launch: ResolvedLaunch,acquired: string,log: PinoLogger,diff --git a/packages/server/src/acp/mcp-injection-skip.test.ts b/packages/server/src/acp/mcp-injection-skip.test.tsindex 9acb19668..65c283aea 100644--- a/packages/server/src/acp/mcp-injection-skip.test.ts+++ b/packages/server/src/acp/mcp-injection-skip.test.ts@@ -7,7 +7,7 @@ import type { AgentSessionManager } from '../agent-sessions.ts';import { resolveOnPath } from '../git-preflight.ts';import { getLogger } from '../logger.ts';import { MCP_HOSTED_AGENT_HEADER } from '../mcp/agent-identity.ts';-import { resolveBrowserNpx } from './browser-mcp.ts';+import { AGENT_BROWSER_MCP_PACKAGE, resolveBrowserNpx } from './browser-mcp.ts';import { agentSpawnPath } from './launch.ts';import { AcpPermissionStore, readAgentBrowserTools } from './permissions.ts';import { AcpRegistry } from './registry.ts';@@ -47,8 +47,10 @@ type BuildMcpServersSeam = {agentRef: { source: 'registry' | 'custom'; id: string };cwd: string;info: { threadId: string };+ agentNpmCache?: string | null;},init: { agentCapabilities?: { mcpCapabilities?: { http?: boolean } } },+ consentBudgetMs?: number,) => Promise<{servers: Array<{name: string;@@ -74,6 +76,8 @@ function makeManager(browser?: {enabled: AcpThreadManagerOptions['agentBrowserTools'];resolveNpx?: AcpThreadManagerOptions['resolveBrowserNpx'];+ ensurePackage?: AcpThreadManagerOptions['ensureBrowserPackage'];+ installWaitMs?: number;localDir?: string;globalDir?: string | null;},@@ -102,6 +106,8 @@ function makeManager(probeHarnessManagedMcpEntry: probe,agentBrowserTools: browser?.enabled,resolveBrowserNpx: browser?.resolveNpx,+ ensureBrowserPackage: browser?.ensurePackage ?? (async () => {}),+ browserInstallWaitMs: browser?.installWaitMs,log,resolveLoginShellPath: async () => null,});@@ -301,7 +307,10 @@ describe.skipIf(process.platform === 'win32')('buildMcpServers × agentBrowserToexpect(browser.args).toContain('--no-webmcp');expect(browser.args?.join(' ')).toContain(`--output-dir ${join(chat, 'files')}`);expect(browser.args?.join(' ')).not.toContain(localDir);- expect(browser.env).toEqual([{ name: 'PATH', value: npx.path }]);+ expect(browser.env).toEqual([+ { name: 'PATH', value: npx.path },+ { name: 'npm_config_prefer_offline', value: 'true' },+ ]);expect(seen[0]?.at(-1)).toBe(agentSpawnPath());});@@ -351,6 +360,96 @@ describe.skipIf(process.platform === 'win32')('buildMcpServers × agentBrowserToexpect(await unavailable(noGlobalDir)).toBe('failed');});+ test('leaves the browser out when installing its package fails from cached and from fresh package data', async () => {+ const npx = fakeNpx();+ const installs: Array<{+ cmd: string;+ path: string | undefined;+ acquired: string;+ reacquire: boolean | undefined;+ preferOffline: string | undefined;+ }> = [];+ const m = makeManager(undefined, undefined, undefined, {+ enabled: () => true,+ resolveNpx: () => npx,+ ensurePackage: async (launch, acquired, _log, acquisition) => {+ installs.push({+ cmd: launch.cmd,+ path: launch.env.PATH,+ acquired,+ reacquire: acquisition.reacquire,+ preferOffline: launch.env.npm_config_prefer_offline,+ });+ throw new Error('npm install failed');+ },+ });+ const { servers, browserUnavailable } = await m.buildMcpServers(+ record('registry', 'claude-acp'),+ HTTP_INIT,+ );+ expect(servers.map((s) => s.name)).toEqual(['open-knowledge']);+ expect(browserUnavailable).toBe('failed');+ expect(installs).toEqual(+ ['true', 'false'].map((preferOffline) => ({+ cmd: npx.npx,+ path: npx.path,+ acquired: AGENT_BROWSER_MCP_PACKAGE,+ reacquire: true,+ preferOffline,+ })),+ );+ });++ test("installs and starts the browser from the npm cache the chat's agent runs with", async () => {+ const npx = fakeNpx();+ const installCaches: Array<string | undefined> = [];+ const m = makeManager(undefined, undefined, undefined, {+ enabled: () => true,+ resolveNpx: () => npx,+ ensurePackage: async (launch) => {+ installCaches.push(launch.env.npm_config_cache);+ },+ });+ const { servers } = await m.buildMcpServers(+ { ...record('registry', 'codex-acp'), agentNpmCache: '/runtime/npm-cache' },+ HTTP_INIT,+ );+ const browser = servers.find((s) => s.name === 'ok-browser');+ expect(browser?.env).toContainEqual({ name: 'npm_config_cache', value: '/runtime/npm-cache' });+ expect(installCaches).toEqual(['/runtime/npm-cache']);+ });++ test('starts the chat without the browser when installing it outlasts the wait', async () => {+ const npx = fakeNpx();+ const m = makeManager(undefined, undefined, undefined, {+ enabled: () => true,+ resolveNpx: () => npx,+ ensurePackage: () => new Promise<void>(() => {}),+ installWaitMs: 20,+ });+ const { servers, browserUnavailable } = await m.buildMcpServers(+ record('registry', 'claude-acp'),+ HTTP_INIT,+ );+ expect(servers.map((s) => s.name)).toEqual(['open-knowledge']);+ expect(browserUnavailable).toBe('failed');+ });++ test('waits on the browser install no longer than the budget of a resume or retry', async () => {+ const npx = fakeNpx();+ const m = makeManager(undefined, undefined, undefined, {+ enabled: () => true,+ resolveNpx: () => npx,+ ensurePackage: () => new Promise<void>(() => {}),+ });+ const { browserUnavailable } = await m.buildMcpServers(+ record('registry', 'claude-acp'),+ HTTP_INIT,+ 20,+ );+ expect(browserUnavailable).toBe('failed');+ });+test('gives the browser only to Claude Code and Codex chats, whose adapters name the tool each call runs', async () => {const npx = fakeNpx();const on = makeManager(undefined, undefined, undefined, {diff --git a/packages/server/src/acp/thread-manager.ts b/packages/server/src/acp/thread-manager.tsindex e16746ea8..04c72513e 100644--- a/packages/server/src/acp/thread-manager.ts+++ b/packages/server/src/acp/thread-manager.ts@@ -87,13 +87,18 @@ import { RUNTIME_VERSION } from '../version-constants.ts';import { isWithin } from './archive.ts';import { buildPromptBlocks } from './attachment-blocks.ts';import {+ AGENT_BROWSER_MCP_PACKAGE,+ agentBrowserInstallLaunch,agentBrowserMcpServer,agentGetsBrowser,type BrowserCallEvidence,+ type BrowserPackageData,browserNpxRunnable,identifyBrowserCall,needsReportedToolCall,+ npmCacheOf,prepareAgentBrowserFolders,+ type ResolvedBrowserNpx,removeAgentBrowserFolders,resolveBrowserNpx,} from './browser-mcp.ts';@@ -109,6 +114,7 @@ import {agentSpawnPath,brokenInterpreterHint,declinedRepairHint,+ ensureNpmPackageInstalled,envPath,expiredFallbackHint,expiredIncompatibleNodeHint,@@ -197,6 +203,7 @@ const DEFAULT_UNWATCHED_TURN_KILL_MS = 20 * 60 * 1000;const DEFAULT_STEER_STALL_MS = 10_000;const DEFAULT_TURN_STALL_MS = 3 * 60 * 1000;const DEFAULT_AUTHENTICATE_TIMEOUT_MS = 5 * 60 * 1000;+const DEFAULT_BROWSER_INSTALL_WAIT_MS = 2 * 60 * 1000;const STDERR_TAIL_LINES = 40;const CRASH_REPORT_STATUSES: ReadonlySet<ThreadStatus> = new Set(['ready',@@ -340,6 +347,7 @@ interface ThreadRecord {lastInit: InitializeResponse | null;terminalAuthBase: TerminalAuthBase | null;agentLaunchPath?: string;+ agentNpmCache?: string | null;sessionId: string | null;agentSessionId: string;events: ThreadEvent[];@@ -469,6 +477,8 @@ export interface AcpThreadManagerOptions {autoApproveOkTools?: () => boolean;agentBrowserTools?: () => boolean;resolveBrowserNpx?: typeof resolveBrowserNpx;+ ensureBrowserPackage?: typeof ensureNpmPackageInstalled;+ browserInstallWaitMs?: number;}export function buildOkMcpStdioCommand(@@ -514,6 +524,7 @@ export class AcpThreadManager {private readonly unwatchedTurnCancelMs: number;private readonly unwatchedTurnKillMs: number;private readonly turnStallMs: number;+ private readonly browserInstallWaitMs: number;private readonly persistence: ThreadPersistenceStore;private readonly npxCacheClears = new Map<string, number>();private readonly resolveLoginShellPath: () => Promise<string | null>;@@ -533,6 +544,7 @@ export class AcpThreadManager {this.unwatchedTurnCancelMs = opts.unwatchedTurnCancelMs ?? DEFAULT_UNWATCHED_TURN_CANCEL_MS;this.unwatchedTurnKillMs = opts.unwatchedTurnKillMs ?? DEFAULT_UNWATCHED_TURN_KILL_MS;this.turnStallMs = opts.turnStallMs ?? DEFAULT_TURN_STALL_MS;+ this.browserInstallWaitMs = opts.browserInstallWaitMs ?? DEFAULT_BROWSER_INSTALL_WAIT_MS;const [primaryDir, legacyDir = null] = acpThreadStoreRoots(opts.globalDir, opts.localDir);this.persistence = new ThreadPersistenceStore({primaryDir,@@ -893,6 +905,7 @@ export class AcpThreadManager {record.terminalAuthBase = terminalAuthBaseFor(launch);record.agentLaunchPath = envPath(launch.env);+ record.agentNpmCache = npmCacheOf(launch.env);launch = applyLaunchContextWindow(launch,record.agentRef.id,@@ -1181,14 +1194,25 @@ export class AcpThreadManager {agentId: record.info.agent.id,npxCacheEntry: redactDiagnostic(entryDir),};+ const outcome = await this.removeStaleNpxCacheEntry(entryDir, logContext);+ if (outcome === 'kept') return false;+ this.opts.log.warn(+ logContext,+ outcome === 'recently-removed'+ ? '[acp-threads] npx cache entry was cleared by another launch moments ago; relaunching without clearing it again'+ : '[acp-threads] cleared a stale npx cache entry; relaunching the agent',+ );+ await this.discardFailedLaunch(record);+ return !isThreadClosed(record);+ }++ private async removeStaleNpxCacheEntry(+ entryDir: NpxCacheEntry,+ logContext: Record<string, unknown>,+ ): Promise<'removed' | 'recently-removed' | 'kept'> {const clearedAt = this.npxCacheClears.get(entryDir);if (clearedAt !== undefined && Date.now() - clearedAt < NPX_CACHE_CLEAR_COOLDOWN_MS) {- this.opts.log.warn(- logContext,- '[acp-threads] npx cache entry was cleared by another launch moments ago; relaunching without clearing it again',- );- await this.discardFailedLaunch(record);- return !isThreadClosed(record);+ return 'recently-removed';}const claimedAt = Date.now();this.npxCacheClears.set(entryDir, claimedAt);@@ -1206,7 +1230,7 @@ export class AcpThreadManager {'[acp-threads] leaving an npx cache entry alone',);releaseClaim();- return false;+ return 'kept';}}try {@@ -1217,14 +1241,9 @@ export class AcpThreadManager {'[acp-threads] stale npx cache entry could not be cleared',);releaseClaim();- return false;+ return 'kept';}- this.opts.log.warn(- logContext,- '[acp-threads] cleared a stale npx cache entry; relaunching the agent',- );- await this.discardFailedLaunch(record);- return !isThreadClosed(record);+ return 'removed';}private async discardFailedLaunch(t: ThreadRecord): Promise<void> {@@ -1663,7 +1682,7 @@ export class AcpThreadManager {record.browserInjected = false;if (this.opts.agentBrowserTools?.() === true) {if (agentGetsBrowser(record.agentRef)) {- const browser = await this.agentBrowserServer(record);+ const browser = await this.agentBrowserServer(record, consentBudgetMs);if (typeof browser === 'string') {browserUnavailable = browser;} else {@@ -1706,6 +1725,7 @@ export class AcpThreadManager {private async agentBrowserServer(record: ThreadRecord,+ waitBudgetMs: number,): Promise<McpServerStdio | BrowserUnavailableReason> {const context = { threadId: record.info.threadId, agentId: record.agentRef.id };const browserRoot = this.opts.globalDir;@@ -1736,11 +1756,13 @@ export class AcpThreadManager {);return 'no-node';}+ const npmCache = record.agentNpmCache ?? null;let server: McpServerStdio | null;try {server = agentBrowserMcpServer({npx,folders: await prepareAgentBrowserFolders(browserRoot, record.info.threadId),+ npmCache,});} catch (err) {this.opts.log.warn(@@ -1756,6 +1778,23 @@ export class AcpThreadManager {);return 'no-node';}+ const waitMs = Math.min(this.browserInstallWaitMs, waitBudgetMs);+ let waitTimer: ReturnType<typeof setTimeout> | undefined;+ const installed = await Promise.race([+ this.installBrowserPackage(record, npx, npmCache),+ new Promise<'still-installing'>((resolve) => {+ waitTimer = setTimeout(() => resolve('still-installing'), waitMs);+ waitTimer.unref?.();+ }),+ ]).finally(() => clearTimeout(waitTimer));+ if (installed === 'still-installing') {+ this.opts.log.warn(+ { ...context, waitedMs: waitMs },+ '[acp-threads] installing the browser is taking too long — the chat starts without a browser',+ );+ return 'failed';+ }+ if (!installed) return 'failed';this.opts.log.info({ ...context, command: server.command, npx: npx.npx },'[acp-threads] browser MCP injected',@@ -1763,6 +1802,52 @@ export class AcpThreadManager {return server;}+ private async installBrowserPackage(+ record: ThreadRecord,+ npx: ResolvedBrowserNpx,+ npmCache: string | null,+ packageData: BrowserPackageData = 'cached',+ npxCacheRecovery: NpxCacheRecovery = 'available',+ ): Promise<boolean> {+ const context = { threadId: record.info.threadId, agentId: record.agentRef.id };+ const ensure = this.opts.ensureBrowserPackage ?? ensureNpmPackageInstalled;+ const launch = agentBrowserInstallLaunch(npx, npmCache, packageData);+ try {+ await ensure(launch, AGENT_BROWSER_MCP_PACKAGE, this.opts.log, { reacquire: true });+ return true;+ } catch (err) {+ if (+ err instanceof AgentLaunchError &&+ err.npxCacheEntry !== undefined &&+ npxCacheRecovery === 'available'+ ) {+ const logContext = { ...context, npxCacheEntry: redactDiagnostic(err.npxCacheEntry) };+ const removal = await this.removeStaleNpxCacheEntry(err.npxCacheEntry, logContext);+ if (removal !== 'kept') {+ this.opts.log.warn(+ logContext,+ removal === 'removed'+ ? '[acp-threads] cleared a stale browser npx cache entry; reinstalling the browser'+ : '[acp-threads] browser npx cache entry was cleared by another launch moments ago; reinstalling the browser without clearing it again',+ );+ return this.installBrowserPackage(record, npx, npmCache, packageData, 'spent');+ }+ }+ if (packageData === 'cached') {+ this.opts.log.info(+ { ...context, err },+ "[acp-threads] installing the browser from npm's cached package data failed; installing it again with fresh package data",+ );+ return this.installBrowserPackage(record, npx, npmCache, 'fresh', npxCacheRecovery);+ }+ this.opts.log.warn(+ { ...context, err },+ '[acp-threads] installing the browser failed — the chat starts without a browser',+ );+ return false;+ }+ }+private async harnessAlreadyHasOkMcp(record: ThreadRecord,): Promise<HarnessManagedMcpEntryHit | null> {@@ -2078,6 +2163,7 @@ export class AcpThreadManager {init,consentBudgetMs,);+ if (isThreadClosed(record)) return false;this.noteBrowserUnavailable(record, browserUnavailable);try {const session = await conn.agent.request(acpMethods.agent.session.new, {@@ -2205,6 +2291,9 @@ export class AcpThreadManager {init,BLOCKING_CONSENT_TIMEOUT_MS,);+ if (isThreadClosed(t)) {+ throw new ThreadOpError('not-ready', 'thread closed during resume');+ }this.noteBrowserUnavailable(t, browserUnavailable);const caps = init.agentCapabilities;const viaResume = caps?.sessionCapabilities?.resume != null;diff --git a/packages/server/tsconfig.test-helper-callers.json b/packages/server/tsconfig.test-helper-callers.jsonindex d810ab925..c47532fcb 100644--- a/packages/server/tsconfig.test-helper-callers.json+++ b/packages/server/tsconfig.test-helper-callers.json@@ -2,6 +2,7 @@"extends": "./tsconfig.json","include": [],"files": [+ "src/acp/browser-install-teardown.integration.test.ts","src/acp/npx-install-server-exit.integration.test.ts","src/config-file-watcher-readiness.test.ts","src/expect-stable.test.ts",