Skip to content

Beautiful, AI-native markdown IDE and LLM wiki

feat(open-knowledge): in-app agent threads via ACP (Start an agent) (#2410)

mike-inkeepae13c506eb2b
diff --git a/.changeset/acp-agents-beta-stance.md b/.changeset/acp-agents-beta-stance.md
new file mode 100644
index 000000000..b39b8f72c
--- /dev/null
+++ b/.changeset/acp-agents-beta-stance.md
@@ -0,0 +1,5 @@
+---
+"@inkeep/open-knowledge": patch
+---
+
+In-app agents ship as a beta. Every agent picker carries a "Beta" tag on its "In this app" section, and the agent catalog dialog is likewise marked. The sessions dock no longer defaults its "New" button to "Start an agent" before you've picked an agent — with none chosen it stays a neutral "New" that opens the picker, so starting an in-app agent is always an explicit choice.
diff --git a/.changeset/acp-external-agents.md b/.changeset/acp-external-agents.md
new file mode 100644
index 000000000..c231f9728
--- /dev/null
+++ b/.changeset/acp-external-agents.md
@@ -0,0 +1,15 @@
+---
+"@inkeep/open-knowledge": minor
+---
+
+Add in-app AI agent threads via the Agent Client Protocol (ACP). "Open with AI" now includes a "Start an agent" option that runs a coding agent (Claude, Codex, Gemini, Cursor, Copilot, OpenCode, and the rest of the ACP registry) inside OpenKnowledge itself, in both the desktop app and the browser.
+
+"Start an agent" is available from every launch surface: the sparkles popover, the file-tree and empty-space right-click menus, and as a selectable default in the Ask AI and create-project composers. Every agent gets OpenKnowledge's MCP tools: agents that support HTTP MCP connect to the running server directly, and all others are handed a stdio bridge, so tools like search, write, and edit work regardless of the agent's transport support. When the agent's own harness already has OpenKnowledge's managed MCP entry installed (a project or user config written by `ok init` or the desktop consent flow), the thread skips injecting a second copy — the agent connects through the installed entry instead of two same-named servers fighting over which one loads. The check matches on what the entry launches (OpenKnowledge's own server command), so a harness's own per-tool approval settings layered onto that entry don't defeat it.
+
+Threads show the agent's messages, its plan, tool calls with diffs, and permission prompts, and you approve or decline each sensitive action. Agent replies render as markdown — headings, lists, tables, links, and code blocks with a copy button — live while the text streams, closing half-finished formatting cleanly mid-stream instead of flashing raw `**` and backticks. Agents edit your notes through OpenKnowledge's own write path, so their changes are attributed to the agent and appear live in the editor. Each agent uses its own account and billing; nothing proprietary is bundled. Registry adapters install on first use and run as separate processes. For adapters that rely on an existing harness, OpenKnowledge detects locally installed Claude, Codex, Cursor, and OpenCode CLIs and offers those agents across the session dock, prompt composers, and Open with AI menus without overriding explicit choices or terminal defaults.
+
+Follow the file: while an agent works, the editor follows along, opening each document the agent creates, reads, or edits so you can watch the work happen live — including documents referenced through OpenKnowledge's own MCP tools (`write`, `edit`, `move`, and paths inside `exec` commands). Toggle it from the thread header (on by default).
+
+Switch agents any time: the thread dock's "+" lists every agent you've registered plus "Choose another agent…" to browse the catalog, so the first pick is never locked in. Reopening an empty sessions dock repeats that same preferred agent, CLI, or terminal choice, and the selected tab stays scrolled into view as the strip fills up. When an agent offers session settings — model, reasoning effort, fast mode, approval policy, or sandbox mode — they appear together in one labeled settings menu in the thread header (Agent Client Protocol session config options).
+
+Lifecycle and cost guarantees: closing a thread (or shutting down the server) kills the agent's entire process tree and waits for it to actually die, so a stuck agent can't keep running — and billing its account — invisibly after you close it. A turn still running with no window attached is asked to stop after 10 minutes and force-closed after 20. Stop shows "Stopping…" and, if the agent ignores the request, offers Force stop; a message that can't be delivered surfaces as a toast instead of vanishing; hiding the thread dock actually hides it. Long transcripts also render much more smoothly — events arrive in batches and the transcript updates incrementally instead of re-rendering the whole history on every streamed chunk.
diff --git a/.changeset/acp-managed-runtime.md b/.changeset/acp-managed-runtime.md
new file mode 100644
index 000000000..2e904a97b
--- /dev/null
+++ b/.changeset/acp-managed-runtime.md
@@ -0,0 +1,5 @@
+---
+"@inkeep/open-knowledge": minor
+---
+
+Agents that need `npx` or `uvx` now work even when those tools aren't installed. When you start an agent whose launcher requires Node.js (most agents — Claude, Codex, Gemini, and the rest of the npm-distributed catalog) or uv, and it isn't on your PATH, OpenKnowledge offers to download a private, pinned, checksum-verified copy for you and launches the agent through it — the same "just works" experience Zed provides, but nothing downloads without your explicit consent. The prompt appears inline in the thread with a size and source disclosure ("~45 MB from nodejs.org"), a progress bar while it installs, and a "Remember" option so you're asked at most once per machine. The runtime installs into `~/.ok/runtimes/` with its own private package cache, so it never touches the rest of your system, and declining still leaves you the manual-install path. This closes the gap where the desktop app — which bundles its own Node runtime but not npm — couldn't launch npm-distributed agents on a machine without a separate Node install.
diff --git a/.changeset/acp-thread-history.md b/.changeset/acp-thread-history.md
new file mode 100644
index 000000000..b9d2be5c1
--- /dev/null
+++ b/.changeset/acp-thread-history.md
@@ -0,0 +1,9 @@
+---
+"@inkeep/open-knowledge": minor
+---
+
+Agent conversations are now saved and resumable. Every agent thread's transcript is persisted on disk as it streams (under the project's machine-local `.ok/local/threads/` — never committed, never shared), so closing a tab, an idle cleanup, or a server restart no longer destroys the conversation.
+
+A history menu in the thread dock lists past conversations (newest first); opening one shows the full transcript — messages, tool calls with diffs, permission decisions — with no agent process running. Closing a tab now always archives (the X is never destructive); permanent delete lives in the history menu behind a confirm.
+
+Type to resume: sending a message into an archived conversation respawns the agent and continues the same session where the agent supports it — via ACP `session/resume` when available (no history replay needed, since OpenKnowledge keeps its own transcript), falling back to `session/load` with the protocol's replay de-duplicated. Agents that can't resume (or whose session has expired on their side — Claude, for example, cleans its own sessions up after 30 days) keep the transcript intact and offer a one-click "New thread with this agent" instead. Document-edit attribution, write-flash, and per-session undo stay continuous across a resume.
diff --git a/.changeset/acp-thread-rendering-parity.md b/.changeset/acp-thread-rendering-parity.md
new file mode 100644
index 000000000..a950299de
--- /dev/null
+++ b/.changeset/acp-thread-rendering-parity.md
@@ -0,0 +1,5 @@
+---
+'@inkeep/open-knowledge': patch
+---
+
+Agent threads now render what the agent actually does. OK implements the ACP terminal surface, so agents can run commands through it and the transcript shows each command with its live output and exit code. Tool-call diffs are genuine line diffs (unchanged lines collapse) instead of full before/after dumps. A permission prompt that parks a turn now surfaces as an "awaiting approval" thread status in the tab strip, every prompt has an explicit Deny, and resolved prompts summarize as approved or denied by what was actually chosen. The composer footer shows the agent's reported context usage, and tool calls display their raw input.
diff --git a/.changeset/acp-thread-titles.md b/.changeset/acp-thread-titles.md
new file mode 100644
index 000000000..42ae064d0
--- /dev/null
+++ b/.changeset/acp-thread-titles.md
@@ -0,0 +1,7 @@
+---
+"@inkeep/open-knowledge": minor
+---
+
+Agent thread tabs now get useful titles. The title comes from what you actually typed to start the thread — not the boilerplate lead-in a launch adds — so a tab reads "Fix the login redirect" rather than the shared "You're an agent working inside OpenKnowledge…" preamble every launch opens with. Auto-titles also skip the filler most prompts open with ("please", "can you", "hey, could you take a look at…"), so the words that actually distinguish a conversation land in the tab instead of a shared prefix; when stripping would leave nothing meaningful, the raw prompt line is kept as before (non-English prompts always pass through untouched). Long titles now truncate at a word boundary, and hovering a tab shows the full title.
+
+Tabs are also renamable: double-click a tab to type a new name (Enter commits, Escape cancels). Manual titles stick — they survive archive and server restarts, win over auto-titling, and apply to archived conversations in the history menu too.
diff --git a/.changeset/create-composer-enter-thread-mode.md b/.changeset/create-composer-enter-thread-mode.md
new file mode 100644
index 000000000..0f2c1e0c9
--- /dev/null
+++ b/.changeset/create-composer-enter-thread-mode.md
@@ -0,0 +1,5 @@
+---
+"@inkeep/open-knowledge": patch
+---
+
+Fixed the empty-state "Create" composer so pressing Enter launches whatever the Create button shows. Previously, when the composer was set to start an in-app agent ("Start an agent" / a registered agent), pressing Enter fell through to a different action instead of launching that agent — only a mouse click on the button worked. Enter now performs the same action as the button in every mode (in-app agent, terminal CLI, or desktop app agent), so the keyboard and pointer paths never diverge. Desktop builds also gain an opt-in `OK_FORCE_A11Y=1` launch flag that exposes the full web UI to the macOS accessibility tree, for VoiceOver and GUI-automation tooling.
diff --git a/.changeset/follow-mode-flash-on-activation.md b/.changeset/follow-mode-flash-on-activation.md
new file mode 100644
index 000000000..e23d041a4
--- /dev/null
+++ b/.changeset/follow-mode-flash-on-activation.md
@@ -0,0 +1,5 @@
+---
+"@inkeep/open-knowledge": patch
+---
+
+Follow mode now flashes and scrolls to the agent's change even when it navigates you to the document *after* the write already landed — the common case that was silently doing nothing. Previously the scroll-and-flash only fired if the write arrived while you were already on that document; when following an agent across files, the tab would switch to each document and the edits would just "pop in" fully applied, with no highlight and no scroll. Agent writes now record which blocks they changed on the write-flash entry, so when follow mode brings a document into view the editor can still light up the changed section and scroll it into view. Writes you're already watching are unaffected (and never double-flash).
diff --git a/.changeset/follow-mode-scroll-and-flash.md b/.changeset/follow-mode-scroll-and-flash.md
new file mode 100644
index 000000000..2eda68c4c
--- /dev/null
+++ b/.changeset/follow-mode-scroll-and-flash.md
@@ -0,0 +1,5 @@
+---
+"@inkeep/open-knowledge": minor
+---
+
+Follow mode now scrolls to where the agent is writing and flashes the exact text it changed. When you're following an agent (the thread's Follow toggle, on by default) and it writes the document you're viewing, the editor scrolls the changed region into view and briefly highlights it — so a section the agent appends to the bottom of a long document pulls the viewport down to it and lights up, instead of the change happening off-screen. The highlight targets only the bytes that actually changed (diffed from before/after), so a full-document rewrite that only appends a section flashes just that section, not the whole page. In-app agent-thread writes now drive the same write-flash the MCP agent writes always have.
diff --git a/.changeset/graph-assembly-and-batch-follow.md b/.changeset/graph-assembly-and-batch-follow.md
new file mode 100644
index 000000000..2ce3f4ef2
--- /dev/null
+++ b/.changeset/graph-assembly-and-batch-follow.md
@@ -0,0 +1,5 @@
+---
+"@inkeep/open-knowledge": patch
+---
+
+The docked Graph tab assembles live while an agent builds a knowledge base: when pages land in a burst with the graph open, the whole project graph frames itself and grows in — new pages scale and fade in with a brief halo, new edges fade in, and nodes are colored by their `cluster:` frontmatter. Follow mode also now understands batch writes (`documents: [...]`), which previously produced no navigation at all — the editor sat still through entire builds; it now follows the agent to the most recent page in each batch. The graph's view choreography is entirely signal-driven, so the `graph_view` MCP tool is retired (one less tool in every agent's context) along with its view-command plumbing; the knowledge-base pack skill sheds its view-choreography instructions in favor of plain authoring guidance: link every page at creation and give related pages a shared cluster.
diff --git a/.changeset/idle-shutdown-spares-live-servers.md b/.changeset/idle-shutdown-spares-live-servers.md
new file mode 100644
index 000000000..052da4db9
--- /dev/null
+++ b/.changeset/idle-shutdown-spares-live-servers.md
@@ -0,0 +1,5 @@
+---
+"@inkeep/open-knowledge": patch
+---
+
+Fix a stale server's idle shutdown killing the live one. When a leftover `ok start` process from an earlier session went idle, its cleanup blindly stopped whatever process was advertised in `ui.lock` — which, with the desktop app, is the live server itself (it serves the editor UI and advertises its own port there). The result was the whole workspace abruptly disconnecting mid-session — agent threads, unsaved cursors, everything — often looking like a random server crash. Idle shutdown now only stops the UI helper process it actually started, never an unrelated lock holder.
diff --git a/.changeset/unified-sessions-dock.md b/.changeset/unified-sessions-dock.md
new file mode 100644
index 000000000..0192e9912
--- /dev/null
+++ b/.changeset/unified-sessions-dock.md
@@ -0,0 +1,9 @@
+---
+"@inkeep/open-knowledge": minor
+---
+
+Fold agent threads into one unified sessions dock. Terminals and in-app AI agents now live as tabs in a single dock instead of two competing right-edge columns — one tab strip, one reveal tab, one ⌘J toggle, one mental model. A shell and an agent are just tabs of a different kind: each carries a kind icon (a shell glyph, or the agent's avatar with a live status dot), and reorder, activate, rename, and close work the same across both, with behavior dispatched by kind (closing a terminal kills its shell; closing an agent archives the conversation, recoverable from history).
+
+The dock is now host-agnostic: it renders in the browser too (agent tabs only there), so web users get the same docked, resizable, right-or-bottom placement the desktop terminal already had. The "New" split button merges every launch into one menu — your registered agents, "Choose another agent" to browse the catalog, and (on desktop) every CLI plus a bare terminal — and its primary button repeats your last pick across all three families. Launching an agent from an "Open with AI" menu opens a tab in this one dock and reveals it automatically. Conversation history moves with it: a history menu next to "New" (and a chooser on an empty dock) reopens or permanently deletes past conversations, so closing a thread archives it rather than losing it.
+
+A full renderer reload now restores the dock's interleaved tab order and which tab was active, alongside the terminals and agent threads it already recovered. The standalone macOS terminal window is unchanged (terminals only). No settings, shortcuts, or stored preferences change.
diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.md
index 5b797cf08..418afa2a7 100644
--- a/THIRD_PARTY_NOTICES.md
+++ b/THIRD_PARTY_NOTICES.md
@@ -594,6 +594,11 @@ Apache License
limitations under the License.
```
+### `@agentclientprotocol/[email protected]`
+Homepage: https://github.com/agentclientprotocol/typescript-sdk#readme
+
+Copyright 2025 Zed Industries, Inc. and contributors
+
### `@chevrotain/[email protected]`
Homepage: https://chevrotain.io/documentation/
@@ -883,11 +888,21 @@ Homepage: https://mozilla.github.io/pdf.js/
_(LICENSE template present but no copyright line filled in; refer to the package source for canonical attribution.)_
+Homepage: https://streamdown.ai/docs/termination
+
+Copyright 2023 Vercel, Inc.
+
Homepage: https://github.com/GoogleChromeLabs/scheduler-polyfill
_(LICENSE template present but no copyright line filled in; refer to the package source for canonical attribution.)_
+Homepage: https://streamdown.ai
+
+Copyright 2023 Vercel, Inc.
+
Homepage: https://github.com/mikeal/tunnel-agent
@@ -3487,16 +3502,36 @@ Homepage: https://github.com/syntax-tree/hast-util-phrasing
Copyright (c) 2016 Titus Wormer <[email protected]>
+Homepage: https://github.com/syntax-tree/hast-util-raw
+
+Copyright (c) Titus Wormer <[email protected]>
+
+Homepage: https://github.com/syntax-tree/hast-util-sanitize
+
+Copyright (c) Titus Wormer <[email protected]>
+
Homepage: https://github.com/syntax-tree/hast-util-to-html
Copyright (c) Titus Wormer <[email protected]>
+Homepage: https://github.com/syntax-tree/hast-util-to-jsx-runtime
+
+Copyright (c) Titus Wormer <[email protected]>
+
Homepage: https://github.com/syntax-tree/hast-util-to-mdast
Copyright (c) Titus Wormer <[email protected]> Copyright (c) Seth Vincent <[email protected]>
+Homepage: https://github.com/syntax-tree/hast-util-to-parse5
+
+Copyright (c) Titus Wormer <[email protected]>
+
Homepage: https://github.com/syntax-tree/hast-util-to-text
@@ -3522,6 +3557,11 @@ Homepage: https://hono.dev
Copyright (c) 2021 - present, Yusuke Wada and Hono contributors
+Homepage: https://github.com/rehypejs/rehype-minify/tree/main/packages/html-url-attributes
+
+Copyright (c) Titus Wormer
+
Homepage: https://github.com/wooorm/html-void-elements
@@ -3564,6 +3604,11 @@ Homepage: https://github.com/vasturiano/index-array-by
Copyright (c) 2018 Vasco Asturiano
+Homepage: https://github.com/remarkablemark/inline-style-parser
+
+Copyright (c) 2012 TJ Holowaychuk <[email protected]>
+
Homepage: https://github.com/beaugunderson/ip-address
@@ -3919,6 +3964,11 @@ Homepage: https://marked.js.org
Copyright (c) 2018+, MarkedJS (https://github.com/markedjs/) Copyright (c) 2011-2018, Christopher Jeffrey (https://github.com/chjj/)
+Homepage: https://marked.js.org
+
+Copyright (c) 2018+, MarkedJS (https://github.com/markedjs/) Copyright (c) 2011-2018, Christopher Jeffrey (https://github.com/chjj/)
+
Homepage: https://github.com/es-shims/math-intrinsics#readme
@@ -4847,6 +4897,11 @@ Homepage: http://github.com/benjamn/recast
Copyright (c) 2012 Ben Newman <[email protected]>
+Homepage: https://github.com/vercel-labs/markdown-sanitizers#readme
+
+Copyright (c) 2025 Vercel Inc.
+
Homepage: https://github.com/rehypejs/rehype-minify/tree/main/packages/rehype-minify-whitespace
@@ -4857,11 +4912,21 @@ Homepage: https://github.com/rehypejs/rehype
Copyright (c) Titus Wormer
+Homepage: https://github.com/rehypejs/rehype-raw
+
+Copyright (c) 2016 Titus Wormer <[email protected]>
+
Homepage: https://github.com/rehypejs/rehype-remark
Copyright (c) Titus Wormer <[email protected]>
+Homepage: https://github.com/rehypejs/rehype-sanitize
+
+Copyright (c) 2016 Titus Wormer <[email protected]>
+
Homepage: https://github.com/rehypejs/rehype
@@ -5174,6 +5239,16 @@ Homepage: https://github.com/marijnh/style-mod
Copyright (C) 2018 by Marijn Haverbeke <[email protected]> and others
+Homepage: https://github.com/remarkablemark/style-to-js
+
+Copyright (c) 2020 Menglin "Mark" Xu <[email protected]>
+
+Homepage: https://github.com/remarkablemark/style-to-object
+
+Copyright (c) 2017 Menglin "Mark" Xu <[email protected]>
+
Homepage: https://github.com/thysultan/stylis.js
diff --git a/knip.config.ts b/knip.config.ts
index cf7d54c4b..6f8bbbc63 100644
--- a/knip.config.ts
+++ b/knip.config.ts
@@ -20,6 +20,7 @@ export default {
'lsof', // open-file listing — diagnose.ts, process-scan.ts
'pgrep', // process lookup — process-scan.ts
'where', // Windows binary lookup — git-preflight.ts
+ 'taskkill', // Windows process-tree termination — acp/launch.ts
'sw_vers', // macOS version query — bug-report.ts
'mkfifo', // named-pipe creation — keepalive-orphan-reaping.test.ts
'xcrun', // macOS notarization tool — desktop afterSign.mjs
@@ -105,6 +106,7 @@ export default {
'tests/**/*.ts',
'src/markdown/fixtures/perf/generate.ts',
'scripts/*.ts',
+ 'src/**/*.typelock.ts',
],
project: 'src/**',
ignoreDependencies: [
diff --git a/packages/app/package.json b/packages/app/package.json
index aca299fe4..98b733807 100644
--- a/packages/app/package.json
+++ b/packages/app/package.json
@@ -52,14 +52,14 @@
{
"name": "all JS chunks combined (gzipped)",
"path": "dist/assets/*.js",
- "limit": "3.36 MB",
+ "limit": "3.5 MB",
"gzip": true,
"running": false
},
{
"name": "main CSS (gzipped)",
"path": "dist/assets/index-*.css",
- "limit": "55 kB",
+ "limit": "57 kB",
"gzip": true,
"running": false
}
@@ -159,6 +159,7 @@
"scheduler-polyfill": "^1.3.0",
"shadcn": "^4.2.0",
"sonner": "^2.0.7",
+ "streamdown": "^2.5.0",
"tailwind-merge": "^3.5.0",
"tailwind-scrollbar": "^4.0.2",
"tailwindcss": "^4.2.2",
diff --git a/packages/app/src/App.tsx b/packages/app/src/App.tsx
index a6d221e66..20ce28ddb 100644
--- a/packages/app/src/App.tsx
+++ b/packages/app/src/App.tsx
@@ -3,6 +3,7 @@ import { lazy, type ReactNode, Suspense, useEffect, useRef, useState } from 'rea
import { CommandPalette } from '@/components/CommandPalette';
import { ConnectingBanner } from '@/components/ConnectingBanner';
import { CreateProjectMenuTrigger } from '@/components/CreateProjectMenuTrigger';
+import { DesktopAgentMigration } from '@/components/DesktopAgentMigration';
import { EditorPane } from '@/components/EditorPane';
import { FileSidebar } from '@/components/FileSidebar';
import { defaultInitialDir } from '@/components/file-tree-utils';
@@ -475,8 +476,8 @@ function AppBody() {
// Null on the web host (no real OS shell) so the menu rows that consume it
// render nothing.
// Which launchable CLIs are on PATH — each launch surface gates its rows from
- // this map via `visibleTerminalClis` so a CLI that isn't installed (e.g.
- // Antigravity) doesn't clutter the menu once the probe confirms it absent.
+ // this map via `isTerminalCliEnabled` so a CLI that isn't installed (e.g.
+ // Antigravity, or Claude) doesn't clutter the menu once the probe confirms it absent.
const installedClis = useInstalledClis();
const terminalLaunch: TerminalLaunchContextValue | null = desktopBridge
? {
@@ -503,6 +504,9 @@ function AppBody() {
Desktop-only — the `new-project` menu action never fires in
the web host, so the dialog stays unmounted there. */}
{desktopBridge ? <CreateProjectMenuTrigger bridge={desktopBridge} /> : null}
+ {/* One-time upgrade migration: carry an existing user's installed desktop
+ apps over into the new opt-in Desktop model. Desktop-only. */}
+ {desktopBridge ? <DesktopAgentMigration /> : null}
{/* Help → Report a Bug… opens ReportBugDialog here — same
desktop-only App-root trigger pattern as CreateProjectMenuTrigger. */}
{desktopBridge ? <ReportBugMenuTrigger /> : null}
diff --git a/packages/app/src/components/BottomComposer.dom.test.tsx b/packages/app/src/components/BottomComposer.dom.test.tsx
index 11860de4f..df865b66d 100644
--- a/packages/app/src/components/BottomComposer.dom.test.tsx
+++ b/packages/app/src/components/BottomComposer.dom.test.tsx
@@ -14,7 +14,7 @@
* `buildComposerHandoffInput` mirrors its workspace-null contract and carries the
* instruction + mentions through so we can assert they survive to dispatch.
*/
-import { afterEach, beforeEach, describe, expect, mock, spyOn, test } from 'bun:test';
+
import * as actualLinguiMacro from '@lingui/react/macro';
import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
@@ -26,7 +26,18 @@ import {
useImperativeHandle,
useRef,
} from 'react';
+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
import type { ComposerMentionInputHandle } from '@/editor/ComposerMentionInput';
+import {
+ desktopEnabledKey,
+ reloadEnabledAgentsFromStorage,
+ setAgentEnabled,
+} from '@/lib/acp/enabled-agents';
+import {
+ getDefaultRegisteredAgent,
+ registerAgent,
+ reloadRegisteredAgentsFromStorage,
+} from '@/lib/acp/registered-agents';
import { VISIBLE_TARGETS } from '@/lib/handoff/targets';
import { matchesKeyboardShortcut } from '@/lib/keyboard-shortcuts';
import {
@@ -34,7 +45,7 @@ import {
saveStickyAgent as saveStickyDefaultAgent,
} from '@/lib/unified-agent-store';
-mock.module('@lingui/react/macro', () => ({
+vi.doMock('@lingui/react/macro', () => ({
...actualLinguiMacro,
Trans: ({ children }: { children: ReactNode }) => <>{children}</>,
useLingui: () => ({
@@ -43,7 +54,7 @@ mock.module('@lingui/react/macro', () => ({
}),
}));
-mock.module('@/components/handoff/OpenInAgentMenuItem', () => ({
+vi.doMock('@/components/handoff/OpenInAgentMenuItem', () => ({
TargetIcon: ({ id }: { id: string }) => <span data-testid={`target-icon-${id}`} />,
}));
@@ -56,7 +67,7 @@ type MenuChild = {
onSelect?: () => void;
[key: string]: unknown;
};
-mock.module('@/components/ui/dropdown-menu', () => ({
+vi.doMock('@/components/ui/dropdown-menu', () => ({
DropdownMenu: ({ children }: MenuChild) => <div>{children}</div>,
DropdownMenuTrigger: ({ children }: MenuChild) => <>{children}</>,
DropdownMenuContent: ({ children, ...props }: MenuChild) => (
@@ -87,7 +98,7 @@ let emitMentions: ((mentions: string[]) => void) | null = null;
// returns the typed text as the instruction plus `mockInlineMentions` as the
// inline `@`-mention set (the inline chips + their on-hover × are exercised
// against the real editor in ComposerMentionInput.dom.test.tsx).
-mock.module('@/editor/ComposerMentionInput', () => ({
+vi.doMock('@/editor/ComposerMentionInput', () => ({
ComposerMentionInput: ({
ref,
ariaLabel,
@@ -144,11 +155,11 @@ mock.module('@/editor/ComposerMentionInput', () => ({
}));
let installStates: Record<string, { installed: boolean | null }> = {};
-mock.module('@/components/handoff/useInstalledAgents', () => ({
+vi.doMock('@/components/handoff/useInstalledAgents', () => ({
useInstalledAgents: () => ({ states: installStates, refresh: () => Promise.resolve() }),
}));
-mock.module('@/lib/use-workspace', () => ({
+vi.doMock('@/lib/use-workspace', () => ({
useWorkspace: () => ({ contentDir: '/tmp/project', pathSeparator: '/' }),
}));
@@ -159,20 +170,22 @@ mock.module('@/lib/use-workspace', () => ({
let liveSelection: unknown = null;
let liveFrontmatterSelection: unknown = null;
let pageMeta: ReadonlyMap<string, { docExt?: string }> = new Map();
-mock.module('@/hooks/use-selection-context', () => ({
+vi.doMock('@/hooks/use-selection-context', () => ({
useSelectionContext: (_docName: string | null, surface: string) =>
surface === 'frontmatter' ? liveFrontmatterSelection : liveSelection,
usePublishFrontmatterSelection: () => {},
}));
-mock.module('@/components/PageListContext', () => ({
+vi.doMock('@/components/PageListContext', () => ({
usePageList: () => ({ pageMeta }),
}));
-const recordAskedAiSpy = mock(() => {});
-mock.module('@/lib/onboarding-signals', () => ({ recordOnboardingAskedAi: recordAskedAiSpy }));
+const recordAskedAiSpy = vi.fn(() => {});
+vi.doMock('@/lib/onboarding-signals', () => ({ recordOnboardingAskedAi: recordAskedAiSpy }));
const dispatchCalls: Array<{ target: string; input: unknown }> = [];
+const startThreadCalls: unknown[] = [];
+const startThreadOpts: unknown[] = [];
const buildArgs: Array<{
docName: string | null;
folderRelativePath?: string;
@@ -186,7 +199,7 @@ let dispatchImpl: () => Promise<{ ok: boolean }> = () => Promise.resolve({ ok: t
let builderReturnsNull = false;
const terminalLaunchCalls: Array<{ input: unknown; cli: string | undefined }> = [];
-mock.module('@/components/handoff/useHandoffDispatch', () => ({
+vi.doMock('@/components/handoff/useHandoffDispatch', () => ({
useHandoffDispatch: () => ({
dispatch: (target: string, input: unknown) => {
dispatchCalls.push({ target, input });
@@ -215,9 +228,17 @@ mock.module('@/components/handoff/useHandoffDispatch', () => ({
},
};
},
+ startAgentThreadForInput: (input: unknown, opts?: unknown) => {
+ startThreadCalls.push(input);
+ startThreadOpts.push(opts);
+ },
+ // BottomComposer imports this for the enabled-but-not-installed install nudge;
+ // a mock.module replaces the whole module, so it must be present or the file
+ // fails to link.
+ openInstallUrl: () => Promise.resolve(),
}));
-mock.module('sonner', () => ({
+vi.doMock('sonner', () => ({
toast: {
error: (message: string) => {
toastErrors.push(message);
@@ -236,10 +257,19 @@ const ALL_INSTALLED: Record<string, { installed: boolean | null }> = {
cursor: { installed: true },
};
+// Desktop is enablement-gated now (off by default); these tests express Desktop
+// visibility via `installStates`, so translate installed → enabled at render.
+function enableInstalledDesktopTargets() {
+ for (const [id, state] of Object.entries(installStates)) {
+ if (state.installed === true) setAgentEnabled(desktopEnabledKey(id), true);
+ }
+}
+
async function renderComposer(
docName = 'notes',
extra: Partial<{ dismissed: boolean; onDismiss: () => void; onReopen: () => void }> = {},
) {
+ enableInstalledDesktopTargets();
const { BottomComposer } = await import('./BottomComposer');
return render(<BottomComposer docName={docName} surface="wysiwyg" {...extra} />);
}
@@ -250,6 +280,7 @@ async function renderComposerWithTerminal(
docName = 'notes',
installedClis: Record<string, boolean> = {},
) {
+ enableInstalledDesktopTargets();
const { BottomComposer } = await import('./BottomComposer');
const { TerminalLaunchProvider } = await import('./handoff/TerminalLaunchContext');
return render(
@@ -260,7 +291,7 @@ async function renderComposerWithTerminal(
},
// The composer reads the install map from here (not its own probe), so it
// drives both the no-pick default (resolveDefaultCli) and row gating
- // (visibleTerminalClis). Default {} ⇒ probe unresolved ⇒ fail-open (all
+ // (isTerminalCliEnabled). Default {} ⇒ probe unresolved ⇒ fail-open (all
// CLIs), matching the ungated rows most tests were written against.
installedClis,
}}
@@ -273,6 +304,7 @@ async function renderComposerWithTerminal(
// Variant whose launcher throws (no terminal session could be opened) — exercises
// the try/catch guard around launchInTerminal.
async function renderComposerWithThrowingTerminal(docName = 'notes') {
+ enableInstalledDesktopTargets();
const { BottomComposer } = await import('./BottomComposer');
const { TerminalLaunchProvider } = await import('./handoff/TerminalLaunchContext');
return render(
@@ -302,6 +334,7 @@ async function renderComposerWithInstalledClis(installed: Record<string, boolean
// Folder mode: the composer is scoped to a folder (no open doc, no surface).
async function renderFolderComposer(folderPath = 'specs/foo') {
+ enableInstalledDesktopTargets();
const { BottomComposer } = await import('./BottomComposer');
return render(<BottomComposer folderPath={folderPath} />);
}
@@ -349,7 +382,7 @@ function stubReducedMotion(matches: boolean): () => void {
let consoleErrorSpy: ReturnType<typeof spyOn>;
beforeEach(() => {
- consoleErrorSpy = spyOn(console, 'error').mockImplementation(() => {});
+ consoleErrorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
installStates = { ...ALL_INSTALLED };
dispatchImpl = () => Promise.resolve({ ok: true });
builderReturnsNull = false;
@@ -359,6 +392,8 @@ beforeEach(() => {
mockInlineMentions = [];
emitMentions = null;
dispatchCalls.length = 0;
+ startThreadCalls.length = 0;
+ startThreadOpts.length = 0;
recordAskedAiSpy.mockClear();
buildArgs.length = 0;
terminalLaunchCalls.length = 0;
@@ -368,6 +403,10 @@ beforeEach(() => {
} catch {
// localStorage may be unavailable in some sandboxes — sticky tests guard.
}
+ // The registered-agents store caches in module scope — re-read the (now
+ // cleared) storage so per-agent thread rows never leak between tests.
+ reloadRegisteredAgentsFromStorage();
+ reloadEnabledAgentsFromStorage();
});
afterEach(() => {
@@ -585,6 +624,83 @@ describe('BottomComposer (dispatch + picker + sticky default)', () => {
expect(dispatchCalls[0]?.target).toBe('codex');
});
+ test('picking an in-app agent launches a thread and persists the choice', async () => {
+ registerAgent({ source: 'registry', id: 'claude-acp', name: 'Claude Agent' });
+ const user = userEvent.setup();
+ await renderComposer();
+
+ await user.click(screen.getByTestId('ask-ai-agent-trigger'));
+ await user.click(await screen.findByTestId('ask-ai-agent-option-thread-registry:claude-acp'));
+
+ // Persisted as the in-app-thread sentinel; the primary reflects the choice.
+ expect(loadStickyDefaultAgent()).toBe('in-app-thread');
+ expect(screen.getByTestId('ask-ai-send').textContent).toContain('Start Claude Agent');
+
+ fireEvent.change(getInput(), { target: { value: 'summarize this doc' } });
+ fireEvent.keyDown(getInput(), { key: 'Enter' });
+
+ await waitFor(() => expect(startThreadCalls).toHaveLength(1));
+ expect(startThreadCalls[0]).toMatchObject({ compose: { instruction: 'summarize this doc' } });
+ // In-app thread mode never deep-link dispatches nor launches a terminal.
+ expect(dispatchCalls).toHaveLength(0);
+ // A successful thread launch records the Ask-AI onboarding step.
+ expect(recordAskedAiSpy).toHaveBeenCalledTimes(1);
+ });
+
+ test('with a registered agent and nothing picked, the primary defaults to in-app thread', async () => {
+ // A registered in-app agent exists; Desktop apps are installed AND enabled
+ // (renderComposer enables them). Nothing is picked. The footer must lead with
+ // the in-app agent, never an installed desktop app.
+ registerAgent({ source: 'registry', id: 'claude-acp', name: 'Claude Agent' });
+ await renderComposer();
+
+ expect(loadStickyDefaultAgent()).toBeNull();
+ expect(screen.getByTestId('ask-ai-send').textContent).toContain('Start Claude Agent');
+
+ fireEvent.change(getInput(), { target: { value: 'summarize this doc' } });
+ fireEvent.keyDown(getInput(), { key: 'Enter' });
+
+ await waitFor(() => expect(startThreadCalls).toHaveLength(1));
+ // Launches the effective enabled agent explicitly, never a desktop target.
+ expect(startThreadOpts[0]).toMatchObject({ agent: { source: 'registry', id: 'claude-acp' } });
+ expect(dispatchCalls).toHaveLength(0);
+ });
+
+ test('registered agents get their own thread rows; picking one becomes the default', async () => {
+ registerAgent({ source: 'registry', id: 'claude-acp', name: 'Claude Agent' });
+ registerAgent({ source: 'registry', id: 'cursor-acp', name: 'Cursor Agent' });
+ const user = userEvent.setup();
+ await renderComposer();
+
+ await user.click(screen.getByTestId('ask-ai-agent-trigger'));
+ // Per-agent rows replace the generic "Start an agent" row.
+ expect(screen.queryByTestId('ask-ai-agent-option-thread')).toBeNull();
+ await user.click(await screen.findByTestId('ask-ai-agent-option-thread-registry:claude-acp'));
+
+ expect(loadStickyDefaultAgent()).toBe('in-app-thread');
+ expect(getDefaultRegisteredAgent()).toMatchObject({ id: 'claude-acp' });
+ expect(screen.getByTestId('ask-ai-send').textContent).toContain('Start Claude Agent');
+
+ fireEvent.change(getInput(), { target: { value: 'summarize this doc' } });
+ fireEvent.keyDown(getInput(), { key: 'Enter' });
+ await waitFor(() => expect(startThreadCalls).toHaveLength(1));
+ });
+
+ test('the Settings row opens Configure agents', async () => {
+ registerAgent({ source: 'registry', id: 'claude-acp', name: 'Claude Agent' });
+ const user = userEvent.setup();
+ await renderComposer();
+
+ window.location.hash = '';
+ await user.click(screen.getByTestId('ask-ai-agent-trigger'));
+ await user.click(await screen.findByTestId('ask-ai-agent-option-settings'));
+
+ // Deep-links to the Configure agents settings tab; no launch, no dispatch.
+ expect(window.location.hash).toBe('#settings/configure-agents');
+ expect(startThreadCalls).toHaveLength(0);
+ expect(dispatchCalls).toHaveLength(0);
+ });
+
test('the Claude CLI option launches in the docked terminal, not a deep-link dispatch', async () => {
const user = userEvent.setup();
await renderComposerWithTerminal();
@@ -698,18 +814,18 @@ describe('BottomComposer (dispatch + picker + sticky default)', () => {
);
});
- test('desktop with no sticky pick and no CLI installed defaults to the Claude CLI', async () => {
+ test('no CLI installed and no in-app agent shows a plain Ask — no forced Claude CLI', async () => {
await renderComposerWithInstalledClis({
claude: false,
codex: false,
opencode: false,
cursor: false,
});
- // The install-nudge default: launching claude surfaces the "Get Claude" banner.
- // The " CLI" suffix distinguishes it from the app-target "Claude" (claude-code).
- await waitFor(() =>
- expect(screen.getByTestId('ask-ai-send').textContent).toContain('Claude CLI'),
- );
+ // With nothing enabled to launch — every CLI probed absent and no registered
+ // in-app agent — the primary no longer forces a Claude CLI fallback that
+ // ignored the toggles. It reads a plain "Ask".
+ await waitFor(() => expect(screen.getByTestId('ask-ai-send').textContent).toContain('Ask'));
+ expect(screen.getByTestId('ask-ai-send').textContent).not.toContain('Claude CLI');
});
test('the Ask X picker lists the Terminal section before the Desktop section (Terminal-first)', async () => {
@@ -1143,7 +1259,7 @@ describe('BottomComposer (compact selection chip + preview)', () => {
describe('BottomComposer (dismiss / reopen)', () => {
test('clicking the collapse handle calls onDismiss', async () => {
- const onDismiss = mock(() => {});
+ const onDismiss = vi.fn(() => {});
await renderComposer('notes', { onDismiss });
fireEvent.click(screen.getByRole('button', { name: 'Collapse Ask AI' }));
@@ -1159,7 +1275,7 @@ describe('BottomComposer (dismiss / reopen)', () => {
});
test('⌘L while dismissed reopens (calls onReopen) instead of focusing', async () => {
- const onReopen = mock(() => {});
+ const onReopen = vi.fn(() => {});
await renderComposer('notes', { dismissed: true, onReopen });
dispatchOpenAskAiShortcut();
diff --git a/packages/app/src/components/BottomComposer.tsx b/packages/app/src/components/BottomComposer.tsx
index 14c43230d..8e3939c72 100644
--- a/packages/app/src/components/BottomComposer.tsx
+++ b/packages/app/src/components/BottomComposer.tsx
@@ -28,15 +28,18 @@
import { type TargetData, TERMINAL_CLIS, type TerminalCli } from '@inkeep/open-knowledge-core';
import { Trans, useLingui } from '@lingui/react/macro';
import { ChevronDown, Loader2, TextQuote, X } from 'lucide-react';
-import { useEffect, useRef, useState } from 'react';
+import { type ReactNode, useEffect, useRef, useState } from 'react';
import { toast } from 'sonner';
+import { RegisteredAgentIcon } from '@/components/acp/RegisteredAgentIcon';
import { ComposerContextChips } from '@/components/ComposerContextChips';
import { AgentSplitButton } from '@/components/handoff/AgentSplitButton';
import { TargetIcon } from '@/components/handoff/OpenInAgentMenuItem';
import { useTerminalLaunch } from '@/components/handoff/TerminalLaunchContext';
-import { cliIconTargetId, visibleTerminalClis } from '@/components/handoff/terminal-cli-display';
+import { cliIconTargetId } from '@/components/handoff/terminal-cli-display';
import {
buildComposerHandoffInput,
+ openInstallUrl,
+ startAgentThreadForInput,
useHandoffDispatch,
} from '@/components/handoff/useHandoffDispatch';
import { useInstalledAgents } from '@/components/handoff/useInstalledAgents';
@@ -54,17 +57,30 @@ import {
} from '@/editor/selection-context';
import type { EditorSurface } from '@/editor/selection-stats';
import { useSelectionContext } from '@/hooks/use-selection-context';
-import { resolveDefaultCli } from '@/lib/default-cli-resolver';
+import { isDesktopTargetEnabled, isInAppAgentEnabled } from '@/lib/acp/agent-visibility';
+import { useEnabledOverrides } from '@/lib/acp/enabled-agents';
+import {
+ enabledDesktopTargets,
+ enabledTerminalClis,
+ resolveLauncherSelection,
+} from '@/lib/acp/launcher-selection';
+import {
+ pickEffectiveDefaultAgent,
+ type RegisteredAgent,
+ registerAgent,
+ useDefaultRegisteredAgent,
+ useRegisteredAgents,
+} from '@/lib/acp/registered-agents';
import { VISIBLE_TARGETS } from '@/lib/handoff/targets';
import { matchesKeyboardShortcut } from '@/lib/keyboard-shortcuts';
import { recordOnboardingAskedAi } from '@/lib/onboarding-signals';
import {
+ IN_APP_THREAD_ID,
loadStickyAgent,
- parseStickyCliId,
- resolveStickyAgent,
saveStickyAgent,
terminalCliId,
} from '@/lib/unified-agent-store';
+import { openAgentSettings } from '@/lib/use-settings-route';
import { useWorkspace } from '@/lib/use-workspace';
import { cn } from '@/lib/utils';
import { docNameToRelativePath } from '@/lib/workspace-paths';
@@ -158,6 +174,15 @@ function useRotatingSuggestion(
return { text: phrases[safeIndex] ?? '', visible };
}
+/**
+ * "Start {agentName}" with the named placeholder — keeps the catalog message
+ * shared with the launcher menus' t-macro form (`t\`Start ${agentName}\``);
+ * inlining a member expression would emit a positional `{0}` and fork it.
+ */
+function StartAgentNameLabel({ agentName }: { agentName: string }): ReactNode {
+ return <Trans>Start {agentName}</Trans>;
+}
+
export function BottomComposer({
docName,
surface,
@@ -201,6 +226,7 @@ export function BottomComposer({
const workspace = useWorkspace();
const { pageMeta } = usePageList();
const { states } = useInstalledAgents();
+ const overrides = useEnabledOverrides();
const { dispatch } = useHandoffDispatch();
// Desktop-only docked-terminal launcher (null on web). Its presence is what
// lets the picker offer "Claude CLI" alongside the deep-link app targets,
@@ -465,33 +491,53 @@ export function BottomComposer({
// sentinel (`terminal-cli:<cli>`) only resolves to terminal mode when the
// launcher is available, so a sticky CLI pick degrades to the first app target
// on the web host.
- const effectiveId = selectedId ?? stickyId;
- // An explicit CLI pick (sticky or this session) launches that CLI regardless of
- // install state — a missing binary just prints "command not found".
- const explicitCli: TerminalCli | null =
- terminalLaunch !== null ? parseStickyCliId(effectiveId) : null;
- // Desktop with nothing picked at all → lead with the first-installed CLI
- // (resolveDefaultCli; Claude if none) instead of the first app target, matching
- // what New chat launches. Derived, never saved, so a freshly-installed CLI can
- // take over the default mid-session; web keeps the app-target default.
- const defaultCli: TerminalCli | null =
- terminalLaunch !== null && effectiveId === null
- ? resolveDefaultCli(null, terminalLaunch.installedClis)
- : null;
- const selectedCli: TerminalCli | null = explicitCli ?? defaultCli;
+ const defaultRegisteredAgent = useDefaultRegisteredAgent();
+ // Every registered agent gets its own picker row — only the ENABLED ones show.
+ const registeredThreadAgents = useRegisteredAgents();
+ const enabledThreadAgents = registeredThreadAgents.filter((agent) =>
+ isInAppAgentEnabled(overrides, agent.source, agent.id, true, agent.supported),
+ );
+ // The in-app agent the primary launches + names: the registered default when
+ // it is still enabled, else the first enabled one.
+ const defaultThreadAgent = pickEffectiveDefaultAgent(enabledThreadAgents, defaultRegisteredAgent);
+
+ // One selection decision, enablement-aware for every category — shared with the
+ // create composer + sessions dock via `resolveLauncherSelection`, so a disabled
+ // agent / CLI / app is never what the primary launches on any surface.
+ const selection = resolveLauncherSelection({
+ sticky: selectedId ?? stickyId,
+ effectiveThreadAgent: defaultThreadAgent,
+ enabledClis:
+ terminalLaunch !== null ? enabledTerminalClis(overrides, terminalLaunch.installedClis) : [],
+ enabledDesktopTargets: enabledDesktopTargets(overrides),
+ installedClis: terminalLaunch?.installedClis ?? {},
+ terminalAvailable: terminalLaunch !== null,
+ threadsAvailable: true,
+ desktopSelectable: true,
+ });
+ const isThreadSelected = selection.kind === 'thread';
+ const selectedCli: TerminalCli | null = selection.kind === 'cli' ? selection.cli : null;
const isTerminalSelected = selectedCli !== null;
- const resolvedTarget = isTerminalSelected ? null : resolveStickyAgent(states, effectiveId);
+ const resolvedTarget: TargetData | null =
+ selection.kind === 'desktop'
+ ? (VISIBLE_TARGETS.find((target) => target.id === selection.target) ?? null)
+ : null;
// Sendable with a typed instruction OR a pinned selection alone (the passage
// is enough context to hand off).
const canSend =
!pending &&
(!isEmpty || pinnedSelection !== null) &&
- (isTerminalSelected || resolvedTarget !== null);
+ (isTerminalSelected || resolvedTarget !== null || isThreadSelected);
- // Picker options for the split button's menu. `agentProbePending` distinguishes
- // "still detecting" from "detected none" for the empty-menu hint.
- const installedAgents = VISIBLE_TARGETS.filter((target) => states[target.id]?.installed === true);
+ // Picker options for the split button's menu. Desktop rows are the agents the
+ // user has ENABLED in Configure agents (source of truth), not just the
+ // install-detected ones — an enabled-but-not-installed agent still shows and
+ // routes to its installer on launch.
+ // `agentProbePending` distinguishes "still detecting" from "none" for the hint.
+ const desktopAgents = VISIBLE_TARGETS.filter((target) =>
+ isDesktopTargetEnabled(overrides, target.id),
+ );
const agentProbePending = VISIBLE_TARGETS.some((target) => states[target.id]?.installed == null);
// The docked-terminal CLI rows (desktop only) — one row per launchable CLI,
@@ -500,13 +546,13 @@ export function BottomComposer({
// name carries "<name> CLI" (WCAG 2.5.3 — the accessible name contains the
// visible label) so AT users can tell a Terminal row apart from a same-named
// Desktop row. The "Terminal" section header plus the brand icon carry that
- // same distinction for sighted users. Gated by `visibleTerminalClis` (Claude
- // plus CLIs the probe hasn't ruled out) so an uninstalled CLI doesn't appear
- // once probed absent; `selectedCli` is kept so the current pick can't be gated
- // out of its own dropdown. Single install-map source: the launch context.
+ // same distinction for sighted users. Rows are the ENABLED CLIs
+ // (`enabledTerminalClis`, the same set the selection resolver reads), so an
+ // uninstalled or toggled-off CLI never appears — and since `selectedCli` is
+ // only ever an enabled CLI, no keep-guard is needed.
const cliRows =
terminalLaunch !== null
- ? visibleTerminalClis(terminalLaunch.installedClis, selectedCli).map((cli) => {
+ ? enabledTerminalClis(overrides, terminalLaunch.installedClis).map((cli) => {
const { displayName } = TERMINAL_CLIS[cli];
return {
cli,
@@ -542,6 +588,19 @@ export function BottomComposer({
saveStickyAgent(id);
};
+ const handleSelectThread = () => {
+ setSelectedId(IN_APP_THREAD_ID);
+ saveStickyAgent(IN_APP_THREAD_ID);
+ };
+
+ // Picking a specific registered agent re-registers it (making it the
+ // default the submit path launches — "the agent you chose last is your
+ // agent") and selects thread mode.
+ const handleSelectThreadAgent = (agent: RegisteredAgent) => {
+ registerAgent(agent);
+ handleSelectThread();
+ };
+
const clearComposer = () => {
inputRef.current?.clear();
setPinnedSelection(null);
@@ -568,6 +627,21 @@ export function BottomComposer({
toast.error(t`Couldn't send your prompt — please try again.`);
return;
}
+ // In-app agent thread: open a server-hosted thread with the composed prompt
+ // (like "Open with AI → Start an agent"), then clear. Works on every host.
+ // Launch the effective (enabled) agent explicitly so a disabled registered
+ // default is never launched.
+ if (isThreadSelected) {
+ startAgentThreadForInput(
+ input,
+ defaultThreadAgent !== null
+ ? { agent: { source: defaultThreadAgent.source, id: defaultThreadAgent.id } }
+ : undefined,
+ );
+ recordOnboardingAskedAi();
+ clearComposer();
+ return;
+ }
// CLI mode: hand the composed prompt to the docked terminal for the selected
// CLI (like Open with AI) and clear. No deep-link dispatch. Stickiness already
// persisted on pick (handleSelectCli), so no save here. If the launch throws
@@ -585,6 +659,15 @@ export function BottomComposer({
return;
}
if (resolvedTarget === null) return;
+ // An enabled-but-not-installed Desktop agent routes to its installer
+ // rather than a failing deep-link dispatch (the toggle can enable an agent
+ // the user hasn't installed yet).
+ if (states[resolvedTarget.id]?.installed !== true) {
+ void openInstallUrl(resolvedTarget);
+ toast.info(t`${resolvedTarget.displayName} isn't installed yet — opening its download page.`);
+ clearComposer();
+ return;
+ }
setPending(true);
// dispatchHandoff never throws and toasts success/error itself; on resolve
// we clear regardless of outcome (the toast carries any retry). The onboarding
@@ -601,8 +684,10 @@ export function BottomComposer({
});
};
- const submit = () => {
- if (!canSend) return;
+ // Compose the current draft (instruction + chips + pinned selection) into a
+ // handoff input — shared by `submit` (which dispatches it) and the picker's
+ // "Choose another agent…" row (which carries it into the catalog).
+ const composeCurrentInput = () => {
const { instruction, mentions } = inputRef.current?.getContent() ?? {
instruction: '',
mentions: [],
@@ -615,16 +700,13 @@ export function BottomComposer({
const dispatchMentions = [...new Set([...fileChips, ...mentions])].filter(
(path) => path !== folderPath,
);
- dispatchComposed(
- buildComposerHandoffInput({
- docName: null,
- folderRelativePath: folderPath,
- workspace,
- instruction,
- mentions: dispatchMentions,
- }),
- );
- return;
+ return buildComposerHandoffInput({
+ docName: null,
+ folderRelativePath: folderPath,
+ workspace,
+ instruction,
+ mentions: dispatchMentions,
+ });
}
// The pinned doc selection rides as a passage: inline text for a short
@@ -654,16 +736,19 @@ export function BottomComposer({
const dispatchMentions = [...new Set([...fileChips, ...mentions])].filter(
(path) => path !== leadPath,
);
- dispatchComposed(
- buildComposerHandoffInput({
- docName: leadDocName,
- ...(leadPath !== null ? { docRelativePath: leadPath } : {}),
- workspace,
- instruction,
- mentions: dispatchMentions,
- selection,
- }),
- );
+ return buildComposerHandoffInput({
+ docName: leadDocName,
+ ...(leadPath !== null ? { docRelativePath: leadPath } : {}),
+ workspace,
+ instruction,
+ mentions: dispatchMentions,
+ selection,
+ });
+ };
+
+ const submit = () => {
+ if (!canSend) return;
+ dispatchComposed(composeCurrentInput());
};
// Dismissed: render nothing (the host shows the footer reopen badge). The
@@ -846,13 +931,25 @@ export function BottomComposer({
<AgentSplitButton
primary={
<>
- {selectedCli !== null ? (
+ {isThreadSelected ? (
+ <RegisteredAgentIcon
+ agentId={defaultThreadAgent?.id ?? ''}
+ iconUrl={defaultThreadAgent?.iconUrl}
+ className="size-4"
+ />
+ ) : selectedCli !== null ? (
<TargetIcon id={cliIconTargetId(selectedCli)} className="size-4" aria-hidden />
) : resolvedTarget ? (
<TargetIcon id={resolvedTarget.id} className="size-4" aria-hidden />
) : null}
<span>
- {selectedCli !== null ? (
+ {isThreadSelected ? (
+ defaultThreadAgent !== null ? (
+ <StartAgentNameLabel agentName={defaultThreadAgent.name} />
+ ) : (
+ <Trans>Start an agent</Trans>
+ )
+ ) : selectedCli !== null ? (
<Trans>Ask {TERMINAL_CLIS[selectedCli].displayName} CLI</Trans>
) : resolvedTarget ? (
<Trans>Ask {resolvedTarget.displayName}</Trans>
@@ -865,16 +962,29 @@ export function BottomComposer({
}
onPrimary={submit}
primaryDisabled={!canSend}
- installedTargets={installedAgents}
+ installedTargets={desktopAgents}
selectedTargetId={isTerminalSelected ? null : (resolvedTarget?.id ?? null)}
onSelectTarget={handleSelectAgent}
+ threadAgents={enabledThreadAgents.map((agent) => ({
+ key: `${agent.source}:${agent.id}`,
+ id: agent.id,
+ name: agent.name,
+ ...(agent.iconUrl !== undefined ? { iconUrl: agent.iconUrl } : {}),
+ selected:
+ isThreadSelected &&
+ defaultThreadAgent !== null &&
+ defaultThreadAgent.source === agent.source &&
+ defaultThreadAgent.id === agent.id,
+ onSelect: () => handleSelectThreadAgent(agent),
+ }))}
+ onOpenSettings={openAgentSettings}
terminals={cliRows}
menuEmptyState={
<p className="px-2 py-1.5 text-sm text-muted-foreground" aria-live="polite">
{agentProbePending ? (
- <Trans>Checking for installed agents</Trans>
+ <Trans>Checking for agents</Trans>
) : (
- <Trans>No installed agents found</Trans>
+ <Trans>No agents enabled</Trans>
)}
</p>
}
@@ -884,6 +994,8 @@ export function BottomComposer({
trigger: 'ask-ai-agent-trigger',
menu: 'ask-ai-agent-menu',
option: (id) => `ask-ai-agent-option-${id}`,
+ threadAgent: (key) => `ask-ai-agent-option-thread-${key}`,
+ settings: 'ask-ai-agent-option-settings',
// Back-compat: the Claude row keeps the original singular id; the
// new Codex / Cursor rows are namespaced under `terminal-` so they
// never collide with the Desktop `ask-ai-agent-option-<id>` rows.
diff --git a/packages/app/src/components/CreatedItemsList.dom.test.tsx b/packages/app/src/components/CreatedItemsList.dom.test.tsx
index ff8950b6a..e8cf2ee9e 100644
--- a/packages/app/src/components/CreatedItemsList.dom.test.tsx
+++ b/packages/app/src/components/CreatedItemsList.dom.test.tsx
@@ -1,20 +1,21 @@
-import { afterEach, describe, expect, mock, test } from 'bun:test';
import * as actualLinguiMacro from '@lingui/react/macro';
import { cleanup, render, screen } from '@testing-library/react';
import type { ReactNode } from 'react';
+import { afterEach, describe, expect, test, vi } from 'vitest';
import { TooltipProvider } from '@/components/ui/tooltip';
import type { OkScaffoldPlan, OkSeedPackInfo } from '@/lib/desktop-bridge-types';
import { renderLinguiTemplate } from '@/test-utils/lingui-mock';
-mock.module('@lingui/react/macro', () => ({
+vi.doMock('@lingui/react/macro', () => ({
...actualLinguiMacro,
Trans: ({ children }: { children: ReactNode }) => <>{children}</>,
useLingui: () => ({ t: renderLinguiTemplate }),
}));
-mock.module('@lingui/core/macro', () => ({
+vi.doMock('@lingui/core/macro', () => ({
...actualLinguiMacro,
t: renderLinguiTemplate,
+ msg: renderLinguiTemplate,
plural: (value: number, options: { one: string; other: string }) =>
(value === 1 ? options.one : options.other).replace('#', String(value)),
}));
diff --git a/packages/app/src/components/DesktopAgentMigration.tsx b/packages/app/src/components/DesktopAgentMigration.tsx
new file mode 100644
index 000000000..0cb2ccdb2
--- /dev/null
+++ b/packages/app/src/components/DesktopAgentMigration.tsx
@@ -0,0 +1,15 @@
+import { useInstalledAgents } from '@/components/handoff/useInstalledAgents';
+import { useMigrateInstalledDesktopAgentsOnce } from '@/lib/acp/desktop-migration';
+
+/**
+ * Desktop-only, renders nothing. Runs the one-time "carry over installed desktop
+ * apps" upgrade migration once the install probe resolves, so a user who was
+ * launching Claude Desktop / Cursor before Desktop went opt-in keeps seeing
+ * those rows. Mount inside the `desktopBridge` guard in `App`. Full rationale:
+ * `lib/acp/desktop-migration.ts`.
+ */
+export function DesktopAgentMigration(): null {
+ const { states } = useInstalledAgents();
+ useMigrateInstalledDesktopAgentsOnce(states);
+ return null;
+}
diff --git a/packages/app/src/components/DocPanel.dom.test.tsx b/packages/app/src/components/DocPanel.dom.test.tsx
index 46c54595c..30a0a8049 100644
--- a/packages/app/src/components/DocPanel.dom.test.tsx
+++ b/packages/app/src/components/DocPanel.dom.test.tsx
@@ -11,9 +11,9 @@
* diagnostics.
*/
-import { afterEach, describe, expect, mock, test } from 'bun:test';
import { cleanup, render, screen } from '@testing-library/react';
import type { ReactNode } from 'react';
+import { afterEach, describe, expect, test, vi } from 'vitest';
import { TooltipProvider } from '@/components/ui/tooltip';
import { renderLinguiTemplate } from '@/test-utils/lingui-mock';
@@ -36,8 +36,12 @@ if (g.ResizeObserver === undefined) {
import * as actualLinguiMacro from '@lingui/react/macro';
-mock.module('@lingui/core/macro', () => ({ ...actualLinguiMacro, t: renderLinguiTemplate }));
-mock.module('@lingui/react/macro', () => ({
+vi.doMock('@lingui/core/macro', () => ({
+ ...actualLinguiMacro,
+ t: renderLinguiTemplate,
+ msg: renderLinguiTemplate,
+}));
+vi.doMock('@lingui/react/macro', () => ({
...actualLinguiMacro,
Trans: ({ children }: { children: ReactNode }) => children,
useLingui: () => ({ t: renderLinguiTemplate }),
@@ -45,39 +49,39 @@ mock.module('@lingui/react/macro', () => ({
// Single-file signal — flipped per test.
let singleFileValue = false;
-mock.module('@/lib/single-file-mode', () => ({ useSingleFileMode: () => singleFileValue }));
+vi.doMock('@/lib/single-file-mode', () => ({ useSingleFileMode: () => singleFileValue }));
// Lint plumbing — DocPanel computes live diagnostics to drive the Problems
// badge. Stub the source so the test controls the count without a provider/fetch.
let diagnosticsValue: Array<{ severity: string }> = [];
let activeProviderValue: unknown = null;
-mock.module('@/editor/DocumentContext', () => ({
+vi.doMock('@/editor/DocumentContext', () => ({
useDocumentContext: () => ({ activeProvider: activeProviderValue, activeDocName: 'notes' }),
}));
-mock.module('@/editor/lint-config-client', () => ({
+vi.doMock('@/editor/lint-config-client', () => ({
useDocLintConfig: () => ({ data: null }),
}));
-mock.module('@/editor/useDocDiagnostics', () => ({
+vi.doMock('@/editor/useDocDiagnostics', () => ({
useDocDiagnostics: () => diagnosticsValue,
}));
// Terminal availability drives the Ask-AI gate — null mirrors the web host.
let terminalLaunchValue: unknown = null;
-mock.module('@/components/handoff/TerminalLaunchContext', () => ({
+vi.doMock('@/components/handoff/TerminalLaunchContext', () => ({
useTerminalLaunch: () => terminalLaunchValue,
}));
// Stub the heavy panel children so the test stays focused on tab visibility.
-mock.module('@/components/OutlinePanel', () => ({
+vi.doMock('@/components/OutlinePanel', () => ({
OutlinePanel: () => <div data-testid="outline-panel" />,
}));
-mock.module('@/components/LinksPanel', () => ({
+vi.doMock('@/components/LinksPanel', () => ({
LinksPanel: () => <div data-testid="links-panel" />,
}));
-mock.module('@/components/TimelinePanel', () => ({
+vi.doMock('@/components/TimelinePanel', () => ({
TimelineContent: () => <div data-testid="timeline-panel" />,
}));
let lastProblemsProps: Record<string, unknown> | null = null;
-mock.module('@/components/ProblemsPanel', () => ({
+vi.doMock('@/components/ProblemsPanel', () => ({
ProblemsPanel: (props: Record<string, unknown>) => {
lastProblemsProps = props;
return <div data-testid="problems-panel" />;
diff --git a/packages/app/src/components/EditorArea.dom.test.tsx b/packages/app/src/components/EditorArea.dom.test.tsx
index 31887cff6..5c48f304a 100644
--- a/packages/app/src/components/EditorArea.dom.test.tsx
+++ b/packages/app/src/components/EditorArea.dom.test.tsx
@@ -1,6 +1,6 @@
-import { afterEach, beforeEach, describe, expect, mock, test } from 'bun:test';
import { act, cleanup, fireEvent, render, screen } from '@testing-library/react';
import { type ReactNode, useEffect } from 'react';
+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
type SettingsDialogShellProps = {
open: boolean;
@@ -8,15 +8,15 @@ type SettingsDialogShellProps = {
};
let settingsRouteOpen = false;
-let closeSettingsRouteMock = mock(() => {});
+let closeSettingsRouteMock = vi.fn(() => {});
let shellProps: SettingsDialogShellProps[] = [];
-mock.module('@/lib/perf', () => ({
+vi.doMock('@/lib/perf', () => ({
mark: () => {},
ProfilerBoundary: ({ children }: { children: ReactNode }) => children,
}));
-mock.module('@/components/PropertyContext', () => ({
+vi.doMock('@/components/PropertyContext', () => ({
PropertyProvider: ({ children }: { children: ReactNode }) => children,
useProperties: () => ({ requestAddProperty: () => {} }),
}));
@@ -24,7 +24,7 @@ mock.module('@/components/PropertyContext', () => ({
// EditorArea reads the project config binding (for the desktop "toggle content
// rules" menu action). These tests mount EditorArea outside a ConfigProvider,
// so stub the hook with a null binding — the toggle handler is a no-op here.
-mock.module('@/lib/config-provider', () => ({
+vi.doMock('@/lib/config-provider', () => ({
useConfigContext: () => ({ projectBinding: null }),
}));
@@ -89,12 +89,12 @@ let docCtx:
| typeof LARGE_FILE_DOC_CTX
| typeof ASSET_DOC_CTX
| typeof DOC_COLD_CTX = FOLDER_DOC_CTX;
-mock.module('@/editor/DocumentContext', () => ({
+vi.doMock('@/editor/DocumentContext', () => ({
useDocumentContext: () => docCtx,
useDocumentTransition: () => ({ openDocumentTransition: null }),
}));
-mock.module('@/components/EmptyEditorState', () => ({
+vi.doMock('@/components/EmptyEditorState', () => ({
// Forward terminalDock so the EditorArea -> EmptyEditorState prop wiring is
// observable (the empty state collapses to the header-only view whenever a
// terminal is up, in either dock).
@@ -106,11 +106,11 @@ mock.module('@/components/EmptyEditorState', () => ({
// Counts TerminalDock mounts so a remount-on-view-switch regression (which
// would dispose xterm + kill the PTY) is observable in tests.
let terminalDockMounts = 0;
-mock.module('@/components/EditorSkeleton', () => ({
+vi.doMock('@/components/EditorSkeleton', () => ({
EditorSkeleton: () => <div data-testid="editor-skeleton" />,
}));
-mock.module('./TerminalDock', () => ({
+vi.doMock('./TerminalDock', () => ({
TerminalDock: ({ children, visible }: { children: ReactNode; visible?: boolean }) => {
useEffect(() => {
terminalDockMounts += 1;
@@ -132,7 +132,7 @@ mock.module('./TerminalDock', () => ({
let groupLayout: Record<string, number> = {};
let groupSetLayoutCalls: Array<Record<string, number>> = [];
let panelIsCollapsed = false;
-mock.module('react-resizable-panels', () => ({
+vi.doMock('react-resizable-panels', () => ({
usePanelRef: () => ({
current: {
collapse: () => {},
@@ -155,7 +155,7 @@ mock.module('react-resizable-panels', () => ({
// panel + optional right panel), so the resizable primitives must resolve in
// the DOM harness. Passthrough mocks render children without the real
// react-resizable-panels engine (which is stubbed).
-mock.module('@/components/ui/resizable', () => ({
+vi.doMock('@/components/ui/resizable', () => ({
ResizablePanelGroup: ({ children }: { children: ReactNode }) => (
<div data-testid="resizable-group">{children}</div>
),
@@ -167,23 +167,23 @@ mock.module('@/components/ui/resizable', () => ({
),
}));
-mock.module('@/hooks/use-doc-panel-layout', () => ({
+vi.doMock('@/hooks/use-doc-panel-layout', () => ({
useDocPanelLayout: () => ({ layout: 'panel', autoCollapse: false }),
}));
-mock.module('@/hooks/use-document-stats', () => ({
+vi.doMock('@/hooks/use-document-stats', () => ({
useDocumentStats: () => null,
}));
-mock.module('@/hooks/use-lifecycle-status', () => ({
+vi.doMock('@/hooks/use-lifecycle-status', () => ({
useLifecycleStatus: () => 'ready',
}));
-mock.module('@/presence/use-sync-status', () => ({
+vi.doMock('@/presence/use-sync-status', () => ({
useSyncStatus: () => 'synced',
}));
-mock.module('@/components/FolderOverview', () => ({
+vi.doMock('@/components/FolderOverview', () => ({
FolderOverview: ({ folderPath }: { folderPath: string }) => (
<div data-testid="folder-overview">{folderPath}</div>
),
@@ -194,32 +194,32 @@ mock.module('@/components/FolderOverview', () => ({
// in its config / workspace / TipTap dependency tree — the gate is unit-tested
// in bottom-composer-gate.test.ts and the composer itself in
// BottomComposer.dom.test.tsx.
-mock.module('./BottomComposer', () => ({
+vi.doMock('./BottomComposer', () => ({
BottomComposer: ({ docName, folderPath }: { docName?: string | null; folderPath?: string }) => (
<div data-testid="bottom-composer" data-doc={docName ?? ''} data-folder={folderPath ?? ''} />
),
}));
-mock.module('@/components/AssetPreview', () => ({
+vi.doMock('@/components/AssetPreview', () => ({
AssetPreview: ({ assetPath }: { assetPath: string }) => (
<div data-testid="asset-preview">{assetPath}</div>
),
}));
-mock.module('@/components/LargeFileEditorState', () => ({
+vi.doMock('@/components/LargeFileEditorState', () => ({
LargeFileEditorState: ({ docName }: { docName: string }) => (
<div data-testid="large-file-state">{docName}</div>
),
}));
-mock.module('@/components/settings/SettingsDialogShell', () => ({
+vi.doMock('@/components/settings/SettingsDialogShell', () => ({
SettingsDialogShell: (props: SettingsDialogShellProps) => {
shellProps.push(props);
return <div data-testid="settings-shell" data-open={String(props.open)} />;
},
}));
-mock.module('@/lib/use-settings-route', () => ({
+vi.doMock('@/lib/use-settings-route', () => ({
useSettingsRoute: () => ({
open: settingsRouteOpen,
close: closeSettingsRouteMock,
@@ -244,7 +244,7 @@ describe('EditorArea SettingsDialogPortal runtime wiring', () => {
cleanup();
docCtx = FOLDER_DOC_CTX;
settingsRouteOpen = false;
- closeSettingsRouteMock = mock(() => {});
+ closeSettingsRouteMock = vi.fn(() => {});
shellProps = [];
});
@@ -323,7 +323,7 @@ describe('EditorArea empty-state terminal host', () => {
expect(emptyState?.getAttribute('data-terminal-dock')).toBe('right');
});
- test('renders the empty state with no terminal dock on the web host (no bridge)', () => {
+ test('renders the empty state; the dock shell is present but inactive on the web host', () => {
render(
<EditorArea
editorMode="wysiwyg"
@@ -333,10 +333,11 @@ describe('EditorArea empty-state terminal host', () => {
/>,
);
- expect(screen.queryByTestId('terminal-dock')).toBeNull();
+ // The dock shell is host-agnostic now, but with nothing docked it stays inactive.
+ expect(screen.getByTestId('terminal-dock').getAttribute('data-visible')).toBe('false');
// Pins the `terminalVisible ? position : null` forwarding: without an open
- // terminal the empty state must receive null, or it would collapse to
- // header-only on every new tab.
+ // dock the empty state must receive null, or it would collapse to header-only
+ // on every new tab.
expect(screen.getByTestId('empty-editor-state').getAttribute('data-terminal-dock')).toBe(
'null',
);
@@ -498,10 +499,12 @@ describe('EditorArea folder-view terminal host', () => {
expect(dock.querySelector('[data-testid="folder-overview"]')).not.toBeNull();
});
- test('renders the folder view with no terminal dock on the web host (no bridge)', () => {
+ test('renders the folder view; the dock shell is present but inactive on the web host', () => {
renderEditorArea();
- expect(screen.queryByTestId('terminal-dock')).toBeNull();
+ // The dock shell is host-agnostic now (it can host thread tabs on web), so it
+ // wraps the view, but with nothing docked it stays inactive.
+ expect(screen.getByTestId('terminal-dock').getAttribute('data-visible')).toBe('false');
expect(screen.getByTestId('folder-overview').textContent).toBe('folder');
});
});
@@ -534,10 +537,10 @@ describe('EditorArea large-file-view terminal host', () => {
expect(dock.querySelector('[data-testid="large-file-state"]')).not.toBeNull();
});
- test('renders the large-file view with no terminal dock on the web host (no bridge)', () => {
+ test('renders the large-file view; the dock shell is present but inactive on the web host', () => {
renderEditorArea();
- expect(screen.queryByTestId('terminal-dock')).toBeNull();
+ expect(screen.getByTestId('terminal-dock').getAttribute('data-visible')).toBe('false');
expect(screen.getByTestId('large-file-state')).toBeTruthy();
});
});
@@ -566,10 +569,10 @@ describe('EditorArea asset-view terminal host', () => {
expect(dock.querySelector('[data-testid="asset-preview"]')).not.toBeNull();
});
- test('renders the asset view with no terminal dock on the web host (no bridge)', () => {
+ test('renders the asset view; the dock shell is present but inactive on the web host', () => {
renderEditorArea();
- expect(screen.queryByTestId('terminal-dock')).toBeNull();
+ expect(screen.getByTestId('terminal-dock').getAttribute('data-visible')).toBe('false');
expect(screen.getByTestId('asset-preview')).toBeTruthy();
});
});
diff --git a/packages/app/src/components/EditorArea.tsx b/packages/app/src/components/EditorArea.tsx
index c1a2cdaf8..0bedb75ed 100644
--- a/packages/app/src/components/EditorArea.tsx
+++ b/packages/app/src/components/EditorArea.tsx
@@ -146,12 +146,16 @@ interface EditorAreaProps {
* is its own column to the right of the doc/agent panel (MD | PANE | TERMINAL)
* instead of docking under the editor. */
terminalDock?: TerminalDockPosition;
+ /** Whether the sessions dock currently holds any tab (terminal or thread),
+ * reported up from the host. Placement predicates key off dock-visible-&-has-tabs
+ * rather than the bridge, so the dock column renders on web (thread tabs only). */
+ terminalHasSessions?: boolean;
/** Report the terminal's attach point up to EditorPane (which owns the session
* host). See {@link TerminalPlacement}. */
onTerminalPlacement?: (placement: TerminalPlacement) => void;
- /** Reveal the terminal (and spawn a default-CLI session if none is open) —
- * drives the edge "Show terminal" tab shown while the terminal is hidden.
- * Absent on the web host (no terminal). */
+ /** Reveal the sessions dock and seed the preferred New-session choice if none is
+ * open — drives the edge "Open session dock" tab shown while the
+ * dock is hidden. Provided on every host now (web reveals thread tabs). */
onRevealTerminal?: () => void;
}
@@ -196,6 +200,7 @@ function SettingsDialogPortal() {
return (
<SettingsDialogShell
open={settingsRoute.open}
+ initialSection={settingsRoute.section}
onOpenChange={(next) => {
if (!next) settingsRoute.close();
}}
@@ -212,6 +217,7 @@ function EditorAreaInner({
terminalVisible = false,
onTerminalVisibleChange,
terminalDock = 'right',
+ terminalHasSessions = false,
onTerminalPlacement,
onRevealTerminal,
}: EditorAreaProps) {
@@ -376,18 +382,28 @@ function EditorAreaInner({
// across EVERY view kind (the column just has no doc panel beside it on
// asset / large-file / empty views). This is why the dock stays on the right
// even when there's nothing else to put there.
+ // Whether the desktop bridge can host TERMINAL-kind tabs (a session-only bridge
+ // has no `terminal` surface). The dock, its placement, and the reveal tab now
+ // key off dock visibility rather than `terminalBridge != null`, so the column
+ // renders on the web host (thread tabs only). `terminalAvailable` gates only the
+ // terminal-*kind* reveal reason (a cold reveal that can spawn a shell).
+ const terminalAvailable = terminalBridge?.terminal != null;
const rightDocked = terminalDock === 'right';
const terminalDockPosition: TerminalDockPosition = rightDocked ? 'right' : 'bottom';
- // Whether the far-right terminal column participates in the panel group this
- // render. Drives the panel-set-change layout assert below and the collapsed
- // doc-panel neutralization — compute it up here so effects can depend on it.
- const terminalColumnPresent = terminalBridge != null && rightDocked && terminalVisible;
- // The edge "Show terminal" reveal tab is up while the terminal is hidden on the
- // desktop host. It floats over a corner other UI also wants: bottom-dock over
- // the editor footer's bottom-right (the footer reserves gutter), right-dock over
- // the far-right top where the toolbar's action buttons sit when the doc panel is
- // collapsed (the toolbar shifts its cluster left).
- const revealTabHidden = terminalBridge != null && !terminalVisible && onRevealTerminal != null;
+ // Whether the far-right dock column participates in the panel group this render.
+ // Drives the panel-set-change layout assert below and the collapsed doc-panel
+ // neutralization — compute it up here so effects can depend on it. Un-gated from
+ // the bridge: on web the column hosts thread tabs. The host renders a starting /
+ // empty state while a session spins up, so keying off visibility (not has-tabs)
+ // keeps the dock's feedback immediate during the seconds-long agent spawn.
+ const terminalColumnPresent = rightDocked && terminalVisible;
+ // The edge "Show sessions" reveal tab is up while the dock is hidden. A terminal
+ // surface always shows it (revealing can seed a shell); a thread-only surface
+ // shows it only with latched tabs to return to (its cold entry is the handoff
+ // menu, not this tab). It floats over a corner other UI also wants: bottom-dock
+ // over the editor footer's bottom-right, right-dock over the far-right top.
+ const revealTabHidden =
+ !terminalVisible && onRevealTerminal != null && (terminalAvailable || terminalHasSessions);
const bottomRevealTabPresent = revealTabHidden && !rightDocked;
const rightRevealTabPresent = revealTabHidden && rightDocked;
const rightTerminalShowing = rightDocked && terminalVisible && rightTerminalContainer != null;
@@ -1247,27 +1263,25 @@ function EditorAreaInner({
// A single TerminalDock wraps the active view's left column. The skeleton
// below is structurally identical for every view kind, so the dock keeps one
- // React position and its PTY survives tab switches and view-kind changes.
- // Desktop-only — the web host passes no bridge and renders the column bare.
- // The live terminal session host lives in EditorPane (above this component) so a
- // dock toggle — which remounts EditorArea's subtree — can't re-spawn it. Here we
- // render only the bottom layout shell, which reports its mount + editor region up
- // (the placement is reported to EditorPane via onTerminalPlacement above).
- const leftColumn =
- terminalBridge != null ? (
- <TerminalDock
- visible={terminalVisible}
- onVisibleChange={onTerminalVisibleChange ?? (() => {})}
- dockPosition={terminalDockPosition}
- onBottomContainer={setBottomTerminalContainer}
- onEditorRegion={setTerminalEditorRegion}
- onReveal={onRevealTerminal}
- >
- {viewContent}
- </TerminalDock>
- ) : (
- viewContent
- );
+ // React position and its PTY survives tab switches and view-kind changes. It
+ // renders on EVERY host now (web too) — the sessions dock is host-agnostic — so
+ // a bottom-docked thread has a mount container. The live session host lives in
+ // EditorPane (above this component) so a dock toggle — which remounts
+ // EditorArea's subtree — can't re-spawn it. Here we render only the bottom layout
+ // shell, which reports its mount + editor region up (via onTerminalPlacement).
+ const leftColumn = (
+ <TerminalDock
+ visible={terminalVisible}
+ onVisibleChange={onTerminalVisibleChange ?? (() => {})}
+ dockPosition={terminalDockPosition}
+ onBottomContainer={setBottomTerminalContainer}
+ onEditorRegion={setTerminalEditorRegion}
+ onReveal={onRevealTerminal}
+ showRevealTab={bottomRevealTabPresent}
+ >
+ {viewContent}
+ </TerminalDock>
+ );
// The terminal column sits to the RIGHT of the doc/agent panel
// (MD | PANE | TERMINAL) when right-docked and visible — the far-right column,
diff --git a/packages/app/src/components/EditorFooter.tsx b/packages/app/src/components/EditorFooter.tsx
index f960276a3..3da349a77 100644
--- a/packages/app/src/components/EditorFooter.tsx
+++ b/packages/app/src/components/EditorFooter.tsx
@@ -22,7 +22,7 @@ interface EditorFooterProps {
* while the bottom composer is dismissed. Clicking it reopens the composer. */
composerBadge?: { onReopen: () => void } | null;
/** Reserve extra right padding so the right-aligned stats clear the
- * bottom-dock "Show terminal" reveal tab, which floats over the footer's
+ * bottom-dock "Open session dock" reveal tab, which floats over the footer's
* bottom-right corner when the terminal is hidden. */
reserveRightGutter?: boolean;
}
diff --git a/packages/app/src/components/EditorPane.dom.test.tsx b/packages/app/src/components/EditorPane.dom.test.tsx
index a1cd4d627..76c996eec 100644
--- a/packages/app/src/components/EditorPane.dom.test.tsx
+++ b/packages/app/src/components/EditorPane.dom.test.tsx
@@ -1,8 +1,8 @@
-import { afterEach, describe, expect, mock, test } from 'bun:test';
import { act, cleanup, render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { isMacOS } from '@tiptap/core';
import { type ReactNode, useEffect } from 'react';
+import { afterEach, describe, expect, test, vi } from 'vitest';
import { publishSelectionContext } from '@/editor/selection-context';
import type { EditorSurface } from '@/editor/selection-stats';
import { subscribeToActiveTerminalInput } from './handoff/terminal-input-events';
@@ -51,7 +51,7 @@ function shiftJKeydownInit(): KeyboardEventInit {
import * as actualLinguiMacro from '@lingui/react/macro';
-mock.module('@lingui/react/macro', () => ({
+vi.doMock('@lingui/react/macro', () => ({
...actualLinguiMacro,
Trans: ({ children }: { children: ReactNode }) => <>{children}</>,
Plural: ({ value, one, other }: { value: number; one: string; other: string }) => (
@@ -69,14 +69,14 @@ let projectSynced = false;
let projectLocalConfig: { autoSync?: { enabled?: boolean | null } } | null = null;
let projectConfig: { autoSync?: { default?: boolean | null } } | null = null;
-mock.module('@/hooks/use-git-sync-status', () => ({
+vi.doMock('@/hooks/use-git-sync-status', () => ({
useGitSyncStatus: () => ({
hasRemote,
pushPermission: { checkStatus: 'allowed' },
}),
}));
-mock.module('@/lib/config-provider', () => ({
+vi.doMock('@/lib/config-provider', () => ({
useConfigContext: () => ({
projectConfig,
projectLocalConfig,
@@ -85,19 +85,19 @@ mock.module('@/lib/config-provider', () => ({
}),
}));
-mock.module('@/lib/use-workspace', () => ({
+vi.doMock('@/lib/use-workspace', () => ({
useWorkspace: () => ({ contentDir: '/tmp/project', pathSeparator: '/' }),
}));
-mock.module('@/editor/DocumentContext', () => ({
+vi.doMock('@/editor/DocumentContext', () => ({
useDocumentContext: () => ({ activeDocName: 'docs/notes', collabUrl: 'ws://test' }),
}));
-mock.module('@/editor/use-editor-mode', () => ({
+vi.doMock('@/editor/use-editor-mode', () => ({
useEditorMode: () => ['wysiwyg', () => {}],
}));
-mock.module('./EditorHeader', () => ({
+vi.doMock('./EditorHeader', () => ({
EditorHeader: () => <div data-testid="editor-header" />,
}));
@@ -107,15 +107,26 @@ mock.module('./EditorHeader', () => ({
// state. The EditorArea mock is a bare stand-in; the TerminalSessionsHost mock
// (below) surfaces the threaded `visible` + `launch` props so these tests keep
// asserting EditorPane's wiring across the prop boundary.
-mock.module('./EditorArea', () => ({
+vi.doMock('./EditorArea', () => ({
EditorArea: () => <div data-testid="editor-area" />,
}));
-mock.module('./TerminalSessionsHost', () => ({
+// The agent-thread client binder opens a WS + polls /api/config on mount; stub it
+// so these EditorPane tests exercise terminal/onboarding wiring in isolation.
+vi.doMock('./acp/AgentThreadClientBinder', () => ({
+ AgentThreadClientBinder: () => null,
+}));
+// The sessions host now mounts UNCONDITIONALLY (web too) — a shell and an agent
+// are just tabs of a different kind. It receives `bridge` (null on web) so these
+// tests assert EditorPane's wiring across the prop boundary, including which host
+// gets a live bridge.
+vi.doMock('./TerminalSessionsHost', () => ({
TerminalSessionsHost: ({
+ bridge,
visible,
launch,
onActiveSessionCliChange,
}: {
+ bridge?: unknown;
visible?: boolean;
launch?: { nonce: number; stagePaste?: string } | null;
onActiveSessionCliChange?: (isCli: boolean) => void;
@@ -128,6 +139,7 @@ mock.module('./TerminalSessionsHost', () => ({
return (
<div
data-testid="terminal-dock"
+ data-has-bridge={String(bridge != null)}
data-visible={String(visible)}
data-launch-nonce={launch ? String(launch.nonce) : 'none'}
data-launch-stage={launch?.stagePaste ?? 'none'}
@@ -137,20 +149,20 @@ mock.module('./TerminalSessionsHost', () => ({
}));
const terminalOpenedCalls: true[] = [];
-mock.module('@/lib/terminal-telemetry', () => ({
+vi.doMock('@/lib/terminal-telemetry', () => ({
recordTerminalOpened: () => terminalOpenedCalls.push(true),
recordShellConsentGranted: () => undefined,
}));
-mock.module('./AuthModal', () => ({
+vi.doMock('./AuthModal', () => ({
AuthModal: () => <div data-testid="auth-modal" />,
}));
-mock.module('@/editor/components/TagDialog', () => ({
+vi.doMock('@/editor/components/TagDialog', () => ({
TagDialog: () => <div data-testid="tag-dialog" />,
}));
-mock.module('./AutoSyncOnboardingDialog', () => ({
+vi.doMock('./AutoSyncOnboardingDialog', () => ({
AutoSyncOnboardingDialog: ({ open, onResolved }: { open: boolean; onResolved: () => void }) => (
<button
type="button"
@@ -348,24 +360,31 @@ describe('EditorPane terminal dock wiring', () => {
mockActiveIsCli = false;
});
- test('web host renders the editor chrome without a terminal dock', async () => {
+ test('web host mounts the sessions host (host-agnostic) with no desktop bridge', async () => {
await renderEditorPane();
- expect(screen.queryByTestId('terminal-dock')).toBeNull();
+ // The unified sessions dock is host-agnostic now — it mounts on web too (thread
+ // tabs only), just without a desktop bridge (terminal-kind affordances gate on
+ // the bridge inside the host).
+ const dock = screen.getByTestId('terminal-dock');
+ expect(dock).toBeTruthy();
+ expect(dock.getAttribute('data-has-bridge')).toBe('false');
expect(screen.getByTestId('editor-header')).toBeTruthy();
expect(screen.getByTestId('editor-area')).toBeTruthy();
});
- test('desktop host renders the editor chrome with the terminal dock under the editor area', async () => {
+ test('desktop host mounts the sessions host with a live bridge under the editor area', async () => {
(window as { okDesktop?: unknown }).okDesktop = makeOkDesktopStub().stub;
await renderEditorPane();
- // The header and the live terminal session host are both siblings of the
- // editor area now (the host lives in EditorPane so a dock toggle can't remount
- // it). The host renders only when the desktop bridge is present.
+ // The header and the live session host are both siblings of the editor area
+ // (the host lives in EditorPane so a dock toggle can't remount it). On desktop
+ // the host gets a live bridge.
expect(screen.getByTestId('editor-header')).toBeTruthy();
expect(screen.getByTestId('editor-area')).toBeTruthy();
- expect(screen.queryByTestId('terminal-dock')).not.toBeNull();
+ const dock = screen.getByTestId('terminal-dock');
+ expect(dock).not.toBeNull();
+ expect(dock.getAttribute('data-has-bridge')).toBe('true');
});
test('desktop: toggle-terminal menu action flips dock visibility and pushes the view-menu state', async () => {
@@ -607,7 +626,9 @@ describe('EditorPane terminal dock wiring', () => {
const event = new KeyboardEvent('keydown', shiftJKeydownInit());
window.dispatchEvent(event);
expect(event.defaultPrevented).toBe(false);
- expect(screen.queryByTestId('terminal-dock')).toBeNull();
+ // The sessions dock still mounts host-agnostic (thread tabs), but ⇧⌘J is a
+ // terminal-launch accelerator: with no desktop bridge it stages nothing.
+ expect(screen.getByTestId('terminal-dock').getAttribute('data-launch-nonce')).toBe('none');
});
test('desktop: ⌘J with a selection injects into the ACTIVE running CLI (no toggle, no launch)', async () => {
diff --git a/packages/app/src/components/EditorPane.tsx b/packages/app/src/components/EditorPane.tsx
index 017000066..2d98d40a5 100644
--- a/packages/app/src/components/EditorPane.tsx
+++ b/packages/app/src/components/EditorPane.tsx
@@ -1,5 +1,5 @@
import type { TerminalCli } from '@inkeep/open-knowledge-core';
-import { useEffect, useEffectEvent, useRef, useState } from 'react';
+import { lazy, Suspense, useEffect, useEffectEvent, useRef, useState } from 'react';
import { TagDialog } from '@/editor/components/TagDialog';
import { useDocumentContext } from '@/editor/DocumentContext';
import { RAW_MDX_NAV_EVENT, type RawMdxNavDetail } from '@/editor/extensions/raw-mdx-nav-event';
@@ -32,7 +32,25 @@ import { EditorHeader } from './EditorHeader';
import { composeTerminalSelectionPaste } from './handoff/compose-terminal-selection';
import { requestActiveTerminalInput } from './handoff/terminal-input-events';
import { subscribeToTerminalLaunchRequests } from './handoff/terminal-launch-events';
-import { TerminalSessionsHost } from './TerminalSessionsHost';
+import {
+ type AgentThreadLaunchDetail,
+ subscribeToAgentThreadLaunchRequests,
+} from './handoff/thread-launch-events';
+
+// Lazy-loaded: these two mounts are the only eager edges into the ACP
+// thread-client + thread-event-model chain (and the whole sessions-dock UI),
+// which the entry chunk must not carry — the same lazy-panel pattern as
+// ThreadView inside the host. Both mount unconditionally below, so the
+// dynamic import fires on first render; behavior is deferred by one chunk
+// fetch, not gated on user action.
+const AgentThreadClientBinder = lazy(() =>
+ import('./acp/AgentThreadClientBinder').then((mod) => ({
+ default: mod.AgentThreadClientBinder,
+ })),
+);
+const TerminalSessionsHost = lazy(() =>
+ import('./TerminalSessionsHost').then((mod) => ({ default: mod.TerminalSessionsHost })),
+);
/**
* Carries an "Open in terminal" launch from a UI click to the docked terminal
@@ -55,6 +73,22 @@ export interface TerminalLaunchIntent {
readonly stagePaste?: string;
}
+/**
+ * Carries a "Start an agent" launch from a UI click (handoff menus) to the
+ * sessions dock's thread-hosting host — the ACP twin of {@link TerminalLaunchIntent}.
+ * `agentId === ''` means "resolve the default registered agent, or open Configure
+ * agents when none is enabled". `nonce` makes each click a distinct one-shot the
+ * host acts on exactly once.
+ */
+export interface ThreadLaunchIntent {
+ readonly agentSource: 'registry' | 'custom';
+ readonly agentId: string;
+ readonly prompt: string | null;
+ readonly docName: string | null;
+ readonly titleHint: string | null;
+ readonly nonce: number;
+}
+
export type EditorMode = EditorModeValue;
interface EditorPaneProps {
@@ -106,6 +140,10 @@ export function EditorPane({ onOpenSearch }: EditorPaneProps = {}) {
// entry point. Null until a UI click; bumping `nonce` makes each click a
// distinct one-shot the session writes exactly once.
const [terminalLaunch, setTerminalLaunch] = useState<TerminalLaunchIntent | null>(null);
+ // "Start an agent" launch intent threaded to the dock's thread host — the ACP
+ // twin of `terminalLaunch`. Both buses target the one host now.
+ const [threadLaunch, setThreadLaunch] = useState<ThreadLaunchIntent | null>(null);
+ const threadLaunchNonceRef = useRef(0);
// Where the terminal docks (right default | bottom), persisted per machine.
// Moving the terminal is also a request to see it, so the setter reveals the
// dock — re-docking a hidden terminal that stays hidden would feel inert.
@@ -160,15 +198,16 @@ export function EditorPane({ onOpenSearch }: EditorPaneProps = {}) {
});
}
- // Reveal the docked terminal and, if no session exists yet, seed a first one.
- // Drives the edge "Show terminal" reveal tab; leaves the right doc-panel
- // untouched (the two coexist). The seed honors the sticky new-tab pick: for a
- // CLI, launch a chat under the default CLI; when the last pick was a bare
- // "Terminal" (persisted terminal-only), skip the CLI launch and let the host's
- // reveal-from-empty fallback seed a bare shell instead.
+ // Reveal the sessions dock and, if no session exists yet, seed a first one.
+ // Drives the edge "Show sessions" reveal tab; leaves the right doc-panel
+ // untouched (the two coexist). On a terminal surface the seed honors the sticky
+ // pick: for a CLI, launch a chat under the default CLI; when the last pick was a
+ // bare "Terminal", skip the CLI launch and let the host's reveal-from-empty
+ // fallback seed a bare shell. On the web host (no terminal) the host's
+ // reveal-from-empty seed handles the sticky agent instead.
function revealTerminal() {
setTerminalVisible(true);
- if (!hasSessions && !readPreferBareTerminal()) launchNewChat();
+ if (terminalAvailable && !hasSessions && !readPreferBareTerminal()) launchNewChat();
}
const syncStatus = useGitSyncStatus();
@@ -310,6 +349,26 @@ export function EditorPane({ onOpenSearch }: EditorPaneProps = {}) {
});
}, []);
+ // "Start an agent" launch — a handoff-menu click fires a window event naming a
+ // catalog agent + the composed prompt. Reveal the dock AND carry the intent to
+ // the host as a fresh one-shot (the host resolves the agent / opens the catalog
+ // and creates the thread). Universal — agent threads are server-hosted, so
+ // unlike the terminal bus this one has no desktop gate.
+ useEffect(() => {
+ return subscribeToAgentThreadLaunchRequests((detail: AgentThreadLaunchDetail) => {
+ setTerminalVisible(true);
+ threadLaunchNonceRef.current += 1;
+ setThreadLaunch({
+ agentSource: detail.agentSource,
+ agentId: detail.agentId,
+ prompt: detail.prompt,
+ docName: detail.docName,
+ titleHint: detail.titleHint,
+ nonce: threadLaunchNonceRef.current,
+ });
+ });
+ }, []);
+
// Clear the one-shot launch intent whenever the terminal hides. The
// exactly-once-per-nonce guard lives inside the session, which is destroyed
// when a kill drops the dock's mount latch — so without clearing here, the
@@ -420,6 +479,11 @@ export function EditorPane({ onOpenSearch }: EditorPaneProps = {}) {
return (
<>
+ {/* Binds the agent-thread client's WS URL — mounted once so threads stay
+ connected + replayable whether or not the sessions dock is open. */}
+ <Suspense fallback={null}>
+ <AgentThreadClientBinder />
+ </Suspense>
<EditorHeader
onSignIn={() => {
setAuthInitialStep('auth');
@@ -431,31 +495,39 @@ export function EditorPane({ onOpenSearch }: EditorPaneProps = {}) {
}}
onOpenSearch={onOpenSearch}
/>
- {/* The terminal docks to the right of the doc panel (its own column) or
- under the editor/file column. EditorArea owns the layout; the dock
- position, visibility, and the dock-toggle/collapse controls' state stay
- owned here and are threaded down — to EditorArea (placement) and to the
- session host (which renders the tab strip's controls via its portal). */}
- <EditorArea
- editorMode={editorMode}
- onModeChange={handleModeChange}
- activeTab={activeTab}
- onActiveTabChange={setActiveTab}
- terminalBridge={desktopBridge}
- terminalVisible={terminalVisible}
- onTerminalVisibleChange={setTerminalVisible}
- terminalDock={terminalDock}
- onTerminalPlacement={setTerminalPlacement}
- onRevealTerminal={terminalAvailable ? revealTerminal : undefined}
- />
- {/* The `desktopBridge != null` clause re-narrows the bridge to non-null for
- the prop — the derived `terminalAvailable` boolean can't narrow it. */}
- {terminalAvailable && desktopBridge != null ? (
+ {/* The editor takes the row's full width. The unified sessions dock
+ (terminals + agent threads) docks WITHIN EditorArea — bottom, or its own
+ right column past the doc panels; EditorArea owns that layout. The live
+ session host is mounted below (above EditorArea) so a dock move never
+ remounts it. */}
+ <div className="flex min-h-0 flex-1 overflow-hidden">
+ <div className="flex min-w-0 flex-1 flex-col">
+ <EditorArea
+ editorMode={editorMode}
+ onModeChange={handleModeChange}
+ activeTab={activeTab}
+ onActiveTabChange={setActiveTab}
+ terminalBridge={desktopBridge}
+ terminalVisible={terminalVisible}
+ onTerminalVisibleChange={setTerminalVisible}
+ terminalDock={terminalDock}
+ terminalHasSessions={hasSessions}
+ onTerminalPlacement={setTerminalPlacement}
+ onRevealTerminal={revealTerminal}
+ />
+ </div>
+ </div>
+ {/* The sessions dock host mounts UNCONDITIONALLY — a shell and an agent are
+ just tabs of a different kind, and agents are server-hosted, so the dock
+ is host-agnostic (web = thread tabs only). Terminal-kind affordances gate
+ on the bridge inside the host. */}
+ <Suspense fallback={null}>
<TerminalSessionsHost
bridge={desktopBridge}
visible={terminalVisible}
onVisibleChange={setTerminalVisible}
launch={terminalLaunch}
+ threadLaunch={threadLaunch}
installedClis={installedClis}
container={terminalPlacement.container}
isShowing={terminalPlacement.isShowing}
@@ -467,7 +539,7 @@ export function EditorPane({ onOpenSearch }: EditorPaneProps = {}) {
activeSessionIsCliRef.current = isCli;
}}
/>
- ) : null}
+ </Suspense>
<AuthModal
open={authModalOpen}
onOpenChange={setAuthModalOpen}
diff --git a/packages/app/src/components/EditorTabs.tsx b/packages/app/src/components/EditorTabs.tsx
index 7c4430c88..d58a732a9 100644
--- a/packages/app/src/components/EditorTabs.tsx
+++ b/packages/app/src/components/EditorTabs.tsx
@@ -26,7 +26,6 @@ import {
useEffect,
useRef,
useState,
- type WheelEvent,
} from 'react';
import { toast } from 'sonner';
import {
@@ -80,6 +79,7 @@ import {
tabRunCollisionDetection,
} from './editor-tabs-chrome';
import { usePageList } from './PageListContext';
+import { scrollTabStripOnWheel } from './tab-strip-wheel';
import { Tooltip, TooltipContent, TooltipTrigger } from './ui/tooltip';
const TAB_RENAME_EXTENSIONS = ['.md', '.mdx'] as const;
@@ -105,13 +105,6 @@ function navigateToDoc(docName: string) {
}
}
-function scrollTabListOnWheel(event: WheelEvent<HTMLDivElement>) {
- if (Math.abs(event.deltaX) >= Math.abs(event.deltaY)) return;
- if (event.currentTarget.scrollWidth <= event.currentTarget.clientWidth) return;
- event.preventDefault();
- event.currentTarget.scrollLeft += event.deltaY;
-}
-
function stripRenameExtensionSuffix(value: string, docExt: string): string {
const extensions = [docExt, ...TAB_RENAME_EXTENSIONS].filter(
(ext, index, all) => ext && all.indexOf(ext) === index,
@@ -877,7 +870,7 @@ export function EditorTabs() {
'pl-2 flex h-12 min-w-0 touch-manipulation flex-1 items-end overflow-x-auto overflow-y-hidden overscroll-x-contain scroll-fade-mask-x [scrollbar-width:none]',
isElectronHost && '[-webkit-app-region:drag]',
)}
- onWheel={scrollTabListOnWheel}
+ onWheel={scrollTabStripOnWheel}
>
<div
className={cn(
diff --git a/packages/app/src/components/EditorToolbar.tsx b/packages/app/src/components/EditorToolbar.tsx
index 962bc3beb..dfb6a333f 100644
--- a/packages/app/src/components/EditorToolbar.tsx
+++ b/packages/app/src/components/EditorToolbar.tsx
@@ -29,7 +29,7 @@ interface EditorToolbarProps {
isPanelCollapsed: boolean;
onTogglePanel: () => void;
/** Reserve right-side room in the action cluster so it sits left of the
- * right-dock "Show terminal" reveal tab (which pins to the far-right corner
+ * right-dock "Open session dock" reveal tab (which pins to the far-right corner
* the cluster reaches once the doc panel is collapsed) — keeping the two in
* one row instead of overlapping. */
reserveRightGutter?: boolean;
@@ -119,7 +119,7 @@ export function EditorToolbar({
<div
className={cn(
'pointer-events-auto absolute top-0 right-0 flex items-center justify-end gap-1 py-2 pr-2',
- // Clear the far-right "Show terminal" reveal tab (icon-sm, flush to the
+ // Clear the far-right "Open session dock" reveal tab (icon-sm, flush to the
// edge) so the action buttons sit to its left in the same row.
reserveRightGutter && 'pr-9',
)}
diff --git a/packages/app/src/components/FileTree.tsx b/packages/app/src/components/FileTree.tsx
index 9ef72868b..34f0d1391 100644
--- a/packages/app/src/components/FileTree.tsx
+++ b/packages/app/src/components/FileTree.tsx
@@ -768,6 +768,7 @@ function FileTreeMenu({
installStates={handoff.installStates}
isElectronHost={handoff.isElectronHost}
dispatch={handoff.dispatch}
+ onBeforeLaunch={close}
/>
{shareMenuItem}
<DropdownMenuSub>
@@ -904,6 +905,7 @@ function FileTreeMenu({
installStates={handoff.installStates}
isElectronHost={handoff.isElectronHost}
dispatch={handoff.dispatch}
+ onBeforeLaunch={close}
/>
)}
{shareMenuItem}
diff --git a/packages/app/src/components/GraphPanel.external-link-open.dom.test.tsx b/packages/app/src/components/GraphPanel.external-link-open.dom.test.tsx
index fbe38637d..4e2b6fed1 100644
--- a/packages/app/src/components/GraphPanel.external-link-open.dom.test.tsx
+++ b/packages/app/src/components/GraphPanel.external-link-open.dom.test.tsx
@@ -10,28 +10,32 @@
* is driven through the captured `onSelectNode` handler instead.
*/
-import { afterEach, beforeEach, describe, expect, mock, test } from 'bun:test';
import * as actualLinguiMacro from '@lingui/react/macro';
import { act, cleanup, render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import type { ReactNode } from 'react';
+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
import { TooltipProvider } from '@/components/ui/tooltip';
import { renderLinguiTemplate } from '@/test-utils/lingui-mock';
-mock.module('@lingui/core/macro', () => ({ ...actualLinguiMacro, t: renderLinguiTemplate }));
+vi.doMock('@lingui/core/macro', () => ({
+ ...actualLinguiMacro,
+ t: renderLinguiTemplate,
+ msg: renderLinguiTemplate,
+}));
-mock.module('@lingui/react/macro', () => ({
+vi.doMock('@lingui/react/macro', () => ({
...actualLinguiMacro,
Plural: ({ one }: { one: string }) => <>{one}</>,
Trans: ({ children }: { children: ReactNode }) => <>{children}</>,
useLingui: () => ({ t: renderLinguiTemplate }),
}));
-mock.module('next-themes', () => ({
+vi.doMock('next-themes', () => ({
useTheme: () => ({ resolvedTheme: 'light' }),
}));
-mock.module('@/components/PageListContext', () => ({
+vi.doMock('@/components/PageListContext', () => ({
usePageList: () => ({
assetPaths: new Set<string>(),
error: null,
@@ -52,7 +56,7 @@ type ExternalSelection = { kind: 'external'; id: string; label: string; url: str
// external node without rendering the real force-graph canvas.
const graphHarness: { select?: (sel: ExternalSelection) => void } = {};
-mock.module('@/components/GraphView', () => ({
+vi.doMock('@/components/GraphView', () => ({
GraphView: ({
isExpanded,
onSelectNode,
@@ -107,9 +111,9 @@ describe('GraphPanel — external "Open link" routes to the OS browser', () => {
}
test('Electron host: "Open link" calls okDesktop.shell.openExternal and never window.open', async () => {
- const openExternal = mock(async () => {});
+ const openExternal = vi.fn(async () => {});
setDesktopBridge(openExternal);
- const openSpy = mock(() => null);
+ const openSpy = vi.fn(() => null);
window.open = openSpy as unknown as typeof window.open;
await expandAndSelectExternal();
@@ -121,7 +125,7 @@ describe('GraphPanel — external "Open link" routes to the OS browser', () => {
});
test('Web host (no bridge): "Open link" falls back to window.open in a new tab', async () => {
- const openSpy = mock(() => null);
+ const openSpy = vi.fn(() => null);
window.open = openSpy as unknown as typeof window.open;
await expandAndSelectExternal();
diff --git a/packages/app/src/components/GraphPanel.fullscreen-safe-area.dom.test.tsx b/packages/app/src/components/GraphPanel.fullscreen-safe-area.dom.test.tsx
index 163deb516..81a24edc9 100644
--- a/packages/app/src/components/GraphPanel.fullscreen-safe-area.dom.test.tsx
+++ b/packages/app/src/components/GraphPanel.fullscreen-safe-area.dom.test.tsx
@@ -1,8 +1,8 @@
-import { afterEach, describe, expect, mock, test } from 'bun:test';
import * as actualLinguiMacro from '@lingui/react/macro';
import { cleanup, render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import type { ReactNode } from 'react';
+import { afterEach, describe, expect, test, vi } from 'vitest';
import { TooltipProvider } from '@/components/ui/tooltip';
import { renderLinguiTemplate } from '@/test-utils/lingui-mock';
import {
@@ -10,20 +10,24 @@ import {
expectVisualClassTokensAbsent,
} from '@/test-utils/visual-contract';
-mock.module('@lingui/core/macro', () => ({ ...actualLinguiMacro, t: renderLinguiTemplate }));
+vi.doMock('@lingui/core/macro', () => ({
+ ...actualLinguiMacro,
+ t: renderLinguiTemplate,
+ msg: renderLinguiTemplate,
+}));
-mock.module('@lingui/react/macro', () => ({
+vi.doMock('@lingui/react/macro', () => ({
...actualLinguiMacro,
Plural: ({ one }: { one: string }) => <>{one}</>,
Trans: ({ children }: { children: ReactNode }) => <>{children}</>,
useLingui: () => ({ t: renderLinguiTemplate }),
}));
-mock.module('next-themes', () => ({
+vi.doMock('next-themes', () => ({
useTheme: () => ({ resolvedTheme: 'light' }),
}));
-mock.module('@/components/PageListContext', () => ({
+vi.doMock('@/components/PageListContext', () => ({
usePageList: () => ({
assetPaths: new Set<string>(),
error: null,
@@ -38,7 +42,7 @@ mock.module('@/components/PageListContext', () => ({
}),
}));
-mock.module('@/components/GraphView', () => ({
+vi.doMock('@/components/GraphView', () => ({
GraphView: ({ isExpanded }: { isExpanded: boolean }) => (
<div data-testid="graph-view" data-expanded={String(isExpanded)} />
),
diff --git a/packages/app/src/components/GraphView.tsx b/packages/app/src/components/GraphView.tsx
index f3376b84a..a4e8524ac 100644
--- a/packages/app/src/components/GraphView.tsx
+++ b/packages/app/src/components/GraphView.tsx
@@ -46,6 +46,43 @@ const FOCUS_RETRY_DISTANCE_PX = 18;
const FINAL_SETTLE_DRIFT_PX = 28;
const BACKGROUND_CLICK_TOLERANCE_PX = 5;
+// "Showcase" growth mode — while an agent is rapidly adding pages (the stub /
+// interlink phase), frame the WHOLE graph and let it assemble instead of
+// zooming to a single "active" node whose neighborhood is churning. Enters when
+// >= GROWTH_MIN_ADDS doc nodes appear within GROWTH_WINDOW_MS; exits after the
+// window goes quiet, handing back to active-node focus (the Phase-2 minimap).
+const GROWTH_WINDOW_MS = 8000;
+const GROWTH_MIN_ADDS = 2;
+const GROWTH_FIT_THROTTLE_MS = 650;
+const GROWTH_FIT_PADDING_PX = 44;
+// Node/link birth animation — a brief scale + fade as each element first lands.
+const NODE_BIRTH_MS = 520;
+const LINK_BIRTH_MS = 480;
+// Showcase staged entrance: a batch of pages lands in one push, so without
+// pacing the whole cluster blooms in a single frame (observed live). Each new
+// node of an apply pops `NODE_ENTRANCE_STEP_MS` after the previous; links wait
+// for both endpoints. Ten pages ≈ 1.3s of sequential assembly + birth tails.
+const NODE_ENTRANCE_STEP_MS = 140;
+const LINK_ENTRANCE_EXTRA_MS = 260;
+// Labels only attach once a node is mostly landed — a label on a not-yet-born
+// (invisible) staggered node would float over empty canvas.
+const LABEL_MIN_BIRTH = 0.65;
+
+/** easeOutCubic — fast start, gentle settle; used for birth + camera feel. */
+function easeOut(p: number): number {
+ const c = 1 - p;
+ return 1 - c * c * c;
+}
+
+/** Birth progress in [0,1] for an element stamped `bornAt`, or 1 if unstamped/aged out. */
+function birthProgress(bornAt: number | undefined, now: number, durationMs: number): number {
+ if (typeof bornAt !== 'number') return 1;
+ const age = now - bornAt;
+ if (age >= durationMs) return 1;
+ if (age < 0) return 0;
+ return easeOut(age / durationMs);
+}
+
interface FocusState {
key: string;
lastX: number | null;
@@ -466,6 +503,8 @@ export function GraphView({
activeDocName,
selectedNodeId = null,
isExpanded = false,
+ showcase = false,
+ showcaseBaseline = null,
showUrlNodes = true,
className = '',
docClickBehavior = 'navigate',
@@ -477,6 +516,14 @@ export function GraphView({
activeDocName: string;
selectedNodeId?: string | null;
isExpanded?: boolean;
+ /** Force the growth-showcase presentation (whole-project fetch, zoom-to-fit
+ * framing, gentler physics) regardless of arrival detection — the
+ * agent-build overlay is always a showcase, it never waits for a burst. */
+ showcase?: boolean;
+ /** The showcase build's start-of-build graph (node ids + doc-link keys).
+ * On a fresh mount that content materializes instantly; only the build's
+ * ADDITIONS get the staged pop-in entrance. */
+ showcaseBaseline?: { nodeIds: ReadonlySet<string>; linkKeys: ReadonlySet<string> } | null;
showUrlNodes?: boolean;
className?: string;
docClickBehavior?: GraphDocClickBehavior;
@@ -506,6 +553,18 @@ export function GraphView({
// of racing the physics.
const simulationSettledRef = useRef(false);
const [dimensions, setDimensions] = useState({ width: 320, height: 400 });
+ // Showcase growth mode (see constants above). `growthMode` drives fetch scope
+ // + camera; the refs track recent doc-node arrivals to decide it and to
+ // throttle zoom-to-fit.
+ const [growthMode, setGrowthMode] = useState(false);
+ const growthAddsRef = useRef<number[]>([]);
+ const appliedDocIdsRef = useRef<Set<string>>(new Set());
+ const growthTimerRef = useRef<number | null>(null);
+ const lastFitAtRef = useRef(0);
+ // Growth showcase only applies docked; `!isExpanded` also neutralizes a stale
+ // growthMode if the panel is toggled to fullscreen mid-growth. The showcase
+ // prop (agent-build overlay) forces it unconditionally.
+ const inGrowth = showcase || (growthMode && !isExpanded);
const { t } = useLingui();
const { resolvedTheme } = useTheme();
const {
@@ -519,10 +578,47 @@ export function GraphView({
useEffect(() => {
let cancelled = false;
- async function load() {
+ // Decide showcase growth from doc-node arrivals. Only live doc changes
+ // (CC1 pushes) count — mount and navigation reseed the baseline without
+ // triggering, so opening a big graph or moving to a denser neighborhood
+ // doesn't read as "the agent is building".
+ function detectGrowth(nextNodes: GraphNode[], countGrowth: boolean) {
+ const nextDocIds = new Set(
+ nextNodes.filter((node) => node.kind === 'doc').map((node) => node.id),
+ );
+ // Growth showcase is a docked-view affordance — fullscreen already frames
+ // the whole graph, and the showcase prop forces the presentation outright,
+ // so never run arrival detection in either.
+ if (!countGrowth || isExpanded || showcase) {
+ appliedDocIdsRef.current = nextDocIds;
+ return;
+ }
+ const now = Date.now();
+ let added = 0;
+ for (const id of nextDocIds) if (!appliedDocIdsRef.current.has(id)) added++;
+ appliedDocIdsRef.current = nextDocIds;
+ if (added <= 0) return;
+ const recent = growthAddsRef.current.filter((ts) => now - ts < GROWTH_WINDOW_MS);
+ for (let i = 0; i < added; i++) recent.push(now);
+ growthAddsRef.current = recent;
+ if (recent.length < GROWTH_MIN_ADDS) return;
+ setGrowthMode(true);
+ if (growthTimerRef.current !== null) clearTimeout(growthTimerRef.current);
+ growthTimerRef.current = window.setTimeout(() => {
+ growthTimerRef.current = null;
+ growthAddsRef.current = growthAddsRef.current.filter(
+ (ts) => Date.now() - ts < GROWTH_WINDOW_MS,
+ );
+ if (growthAddsRef.current.length < GROWTH_MIN_ADDS) setGrowthMode(false);
+ }, GROWTH_WINDOW_MS + 120);
+ }
+
+ async function load(countGrowth: boolean) {
try {
const params = new URLSearchParams();
- if (!isExpanded && activeDocName) {
+ // Scope to the active doc's 2-hop neighborhood normally; during showcase
+ // growth, fetch the whole project graph so it assembles in one frame.
+ if (!showcase && !isExpanded && activeDocName && !growthMode) {
params.set('docName', activeDocName);
params.set('degrees', '2');
}
@@ -549,11 +645,34 @@ export function GraphView({
const nextLinkSig = buildGraphLinkSignature(nextLinks);
if (nextNodeSig !== lastSigRef.current.nodes || nextLinkSig !== lastSigRef.current.links) {
lastSigRef.current = { nodes: nextNodeSig, links: nextLinkSig };
+ detectGrowth(nextNodes, countGrowth);
+ // Showcase paces same-push node clumps into a sequential entrance —
+ // but the build-start baseline materializes instantly (the replay is
+ // of the agent's additions, not of pre-existing content). Reduced
+ // motion gets the instant (unpaced) presentation.
+ const entrance =
+ showcase && !window.matchMedia('(prefers-reduced-motion: reduce)').matches
+ ? {
+ nodeStepMs: NODE_ENTRANCE_STEP_MS,
+ linkExtraMs: LINK_ENTRANCE_EXTRA_MS,
+ ...(showcaseBaseline !== null
+ ? {
+ instantNodeIds: showcaseBaseline.nodeIds,
+ instantLinkKeys: showcaseBaseline.linkKeys,
+ }
+ : {}),
+ }
+ : undefined;
setGraphData((previous) =>
- reconcileGraphData(previous, {
- nodes: nextNodes,
- links: nextLinks,
- }),
+ reconcileGraphData(
+ previous,
+ {
+ nodes: nextNodes,
+ links: nextLinks,
+ },
+ Date.now(),
+ entrance,
+ ),
);
}
setError(null);
@@ -566,17 +685,17 @@ export function GraphView({
}
setLoading(true);
- void load();
+ void load(false);
const handleResume = () => {
if (document.visibilityState === 'visible') {
- void load();
+ void load(false);
}
};
window.addEventListener('focus', handleResume);
window.addEventListener('visibilitychange', handleResume);
const unsubscribe = subscribeToDocumentsChanged((channels) => {
if (channels.includes('files') || channels.includes('graph')) {
- void load();
+ void load(true);
}
});
@@ -586,7 +705,16 @@ export function GraphView({
window.removeEventListener('visibilitychange', handleResume);
unsubscribe();
};
- }, [activeDocName, isExpanded, t]);
+ }, [activeDocName, isExpanded, growthMode, showcase, showcaseBaseline, t]);
+
+ // Growth-off timer is component-lifetime (it must survive load-effect re-runs
+ // that fire on every activeDocName change), so it's cleared only on unmount.
+ useEffect(
+ () => () => {
+ if (growthTimerRef.current !== null) clearTimeout(growthTimerRef.current);
+ },
+ [],
+ );
useEffect(() => {
const container = containerRef.current;
@@ -610,7 +738,9 @@ export function GraphView({
const externalNodeColor = isDark ? '#f59e0b' : '#c2410c';
const folderNodeColor = isDark ? '#a78bfa' : '#7c3aed';
const missingNodeColor = isDark ? '#f87171' : '#dc2626';
- const edgeColor = isDark ? 'rgba(75,85,99,0.6)' : 'rgba(209,213,219,0.8)';
+ const edgeRgb = isDark ? '75,85,99' : '209,213,219';
+ const edgeBaseAlpha = isDark ? 0.6 : 0.8;
+ const edgeColor = `rgba(${edgeRgb},${edgeBaseAlpha})`;
const labelColor = isDark ? '#f3f4f6' : '#111827';
const activeNodeRingColor = isDark ? 'rgba(105,163,255,0.45)' : 'rgba(55,132,255,0.3)';
const folderNodeRingColor = isDark ? 'rgba(167,139,250,0.38)' : 'rgba(124,58,237,0.22)';
@@ -690,6 +820,9 @@ export function GraphView({
lastY: null,
lastAt: 0,
};
+ // In showcase growth mode the camera frames the whole graph (zoom-to-fit on
+ // each tick), so don't yank focus to the active node here.
+ if (inGrowth) return;
const animationFrame = window.requestAnimationFrame(() => {
focusStateRef.current = maybeFocusActiveGraphNode({
fg: fgRef.current,
@@ -702,7 +835,18 @@ export function GraphView({
});
});
return () => window.cancelAnimationFrame(animationFrame);
- }, [focusKey, activeDocName, focusZoom]);
+ }, [focusKey, activeDocName, focusZoom, inGrowth]);
+
+ // Frame the whole graph during growth; throttled so bursts don't jitter the
+ // camera. `force` bypasses the throttle for the final settle.
+ const fitGraphToView = (force: boolean): void => {
+ const fg = fgRef.current;
+ if (!fg) return;
+ const now = Date.now();
+ if (!force && now - lastFitAtRef.current < GROWTH_FIT_THROTTLE_MS) return;
+ lastFitAtRef.current = now;
+ fg.zoomToFit(400, GROWTH_FIT_PADDING_PX);
+ };
useEffect(() => {
// DEV-gate guards all `window.__graphHarness` writes below; see
@@ -975,8 +1119,15 @@ export function GraphView({
ref={fgRef}
graphData={displayData}
cooldownTicks={150}
+ autoPauseRedraw={!inGrowth}
+ d3AlphaDecay={inGrowth ? 0.035 : 0.0228}
+ d3VelocityDecay={inGrowth ? 0.5 : 0.4}
onEngineTick={() => {
simulationSettledRef.current = false;
+ if (inGrowth) {
+ fitGraphToView(false);
+ return;
+ }
focusStateRef.current = maybeFocusActiveGraphNode({
fg: fgRef.current,
nodes: graphData.nodes,
@@ -988,6 +1139,10 @@ export function GraphView({
}}
onEngineStop={() => {
simulationSettledRef.current = true;
+ if (inGrowth) {
+ fitGraphToView(true);
+ return;
+ }
const coords = getActiveGraphNodeCoords({
nodes: graphData.nodes,
activeDocName,
@@ -1061,10 +1216,7 @@ export function GraphView({
const docCluster = node.kind === 'doc' ? node.cluster : undefined;
const clusterFill = docCluster ? clusterColor(docCluster, isDark) : defaultNodeColor;
-
- ctx.beginPath();
- ctx.arc(node.x, node.y, nodeRadius, 0, 2 * Math.PI, false);
- ctx.fillStyle =
+ const fill =
state === 'active'
? activeNodeColor
: state === 'active-selected'
@@ -1078,6 +1230,28 @@ export function GraphView({
: isFolderTarget
? folderNodeColor
: clusterFill;
+
+ // Birth animation — a new node scales + fades in with a halo that
+ // collapses onto it, so each page the agent creates visibly lands.
+ const birth = birthProgress(node.bornAt, Date.now(), NODE_BIRTH_MS);
+ const drawRadius = nodeRadius * (0.4 + 0.6 * birth);
+
+ ctx.save();
+ ctx.globalAlpha = birth;
+
+ if (birth < 1) {
+ const haloRadius = drawRadius + (nodeRadius * 1.4 * (1 - birth) + 2 / globalScale);
+ ctx.beginPath();
+ ctx.arc(node.x, node.y, haloRadius, 0, 2 * Math.PI, false);
+ ctx.globalAlpha = 0.4 * (1 - birth);
+ ctx.fillStyle = fill;
+ ctx.fill();
+ ctx.globalAlpha = birth;
+ }
+
+ ctx.beginPath();
+ ctx.arc(node.x, node.y, drawRadius, 0, 2 * Math.PI, false);
+ ctx.fillStyle = fill;
ctx.fill();
if (pointerRadius > nodeRadius) {
@@ -1096,11 +1270,12 @@ export function GraphView({
ctx.setLineDash([]);
} else if (isFolderTarget) {
ctx.beginPath();
- ctx.arc(node.x, node.y, nodeRadius + 2 / globalScale, 0, 2 * Math.PI, false);
+ ctx.arc(node.x, node.y, drawRadius + 2 / globalScale, 0, 2 * Math.PI, false);
ctx.strokeStyle = folderNodeRingColor;
ctx.lineWidth = 1.5 / globalScale;
ctx.stroke();
}
+ ctx.restore();
}}
nodePointerAreaPaint={(
node: NodeObject<GraphNode>,
@@ -1146,8 +1321,16 @@ export function GraphView({
ctx.setTransform(pxRatio, 0, 0, pxRatio, 0, 0);
ctx.font = '10px system-ui, sans-serif';
+ // Unborn (staggered-entrance) nodes are invisible — planning a
+ // label for one would float text over empty canvas.
+ const labelNowMs = Date.now();
+ const bornLayoutNodes = layoutNodes.filter(
+ (node) =>
+ birthProgress((node as GraphNode).bornAt, labelNowMs, NODE_BIRTH_MS) >=
+ LABEL_MIN_BIRTH,
+ );
const placements = planGraphLabels({
- nodes: layoutNodes,
+ nodes: bornLayoutNodes,
links: layoutLinks,
activeDocName,
viewport: dimensions,
@@ -1186,7 +1369,16 @@ export function GraphView({
});
ctx.restore();
}}
- linkColor={() => edgeColor}
+ linkColor={(link: LinkObject<GraphNode, GraphLink>) => {
+ // Fade each edge in as it lands (birth animation counterpart).
+ const born = birthProgress(
+ (link as { bornAt?: number }).bornAt,
+ Date.now(),
+ LINK_BIRTH_MS,
+ );
+ if (born >= 1) return edgeColor;
+ return `rgba(${edgeRgb},${(edgeBaseAlpha * born).toFixed(3)})`;
+ }}
linkDirectionalArrowLength={3}
linkDirectionalArrowRelPos={1}
linkWidth={1}
diff --git a/packages/app/src/components/ProblemsPanel.dom.test.tsx b/packages/app/src/components/ProblemsPanel.dom.test.tsx
index c4e81c8d7..6681bb088 100644
--- a/packages/app/src/components/ProblemsPanel.dom.test.tsx
+++ b/packages/app/src/components/ProblemsPanel.dom.test.tsx
@@ -7,10 +7,10 @@
* affordance, and click-navigates to the offending doc by hash.
*/
-import { afterEach, beforeEach, describe, expect, mock, test } from 'bun:test';
import type { LintAuditResponse, LintDiagnostic } from '@inkeep/open-knowledge-core';
import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
import type { ReactNode } from 'react';
+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
import { renderLinguiTemplate } from '@/test-utils/lingui-mock';
// Both lingui macro specifiers alias to ONE shim module under the vitest dom
@@ -21,24 +21,25 @@ import { renderLinguiTemplate } from '@/test-utils/lingui-mock';
// won).
const linguiMacroMock = {
t: renderLinguiTemplate,
+ msg: renderLinguiTemplate,
Trans: ({ children }: { children: ReactNode }) => children,
Plural: ({ value, one, other }: { value: number; one: string; other: string }) => (
<>{(value === 1 ? one : other).replace('#', String(value))}</>
),
useLingui: () => ({ t: renderLinguiTemplate }),
};
-mock.module('@lingui/core/macro', () => linguiMacroMock);
-mock.module('@lingui/react/macro', () => linguiMacroMock);
+vi.doMock('@lingui/core/macro', () => linguiMacroMock);
+vi.doMock('@lingui/react/macro', () => linguiMacroMock);
let auditCalls = 0;
let runLintAuditImpl: () => Promise<LintAuditResponse | null> = async () => null;
let fixLintDocCalls: string[] = [];
let fixLintDocImpl: (docName: string) => Promise<{ ok: boolean; errorDetail?: string | null }> =
async () => ({ ok: true });
-const toastError = mock((_message: string) => {});
+const toastError = vi.fn((_message: string) => {});
-mock.module('sonner', () => ({ toast: { error: toastError } }));
-mock.module('@/editor/lint-config-client', () => ({
+vi.doMock('sonner', () => ({ toast: { error: toastError } }));
+vi.doMock('@/editor/lint-config-client', () => ({
emitLintConfigChanged: () => {},
subscribeToLintConfigChanged: () => () => {},
runLintAudit: () => {
@@ -114,7 +115,7 @@ describe('ProblemsPanel', () => {
],
});
const unfixable = diag({ line: 5, code: 'MD025', message: 'Multiple H1' });
- const onFix = mock(() => {});
+ const onFix = vi.fn(() => {});
render(<ProblemsPanel docName="notes" diagnostics={[fixable, unfixable]} onFix={onFix} />);
const fixButtons = screen.getAllByRole('button', { name: /Fix markdownlint\/MD010/ });
expect(fixButtons).toHaveLength(1);
@@ -149,7 +150,7 @@ describe('ProblemsPanel', () => {
],
});
const unfixable = diag({ line: 5, code: 'MD025', message: 'Multiple H1' });
- const onFixAll = mock(() => {});
+ const onFixAll = vi.fn(() => {});
render(
<ProblemsPanel docName="notes" diagnostics={[fixable, unfixable]} onFixAll={onFixAll} />,
);
@@ -174,7 +175,7 @@ describe('ProblemsPanel', () => {
],
});
const unfixable = diag({ line: 5, code: 'MD025', message: 'Multiple H1' });
- const onAskAi = mock(() => {});
+ const onAskAi = vi.fn(() => {});
const { unmount } = render(
<ProblemsPanel docName="notes" diagnostics={[fixable, unfixable]} onAskAi={onAskAi} />,
);
@@ -192,7 +193,7 @@ describe('ProblemsPanel', () => {
});
test('doc-scope Fix all is disabled when no diagnostic is fixable', () => {
- const onFixAll = mock(() => {});
+ const onFixAll = vi.fn(() => {});
render(
<ProblemsPanel
docName="notes"
@@ -210,7 +211,7 @@ describe('ProblemsPanel', () => {
expect(screen.queryByTestId('problems-fix-all')).toBeNull();
unmount();
// Empty state renders no action row at all.
- render(<ProblemsPanel docName="notes" diagnostics={[]} onFixAll={mock(() => {})} />);
+ render(<ProblemsPanel docName="notes" diagnostics={[]} onFixAll={vi.fn(() => {})} />);
expect(screen.queryByTestId('problems-fix-all')).toBeNull();
});
diff --git a/packages/app/src/components/SeedDialog.dom.test.tsx b/packages/app/src/components/SeedDialog.dom.test.tsx
index 6522d23cf..68dfdd001 100644
--- a/packages/app/src/components/SeedDialog.dom.test.tsx
+++ b/packages/app/src/components/SeedDialog.dom.test.tsx
@@ -1,8 +1,8 @@
-import { afterEach, describe, expect, mock, test } from 'bun:test';
import * as actualLinguiMacro from '@lingui/react/macro';
import { act, cleanup, render, screen, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import type { ReactNode } from 'react';
+import { afterEach, describe, expect, test, vi } from 'vitest';
import { TooltipProvider } from '@/components/ui/tooltip';
import type {
OkPackId,
@@ -12,20 +12,21 @@ import type {
} from '@/lib/desktop-bridge-types';
import { renderLinguiTemplate } from '@/test-utils/lingui-mock';
-mock.module('@lingui/react/macro', () => ({
+vi.doMock('@lingui/react/macro', () => ({
...actualLinguiMacro,
Trans: ({ children }: { children: ReactNode }) => <>{children}</>,
useLingui: () => ({ t: renderLinguiTemplate }),
}));
-mock.module('@lingui/core/macro', () => ({
+vi.doMock('@lingui/core/macro', () => ({
...actualLinguiMacro,
t: renderLinguiTemplate,
+ msg: renderLinguiTemplate,
plural: (value: number, options: { one: string; other: string }) =>
(value === 1 ? options.one : options.other).replace('#', String(value)),
}));
-mock.module('@/components/PackCardGrid', () => ({
+vi.doMock('@/components/PackCardGrid', () => ({
PackCardGrid: ({
packs,
onPackSelect,
@@ -99,7 +100,7 @@ let planImpl: (options: { packId?: OkPackId; rootDir?: string }) => Promise<OkSe
plan: options.packId === 'plain-notes' ? plainNotesPlan : knowledgeBasePlan,
});
-mock.module('@/lib/seed-client', () => ({
+vi.doMock('@/lib/seed-client', () => ({
seedClient: () => ({
listPacks: async () => {
listPacksCalls.push('list');
@@ -119,7 +120,7 @@ mock.module('@/lib/seed-client', () => ({
}),
}));
-mock.module('sonner', () => ({
+vi.doMock('sonner', () => ({
toast: {
success: (message: string) => toastSuccesses.push(message),
error: (message: string) => toastErrors.push(message),
diff --git a/packages/app/src/components/SyncStatusBadge.dom.test.tsx b/packages/app/src/components/SyncStatusBadge.dom.test.tsx
index 47a1a86fe..8bd58e5ce 100644
--- a/packages/app/src/components/SyncStatusBadge.dom.test.tsx
+++ b/packages/app/src/components/SyncStatusBadge.dom.test.tsx
@@ -1,20 +1,21 @@
-import { afterEach, describe, expect, mock, test } from 'bun:test';
import * as actualLinguiMacro from '@lingui/react/macro';
import { cleanup, render, screen, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import type { ReactNode } from 'react';
+import { afterEach, describe, expect, test, vi } from 'vitest';
import { TooltipProvider } from '@/components/ui/tooltip';
import type { GitSyncStatus } from '@/hooks/use-git-sync-status';
import { renderLinguiTemplate } from '@/test-utils/lingui-mock';
-mock.module('@lingui/core/macro', () => ({
+vi.doMock('@lingui/core/macro', () => ({
...actualLinguiMacro,
t: renderLinguiTemplate,
+ msg: renderLinguiTemplate,
plural: (value: number, options: { one: string; other: string }) =>
(value === 1 ? options.one : options.other).replace('#', String(value)),
}));
-mock.module('@lingui/react/macro', () => ({
+vi.doMock('@lingui/react/macro', () => ({
...actualLinguiMacro,
Trans: ({ children }: { children: ReactNode }) => <>{children}</>,
Plural: ({ value, one, other }: { value: number; one: string; other: string }) => (
@@ -31,15 +32,15 @@ let projectLocalConfig: { autoSync?: { enabled?: boolean | null } } | null = {
let projectLocalSynced = true;
const patches: unknown[] = [];
-mock.module('@/hooks/use-git-sync-status', () => ({
+vi.doMock('@/hooks/use-git-sync-status', () => ({
useGitSyncStatusDetailed: () => ({ status, fetchError }),
}));
-mock.module('@/hooks/use-conflicts', () => ({
+vi.doMock('@/hooks/use-conflicts', () => ({
useConflicts: () => ({ conflicts: [{ file: 'docs/conflicted.md' }] }),
}));
-mock.module('@/lib/config-provider', () => ({
+vi.doMock('@/lib/config-provider', () => ({
useConfigContext: () => ({
projectLocalConfig,
projectLocalSynced,
diff --git a/packages/app/src/components/TerminalDock.dom.test.tsx b/packages/app/src/components/TerminalDock.dom.test.tsx
index 183465264..b5eaf7d2c 100644
--- a/packages/app/src/components/TerminalDock.dom.test.tsx
+++ b/packages/app/src/components/TerminalDock.dom.test.tsx
@@ -15,11 +15,11 @@
* covered in TerminalPanel.dom.test.tsx.
*/
-import { afterEach, beforeEach, describe, expect, mock, test } from 'bun:test';
import type { TerminalCli } from '@inkeep/open-knowledge-core';
import { act, cleanup, render, screen, waitFor, within } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { useEffect, useRef, useState } from 'react';
+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
import { TooltipProvider } from '@/components/ui/tooltip';
import type { OkDesktopBridge, OkMenuAction } from '@/lib/desktop-bridge-types';
import {
@@ -27,6 +27,8 @@ import {
emitLocalMenuAction,
} from '@/lib/local-menu-action-bus';
import type { TerminalDockPosition } from '@/lib/terminal-dock-store';
+import { writePreferBareTerminal } from '@/lib/terminal-new-tab-store';
+import { saveStickyAgent, terminalCliId } from '@/lib/unified-agent-store';
import { requestActiveTerminalInput } from './handoff/terminal-input-events';
const TERMINAL_PANEL_ID = 'terminal-dock-panel';
@@ -35,20 +37,27 @@ const TERMINAL_PANEL_ID = 'terminal-dock-panel';
let terminalPanelProps: Record<string, any> | null = null;
const panelHandle = {
- collapse: mock(() => terminalPanelProps?.onResize?.({ asPercentage: 0, inPixels: 0 })),
- expand: mock(() => terminalPanelProps?.onResize?.({ asPercentage: 40, inPixels: 240 })),
- resize: mock((s: string) => {
+ collapse: vi.fn(() => terminalPanelProps?.onResize?.({ asPercentage: 0, inPixels: 0 })),
+ expand: vi.fn(() => terminalPanelProps?.onResize?.({ asPercentage: 40, inPixels: 240 })),
+ resize: vi.fn((s: string) => {
const px = Number.parseInt(s, 10) || 0;
terminalPanelProps?.onResize?.({ asPercentage: px > 0 ? 30 : 0, inPixels: px });
}),
};
const sharedPanelRef: { current: unknown } = { current: panelHandle };
-mock.module('react-resizable-panels', () => ({
+// The sessions-dock New split-button (+ catalog dialog) call react-query's
+// useQuery; these terminal-focused tests don't exercise the catalog, so stub it
+// so they need no QueryClientProvider / network.
+vi.doMock('@tanstack/react-query', () => ({
+ useQuery: () => ({ data: undefined, isLoading: false, isError: false }),
+}));
+
+vi.doMock('react-resizable-panels', () => ({
usePanelRef: () => sharedPanelRef,
}));
-mock.module('@/components/ui/resizable', () => ({
+vi.doMock('@/components/ui/resizable', () => ({
// biome-ignore lint/suspicious/noExplicitAny: test stub
ResizablePanelGroup: ({ children, orientation }: any) => (
<div data-testid="rrp-group" data-orientation={orientation}>
@@ -98,7 +107,7 @@ function emitTitle(ptyId: string, title: string): boolean {
return true;
}
-mock.module('./TerminalGate', () => ({
+vi.doMock('./TerminalGate', () => ({
// biome-ignore lint/suspicious/noExplicitAny: test stub
TerminalGate: ({ bridge, launch, onTitleChange, onPtyId }: any) => {
const ptyIdRef = useRef<string | null>(null);
@@ -142,6 +151,7 @@ mock.module('./TerminalGate', () => ({
<span
data-testid="terminal-session"
data-launch={launch?.nonce ?? 'none'}
+ data-cli={launch?.cli ?? 'none'}
className="xterm-helper-textarea"
tabIndex={-1}
/>
@@ -149,7 +159,7 @@ mock.module('./TerminalGate', () => ({
},
}));
-mock.module('@/lib/terminal-height-store', () => ({
+vi.doMock('@/lib/terminal-height-store', () => ({
getInitialTerminalHeight: () => 240,
writeTerminalHeight: () => {},
}));
@@ -164,14 +174,14 @@ function makeBridge() {
// Hand each session a distinct PTY id (pty-1, pty-2, …) so a close can assert
// exactly which session's PTY was reaped — the demux the dock owns.
let ptyCounter = 0;
- const create = mock(async () => {
+ const create = vi.fn(async () => {
ptyCounter += 1;
return { ok: true as const, ptyId: `pty-${ptyCounter}` };
});
- const kill = mock(async (_id: string) => {});
+ const kill = vi.fn(async (_id: string) => {});
// Observes PTY writes at the dock boundary — a launch must never write into an
// existing PTY (it opens its own tab), so tests assert `input` stays unused.
- const input = mock((_ptyId: string, _data: string) => {});
+ const input = vi.fn((_ptyId: string, _data: string) => {});
const bridge = {
onMenuAction: () => () => {},
editor: {
@@ -233,6 +243,9 @@ function DockHarness({
onBottomContainer={setBottomContainer}
onEditorRegion={setEditorRegionEl}
onReveal={onReveal}
+ // Mirrors EditorArea's predicate (a terminal surface shows the reveal tab
+ // whenever hidden). The dock's terminal bridge is always present here.
+ showRevealTab={!v && onReveal != null}
>
<div data-testid="editor-child" />
</TerminalDock>
@@ -258,7 +271,7 @@ function renderDock(
onReveal?: () => void,
onActiveSessionCliChange?: (isCli: boolean) => void,
) {
- const onVisibleChange = mock((_v: boolean) => {});
+ const onVisibleChange = vi.fn((_v: boolean) => {});
const { bridge, create, kill, input, viewMenuPushes, dispatchMenuAction } = makeBridge();
const ui = (v: boolean, l?: TestLaunch | null, dock?: TerminalDockPosition) => (
<DockHarness
@@ -318,12 +331,13 @@ function editorRegion(): HTMLElement {
// path that replaced the standalone "New terminal tab" button. Opens a bare shell
// (no CLI launch), the same session the old button created.
async function addTerminalTab(user: ReturnType<typeof userEvent.setup>) {
- await user.click(screen.getByRole('button', { name: 'Choose CLI for new chat' }));
+ await user.click(screen.getByRole('button', { name: 'Choose what a new session starts' }));
await user.click(await screen.findByRole('menuitem', { name: 'Terminal' }));
}
describe('TerminalDock multi-session', () => {
beforeEach(() => {
+ localStorage.clear();
terminalPanelProps = null;
panelHandle.collapse.mockClear();
panelHandle.resize.mockClear();
@@ -341,8 +355,8 @@ describe('TerminalDock multi-session', () => {
renderDock(true);
// The dock-toggle button is the dock-move affordance now (dragging removed).
// The harness is bottom-docked, so the toggle offers "move to the right".
- expect(screen.getByRole('button', { name: 'Dock terminal to the right' })).not.toBeNull();
- expect(screen.getByRole('button', { name: 'Collapse terminal' })).not.toBeNull();
+ expect(screen.getByRole('button', { name: 'Dock sessions on the right' })).not.toBeNull();
+ expect(screen.getByRole('button', { name: 'Collapse session dock' })).not.toBeNull();
// The old drag grip is gone.
expect(screen.queryByRole('button', { name: 'Drag to dock the terminal' })).toBeNull();
});
@@ -369,6 +383,16 @@ describe('TerminalDock multi-session', () => {
expect(view.create).toHaveBeenCalledTimes(1);
});
+ test('opening an empty dock launches the same preferred CLI as the New-session button', () => {
+ writePreferBareTerminal(false);
+ saveStickyAgent(terminalCliId('cursor'));
+ const view = renderDock(false);
+
+ act(() => view.rerender(true));
+
+ expect(screen.getByTestId('terminal-session').getAttribute('data-cli')).toBe('cursor');
+ });
+
test('the new-terminal control adds a session, activates it, and spawns its PTY', async () => {
const user = userEvent.setup();
const view = renderDock(true);
@@ -1139,7 +1163,7 @@ describe('TerminalDock multi-session', () => {
renderDock(true);
await addTerminalTab(user);
- const tablist = screen.getByRole('tablist', { name: 'Terminal sessions' });
+ const tablist = screen.getByRole('tablist', { name: 'Sessions' });
const tabs = within(tablist).getAllByRole('tab');
expect(tabs).toHaveLength(2);
// Each tab's aria-controls resolves to a rendered panel (no dangling ref).
@@ -1173,34 +1197,34 @@ describe('TerminalDock multi-session', () => {
expect(document.activeElement).toBe(session);
});
- test('shows the bottom-edge "Show terminal" tab only while hidden, inside the editor column', () => {
- const onReveal = mock(() => {});
+ test('shows the bottom-edge "Open session dock" tab only while hidden, inside the editor column', () => {
+ const onReveal = vi.fn(() => {});
const view = renderDock(false, null, onReveal);
// Hidden → the reveal tab is present, and lives inside the editor region (not
// the doc panel), since a bottom-docked terminal slides up from there.
- const reveal = screen.getByRole('button', { name: 'Show terminal' });
+ const reveal = screen.getByRole('button', { name: 'Open session dock' });
expect(editorRegion().contains(reveal)).toBe(true);
// Visible → the reveal tab is gone (the tab strip's collapse control is the
// hide affordance while open).
act(() => view.rerender(true));
- expect(screen.queryByRole('button', { name: 'Show terminal' })).toBeNull();
+ expect(screen.queryByRole('button', { name: 'Open session dock' })).toBeNull();
});
test('clicking the reveal tab requests a reveal', async () => {
const user = userEvent.setup();
- const onReveal = mock(() => {});
+ const onReveal = vi.fn(() => {});
renderDock(false, null, onReveal);
- await user.click(screen.getByRole('button', { name: 'Show terminal' }));
+ await user.click(screen.getByRole('button', { name: 'Open session dock' }));
expect(onReveal).toHaveBeenCalledTimes(1);
});
test('renders no reveal tab when no reveal handler is wired (web host)', () => {
renderDock(false);
- expect(screen.queryByRole('button', { name: 'Show terminal' })).toBeNull();
+ expect(screen.queryByRole('button', { name: 'Open session dock' })).toBeNull();
});
test('disables the resize handle while hidden so there is no drag-to-open', () => {
@@ -1273,7 +1297,7 @@ describe('TerminalSessionsHost focus-return gating across a dock move', () => {
}
test('a dock move keeps focus (visible stays true); a genuine hide returns focus to the editor', () => {
- const onEditorFocus = mock(() => {});
+ const onEditorFocus = vi.fn(() => {});
const { bridge } = makeBridge();
const ui = (isShowing: boolean, visible: boolean) => (
<FocusHarness
diff --git a/packages/app/src/components/TerminalDock.reload-survival.dom.test.tsx b/packages/app/src/components/TerminalDock.reload-survival.dom.test.tsx
index 694ff7d0e..e585b0330 100644
--- a/packages/app/src/components/TerminalDock.reload-survival.dom.test.tsx
+++ b/packages/app/src/components/TerminalDock.reload-survival.dom.test.tsx
@@ -27,10 +27,10 @@
* Radix Tabs render so the tab/active-tab a11y wiring is exercised.
*/
-import { afterEach, describe, expect, mock, test } from 'bun:test';
import { act, cleanup, render, screen, waitFor, within } from '@testing-library/react';
import { userEvent } from '@testing-library/user-event';
import { useEffect, useRef, useState } from 'react';
+import { afterEach, describe, expect, test, vi } from 'vitest';
import { TooltipProvider } from '@/components/ui/tooltip';
import type { OkDesktopBridge } from '@/lib/desktop-bridge-types';
import { requestActiveTerminalInput } from './handoff/terminal-input-events';
@@ -40,14 +40,20 @@ const TERMINAL_PANEL_ID = 'terminal-dock-panel';
// biome-ignore lint/suspicious/noExplicitAny: captured mock-component props
let terminalPanelProps: Record<string, any> | null = null;
const panelHandle = {
- collapse: mock(() => terminalPanelProps?.onResize?.({ asPercentage: 0, inPixels: 0 })),
- expand: mock(() => terminalPanelProps?.onResize?.({ asPercentage: 40, inPixels: 240 })),
- resize: mock(() => {}),
+ collapse: vi.fn(() => terminalPanelProps?.onResize?.({ asPercentage: 0, inPixels: 0 })),
+ expand: vi.fn(() => terminalPanelProps?.onResize?.({ asPercentage: 40, inPixels: 240 })),
+ resize: vi.fn(() => {}),
};
const sharedPanelRef: { current: unknown } = { current: panelHandle };
-mock.module('react-resizable-panels', () => ({ usePanelRef: () => sharedPanelRef }));
-mock.module('@/components/ui/resizable', () => ({
+// The sessions-dock New split-button (+ catalog dialog) call react-query's
+// useQuery; stub it so this terminal-focused test needs no QueryClientProvider.
+vi.doMock('@tanstack/react-query', () => ({
+ useQuery: () => ({ data: undefined, isLoading: false, isError: false }),
+}));
+
+vi.doMock('react-resizable-panels', () => ({ usePanelRef: () => sharedPanelRef }));
+vi.doMock('@/components/ui/resizable', () => ({
// biome-ignore lint/suspicious/noExplicitAny: test stub
ResizablePanelGroup: ({ children }: any) => <div>{children}</div>,
// biome-ignore lint/suspicious/noExplicitAny: test stub
@@ -65,7 +71,7 @@ mock.module('@/components/ui/resizable', () => ({
// dock's tab management (one tab per recovered session) is what this test pins;
// the adopt-vs-spawn wiring lives in TerminalGate/TerminalPanel and the live
// reload smoke.
-mock.module('./TerminalGate', () => ({
+vi.doMock('./TerminalGate', () => ({
// biome-ignore lint/suspicious/noExplicitAny: test stub
TerminalGate: ({ adoptPtyId, onPtyId }: any) => {
// Mirror the real panel's adopt path: a rehydrated session reconnects the
@@ -86,7 +92,7 @@ mock.module('./TerminalGate', () => ({
},
}));
-mock.module('@/lib/terminal-height-store', () => ({
+vi.doMock('@/lib/terminal-height-store', () => ({
getInitialTerminalHeight: () => 240,
writeTerminalHeight: () => {},
}));
@@ -150,17 +156,17 @@ function makeSurvivingMainBridge(
}>,
) {
let freshCounter = 0;
- const create = mock(async () => {
+ const create = vi.fn(async () => {
freshCounter += 1;
return { ok: true as const, ptyId: `fresh-pty-${freshCounter}` };
});
- const kill = mock(async (_id: string) => {});
+ const kill = vi.fn(async (_id: string) => {});
// Records launch-command writes so an Ask-AI reuse into an adopted (survivor)
// session's live PTY is observable.
- const input = mock((_id: string, _d: string) => {});
- const listLive = mock(async () => preExisting);
- const setMeta = mock((_ptyId: string, _meta: unknown) => {});
- const setOrder = mock((_ids: readonly string[]) => {});
+ const input = vi.fn((_id: string, _d: string) => {});
+ const listLive = vi.fn(async () => preExisting);
+ const setMeta = vi.fn((_ptyId: string, _meta: unknown) => {});
+ const setOrder = vi.fn((_ids: readonly string[]) => {});
const bridge = {
onMenuAction: () => () => {},
editor: { notifyViewMenuStateChanged: () => {} },
@@ -231,7 +237,7 @@ describe('issue #351 — the terminal dock rehydrates surviving sessions after a
// Tabs come back in main's returned (reordered) order with the custom names
// restored; the un-named survivor falls back to its RESTORED sticky ordinal
// (Terminal 1), not a positional renumber to Terminal 2.
- const tablist = screen.getByRole('tablist', { name: 'Terminal sessions' });
+ const tablist = screen.getByRole('tablist', { name: 'Sessions' });
const tabs = within(tablist).getAllByRole('tab');
expect(tabs.map((tab) => tab.textContent)).toEqual(['deploy', 'Terminal 1', 'logs']);
});
@@ -285,15 +291,15 @@ describe('issue #351 — the terminal dock rehydrates surviving sessions after a
});
test('a rejecting list() still settles so a later open cold-starts (no hang on IPC error)', async () => {
- const listLive = mock(async () => {
+ const listLive = vi.fn(async () => {
throw new Error('ipc boom');
});
const bridge = {
onMenuAction: () => () => {},
editor: { notifyViewMenuStateChanged: () => {} },
terminal: {
- create: mock(async () => ({ ok: true as const, ptyId: 'fresh-pty-1' })),
- kill: mock(async (_id: string) => {}),
+ create: vi.fn(async () => ({ ok: true as const, ptyId: 'fresh-pty-1' })),
+ kill: vi.fn(async (_id: string) => {}),
list: listLive,
listSessions: listLive,
getSessions: listLive,
diff --git a/packages/app/src/components/TerminalDock.tsx b/packages/app/src/components/TerminalDock.tsx
index df9641984..1c40d57b6 100644
--- a/packages/app/src/components/TerminalDock.tsx
+++ b/packages/app/src/components/TerminalDock.tsx
@@ -39,13 +39,18 @@ interface TerminalDockProps {
*/
readonly onEditorRegion: (el: HTMLDivElement | null) => void;
/**
- * Reveal the terminal (spawning a default-CLI session if none is open). When
- * provided and the terminal is bottom-docked-and-hidden, this shell renders an
- * edge "Show terminal" tab at the bottom of the editor region — where the
- * bottom dock actually lives. Absent on the web host (no terminal). The
+ * Reveal the sessions dock, launching the user's preferred New-session choice
+ * if none is open. Wired to the edge "Open session dock" tab this shell renders at
+ * the bottom of the editor region when {@link showRevealTab} is set. The
* right-dock reveal tab is owned by EditorArea instead (different container).
*/
readonly onReveal?: () => void;
+ /**
+ * Whether to render the bottom edge reveal tab. EditorArea owns the predicate
+ * (dock-hidden with a reason to reveal: a terminal surface, or latched tabs to
+ * return to on the web host), so this shell just renders it when told.
+ */
+ readonly showRevealTab?: boolean;
}
/**
@@ -65,6 +70,7 @@ export function TerminalDock({
onBottomContainer,
onEditorRegion,
onReveal,
+ showRevealTab = false,
}: TerminalDockProps) {
const { resolvedTheme } = useTheme();
const panelRef = usePanelRef();
@@ -74,10 +80,10 @@ export function TerminalDock({
// and empty — the handle must gate on this, not `visible`, or the grabber
// lingers and drags up an empty panel.
const bottomOpen = visible && dockPosition === 'bottom';
- // The edge "Show terminal" tab belongs to the bottom dock only — it hugs the
- // bottom of the editor column, where a bottom-docked terminal slides up from.
- // Right-docked reveal is owned by EditorArea (far-right column edge).
- const showBottomRevealTab = !visible && dockPosition === 'bottom' && onReveal != null;
+ // The edge "Show sessions" tab belongs to the bottom dock only — it hugs the
+ // bottom of the editor column, where a bottom-docked dock slides up from.
+ // EditorArea owns the predicate (dock hidden + a reason to reveal).
+ const showBottomRevealTab = showRevealTab && dockPosition === 'bottom' && onReveal != null;
// Snapshot the persisted height once at mount; the ref carries the running value
// during user drag.
diff --git a/packages/app/src/components/TerminalNewChatButton.dom.test.tsx b/packages/app/src/components/TerminalNewChatButton.dom.test.tsx
index e6c7842f6..584e070bd 100644
--- a/packages/app/src/components/TerminalNewChatButton.dom.test.tsx
+++ b/packages/app/src/components/TerminalNewChatButton.dom.test.tsx
@@ -1,61 +1,86 @@
-import { afterEach, describe, expect, mock, test } from 'bun:test';
import type { TerminalCli } from '@inkeep/open-knowledge-core';
+import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { cleanup, render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
+import { afterEach, describe, expect, test, vi } from 'vitest';
import { TooltipProvider } from '@/components/ui/tooltip';
-import { TerminalNewChatButton, type TerminalNewTabChoice } from './TerminalNewChatButton';
-
-function renderButton(
- selected: TerminalNewTabChoice = 'claude',
- visibleClis?: readonly TerminalCli[],
-) {
- const onLaunchSelected = mock(() => {});
- const onPickCli = mock((_cli: TerminalCli) => {});
- const onPickTerminal = mock(() => {});
+import type { RegisteredAgent } from '@/lib/acp/registered-agents';
+import type { NewSessionChoice } from '@/lib/new-session-choice';
+import { TerminalNewChatButton } from './TerminalNewChatButton';
+
+const AGENT_A: RegisteredAgent = { source: 'registry', id: 'agent-a', name: 'Agent A' };
+const AGENT_B: RegisteredAgent = { source: 'registry', id: 'agent-b', name: 'Agent B' };
+
+function renderButton(overrides: Partial<React.ComponentProps<typeof TerminalNewChatButton>> = {}) {
+ const onLaunchSelected = vi.fn(() => {});
+ const onPickCli = vi.fn((_cli: TerminalCli) => {});
+ const onPickTerminal = vi.fn(() => {});
+ const onPickAgent = vi.fn((_agent: RegisteredAgent) => {});
+ const onOpenSettings = vi.fn(() => {});
+ const selected: NewSessionChoice = overrides.selected ?? { kind: 'cli', cli: 'claude' };
+ // A QueryClient with no network — the catalog query stays disabled/idle in tests,
+ // so the cap defaults to 8 and no agent row is disabled.
+ const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
render(
- <TooltipProvider>
- <TerminalNewChatButton
- selected={selected}
- onLaunchSelected={onLaunchSelected}
- onPickCli={onPickCli}
- onPickTerminal={onPickTerminal}
- visibleClis={visibleClis}
- />
- </TooltipProvider>,
+ <QueryClientProvider client={queryClient}>
+ <TooltipProvider>
+ <TerminalNewChatButton
+ selected={selected}
+ onLaunchSelected={onLaunchSelected}
+ showAgents={overrides.showAgents ?? true}
+ registeredAgents={overrides.registeredAgents ?? [AGENT_A, AGENT_B]}
+ onPickAgent={onPickAgent}
+ onOpenSettings={onOpenSettings}
+ liveThreadCount={overrides.liveThreadCount ?? 0}
+ showClis={overrides.showClis ?? true}
+ onPickCli={onPickCli}
+ onPickTerminal={onPickTerminal}
+ visibleClis={overrides.visibleClis}
+ />
+ </TooltipProvider>
+ </QueryClientProvider>,
);
- return { onLaunchSelected, onPickCli, onPickTerminal };
+ return { onLaunchSelected, onPickCli, onPickTerminal, onPickAgent, onOpenSettings };
}
-describe('TerminalNewChatButton', () => {
+describe('TerminalNewChatButton (merged sessions-dock New button)', () => {
afterEach(() => cleanup());
test('the primary launches the current selection (a CLI) without changing it', async () => {
const user = userEvent.setup();
- const { onLaunchSelected, onPickCli } = renderButton('codex');
+ const { onLaunchSelected, onPickCli } = renderButton({
+ selected: { kind: 'cli', cli: 'codex' },
+ });
await user.click(screen.getByRole('button', { name: 'New Codex chat' }));
expect(onLaunchSelected).toHaveBeenCalledTimes(1);
- // Primary is a plain launch — it never re-picks.
expect(onPickCli).not.toHaveBeenCalled();
});
test('when Terminal is the selection the primary opens a bare terminal', async () => {
const user = userEvent.setup();
- const { onLaunchSelected, onPickTerminal } = renderButton('terminal');
+ const { onLaunchSelected } = renderButton({ selected: { kind: 'terminal' } });
await user.click(screen.getByRole('button', { name: 'New terminal' }));
expect(onLaunchSelected).toHaveBeenCalledTimes(1);
- expect(onPickTerminal).not.toHaveBeenCalled();
});
- test('the dropdown lists every available CLI plus a Terminal option', async () => {
+ test('when an agent is the selection the primary reads "New <agent> chat"', () => {
+ renderButton({ selected: { kind: 'agent', agent: AGENT_A } });
+ expect(screen.getByRole('button', { name: 'New Agent A chat' })).toBeDefined();
+ });
+
+ test('the dropdown lists registered agents, Configure agents, every available CLI, and Terminal', async () => {
const user = userEvent.setup();
- renderButton('claude');
+ renderButton();
- await user.click(screen.getByRole('button', { name: 'Choose CLI for new chat' }));
+ await user.click(screen.getByRole('button', { name: 'Choose what a new session starts' }));
+ expect(await screen.findByRole('menuitem', { name: 'Agent A' })).toBeDefined();
+ expect(screen.getByRole('menuitem', { name: 'Agent B' })).toBeDefined();
+ expect(screen.getByRole('menuitem', { name: 'Configure agents' })).toBeDefined();
for (const name of [
'Claude CLI',
'Codex CLI',
@@ -63,22 +88,22 @@ describe('TerminalNewChatButton', () => {
'OpenCode CLI',
'Cursor CLI',
]) {
- expect(await screen.findByRole('menuitem', { name })).toBeDefined();
+ expect(screen.getByRole('menuitem', { name })).toBeDefined();
}
expect(screen.getByRole('menuitem', { name: 'Terminal' })).toBeDefined();
});
test('lists only the CLIs in visibleClis (Claude + detected), hiding the rest', async () => {
const user = userEvent.setup();
- // The host passes the already-gated list from `visibleTerminalClis`: Claude
- // (always-visible anchor) plus detected `codex`. Antigravity/Cursor weren't
- // detected on PATH, so their rows are absent.
- renderButton('claude', ['claude', 'codex']);
+ // The host passes the already-gated list (via `isTerminalCliEnabled`): here
+ // Claude plus detected Codex. Undetected CLIs are absent.
+ renderButton({ visibleClis: ['claude', 'codex'] });
- await user.click(screen.getByRole('button', { name: 'Choose CLI for new chat' }));
+ await user.click(screen.getByRole('button', { name: 'Choose what a new session starts' }));
expect(await screen.findByRole('menuitem', { name: 'Claude CLI' })).toBeDefined();
expect(screen.getByRole('menuitem', { name: 'Codex CLI' })).toBeDefined();
+ expect(screen.queryByRole('menuitem', { name: 'OpenCode CLI' })).toBeNull();
expect(screen.queryByRole('menuitem', { name: 'GitHub Copilot CLI' })).toBeNull();
expect(screen.queryByRole('menuitem', { name: 'Antigravity CLI' })).toBeNull();
expect(screen.queryByRole('menuitem', { name: 'Cursor CLI' })).toBeNull();
@@ -86,11 +111,33 @@ describe('TerminalNewChatButton', () => {
expect(screen.getByRole('menuitem', { name: 'Terminal' })).toBeDefined();
});
- test('picking a CLI from the dropdown switches the default (persist + launch)', async () => {
+ test('web surface (showClis=false) hides the CLI + Terminal rows', async () => {
+ const user = userEvent.setup();
+ renderButton({ showClis: false });
+
+ await user.click(screen.getByRole('button', { name: 'Choose what a new session starts' }));
+
+ expect(await screen.findByRole('menuitem', { name: 'Agent A' })).toBeDefined();
+ expect(screen.queryByRole('menuitem', { name: 'Claude CLI' })).toBeNull();
+ expect(screen.queryByRole('menuitem', { name: 'Terminal' })).toBeNull();
+ });
+
+ test('terminal window surface (showAgents=false) hides the agent rows', async () => {
const user = userEvent.setup();
- const { onPickCli, onLaunchSelected, onPickTerminal } = renderButton('claude');
+ renderButton({ showAgents: false });
- await user.click(screen.getByRole('button', { name: 'Choose CLI for new chat' }));
+ await user.click(screen.getByRole('button', { name: 'Choose what a new session starts' }));
+
+ expect(await screen.findByRole('menuitem', { name: 'Claude CLI' })).toBeDefined();
+ expect(screen.queryByRole('menuitem', { name: 'Agent A' })).toBeNull();
+ expect(screen.queryByRole('menuitem', { name: 'Configure agents' })).toBeNull();
+ });
+
+ test('picking a CLI switches the default (persist + launch), not the primary', async () => {
+ const user = userEvent.setup();
+ const { onPickCli, onLaunchSelected, onPickTerminal } = renderButton();
+
+ await user.click(screen.getByRole('button', { name: 'Choose what a new session starts' }));
await user.click(await screen.findByRole('menuitem', { name: 'OpenCode CLI' }));
expect(onPickCli).toHaveBeenCalledTimes(1);
@@ -99,43 +146,50 @@ describe('TerminalNewChatButton', () => {
expect(onPickTerminal).not.toHaveBeenCalled();
});
- test('marks the current pick with aria-current so it is in the a11y tree', async () => {
+ test('picking a registered agent switches the default (persist + launch)', async () => {
const user = userEvent.setup();
- renderButton('codex');
+ const { onPickAgent, onLaunchSelected } = renderButton();
- await user.click(screen.getByRole('button', { name: 'Choose CLI for new chat' }));
+ await user.click(screen.getByRole('button', { name: 'Choose what a new session starts' }));
+ await user.click(await screen.findByRole('menuitem', { name: 'Agent B' }));
- // The active CLI row is programmatically current; siblings + Terminal are not.
- expect(
- (await screen.findByRole('menuitem', { name: 'Codex CLI' })).getAttribute('aria-current'),
- ).toBe('true');
- expect(
- screen.getByRole('menuitem', { name: 'Claude CLI' }).getAttribute('aria-current'),
- ).toBeNull();
- expect(
- screen.getByRole('menuitem', { name: 'Terminal' }).getAttribute('aria-current'),
- ).toBeNull();
+ expect(onPickAgent).toHaveBeenCalledTimes(1);
+ expect(onPickAgent).toHaveBeenCalledWith(AGENT_B);
+ expect(onLaunchSelected).not.toHaveBeenCalled();
});
- test('marks the Terminal row current when a bare shell is the selection', async () => {
+ test('"Configure agents" opens the settings tab', async () => {
const user = userEvent.setup();
- renderButton('terminal');
+ const { onOpenSettings } = renderButton();
- await user.click(screen.getByRole('button', { name: 'Choose CLI for new chat' }));
+ await user.click(screen.getByRole('button', { name: 'Choose what a new session starts' }));
+ await user.click(await screen.findByRole('menuitem', { name: 'Configure agents' }));
+
+ expect(onOpenSettings).toHaveBeenCalledTimes(1);
+ });
+
+ test('marks the selected agent / CLI / terminal row current via aria-current', async () => {
+ const user = userEvent.setup();
+ renderButton({ selected: { kind: 'agent', agent: AGENT_A } });
+
+ await user.click(screen.getByRole('button', { name: 'Choose what a new session starts' }));
expect(
- (await screen.findByRole('menuitem', { name: 'Terminal' })).getAttribute('aria-current'),
+ (await screen.findByRole('menuitem', { name: 'Agent A' })).getAttribute('aria-current'),
).toBe('true');
expect(
- screen.getByRole('menuitem', { name: 'Claude CLI' }).getAttribute('aria-current'),
+ screen.getByRole('menuitem', { name: 'Agent B' }).getAttribute('aria-current'),
+ ).toBeNull();
+ expect(
+ screen.getByRole('menuitem', { name: 'Terminal' }).getAttribute('aria-current'),
).toBeNull();
});
- test('picking Terminal from the dropdown switches the default to a bare shell', async () => {
+ test('picking Terminal switches the default to a bare shell', async () => {
const user = userEvent.setup();
- const { onPickTerminal, onPickCli, onLaunchSelected } = renderButton('claude');
+ const { onPickTerminal, onPickCli, onLaunchSelected } = renderButton();
- await user.click(screen.getByRole('button', { name: 'Choose CLI for new chat' }));
+ await user.click(screen.getByRole('button', { name: 'Choose what a new session starts' }));
await user.click(await screen.findByRole('menuitem', { name: 'Terminal' }));
expect(onPickTerminal).toHaveBeenCalledTimes(1);
diff --git a/packages/app/src/components/TerminalNewChatButton.tsx b/packages/app/src/components/TerminalNewChatButton.tsx
index 0b68f4ff5..c7871a4a0 100644
--- a/packages/app/src/components/TerminalNewChatButton.tsx
+++ b/packages/app/src/components/TerminalNewChatButton.tsx
@@ -1,69 +1,123 @@
import { TERMINAL_CLIS, type TerminalCli } from '@inkeep/open-knowledge-core';
import { Trans, useLingui } from '@lingui/react/macro';
-import { CheckIcon, ChevronDownIcon, PlusIcon, SquareTerminalIcon } from 'lucide-react';
+import { useQuery } from '@tanstack/react-query';
+import {
+ Bot,
+ CheckIcon,
+ ChevronDownIcon,
+ PlusIcon,
+ SlidersHorizontal,
+ SquareTerminalIcon,
+} from 'lucide-react';
+import { useState } from 'react';
+import { AgentBetaBadge } from '@/components/acp/AgentBetaBadge';
+import { RegisteredAgentIcon } from '@/components/acp/RegisteredAgentIcon';
import { TargetIcon } from '@/components/handoff/OpenInAgentMenuItem';
import { cliIconTargetId, VISIBLE_CLIS } from '@/components/handoff/terminal-cli-display';
import { Button } from '@/components/ui/button';
import {
DropdownMenu,
DropdownMenuContent,
+ DropdownMenuGroup,
DropdownMenuItem,
DropdownMenuLabel,
DropdownMenuSeparator,
DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip';
+import { fetchAgentCatalog } from '@/lib/acp/catalog';
+import type { RegisteredAgent } from '@/lib/acp/registered-agents';
+import type { NewSessionChoice } from '@/lib/new-session-choice';
import { cn } from '@/lib/utils';
-/** The New-tab split button's current pick: a CLI, or a bare shell ("terminal"). */
-export type TerminalNewTabChoice = TerminalCli | 'terminal';
-
interface TerminalNewChatButtonProps {
- /** The current pick — a CLI (resolved from the sticky pick + installed set, the
- * same default logic the Ask-AI surfaces use) or `'terminal'` (a bare shell).
- * Drives the primary icon/label + the dropdown checkmark. */
- readonly selected: TerminalNewTabChoice;
- /** Primary click — open a new tab running the current {@link selected} pick
- * (a CLI chat, or a bare shell). A plain launch: it does not change the pick. */
+ /** The current primary pick — an in-app agent, a CLI, or a bare shell. Drives
+ * the primary icon/label and the dropdown checkmark. */
+ readonly selected: NewSessionChoice;
+ /** Primary click — launch the current {@link selected} pick. A plain launch: it
+ * does not change the pick. (When the pick is an agent with no concrete agent
+ * remembered, the host routes this to Configure agents instead.) */
readonly onLaunchSelected: () => void;
- /** Dropdown CLI row — make `cli` the new default (persist, like the Ask-AI
- * picker) AND open a new tab running it. */
+ /** Render the in-app agent rows (the dock) — false in the standalone terminal
+ * window, which hosts only shells. */
+ readonly showAgents: boolean;
+ /** The user's registered agents (most-recently-registered first). */
+ readonly registeredAgents: readonly RegisteredAgent[];
+ /** Dropdown agent row — register it as the new default AND start a thread. */
+ readonly onPickAgent: (agent: RegisteredAgent) => void;
+ /** "Configure agents" row — opens the Configure agents settings tab. */
+ readonly onOpenSettings: () => void;
+ /** Live (non-archived) agent-thread count, checked against the server cap to
+ * disable the agent rows when the workspace is at its running-agent limit. */
+ readonly liveThreadCount: number;
+ /** Render the CLI + bare-Terminal rows (a desktop bridge with a PTY). */
+ readonly showClis: boolean;
+ /** Dropdown CLI row — make `cli` the new default (persist) AND open a tab in it. */
readonly onPickCli: (cli: TerminalCli) => void;
- /** Dropdown "Terminal" row — make a bare shell the new default (persist,
- * terminal-only) AND open a new bare-shell tab. */
+ /** Dropdown "Terminal" row — make a bare shell the new default AND open one. */
readonly onPickTerminal: () => void;
- /** The CLIs to list — already gated by the host via {@link visibleTerminalClis}
- * (Claude plus CLIs the probe hasn't ruled out, and always the current pick),
- * so a CLI that's been probed absent doesn't appear. This is a presentational
- * component: it renders the list as given. Falls back to the full
- * {@link VISIBLE_CLIS} only for callers/tests that don't pass a gated list. */
+ /** The CLIs to list — already gated by the host via `isTerminalCliEnabled`
+ * (CLIs the probe hasn't ruled out, plus the current pick), so a CLI that's
+ * been probed absent doesn't appear. This is a presentational component: it
+ * renders the list as given. Falls back to the full {@link VISIBLE_CLIS} only
+ * for callers/tests that don't pass a gated list. */
readonly visibleClis?: readonly TerminalCli[];
readonly className?: string;
}
/**
- * The docked terminal's "new tab" control: a split button pairing a primary
- * launch of the current pick with a dropdown to switch it. Clicking the primary
- * opens a new tab in whatever is currently selected (a CLI chat, or a bare
- * terminal); the carat lists every CLI — picking one makes it the new default and
- * opens a tab in it — plus a "Terminal" row that does the same for a bare shell.
- * The pick sticks: CLI picks via the shared Ask-AI store, the bare-terminal pick
- * via a terminal-only flag. The brand icon mirrors the Ask-AI surfaces so a glance
- * tells you what a new tab will start.
+ * The sessions dock's "new session" control: a split button pairing a primary
+ * launch of the current pick with a dropdown to switch it across all three
+ * families. The primary opens whatever is currently selected: a bare terminal, a
+ * CLI chat, or an in-app agent thread. The menu mirrors the Ask-AI surfaces: an
+ * "In this app" group (enabled agents), then — on the desktop host — a "Terminal"
+ * group (every CLI plus a bare "Terminal" shell), then a "Configure agents" footer last.
+ *
+ * The pick sticks: agent + CLI picks via the shared Ask-AI store, the bare-terminal
+ * pick via a terminal-only flag. The brand icon / agent avatar mirrors the Ask-AI
+ * surfaces so a glance tells you what a new session will start.
*/
export function TerminalNewChatButton({
selected,
onLaunchSelected,
+ showAgents,
+ registeredAgents,
+ onPickAgent,
+ onOpenSettings,
+ liveThreadCount,
+ showClis,
onPickCli,
onPickTerminal,
visibleClis = VISIBLE_CLIS,
className,
}: TerminalNewChatButtonProps) {
const { t } = useLingui();
- const isTerminal = selected === 'terminal';
- const primaryLabel = isTerminal
- ? t`New terminal`
- : t`New ${TERMINAL_CLIS[selected].displayName} chat`;
+ const [menuOpen, setMenuOpen] = useState(false);
+
+ // Fetch the catalog lazily — only while the menu is open on a thread surface —
+ // for the max-running-agents cap. Shares the `['acp-catalog']` query cache (and
+ // 5-min staleness) with the catalog dialog, so opening the menu after browsing
+ // the catalog is free. Default 8 until it resolves (matches the server default).
+ const catalog = useQuery({
+ queryKey: ['acp-catalog'],
+ queryFn: ({ signal }) => fetchAgentCatalog(signal),
+ enabled: menuOpen && showAgents,
+ staleTime: 5 * 60 * 1000,
+ });
+ const maxThreads = catalog.data?.maxThreads ?? 8;
+ const atCap = liveThreadCount >= maxThreads;
+
+ // The `t` template macro is scope-bound, so the label is computed inline here
+ // rather than in a helper that receives `t` as an argument.
+ const primaryLabel =
+ selected.kind === 'terminal'
+ ? t`New terminal`
+ : selected.kind === 'cli'
+ ? t`New ${TERMINAL_CLIS[selected.cli].displayName} chat`
+ : selected.agent !== null
+ ? t`New ${selected.agent.name} chat`
+ : t`Start an agent`;
+
return (
<div className={cn('flex shrink-0 items-center', className)}>
<Tooltip>
@@ -77,11 +131,7 @@ export function TerminalNewChatButton({
className="cursor-pointer gap-0.5 rounded-r-none px-1.5 text-muted-foreground hover:text-foreground"
onClick={onLaunchSelected}
>
- {isTerminal ? (
- <SquareTerminalIcon aria-hidden="true" className="size-3.5" />
- ) : (
- <TargetIcon id={cliIconTargetId(selected)} className="size-3.5" aria-hidden="true" />
- )}
+ <NewSessionPrimaryIcon selected={selected} className="size-3.5" />
<PlusIcon aria-hidden="true" className="size-3" />
</Button>
</TooltipTrigger>
@@ -89,63 +139,158 @@ export function TerminalNewChatButton({
{primaryLabel}
</TooltipContent>
</Tooltip>
- <DropdownMenu>
+ <DropdownMenu open={menuOpen} onOpenChange={setMenuOpen}>
<DropdownMenuTrigger asChild>
<Button
type="button"
variant="ghost"
size="icon-xs"
- aria-label={t`Choose CLI for new chat`}
+ aria-label={t`Choose what a new session starts`}
data-testid="terminal-new-chat-menu"
className="cursor-pointer rounded-l-none text-muted-foreground hover:text-foreground"
>
<ChevronDownIcon aria-hidden="true" className="size-3" />
</Button>
</DropdownMenuTrigger>
- <DropdownMenuContent align="start" className="min-w-[180px]">
- <DropdownMenuLabel>
- <Trans>New chat</Trans>
- </DropdownMenuLabel>
- {visibleClis.map((cli) => {
- const { displayName: name } = TERMINAL_CLIS[cli];
- return (
+ <DropdownMenuContent align="start" className="max-h-80 min-w-[200px]">
+ {/* Same section structure as the Ask-AI menus — an "In this app" group
+ over the agent rows, a "Terminal" group over the CLIs, and a
+ "Configure agents" footer last — so the dock picker reads consistently. The
+ bare "Terminal" (plain shell) is the last row of the Terminal group,
+ where it belongs alongside the CLIs. */}
+ {showAgents && registeredAgents.length > 0 ? (
+ <DropdownMenuGroup aria-label={t`In app (beta)`}>
+ <DropdownMenuLabel className="flex items-center gap-1.5">
+ <Trans>In app</Trans>
+ <AgentBetaBadge />
+ </DropdownMenuLabel>
+ {registeredAgents.map((agent) => {
+ const isSelected =
+ selected.kind === 'agent' &&
+ selected.agent?.source === agent.source &&
+ selected.agent?.id === agent.id;
+ return (
+ <DropdownMenuItem
+ key={`${agent.source}:${agent.id}`}
+ onSelect={() => onPickAgent(agent)}
+ disabled={atCap}
+ data-testid={`terminal-new-chat-agent-${agent.id}`}
+ aria-current={isSelected ? 'true' : undefined}
+ >
+ <RegisteredAgentIcon
+ agentId={agent.id}
+ iconUrl={agent.iconUrl}
+ className="size-4"
+ />
+ <span className="flex-1 truncate">{agent.name}</span>
+ {isSelected ? (
+ <CheckIcon aria-hidden="true" className="size-4 text-muted-foreground" />
+ ) : null}
+ </DropdownMenuItem>
+ );
+ })}
+ {atCap ? (
+ <DropdownMenuLabel
+ className="py-1 font-normal text-muted-foreground text-xs"
+ data-testid="terminal-new-chat-cap"
+ >
+ <Trans>Maximum agents already running</Trans>
+ </DropdownMenuLabel>
+ ) : null}
+ </DropdownMenuGroup>
+ ) : null}
+ {showAgents && registeredAgents.length > 0 && showClis ? <DropdownMenuSeparator /> : null}
+ {showClis ? (
+ <DropdownMenuGroup aria-label={t`Terminal`}>
+ <DropdownMenuLabel>
+ <Trans>Terminal</Trans>
+ </DropdownMenuLabel>
+ {visibleClis.map((cli) => {
+ const { displayName: name } = TERMINAL_CLIS[cli];
+ const isSelected = selected.kind === 'cli' && selected.cli === cli;
+ return (
+ <DropdownMenuItem
+ key={cli}
+ onSelect={() => onPickCli(cli)}
+ data-testid={`terminal-new-chat-cli-${cli}`}
+ // The accessible name carries "<name> CLI" so it is distinct and
+ // unambiguous (matches the Ask-AI Terminal rows, WCAG 2.5.3).
+ aria-label={t`${name} CLI`}
+ // `aria-current` over menuitemradio: each row both selects a
+ // default AND launches, so radio semantics overstate the
+ // selection aspect (WCAG 1.3.1).
+ aria-current={isSelected ? 'true' : undefined}
+ >
+ <TargetIcon id={cliIconTargetId(cli)} className="size-4" aria-hidden="true" />
+ <span className="flex-1">{name}</span>
+ {isSelected ? (
+ <CheckIcon aria-hidden="true" className="size-4 text-muted-foreground" />
+ ) : null}
+ </DropdownMenuItem>
+ );
+ })}
+ {/* Bare shell — last row of the Terminal group. */}
<DropdownMenuItem
- key={cli}
- onSelect={() => onPickCli(cli)}
- data-testid={`terminal-new-chat-cli-${cli}`}
- // The accessible name carries "<name> CLI" so it is distinct and
- // unambiguous (matches the Ask-AI Terminal rows, WCAG 2.5.3).
- aria-label={t`${name} CLI`}
- // Surface the current pick to assistive tech (the CheckIcon is
- // aria-hidden). `aria-current` over menuitemradio: each row both
- // selects a default AND launches, so radio semantics overstate the
- // selection aspect (WCAG 1.3.1).
- aria-current={selected === cli ? 'true' : undefined}
+ onSelect={onPickTerminal}
+ data-testid="terminal-new-chat-terminal"
+ aria-current={selected.kind === 'terminal' ? 'true' : undefined}
>
- <TargetIcon id={cliIconTargetId(cli)} className="size-4" aria-hidden="true" />
- <span className="flex-1">{name}</span>
- {selected === cli ? (
+ <SquareTerminalIcon aria-hidden="true" className="size-4" />
+ <span className="flex-1">
+ <Trans>Terminal</Trans>
+ </span>
+ {selected.kind === 'terminal' ? (
<CheckIcon aria-hidden="true" className="size-4 text-muted-foreground" />
) : null}
</DropdownMenuItem>
- );
- })}
- <DropdownMenuSeparator />
- <DropdownMenuItem
- onSelect={onPickTerminal}
- data-testid="terminal-new-chat-terminal"
- aria-current={isTerminal ? 'true' : undefined}
- >
- <SquareTerminalIcon aria-hidden="true" className="size-4" />
- <span className="flex-1">
- <Trans>Terminal</Trans>
- </span>
- {isTerminal ? (
- <CheckIcon aria-hidden="true" className="size-4 text-muted-foreground" />
- ) : null}
- </DropdownMenuItem>
+ </DropdownMenuGroup>
+ ) : null}
+ {/* Settings — the global footer, last in every menu (matches the Ask-AI
+ surfaces). Opens Configure agents; only on the agent-hosting dock,
+ never the standalone terminal window. "Settings" is never capped. */}
+ {showAgents ? (
+ <>
+ {/* Separator only when a section sits above it, so the all-disabled
+ dock menu isn't a lone rule over the footer. */}
+ {registeredAgents.length > 0 || showClis ? <DropdownMenuSeparator /> : null}
+ <DropdownMenuItem onSelect={onOpenSettings} data-testid="terminal-new-chat-settings">
+ <SlidersHorizontal aria-hidden="true" className="size-4 text-muted-foreground" />
+ <span className="flex-1">
+ <Trans>Configure agents</Trans>
+ </span>
+ </DropdownMenuItem>
+ </>
+ ) : null}
</DropdownMenuContent>
</DropdownMenu>
</div>
);
}
+
+/** Primary-button icon for the current pick (brand icon / agent avatar / shell). */
+function NewSessionPrimaryIcon({
+ selected,
+ className,
+}: {
+ selected: NewSessionChoice;
+ className?: string;
+}) {
+ if (selected.kind === 'terminal') {
+ return <SquareTerminalIcon aria-hidden="true" className={className} />;
+ }
+ if (selected.kind === 'cli') {
+ return (
+ <TargetIcon id={cliIconTargetId(selected.cli)} className={className} aria-hidden="true" />
+ );
+ }
+ if (selected.agent !== null) {
+ return (
+ <RegisteredAgentIcon
+ agentId={selected.agent.id}
+ iconUrl={selected.agent.iconUrl}
+ className={className}
+ />
+ );
+ }
+ return <Bot aria-hidden="true" className={className} />;
+}
diff --git a/packages/app/src/components/TerminalRevealTab.dom.test.tsx b/packages/app/src/components/TerminalRevealTab.dom.test.tsx
index 977fa41c2..aae0d1eda 100644
--- a/packages/app/src/components/TerminalRevealTab.dom.test.tsx
+++ b/packages/app/src/components/TerminalRevealTab.dom.test.tsx
@@ -1,11 +1,11 @@
-import { afterEach, describe, expect, mock, test } from 'bun:test';
import { cleanup, render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
+import { afterEach, describe, expect, test, vi } from 'vitest';
import { TooltipProvider } from '@/components/ui/tooltip';
import { TerminalRevealTab } from './TerminalRevealTab';
function renderTab(dockPosition: 'bottom' | 'right') {
- const onReveal = mock(() => {});
+ const onReveal = vi.fn(() => {});
render(
// The app mounts a root TooltipProvider (main.tsx); supply one here so the
// reveal tab's tooltip has its context in isolation.
@@ -19,11 +19,11 @@ function renderTab(dockPosition: 'bottom' | 'right') {
describe('TerminalRevealTab', () => {
afterEach(() => cleanup());
- test('exposes a "Show terminal" control and fires onReveal on click', async () => {
+ test('exposes an "Open session dock" control and fires onReveal on click', async () => {
const user = userEvent.setup();
const { onReveal } = renderTab('right');
- await user.click(screen.getByRole('button', { name: 'Show terminal' }));
+ await user.click(screen.getByRole('button', { name: 'Open session dock' }));
expect(onReveal).toHaveBeenCalledTimes(1);
});
@@ -31,13 +31,17 @@ describe('TerminalRevealTab', () => {
test('marks which edge it hugs so it sits where the collapse control was', () => {
renderTab('right');
expect(
- screen.getByRole('button', { name: 'Show terminal' }).getAttribute('data-terminal-reveal'),
+ screen
+ .getByRole('button', { name: 'Open session dock' })
+ .getAttribute('data-terminal-reveal'),
).toBe('right');
cleanup();
renderTab('bottom');
expect(
- screen.getByRole('button', { name: 'Show terminal' }).getAttribute('data-terminal-reveal'),
+ screen
+ .getByRole('button', { name: 'Open session dock' })
+ .getAttribute('data-terminal-reveal'),
).toBe('bottom');
});
@@ -45,9 +49,9 @@ describe('TerminalRevealTab', () => {
const user = userEvent.setup();
renderTab('bottom');
- await user.hover(screen.getByRole('button', { name: 'Show terminal' }));
+ await user.hover(screen.getByRole('button', { name: 'Open session dock' }));
const tooltip = await screen.findByRole('tooltip');
- expect(tooltip.textContent).toContain('Show terminal');
+ expect(tooltip.textContent).toContain('Open session dock');
});
});
diff --git a/packages/app/src/components/TerminalRevealTab.tsx b/packages/app/src/components/TerminalRevealTab.tsx
index 781dba7b2..83c954da4 100644
--- a/packages/app/src/components/TerminalRevealTab.tsx
+++ b/packages/app/src/components/TerminalRevealTab.tsx
@@ -10,7 +10,7 @@ interface TerminalRevealTabProps {
* tab is flush against, and the tooltip side so it sits right where the
* collapse control was. */
readonly dockPosition: TerminalDockPosition;
- /** Reveal the terminal (and spawn a default-CLI session if none is open). */
+ /** Reveal the sessions dock (and launch the preferred session if none is open). */
readonly onReveal: () => void;
/** Absolute-placement offsets from the call site (which edge/corner it pins to).
* The caller owns placement because the two dock positions attach to different
@@ -19,7 +19,7 @@ interface TerminalRevealTabProps {
}
/**
- * Persistent "Show terminal" affordance shown only while the terminal is hidden.
+ * Persistent "Open session dock" affordance shown only while the sessions dock is hidden.
* The header chat toggle is one icon among many and reads ambiguously; this tab
* hugs the same edge the terminal lives on so a user who collapsed or closed the
* terminal has an obvious, in-place way to bring it back — right where the
@@ -36,7 +36,7 @@ interface TerminalRevealTabProps {
export function TerminalRevealTab({ dockPosition, onReveal, className }: TerminalRevealTabProps) {
const { t } = useLingui();
const rightDocked = dockPosition === 'right';
- const label = t`Show terminal`;
+ const label = t`Open session dock`;
return (
<Tooltip>
<TooltipTrigger asChild>
diff --git a/packages/app/src/components/TerminalSessionsHost.threads.dom.test.tsx b/packages/app/src/components/TerminalSessionsHost.threads.dom.test.tsx
new file mode 100644
index 000000000..e4747fdf7
--- /dev/null
+++ b/packages/app/src/components/TerminalSessionsHost.threads.dom.test.tsx
@@ -0,0 +1,337 @@
+/**
+ * Behavioral tests for the sessions dock hosting AGENT THREADS (the unified-dock
+ * half of the host). TerminalGate + ThreadView + the thread store are stubbed so
+ * the assertions pin what the host owns for thread tabs: mirroring the server
+ * thread list into tabs, kind-aware close (archive) + focus (composer), rename →
+ * server, and auto-reveal on a new live thread. The terminal half is covered by
+ * TerminalDock.dom.test.tsx (same host).
+ */
+
+import type { ThreadInfo } from '@inkeep/open-knowledge-core/acp/thread-protocol';
+import { cleanup, render, screen, waitFor } from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
+import { useState, useSyncExternalStore } from 'react';
+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
+import { TooltipProvider } from '@/components/ui/tooltip';
+import type { OkDesktopBridge } from '@/lib/desktop-bridge-types';
+
+// A tiny controllable stand-in for the server-authoritative thread store.
+let openThreads: ThreadInfo[] = [];
+const storeListeners = new Set<() => void>();
+let archivedThreads: ThreadInfo[] = [];
+function notifyStore() {
+ for (const l of storeListeners) l();
+}
+function setOpenThreads(next: ThreadInfo[]) {
+ openThreads = next;
+ notifyStore();
+}
+function setArchivedThreads(next: ThreadInfo[]) {
+ archivedThreads = next;
+ notifyStore();
+}
+const closeThread = vi.fn((_id: string) => {});
+const renameThread = vi.fn((_id: string, _title: string) => {});
+// Reopening an archived thread adds it to the open set (it stays archived).
+const openArchivedThread = vi.fn((id: string) => {
+ const thread = archivedThreads.find((t) => t.threadId === id);
+ if (thread != null) setOpenThreads([...openThreads, thread]);
+});
+const deleteThread = vi.fn((id: string) => {
+ setArchivedThreads(archivedThreads.filter((t) => t.threadId !== id));
+});
+
+let connectionStatus: 'idle' | 'connecting' | 'open' | 'closed' = 'open';
+function setConnectionStatus(next: typeof connectionStatus) {
+ connectionStatus = next;
+ notifyStore();
+}
+
+function subscribeStore(cb: () => void) {
+ storeListeners.add(cb);
+ return () => storeListeners.delete(cb);
+}
+
+vi.doMock('@/lib/acp/thread-client', () => ({
+ useOpenAgentThreadTabs: () =>
+ useSyncExternalStore(
+ subscribeStore,
+ () => openThreads,
+ () => openThreads,
+ ),
+ useArchivedAgentThreads: () =>
+ useSyncExternalStore(
+ subscribeStore,
+ () => archivedThreads,
+ () => archivedThreads,
+ ),
+ useAgentThreadConnection: () =>
+ useSyncExternalStore(
+ subscribeStore,
+ () => connectionStatus,
+ () => connectionStatus,
+ ),
+ getAgentThreadClient: () => ({ closeThread, renameThread, openArchivedThread, deleteThread }),
+}));
+
+// ThreadView is lazy-loaded by the host; stub it (with the composer focus hook).
+vi.doMock('@/components/acp/ThreadView', () => ({
+ ThreadView: ({ info }: { info: ThreadInfo }) => (
+ <div data-testid="thread-view" data-thread-id={info.threadId}>
+ <textarea data-testid="agent-thread-composer" />
+ </div>
+ ),
+}));
+
+vi.doMock('@/lib/acp/registered-agents', () => ({
+ useRegisteredAgents: () => [],
+ useDefaultRegisteredAgent: () => null,
+ getDefaultRegisteredAgent: () => null,
+ registerAgent: () => {},
+ // Real code loaded here imports these too (TerminalSessionsHost →
+ // pickEffectiveDefaultAgent; catalog → hydrateRegisteredAgentMeta). A
+ // mock.module replaces the whole module, so any omitted export becomes an
+ // unresolved import that fails the file (and can cascade to siblings).
+ pickEffectiveDefaultAgent: () => null,
+ hydrateRegisteredAgentMeta: () => {},
+}));
+
+const launchAgentThread = vi.fn(() => {});
+vi.doMock('@/lib/acp/launch-agent-thread', () => ({ launchAgentThread }));
+
+let catalogData: unknown;
+// The host and New split-button share the catalog query; keep it controllable.
+vi.doMock('@tanstack/react-query', () => ({
+ useQuery: () => ({ data: catalogData, isLoading: false, isError: false }),
+}));
+
+const { TerminalSessionsHost } = await import('./TerminalSessionsHost');
+
+function makeThread(overrides: Partial<ThreadInfo> & { threadId: string }): ThreadInfo {
+ return {
+ agent: { id: 'a', name: 'Agent', source: 'registry' },
+ title: overrides.threadId,
+ status: 'ready',
+ createdAt: 1,
+ lastActivityAt: 1,
+ lastSeq: 0,
+ archived: false,
+ ...overrides,
+ };
+}
+
+function Harness({
+ bridge = null,
+ initialVisible = true,
+ onVisibleChange,
+}: {
+ bridge?: OkDesktopBridge | null;
+ initialVisible?: boolean;
+ onVisibleChange?: (v: boolean) => void;
+}) {
+ const [container, setContainer] = useState<HTMLDivElement | null>(null);
+ const [visible, setVisible] = useState(initialVisible);
+ return (
+ <TooltipProvider>
+ <div ref={setContainer} data-testid="dock-container" />
+ <TerminalSessionsHost
+ bridge={bridge}
+ visible={visible}
+ onVisibleChange={(v) => {
+ onVisibleChange?.(v);
+ setVisible(v);
+ }}
+ installedClis={{}}
+ container={container}
+ isShowing={visible && container != null}
+ onRequestEditorFocus={() => {}}
+ dockPosition="bottom"
+ />
+ </TooltipProvider>
+ );
+}
+
+describe('TerminalSessionsHost — agent-thread hosting (web / no bridge)', () => {
+ beforeEach(() => {
+ openThreads = [];
+ archivedThreads = [];
+ connectionStatus = 'open';
+ closeThread.mockClear();
+ renameThread.mockClear();
+ openArchivedThread.mockClear();
+ deleteThread.mockClear();
+ launchAgentThread.mockClear();
+ catalogData = undefined;
+ });
+ afterEach(() => cleanup());
+
+ test('a server thread becomes a tab rendering its ThreadView', async () => {
+ render(<Harness />);
+ setOpenThreads([makeThread({ threadId: 't1', title: 'Refactor' })]);
+
+ expect(await screen.findByRole('tab', { name: /Refactor/ })).toBeDefined();
+ expect(await screen.findByTestId('thread-view')).toBeDefined();
+ });
+
+ test('without an explicit default the primary reads "Start an agent" and opens Settings', async () => {
+ const user = userEvent.setup();
+ render(<Harness />);
+
+ const button = await screen.findByTestId('terminal-new-chat');
+ // No default agent → "Start an agent"; the click opens Configure agents
+ // rather than launching an agent directly (the catalog was retired).
+ expect(button.getAttribute('aria-label')).toBe('Start an agent');
+ await user.click(button);
+
+ expect(launchAgentThread).not.toHaveBeenCalled();
+ expect(window.location.hash).toBe('#settings/configure-agents');
+ });
+
+ test('the tab list mirrors the store: add + remove', async () => {
+ render(<Harness />);
+ setOpenThreads([makeThread({ threadId: 't1', title: 'One' })]);
+ await screen.findByRole('tab', { name: /One/ });
+
+ setOpenThreads([
+ makeThread({ threadId: 't1', title: 'One' }),
+ makeThread({ threadId: 't2', title: 'Two' }),
+ ]);
+ await screen.findByRole('tab', { name: /Two/ });
+
+ // Remove t1 from the store (archived elsewhere) → its tab drops.
+ setOpenThreads([makeThread({ threadId: 't2', title: 'Two' })]);
+ await waitFor(() => expect(screen.queryByRole('tab', { name: /One/ })).toBeNull());
+ expect(screen.getByRole('tab', { name: /Two/ })).toBeDefined();
+ });
+
+ test('closing a thread tab archives it via the client (not a local remove)', async () => {
+ const user = userEvent.setup();
+ render(<Harness />);
+ setOpenThreads([makeThread({ threadId: 't1', title: 'Doomed' })]);
+ await screen.findByRole('tab', { name: /Doomed/ });
+
+ await user.click(screen.getByRole('button', { name: 'Close Doomed' }));
+
+ expect(closeThread).toHaveBeenCalledTimes(1);
+ expect(closeThread).toHaveBeenCalledWith('t1');
+ });
+
+ test('renaming a thread tab routes to the server rename', async () => {
+ const user = userEvent.setup();
+ render(<Harness />);
+ setOpenThreads([makeThread({ threadId: 't1', title: 'Old name' })]);
+ await screen.findByRole('tab', { name: /Old name/ });
+
+ await user.dblClick(screen.getByRole('tab', { name: /Old name/ }));
+ const input = screen.getByRole('textbox', { name: /Rename/ });
+ await user.clear(input);
+ await user.type(input, 'New name');
+ await user.keyboard('{Enter}');
+
+ await waitFor(() => expect(renameThread).toHaveBeenCalledWith('t1', 'New name'));
+ });
+
+ test('a newly live thread reveals a hidden dock (auto-reveal)', async () => {
+ const onVisibleChange = vi.fn((_v: boolean) => {});
+ render(<Harness initialVisible={false} onVisibleChange={onVisibleChange} />);
+
+ setOpenThreads([makeThread({ threadId: 't1', title: 'Fresh' })]);
+
+ await waitFor(() => expect(onVisibleChange).toHaveBeenCalledWith(true));
+ });
+
+ test('an archived-only backlog does NOT auto-reveal the dock', async () => {
+ const onVisibleChange = vi.fn((_v: boolean) => {});
+ render(<Harness initialVisible={false} onVisibleChange={onVisibleChange} />);
+
+ // Archived threads (history) must never pop a dock the user closed.
+ setOpenThreads([makeThread({ threadId: 't1', title: 'History', archived: true })]);
+
+ await new Promise((r) => setTimeout(r, 50));
+ expect(onVisibleChange).not.toHaveBeenCalledWith(true);
+ });
+
+ test('the history menu reopens an archived conversation as a tab', async () => {
+ const user = userEvent.setup();
+ render(<Harness />);
+ // One live tab (so the strip renders) + archived history to return to.
+ setOpenThreads([makeThread({ threadId: 'live', title: 'Live' })]);
+ setArchivedThreads([makeThread({ threadId: 'arch', title: 'Old chat', archived: true })]);
+ await screen.findByRole('tab', { name: /Live/ });
+
+ await user.click(screen.getByRole('button', { name: 'Restore sessions' }));
+ await user.click(await screen.findByTestId('agent-thread-history-open-arch'));
+
+ expect(openArchivedThread).toHaveBeenCalledWith('arch');
+ // The store reopen brought it in as a tab.
+ expect(await screen.findByRole('tab', { name: /Old chat/ })).toBeDefined();
+ });
+
+ test('the restore and delete controls explain themselves on hover', async () => {
+ const user = userEvent.setup();
+ render(<Harness />);
+ setOpenThreads([makeThread({ threadId: 'live', title: 'Live' })]);
+ setArchivedThreads([makeThread({ threadId: 'arch', title: 'Old chat', archived: true })]);
+ await screen.findByRole('tab', { name: /Live/ });
+
+ const restore = screen.getByRole('button', { name: 'Restore sessions' });
+ await user.hover(restore);
+ expect((await screen.findByRole('tooltip')).textContent).toContain('Restore sessions');
+
+ await user.click(restore);
+ const deleteButton = await screen.findByRole('button', { name: 'Delete Old chat' });
+ await user.hover(deleteButton);
+ expect((await screen.findByRole('tooltip')).textContent).toContain('Delete Old chat');
+ });
+
+ test('the history menu deletes an archived conversation behind an inline confirm', async () => {
+ const user = userEvent.setup();
+ render(<Harness />);
+ setOpenThreads([makeThread({ threadId: 'live', title: 'Live' })]);
+ setArchivedThreads([makeThread({ threadId: 'arch', title: 'Old chat', archived: true })]);
+ await screen.findByRole('tab', { name: /Live/ });
+
+ await user.click(screen.getByRole('button', { name: 'Restore sessions' }));
+ await user.click(await screen.findByTestId('agent-thread-history-delete-arch'));
+ // Delete is confirm-gated (no undo) — the first click only arms it.
+ expect(deleteThread).not.toHaveBeenCalled();
+ await user.click(await screen.findByTestId('agent-thread-history-confirm-delete'));
+
+ expect(deleteThread).toHaveBeenCalledWith('arch');
+ });
+
+ test('an empty dock offers a chooser to reopen a past conversation', async () => {
+ const user = userEvent.setup();
+ render(<Harness />);
+ // No open sessions, but archived history exists → the chooser, not a dead end.
+ setArchivedThreads([makeThread({ threadId: 'arch', title: 'Yesterday', archived: true })]);
+
+ await user.click(await screen.findByTestId('agent-thread-empty-open-arch'));
+
+ expect(openArchivedThread).toHaveBeenCalledWith('arch');
+ expect(await screen.findByRole('tab', { name: /Yesterday/ })).toBeDefined();
+ });
+
+ test('the history menu is absent with no archived history', () => {
+ render(<Harness />);
+ setOpenThreads([makeThread({ threadId: 'live', title: 'Live' })]);
+ expect(screen.queryByRole('button', { name: 'Restore sessions' })).toBeNull();
+ });
+
+ test('a dropped WS shows the reconnecting banner above the active thread', async () => {
+ render(<Harness />);
+ setOpenThreads([makeThread({ threadId: 't1', title: 'Work' })]);
+ await screen.findByTestId('thread-view');
+
+ // Healthy channel: no banner.
+ expect(screen.queryByTestId('agent-thread-reconnecting')).toBeNull();
+
+ // WS drops → the reconnecting feedback appears.
+ setConnectionStatus('closed');
+ expect(await screen.findByTestId('agent-thread-reconnecting')).toBeDefined();
+
+ // Recovered → it clears.
+ setConnectionStatus('open');
+ await waitFor(() => expect(screen.queryByTestId('agent-thread-reconnecting')).toBeNull());
+ });
+});
diff --git a/packages/app/src/components/TerminalSessionsHost.tsx b/packages/app/src/components/TerminalSessionsHost.tsx
index 0b1f1713e..f11871ba3 100644
--- a/packages/app/src/components/TerminalSessionsHost.tsx
+++ b/packages/app/src/components/TerminalSessionsHost.tsx
@@ -1,126 +1,248 @@
import type { TerminalCli } from '@inkeep/open-knowledge-core';
+import type { ThreadInfo, ThreadStatus } from '@inkeep/open-knowledge-core/acp/thread-protocol';
import { useLingui } from '@lingui/react/macro';
-import { useEffect, useLayoutEffect, useRef, useState } from 'react';
+import { Loader2, SquareTerminalIcon } from 'lucide-react';
+import {
+ lazy,
+ type ReactNode,
+ Suspense,
+ useEffect,
+ useLayoutEffect,
+ useRef,
+ useState,
+} from 'react';
import { createPortal } from 'react-dom';
+import { RegisteredAgentIcon } from '@/components/acp/RegisteredAgentIcon';
+import { ArchivedThreadChooser, ThreadHistoryMenu } from '@/components/acp/ThreadHistoryMenu';
import { TabsContent } from '@/components/ui/tabs';
-import { resolveDefaultCli } from '@/lib/default-cli-resolver';
+import { isInAppAgentEnabled } from '@/lib/acp/agent-visibility';
+import { useEnabledOverrides } from '@/lib/acp/enabled-agents';
+import { launchAgentThread } from '@/lib/acp/launch-agent-thread';
+import { enabledTerminalClis, resolveLauncherSelection } from '@/lib/acp/launcher-selection';
+import {
+ getDefaultRegisteredAgent,
+ pickEffectiveDefaultAgent,
+ type RegisteredAgent,
+ registerAgent,
+ useDefaultRegisteredAgent,
+ useRegisteredAgents,
+} from '@/lib/acp/registered-agents';
+import {
+ getAgentThreadClient,
+ useAgentThreadConnection,
+ useArchivedAgentThreads,
+ useOpenAgentThreadTabs,
+} from '@/lib/acp/thread-client';
import type { OkDesktopBridge } from '@/lib/desktop-bridge-types';
+import {
+ type DockSessionOrder,
+ readDockSessionOrder,
+ readWebDockSessionOrder,
+ writeDockSessionOrder,
+} from '@/lib/dock-session-persistence';
import { subscribeLocalMenuAction } from '@/lib/local-menu-action-bus';
+import type { NewSessionChoice } from '@/lib/new-session-choice';
import type { TerminalDockPosition } from '@/lib/terminal-dock-store';
import {
getInitialPreferBareTerminal,
writePreferBareTerminal,
} from '@/lib/terminal-new-tab-store';
-import { loadStickyAgent, saveStickyAgent, terminalCliId } from '@/lib/unified-agent-store';
+import {
+ loadStickyAgent,
+ saveStickyAgent,
+ terminalCliId,
+ threadAgentId,
+} from '@/lib/unified-agent-store';
+import { openAgentSettings } from '@/lib/use-settings-route';
import { cn } from '@/lib/utils';
import { setViewMenuState } from '@/lib/view-menu-state-store';
-import type { TerminalLaunchIntent } from './EditorPane';
-import { visibleTerminalClis } from './handoff/terminal-cli-display';
+import type { TerminalLaunchIntent, ThreadLaunchIntent } from './EditorPane';
+
+// Lazy-loaded: ThreadView pulls the heavy agent-transcript + editor-navigation
+// chain, which terminal-only sessions (and the standalone terminal window) never
+// need. Deferring it keeps the host lightweight and its import graph clean — the
+// same lazy-panel pattern the editor uses for ActivityModeContent + TerminalPanel.
+const ThreadView = lazy(() =>
+ import('@/components/acp/ThreadView').then((mod) => ({ default: mod.ThreadView })),
+);
+
import { subscribeToActiveTerminalInput } from './handoff/terminal-input-events';
import { requestTerminalLaunch } from './handoff/terminal-launch-events';
import { TerminalGate } from './TerminalGate';
-import type { TerminalNewTabChoice } from './TerminalNewChatButton';
-import { TerminalTabStrip } from './TerminalTabStrip';
-
-/** A concurrent terminal session the host keeps as a tab. `id` is a stable
- * client-side identity (not the async PTY id — the session resolves its own PTY
- * on mount). `launch` is the one-shot intent the session writes once it is live;
- * sessions opened from the tab strip carry none. `title` is the latest OSC 0/2
- * title the running program set (null → the tab shows its positional default).
- * `adoptPtyId` is the surviving ptyId after a renderer reload — the session
- * adopts that live shell instead of spawning a fresh one; null for new tabs.
- * `customLabel` is a user-set tab name that pins over `title`; null until the
- * user renames the tab (an empty rename commit clears it back to null).
- * `ordinal` is an immutable per-session number assigned at creation from the
- * monotonic counter — the positional-fallback label ("Terminal N") uses it so a
- * reorder does not renumber untitled tabs (the number sticks to the session, not
- * the slot). Ordinals can have gaps (closing a tab leaves one) and reset to
- * positional on a renderer reload. */
-interface TerminalSessionDescriptor {
+import { TerminalNewChatButton } from './TerminalNewChatButton';
+import { type TerminalTabDescriptor, TerminalTabStrip } from './TerminalTabStrip';
+
+/** A session the host keeps as a tab. Two kinds share one ordered list + one
+ * active id (the unified sessions dock). Terminal fields carry PTY state; the
+ * thread variant carries only its server-owned `threadId` (its live title +
+ * status come from the thread store). `ordinal` is a shared monotonic number the
+ * panel render sorts by (so a tab reorder never moves a panel's DOM node); the
+ * terminal positional label ("Terminal N") also reads it. `id` is a stable
+ * client identity: `terminal-session-<n>` for a terminal, the threadId itself
+ * for a thread. */
+interface BaseSessionDescriptor {
readonly id: string;
+ readonly ordinal: number;
+}
+interface TerminalSessionDescriptor extends BaseSessionDescriptor {
+ readonly kind: 'terminal';
+ /** One-shot launch intent the session writes once it is live; null for a bare tab. */
readonly launch: TerminalLaunchIntent | null;
+ /** Latest OSC 0/2 title the running program set (null → positional default). */
readonly title: string | null;
+ /** User-set tab name that pins over `title`; null until renamed. */
readonly customLabel: string | null;
- readonly ordinal: number;
+ /** Surviving ptyId adopted after a renderer reload (live shell + replay); null for new tabs. */
readonly adoptPtyId: string | null;
}
+interface ThreadSessionDescriptor extends BaseSessionDescriptor {
+ readonly kind: 'thread';
+ /** Server-owned thread id — the reload-stable key AND the store lookup key. */
+ readonly threadId: string;
+}
+type SessionDescriptor = TerminalSessionDescriptor | ThreadSessionDescriptor;
function makeSessionId(counter: number): string {
return `terminal-session-${counter}`;
}
-/** Move focus into a session's terminal. xterm routes keystrokes through its
- * helper textarea, so focusing it is equivalent to term.focus(). No-ops when
- * the textarea has not mounted yet (xterm mounts asynchronously). */
+/** Attribute-escape a session id for a `querySelector` (jsdom's preload lacks `CSS.escape`). */
+function escapeSelector(id: string): string {
+ return typeof CSS !== 'undefined' && CSS.escape ? CSS.escape(id) : id;
+}
+
+/** Move focus into a terminal session's xterm (routes keystrokes through its
+ * helper textarea). No-ops until the textarea has mounted (xterm mounts async). */
function focusTerminalSession(id: string) {
if (id === '') return;
document
- .querySelector<HTMLElement>(`[data-terminal-session="${id}"] .xterm-helper-textarea`)
+ .querySelector<HTMLElement>(
+ `[data-terminal-session="${escapeSelector(id)}"] .xterm-helper-textarea`,
+ )
+ ?.focus();
+}
+
+/** Move focus into a thread session's composer so the user can type immediately. */
+function focusThreadSession(id: string) {
+ if (id === '') return;
+ document
+ .querySelector<HTMLElement>(
+ `[data-session-id="${escapeSelector(id)}"] [data-testid="agent-thread-composer"]`,
+ )
?.focus();
}
+function focusSession(session: SessionDescriptor) {
+ if (session.kind === 'terminal') focusTerminalSession(session.id);
+ else focusThreadSession(session.id);
+}
+
/** True when keyboard focus currently sits inside the stable host div. */
function focusInsideHost(hostEl: HTMLElement | null): boolean {
return hostEl?.contains(document.activeElement) ?? false;
}
-/** Focus-gate shared by the terminal host's capture-phase keyboard chords (⌘1–9,
- * ⌘⇧←/→): a chord is in scope always in the window variant (the whole window IS
- * the terminal), and in the dock variant only while focus sits inside the host —
- * so the chords stay free everywhere else in the editor window. */
+/** Focus-gate for the host's capture-phase chords (⌘1–9, ⌘⇧←/→): always in the
+ * window variant (the whole window IS the terminal), in the dock only while
+ * focus sits inside the host. */
function chordTargetsHost(hostEl: HTMLElement | null, variant: 'dock' | 'window'): boolean {
return variant === 'window' || focusInsideHost(hostEl);
}
+/** Colour of a thread tab's status dot, by lifecycle. Transitional states pulse;
+ * solid amber means "blocked on you" (sign-in or a permission prompt). */
+function threadStatusDotClass(status: ThreadStatus): string {
+ switch (status) {
+ case 'running':
+ return 'bg-amber-500 animate-pulse';
+ case 'installing':
+ case 'spawning':
+ return 'bg-sky-500 animate-pulse';
+ case 'auth_required':
+ case 'awaiting_permission':
+ return 'bg-amber-500';
+ case 'ready':
+ return 'bg-emerald-500';
+ case 'error':
+ return 'bg-red-500';
+ default:
+ return 'bg-muted-foreground';
+ }
+}
+
+/** The kind glyph the strip shows before a terminal tab's label. */
+function terminalTabIcon(): ReactNode {
+ return (
+ <SquareTerminalIcon className="size-3.5 shrink-0 text-muted-foreground" aria-hidden="true" />
+ );
+}
+
+/** The agent avatar + live status dot the strip shows before a thread tab's label. */
+function threadTabIcon(info: ThreadInfo | undefined): ReactNode {
+ return (
+ <span className="relative inline-flex shrink-0">
+ <RegisteredAgentIcon
+ agentId={info?.agent.id ?? ''}
+ iconUrl={info?.agent.iconUrl}
+ className="size-3.5"
+ />
+ {info != null ? (
+ <span
+ className={cn(
+ '-right-0.5 -bottom-0.5 absolute size-1.5 rounded-full ring-1 ring-background',
+ threadStatusDotClass(info.status),
+ )}
+ aria-hidden="true"
+ />
+ ) : null}
+ </span>
+ );
+}
+
interface TerminalSessionsHostProps {
- /** Desktop bridge — the host renders only on the Electron surface. */
- readonly bridge: OkDesktopBridge;
/**
- * Which surface hosts the sessions. `'dock'` (default) is the editor's
- * docked terminal: visibility-driven seeding, dock-toggle + collapse controls,
- * ⌘1–9 scoped to focus inside the host. `'window'` is the standalone terminal
- * window: always visible, seeds its first tab on mount, the tab row doubles as
- * the macOS title bar, no dock/collapse controls (window management is the
- * OS's), and ⌘1–9 is scope-free (the whole window is the terminal). Everything
- * else — the new-chat split button, OSC tab titles, menu actions, liveness,
- * reload rehydration — is identical by construction: one session model, two
- * placements.
+ * Desktop bridge, or `null` on the web host. The host mounts unconditionally
+ * now — a shell and an agent are just tabs of a different kind in one dock, and
+ * agents are server-hosted, so the dock is host-agnostic. Terminal-*kind*
+ * affordances (creation, PTY bodies, reload adopt) gate on the bridge exposing a
+ * `terminal` surface; thread tabs work with no bridge at all.
+ */
+ readonly bridge: OkDesktopBridge | null;
+ /**
+ * Which surface hosts the sessions. `'dock'` (default) is the editor's sessions
+ * dock: terminals AND agent threads, visibility-driven seeding, dock-toggle +
+ * collapse controls, ⌘1–9 scoped to focus inside the host. `'window'` is the
+ * standalone terminal window: terminals ONLY (no agent threads), always visible,
+ * seeds its first tab on mount, the tab row doubles as the macOS title bar, no
+ * dock/collapse controls, and ⌘1–9 is scope-free.
*/
readonly variant?: 'dock' | 'window';
- /** Controlled visibility. The host reflects this and reports close-last back
- * through {@link onVisibleChange}; it never owns it. The window variant pins
- * it `true` and maps the close-last report to `window.close()`. */
+ /** Controlled visibility. The host reflects it and reports close-last back
+ * through {@link onVisibleChange}; it never owns it. */
readonly visible: boolean;
readonly onVisibleChange: (visible: boolean) => void;
- /** "Open in terminal" launch intent — each new intent opens its own tab. */
+ /** "Open in terminal" launch intent — each new intent opens its own terminal tab. */
readonly launch?: TerminalLaunchIntent | null;
- /** Which CLIs are on PATH (desktop probe). The tab strip's "New chat" resolves
- * its default CLI from this + the sticky pick. */
+ /** "Start an agent" launch intent — each new intent opens its own thread tab (or
+ * the agent catalog when no concrete agent is resolvable). Dock variant only. */
+ readonly threadLaunch?: ThreadLaunchIntent | null;
+ /** Which CLIs are on PATH (desktop probe). The New split-button resolves its
+ * default CLI from this + the sticky pick. */
readonly installedClis?: Partial<Record<TerminalCli, boolean>>;
- /**
- * The DOM container the live terminal portals into right now — the bottom dock's
- * mount or the right region's terminal tenant. The single stable host div is
- * physically appended here; relocating the DOM (rather than swapping the portal
- * target, or remounting the host) is what keeps a dock move from re-spawning the
- * PTY. This component is mounted ONCE, above the editor's resizable panel group,
- * so it never remounts on a dock change. Null only transiently before a
- * container attaches.
- */
+ /** The DOM container the live session subtree portals into right now (bottom
+ * dock mount or right region tenant). Null only transiently before a container
+ * attaches. */
readonly container: HTMLElement | null;
- /** Whether the terminal is actually on screen — drives focus in/out. */
+ /** Whether the dock is actually on screen — drives focus in/out. */
readonly isShowing: boolean;
- /** Return focus to the editor when the terminal hides or the last tab closes. */
+ /** Return focus to the editor when the dock hides or the last tab closes. */
readonly onRequestEditorFocus: () => void;
- /** Current dock position — passed to the tab strip's dock-toggle + collapse
- * controls so their icons/labels reflect where the terminal lives. Dock
- * variant only. */
+ /** Current dock position — passed to the strip's dock-toggle + collapse controls. */
readonly dockPosition?: TerminalDockPosition;
- /** Flip the dock between bottom and right (the tab strip's dock-toggle button).
- * Dock variant only — the strip renders no toggle without it. */
+ /** Flip the dock between bottom and right. Dock variant only. */
readonly onToggleDock?: () => void;
- /** Reports whether any PTY session is currently open. The header's New chat
- * button reads this to decide between spawning a first chat and merely
- * revealing the existing dock. */
+ /** Reports whether ANY session (terminal or thread) is open, so the placement
+ * owner (EditorArea via EditorPane) can render the dock column/shell. */
readonly onHasSessionsChange?: (hasSessions: boolean) => void;
/** Reports whether the ACTIVE tab is an AI-CLI session (was launched with a
* `cli`, e.g. a "New chat" / "Open with AI" tab) rather than a bare shell.
@@ -132,12 +254,17 @@ interface TerminalSessionsHostProps {
}
/**
- * Owns the terminal session collection and the single stable host div. Mounted
- * ONCE at a stable position ABOVE the editor's resizable panel group (in
- * EditorArea) so a dock change cannot remount it — the live shell, scrollback, and
- * tabs survive the move. The sessions render into the host div via a portal whose
- * target never changes; the host div is appended into whichever {@link container}
- * is active (bottom dock ↔ right region).
+ * Owns the unified session collection (terminals + agent threads) and the single
+ * stable host div. Mounted ONCE at a stable position ABOVE the editor's resizable
+ * panel group so a dock change cannot remount it — live shells, scrollback,
+ * transcripts, and tabs survive the move. The sessions render into the host div
+ * via a portal whose target never changes; the host div is appended into whichever
+ * {@link container} is active (bottom dock ↔ right region).
+ *
+ * The tab strip + panels dispatch by `kind`: reorder / activate / rename / close
+ * are strip-uniform, their behavior kind-specific. Terminals are host-owned (PTY
+ * lifecycle); threads mirror the server-authoritative thread store (the host owns
+ * only the dock/tab model — order, active, visibility — never thread lifecycle).
*/
export function TerminalSessionsHost({
bridge,
@@ -145,6 +272,7 @@ export function TerminalSessionsHost({
visible,
onVisibleChange,
launch = null,
+ threadLaunch = null,
installedClis,
container,
isShowing,
@@ -156,9 +284,15 @@ export function TerminalSessionsHost({
}: TerminalSessionsHostProps) {
const { t } = useLingui();
- // The single stable host div for the terminal session subtree. Created once via
- // a useState lazy initializer (never a render-time ref write — the React
- // Compiler forbids touching refs during render) and never recreated.
+ // Terminal affordances need a bridge that actually exposes the `terminal`
+ // surface (a session-only bridge, some E2E hosts, has none). Thread hosting is
+ // the dock variant only (the standalone terminal window is shells-only).
+ const terminalAvailable = bridge?.terminal != null;
+ const hostThreads = variant === 'dock';
+
+ // The single stable host div for the session subtree. Created once via a
+ // useState lazy initializer (never a render-time ref write — React Compiler
+ // forbids touching refs during render) and never recreated.
const [hostEl] = useState<HTMLDivElement | null>(() => {
if (typeof document === 'undefined') return null;
const el = document.createElement('div');
@@ -169,32 +303,44 @@ export function TerminalSessionsHost({
// Append the stable host div into the active container. A constant portal target
// plus DOM relocation means no remount on a dock move. useLayoutEffect runs
// before the focus passive effects below, so the host is attached before a
- // focus-on-reveal (focusing an element outside the document is a no-op).
+ // focus-on-reveal.
useLayoutEffect(() => {
if (hostEl == null || container == null) return;
if (hostEl.parentElement !== container) container.appendChild(hostEl);
}, [hostEl, container]);
// A capable desktop bridge can report the PTY sessions that survived a renderer
- // reload in the main process, so the host rehydrates them on mount instead of
- // starting fresh. When it can, the synchronous seed below stands down and the
- // async mount effect becomes the single source of truth for the initial sessions
- // (adopt survivors, or settle to let the seed path run). A session-only bridge
- // with no `terminal` surface keeps the synchronous cold-start.
- const canRehydrate = typeof bridge.terminal?.list === 'function';
-
- // The session collection is the mount latch generalized to N tabs: a session
- // stays in the list across hide/show (hide is not kill) so a long-running shell
- // survives a collapse. Before the first open the list is empty — no PTY until
- // the user opens the terminal. Opening with the terminal already visible seeds
- // the first session (with any launch intent) so it never flashes empty. When the
- // bridge can rehydrate, start empty and let the mount effect populate it so a
- // survived reload never spawns a fresh shell only to replace it with the adopted
- // set.
- const [sessions, setSessions] = useState<readonly TerminalSessionDescriptor[]>(() =>
- !canRehydrate && visible
+ // reload, so the host rehydrates them on mount instead of starting fresh. When
+ // it can, the synchronous terminal seed below stands down. Web + session-only
+ // bridges keep the synchronous cold-start (no terminals to rehydrate).
+ const canRehydrate = typeof bridge?.terminal?.list === 'function';
+
+ // Seed the first terminal synchronously only on a terminal surface with no
+ // rehydrate capability — web + session-only bridges never seed a terminal.
+ const coldSeedTerminal = !canRehydrate && terminalAvailable && visible;
+
+ // Persisted reload order (unified keys: ptyIds + threadIds) + active key. Web
+ // reads it synchronously from localStorage here; desktop reads it async from
+ // main in the rehydration effect (which sets the refs before seeding). Restored
+ // sessions are placed by this order; sessions created after mount append. Skipped
+ // for a cold-seeded surface (a fresh terminal-only start with no rehydrate) — it
+ // has no reload to restore, and its terminal persist goes through the bridge, not
+ // localStorage — so a stale localStorage arrangement never yanks a fresh seed.
+ const [webReloadOrder] = useState<DockSessionOrder | null>(() => {
+ if (canRehydrate || !hostThreads || coldSeedTerminal) return null;
+ // Only the web dock persists to localStorage; skip for the window variant.
+ return typeof bridge?.terminal?.getDockState === 'function' ? null : readWebDockSessionOrder();
+ });
+ const reloadOrderRef = useRef<readonly string[]>(webReloadOrder?.order ?? []);
+ // Active key still awaiting a matching session (reload restore). Cleared once
+ // matched, when the user takes over the active tab, or when the reload settles —
+ // so it never blocks nor steals live activation.
+ const pendingActiveKeyRef = useRef<string | null>(webReloadOrder?.activeKey ?? null);
+ const [sessions, setSessions] = useState<readonly SessionDescriptor[]>(() =>
+ coldSeedTerminal
? [
{
+ kind: 'terminal',
id: makeSessionId(1),
launch,
title: null,
@@ -206,65 +352,101 @@ export function TerminalSessionsHost({
: [],
);
const [activeSessionId, setActiveSessionId] = useState(() =>
- !canRehydrate && visible ? makeSessionId(1) : '',
+ coldSeedTerminal ? makeSessionId(1) : '',
);
- // False until the async rehydrate settles (capable bridge only); gates the
- // open/launch effect's seed so a transient visibility flip during the in-flight
- // inventory query can't spawn a shell the adopted set would then replace.
const [rehydrationSettled, setRehydrationSettled] = useState(!canRehydrate);
const rehydratedRef = useRef(false);
- // Mirror so the reveal-focus effect can target the active session without
- // re-running on every tab switch (which would steal focus during arrow-key nav).
const activeSessionIdRef = useRef(activeSessionId);
- // Live tab order, mirrored so the ⌘-number key handler reads it without
- // re-subscribing its window listener on every session change.
const sessionsRef = useRef(sessions);
- // Monotonic, never reused, so a closed tab's id can't collide with a later one.
- const sessionCounterRef = useRef(!canRehydrate && visible ? 1 : 0);
- // Highest launch nonce already turned into a tab — guards exactly-one-tab-per
- // intent across re-renders.
- const lastHandledLaunchNonceRef = useRef<number | null>(visible && launch ? launch.nonce : null);
- // Tracks the prior `visible` so the open-from-hidden transition (false→true) is
- // distinguishable from "still visible". The window variant mounts already
- // visible, so its mount IS the open transition — starting the ref false routes
- // the first-tab seed through the same open path the dock uses (after any
- // rehydration settles, so adopted reload survivors still win over a fresh seed).
+ // Monotonic, never reused — shared by both kinds so a closed tab's id/ordinal
+ // can't collide with a later one.
+ const sessionCounterRef = useRef(coldSeedTerminal ? 1 : 0);
+ const lastHandledLaunchNonceRef = useRef<number | null>(
+ coldSeedTerminal && launch ? launch.nonce : null,
+ );
+ const lastHandledThreadNonceRef = useRef<number | null>(null);
const prevVisibleRef = useRef(variant === 'window' ? false : visible);
- // Live PTY id per session, reported up from each panel (null on teardown). Lets
- // the selection-bubble "Ask AI" input (requestActiveTerminalInput) write into an
- // already-open terminal's live shell (reuse) instead of the caret going to the
- // composer. A session absent from the map has no live PTY yet (still starting,
- // or torn down).
const ptyIdBySessionRef = useRef(new Map<string, string>());
+ const stripLaunchNonceRef = useRef(0);
+
+ // Live agent-thread tabs (server-authoritative). Always subscribed (the hook is
+ // cheap + the store is empty until a URL is bound), reconciled into thread
+ // descriptors only in the dock variant.
+ const openThreadTabs = useOpenAgentThreadTabs();
+ const archivedThreads = useArchivedAgentThreads();
+ // WS status for the agent-thread channel — drives a "reconnecting" banner shown
+ // only above an active thread's transcript (never while a terminal is focused).
+ const threadConnection = useAgentThreadConnection();
+ const threadConnectionDown = threadConnection === 'connecting' || threadConnection === 'closed';
+ const registeredAgents = useRegisteredAgents();
+ const enabledOverrides = useEnabledOverrides();
+ // Only the in-app agents the user enabled in Configure agents appear in the
+ // New-chat picker (registered agents default to enabled).
+ const enabledRegisteredAgents = registeredAgents.filter((agent) =>
+ isInAppAgentEnabled(enabledOverrides, agent.source, agent.id, true, agent.supported),
+ );
+ const defaultRegisteredAgent = useDefaultRegisteredAgent();
+ // The primary "+" launch must honor Configure agents too: resolve it against
+ // the enabled agents only, and lead with the effective default (the registered
+ // default when still enabled, else the first enabled one). Otherwise disabling
+ // the sticky/default agent would hide it from the picker yet still launch it.
+ const effectiveDefaultAgent = pickEffectiveDefaultAgent(
+ enabledRegisteredAgents,
+ defaultRegisteredAgent,
+ );
+ const liveThreadCount = openThreadTabs.filter((info) => info.archived !== true).length;
+ const threadInfoById = new Map(openThreadTabs.map((info) => [info.threadId, info]));
+
+ // Reopen an archived conversation as a tab (history menu / empty-dock chooser).
+ // The store adds it to the open set; the reconcile + activation effects bring it
+ // in as the active tab.
+ function openArchivedThread(threadId: string) {
+ getAgentThreadClient().openArchivedThread(threadId);
+ }
+
+ /** Persist the current unified dock order + active key (reload-durable). Reads
+ * the post-commit refs so it is correct when called from a ptyId callback. */
+ function persistDockOrderNow() {
+ if (!hostThreads) return; // the window variant IS the surface — nothing to restore into
+ const ptyMap = ptyIdBySessionRef.current;
+ const order = sessionsRef.current
+ .map((session) => computePersistKey(session, ptyMap))
+ .filter((key): key is string => key != null);
+ const active = sessionsRef.current.find((s) => s.id === activeSessionIdRef.current);
+ writeDockSessionOrder(bridge, {
+ order,
+ activeKey: active != null ? computePersistKey(active, ptyMap) : null,
+ });
+ }
+
function setSessionPtyId(id: string, ptyId: string | null) {
if (ptyId === null) {
ptyIdBySessionRef.current.delete(id);
return;
}
ptyIdBySessionRef.current.set(id, ptyId);
- // Seed main with this session's reload-survival metadata as soon as its PTY
- // exists — the sticky ordinal (fixed at creation) plus any name set before the
- // shell spawned. Main outlives a renderer reload, so `list` reads it back.
const session = sessionsRef.current.find((s) => s.id === id);
- if (session != null) {
- bridge.terminal?.setMeta?.(ptyId, {
+ if (session != null && session.kind === 'terminal') {
+ bridge?.terminal?.setMeta?.(ptyId, {
ordinal: session.ordinal,
customLabel: session.customLabel,
});
}
+ // A terminal's persist key only exists once its PTY does — refresh the
+ // persisted order so a reload can restore this tab in place.
+ persistDockOrderNow();
}
- // Monotonic nonce for tab-strip "New chat" launches. TerminalLaunchIntent
- // requires a nonce, but it is only load-bearing for the EditorPane→prop
- // launch-channel dedup; a direct openSession writes its launch once on mount,
- // so this just keeps each strip launch a distinct, never-reused intent.
- const stripLaunchNonceRef = useRef(0);
function openSession(launchForSession: TerminalLaunchIntent | null) {
+ // Opening a tab is the user taking over the active slot — a lingering reload
+ // restore must not later yank the active tab back.
+ pendingActiveKeyRef.current = null;
sessionCounterRef.current += 1;
const id = makeSessionId(sessionCounterRef.current);
setSessions((prev) => [
...prev,
{
+ kind: 'terminal',
id,
launch: launchForSession,
title: null,
@@ -276,110 +458,169 @@ export function TerminalSessionsHost({
setActiveSessionId(id);
}
- // Sticky CLI mirror, mount-read from the shared Ask-AI store, so the New-chat
- // split button's default reflects the user's last pick and updates its primary
- // icon reactively when they switch CLI from the dropdown. `resolveDefaultCli`
- // also honors the live `installedClis` when there is no sticky pick.
- const [stickyCliId, setStickyCliId] = useState<string | null>(() => loadStickyAgent());
- // Terminal-only "last New-tab pick was a bare shell" flag. The shared store has
- // no terminal concept, so a "Terminal" pick sticks here instead; when set it
- // overrides the CLI default. Cleared on any CLI pick (CLI behavior is unchanged).
+ // Sticky pick mirror (raw id from the shared Ask-AI store) so the New split
+ // button's primary reflects the last pick across agents/CLIs/bare and updates
+ // reactively when the user switches it from the dropdown.
+ const [stickyAgentId, setStickyAgentId] = useState<string | null>(() => loadStickyAgent());
const [preferBareTerminal, setPreferBareTerminal] = useState(() =>
getInitialPreferBareTerminal(),
);
- const newChatDefaultCli = resolveDefaultCli(stickyCliId, installedClis ?? {});
- const newChatSelected: TerminalNewTabChoice = preferBareTerminal ? 'terminal' : newChatDefaultCli;
- // Gate the New-chat dropdown rows to Claude + CLIs the probe hasn't ruled out,
- // keeping the resolved default (`newChatDefaultCli`) so the split button's
- // current pick is always present in its own dropdown (with its checkmark).
- const newChatVisibleClis = visibleTerminalClis(installedClis ?? {}, newChatDefaultCli);
-
- // Tab-strip New-chat primary: open a promptless session running `cli`.
+
+ // The shared, enablement-aware selection — the SAME `resolveLauncherSelection`
+ // the Ask + Create composers use, so a disabled agent / CLI is never what the
+ // dock primary launches (the old `resolveNewSessionChoice` forced a Claude CLI
+ // fallback that ignored the toggles). The dock offers no Desktop rows and falls
+ // back to a bare terminal, so it only ever yields agent / cli / terminal.
+ const selection = resolveLauncherSelection({
+ sticky: stickyAgentId,
+ effectiveThreadAgent: effectiveDefaultAgent,
+ enabledClis: enabledTerminalClis(enabledOverrides, installedClis ?? {}),
+ enabledDesktopTargets: [],
+ installedClis: installedClis ?? {},
+ terminalAvailable,
+ threadsAvailable: hostThreads,
+ desktopSelectable: false,
+ preferBareTerminal,
+ bareTerminalFallback: true,
+ });
+ const newSessionChoice: NewSessionChoice =
+ selection.kind === 'thread'
+ ? { kind: 'agent', agent: selection.agent }
+ : selection.kind === 'cli'
+ ? { kind: 'cli', cli: selection.cli }
+ : selection.kind === 'terminal'
+ ? { kind: 'terminal' }
+ : // 'none' (thread-only surface, nothing enabled) → primary opens Settings.
+ { kind: 'agent', agent: null };
+
+ // Tab-strip New-chat primary: open a promptless terminal session running `cli`.
function openNewChatSession(cli: TerminalCli) {
stripLaunchNonceRef.current += 1;
openSession({ prompt: null, cli, nonce: stripLaunchNonceRef.current });
}
- // Primary click: launch the current pick — a bare shell when Terminal is the
- // default, else a promptless session in the default CLI.
+ // Primary click: launch the current sticky pick across all three families.
function launchSelectedNewTab() {
- if (preferBareTerminal) openSession(null);
- else openNewChatSession(newChatDefaultCli);
+ if (newSessionChoice.kind === 'terminal') openSession(null);
+ else if (newSessionChoice.kind === 'cli') openNewChatSession(newSessionChoice.cli);
+ else if (newSessionChoice.kind === 'agent' && newSessionChoice.agent != null)
+ launchAgentThread(
+ { source: newSessionChoice.agent.source, id: newSessionChoice.agent.id },
+ null,
+ null,
+ null,
+ );
+ else openAgentSettings();
+ }
+
+ // Seed the dock when it opens empty (⌘J / edge reveal with nothing latched) by
+ // repeating the choice shown on the New-session primary button — EXCEPT the
+ // neutral `choose` (no default agent). A passive reveal must NOT auto-open the
+ // agent catalog: revealing an empty dock just shows it empty; starting an
+ // in-app agent stays an explicit New-button click.
+ function seedOnReveal() {
+ if (newSessionChoice.kind === 'terminal') openSession(null);
+ else if (newSessionChoice.kind === 'cli') openNewChatSession(newSessionChoice.cli);
+ else if (newSessionChoice.kind === 'agent' && newSessionChoice.agent != null)
+ launchAgentThread(
+ { source: newSessionChoice.agent.source, id: newSessionChoice.agent.id },
+ null,
+ null,
+ null,
+ );
+ // `choose` → reveal the empty dock without auto-opening the catalog.
}
- // Dropdown CLI pick: clear the bare-terminal preference, persist `cli` to the
- // shared Ask-AI store (so every entry point agrees), and open a session in it.
+ // Dropdown CLI pick: clear the bare-terminal preference, persist `cli`, open it.
function pickNewChatCli(cli: TerminalCli) {
setPreferBareTerminal(false);
writePreferBareTerminal(false);
const id = terminalCliId(cli);
- setStickyCliId(id);
+ setStickyAgentId(id);
saveStickyAgent(id);
openNewChatSession(cli);
}
- // Dropdown "Terminal" pick: persist the bare-shell preference (terminal-only)
- // and open a bare shell. A subsequent primary click then opens a terminal too.
+ // Dropdown "Terminal" pick: persist the bare-shell preference, open a bare shell.
function pickNewChatTerminal() {
setPreferBareTerminal(true);
writePreferBareTerminal(true);
openSession(null);
}
- // Record the title the session's program set via OSC 0/2. A trimmed-empty title
- // clears it so the tab reverts to its positional `Terminal N` default (some
- // programs emit an empty title on exit). Shells re-emit the title on every
- // prompt, so when nothing changed we return the SAME array reference — React's
- // Object.is bailout then skips the re-render entirely (a per-element guard alone
- // wouldn't: a fresh array always fails the bailout).
+ // Dropdown agent pick: register it (making it the default), persist it as the
+ // sticky pick so the primary repeats it, clear the bare-terminal flag, and start
+ // a thread. Mirrors the catalog pick's "the agent you chose last is your agent".
+ function pickNewChatAgent(agent: RegisteredAgent) {
+ registerAgent(agent);
+ setPreferBareTerminal(false);
+ writePreferBareTerminal(false);
+ const id = threadAgentId(agent);
+ setStickyAgentId(id);
+ saveStickyAgent(id);
+ launchAgentThread({ source: agent.source, id: agent.id }, null, null, null);
+ }
+
+ // Record a terminal session's OSC 0/2 title. Same same-reference bailout as the
+ // rename below so an unchanged value causes no re-render.
function setSessionTitle(id: string, title: string) {
const next = title.trim() === '' ? null : title.trim();
setSessions((prev) => {
- if (!prev.some((session) => session.id === id && session.title !== next)) return prev;
- return prev.map((session) => (session.id === id ? { ...session, title: next } : session));
+ if (
+ !prev.some(
+ (session) => session.id === id && session.kind === 'terminal' && session.title !== next,
+ )
+ )
+ return prev;
+ return prev.map((session) =>
+ session.id === id && session.kind === 'terminal' ? { ...session, title: next } : session,
+ );
});
}
- // Commit a manual tab rename. A trimmed-empty value clears the custom label
- // (revert to OSC title / positional default). Same same-reference bailout as
- // setSessionTitle so an unchanged value causes no re-render.
- function setSessionCustomLabel(id: string, label: string) {
+ // Commit a manual tab rename — kind-dispatched. A terminal stores a custom label
+ // (empty clears it back to the OSC / positional default) that persists to main; a
+ // thread routes the rename to the server (blank is a no-op there).
+ function renameSession(id: string, label: string) {
+ const session = sessionsRef.current.find((s) => s.id === id);
+ if (session == null) return;
+ if (session.kind === 'thread') {
+ getAgentThreadClient().renameThread(session.threadId, label);
+ return;
+ }
const next = label.trim() === '' ? null : label.trim();
setSessions((prev) => {
- if (!prev.some((session) => session.id === id && session.customLabel !== next)) return prev;
- return prev.map((session) =>
- session.id === id ? { ...session, customLabel: next } : session,
+ if (!prev.some((s) => s.id === id && s.kind === 'terminal' && s.customLabel !== next))
+ return prev;
+ return prev.map((s) =>
+ s.id === id && s.kind === 'terminal' ? { ...s, customLabel: next } : s,
);
});
- // Persist the rename to main so it survives a renderer reload.
const ptyId = ptyIdBySessionRef.current.get(id);
- if (ptyId != null) bridge.terminal?.setMeta?.(ptyId, { customLabel: next });
+ if (ptyId != null) bridge?.terminal?.setMeta?.(ptyId, { customLabel: next });
}
- // Display label precedence, shared by the tab list and the reorder announcer:
- // a manual name pins over the OSC title, which pins over the sticky ordinal.
- function sessionLabel(session: TerminalSessionDescriptor): string {
- return session.customLabel ?? session.title ?? t`Terminal ${session.ordinal}`;
+ // Display label precedence, shared by the tab list and the reorder announcer.
+ function sessionLabel(session: SessionDescriptor): string {
+ if (session.kind === 'terminal') {
+ return session.customLabel ?? session.title ?? t`Terminal ${session.ordinal}`;
+ }
+ return threadInfoById.get(session.threadId)?.title ?? t`Agent`;
}
- // True while a pointer drag is lifted (reported by the strip); the ⌘⇧←/→ chord
- // is suppressed then so the two reorder inputs never mutate order concurrently.
const dragActiveRef = useRef(false);
- // sr-only polite live region for keyboard-reorder announcements. Imperative
- // textContent + trailing debounce (React batching would swallow rapid updates —
- // the app's announcer precedent); pointer drags keep dnd-kit's own announcements.
const announcerRef = useRef<HTMLSpanElement>(null);
const announceTimerRef = useRef<number | null>(null);
// Apply a reorder from a desired visual order of session ids — the single spine
- // for both the pointer drag (strip) and the keyboard path. A length or unknown-id
- // mismatch refuses the whole reorder (no partial mutation); an unchanged order
- // keeps the same array reference (render bailout).
+ // for both the pointer drag and the keyboard path. A length or unknown-id
+ // mismatch refuses the whole reorder; an unchanged order keeps the same array
+ // reference (render bailout).
function reorderSessions(newOrderIds: readonly string[]) {
setSessions((prev) => {
if (newOrderIds.length !== prev.length) return prev;
const byId = new Map(prev.map((session) => [session.id, session]));
- const next: TerminalSessionDescriptor[] = [];
+ const next: SessionDescriptor[] = [];
for (const id of newOrderIds) {
const session = byId.get(id);
if (session == null) return prev;
@@ -388,18 +629,15 @@ export function TerminalSessionsHost({
if (next.every((session, index) => session === prev[index])) return prev;
return next;
});
- // Persist the new display order to main (ptyIds in visual order) so a drag /
- // keyboard reorder survives a renderer reload. Sessions without a live PTY yet
- // are skipped; main slots them after the listed block via its own fallback.
+ // Persist the terminal-only display order to main (ptyIds in visual order) so a
+ // reorder survives a renderer reload — keeps `list()` self-consistent — and the
+ // unified cross-kind order for the mixed strip.
const orderedPtyIds = newOrderIds
.map((id) => ptyIdBySessionRef.current.get(id))
.filter((ptyId): ptyId is string => ptyId != null);
- if (orderedPtyIds.length > 0) bridge.terminal?.setOrder?.(orderedPtyIds);
+ if (orderedPtyIds.length > 0) bridge?.terminal?.setOrder?.(orderedPtyIds);
}
- // Move the active tab one slot (keyboard reorder). Reads the post-commit mirror
- // (same source as ⌘1–9), no-ops at the edges, and returns the moved tab's label
- // + new 1-based position for the SR announcement (null = nothing moved).
function moveActiveSession(
direction: -1 | 1,
): { label: string; position: number; total: number } | null {
@@ -414,36 +652,34 @@ export function TerminalSessionsHost({
reorderSessions(ids);
return { label: sessionLabel(current[from]), position: to + 1, total: current.length };
}
- // Latest-ref so the keyboard effect calls the current closure without
- // re-subscribing (React Compiler forbids writing the ref during render).
const moveActiveSessionRef = useRef(moveActiveSession);
-
- // Latest-ref so deps-stable effects below call the current closure without
- // re-subscribing (React Compiler forbids writing the ref during render).
const openSessionRef = useRef(openSession);
+ const seedOnRevealRef = useRef(seedOnReveal);
+ // Close a tab — kind-dispatched. A terminal is removed from the list (its panel
+ // unmounts, killing the PTY); a thread is archived server-side (discarded if it
+ // never received a message), and the reconcile effect drops its descriptor when
+ // the store does. The active-neighbor activation + close-last hide are uniform.
function closeSession(id: string) {
- // Read the live list from the ref (kept in sync post-commit), not the render
- // closure, so two close actions that coalesce into one batch can't act on a
- // stale snapshot — the same source the ⌘-number handler reads.
const current = sessionsRef.current;
const index = current.findIndex((session) => session.id === id);
if (index === -1) return;
- const next = current.filter((session) => session.id !== id);
- // Closing the active tab activates its left neighbor, else the right one.
- if (id === activeSessionId) {
+ const session = current[index];
+ const isLast = current.length === 1;
+ // The user is driving the active tab — stop any lingering reload restore.
+ pendingActiveKeyRef.current = null;
+ if (id === activeSessionIdRef.current) {
const neighbor = current[index - 1] ?? current[index + 1];
const neighborId = neighbor?.id ?? '';
setActiveSessionId(neighborId);
- // Move focus into the surviving neighbor's terminal so a keyboard user who
- // closed the focused tab is not stranded on the body. Deferred so the newly
- // active panel has committed to shown before focusing.
- if (neighborId !== '') queueMicrotask(() => focusTerminalSession(neighborId));
+ if (neighbor != null) queueMicrotask(() => focusSession(neighbor));
}
- setSessions(next);
- // Closing the last tab hides the terminal and returns focus to the editor; the
- // none-left state means the next open spawns a fresh session.
- if (next.length === 0) {
+ if (session.kind === 'thread') {
+ getAgentThreadClient().closeThread(session.threadId);
+ } else {
+ setSessions(current.filter((s) => s.id !== id));
+ }
+ if (isLast) {
onVisibleChange(false);
onRequestEditorFocus();
}
@@ -452,54 +688,209 @@ export function TerminalSessionsHost({
useEffect(() => {
openSessionRef.current = openSession;
+ seedOnRevealRef.current = seedOnReveal;
moveActiveSessionRef.current = moveActiveSession;
activeSessionIdRef.current = activeSessionId;
sessionsRef.current = sessions;
+ // The Terminal menu's "Kill Terminal" acts on a terminal: close the active tab
+ // when it is a terminal, else the newest terminal (so it stays meaningful while
+ // an agent tab is focused).
closeActiveRef.current = () => {
- if (activeSessionId !== '') closeSession(activeSessionId);
+ const active = sessionsRef.current.find((s) => s.id === activeSessionIdRef.current);
+ if (active?.kind === 'terminal') {
+ closeSession(active.id);
+ return;
+ }
+ const lastTerminal = [...sessionsRef.current].reverse().find((s) => s.kind === 'terminal');
+ if (lastTerminal != null) closeSession(lastTerminal.id);
};
});
- // Open/launch lifecycle: a fresh launch intent opens its own tab; otherwise an
- // open-from-hidden transition seeds the first session. Reacting to
- // `sessions.length` lets the close-last settle without a re-create.
+ // Persist the unified dock order + active whenever the tab set or active tab
+ // changes (reorder, add, remove, activate). Reads the ptyId map by ref; the
+ // computation uses only listed deps + the module-pure `computePersistKey`.
useEffect(() => {
- // While the async rehydrate is in flight (capable bridge), it owns the initial
- // session set — stand down entirely, including the prevVisible bookkeeping, so
- // a false→true visibility restore that lands mid-flight is still seen as a
- // fresh open transition once rehydration settles.
- if (!rehydrationSettled) return;
+ if (!hostThreads) return;
+ const ptyMap = ptyIdBySessionRef.current;
+ const order = sessions
+ .map((session) => computePersistKey(session, ptyMap))
+ .filter((key): key is string => key != null);
+ const active = sessions.find((s) => s.id === activeSessionId);
+ writeDockSessionOrder(bridge, {
+ order,
+ activeKey: active != null ? computePersistKey(active, ptyMap) : null,
+ });
+ }, [sessions, activeSessionId, hostThreads, bridge]);
+
+ // ── Thread reconciliation (dock variant) ────────────────────────────────
+ // Mirror the server-authoritative open-thread list into thread descriptors: add
+ // one per newly-open thread, drop one when its thread leaves the open set. The
+ // host owns only order/active; the thread store owns thread lifecycle. Restored
+ // threads land in the persisted reload order; live-created ones append.
+ useEffect(() => {
+ if (!hostThreads) return;
+ const openIds = new Set(openThreadTabs.map((info) => info.threadId));
+ const current = sessionsRef.current;
+ const knownThreadIds = new Set(
+ current
+ .filter((s): s is ThreadSessionDescriptor => s.kind === 'thread')
+ .map((s) => s.threadId),
+ );
+ // Compute additions (with fresh ordinals) OUTSIDE setState — ref writes are
+ // forbidden inside a (possibly re-invoked) updater.
+ const additions: ThreadSessionDescriptor[] = [];
+ for (const info of openThreadTabs) {
+ if (knownThreadIds.has(info.threadId)) continue;
+ sessionCounterRef.current += 1;
+ additions.push({
+ kind: 'thread',
+ id: info.threadId,
+ threadId: info.threadId,
+ ordinal: sessionCounterRef.current,
+ });
+ }
+ const removedAny = current.some((s) => s.kind === 'thread' && !openIds.has(s.threadId));
+ if (additions.length === 0 && !removedAny) return;
+ setSessions((prev) => {
+ const kept = prev.filter((s) => s.kind !== 'thread' || openIds.has(s.threadId));
+ // Dedup additions against the committed list too, so a StrictMode double-run
+ // never inserts the same thread twice.
+ const keptThreadIds = new Set(
+ kept
+ .filter((s): s is ThreadSessionDescriptor => s.kind === 'thread')
+ .map((s) => s.threadId),
+ );
+ const fresh = additions.filter((a) => !keptThreadIds.has(a.threadId));
+ const ptyMap = ptyIdBySessionRef.current;
+ const next =
+ fresh.length > 0
+ ? placeSessionAdditions(kept, fresh, reloadOrderRef.current, (s) =>
+ computePersistKey(s, ptyMap),
+ )
+ : kept;
+ if (next.length === prev.length && next.every((s, i) => s === prev[i])) return prev;
+ return next;
+ });
+ }, [openThreadTabs, hostThreads]);
+
+ // Bring a newly-created thread to the front (createThread → active), and focus
+ // its composer. Skipped while a reload-active restore is still pending so the
+ // initial batch of restored threads does not steal the restored active tab.
+ const prevOpenThreadIdsRef = useRef<readonly string[]>([]);
+ useEffect(() => {
+ if (!hostThreads) return;
+ const ids = openThreadTabs.map((info) => info.threadId);
+ const previous = prevOpenThreadIdsRef.current;
+ prevOpenThreadIdsRef.current = ids;
+ if (pendingActiveKeyRef.current != null) return;
+ const added = ids.filter((id) => !previous.includes(id));
+ const newest = added[added.length - 1];
+ if (newest != null) {
+ setActiveSessionId(newest);
+ queueMicrotask(() => focusThreadSession(newest));
+ }
+ }, [openThreadTabs, hostThreads]);
+
+ // A newly created LIVE thread reveals the dock (auto-reveal). Gated on the live
+ // count INCREASING so hiding the dock is never instantly undone, and a boot-time
+ // backlog of archived history never pops it.
+ const prevLiveThreadCountRef = useRef(liveThreadCount);
+ useEffect(() => {
+ if (!hostThreads) return;
+ const previous = prevLiveThreadCountRef.current;
+ prevLiveThreadCountRef.current = liveThreadCount;
+ if (liveThreadCount > previous && !visible) onVisibleChange(true);
+ }, [liveThreadCount, visible, hostThreads, onVisibleChange]);
+
+ // Reload-active restore + active-validity guard. Restores the persisted active
+ // tab once its session exists, then keeps `activeSessionId` valid: when the
+ // active session leaves (a thread archived elsewhere, a terminal closed), fall
+ // back to the newest remaining tab.
+ useEffect(() => {
+ const pending = pendingActiveKeyRef.current;
+ if (pending != null) {
+ const ptyMap = ptyIdBySessionRef.current;
+ const match = sessions.find((s) => computePersistKey(s, ptyMap) === pending);
+ if (match != null) {
+ pendingActiveKeyRef.current = null;
+ setActiveSessionId(match.id);
+ return;
+ }
+ // Still waiting for the restored active session to arrive — don't override.
+ if (sessions.some((s) => s.id === activeSessionId)) return;
+ }
+ if (activeSessionId !== '' && sessions.some((s) => s.id === activeSessionId)) return;
+ if (sessions.length === 0) {
+ if (activeSessionId !== '') setActiveSessionId('');
+ return;
+ }
+ setActiveSessionId(sessions[sessions.length - 1].id);
+ }, [sessions, activeSessionId]);
+ // Open/launch lifecycle: a fresh terminal launch intent opens its own tab;
+ // otherwise an open-from-hidden transition seeds the dock — UNLESS a fresh thread
+ // launch is being handled this cycle (the thread launch effect owns the seed
+ // then, so we don't open a bare terminal alongside the agent). Defined before the
+ // thread launch effect so `threadLaunchPending` reads the not-yet-handled nonce.
+ useEffect(() => {
+ if (!rehydrationSettled) return;
const wasVisible = prevVisibleRef.current;
prevVisibleRef.current = visible;
if (launch != null && launch.nonce !== lastHandledLaunchNonceRef.current) {
lastHandledLaunchNonceRef.current = launch.nonce;
- // A CLI launch (create composer, "Open in terminal" menus, bottom composer)
- // always opens its own tab: "create" means a fresh terminal, never hijacking
- // a shell the user already has running. Reuse of an open terminal is
- // exclusively the selection-bubble path (requestActiveTerminalInput), which
- // writes the highlighted text into the live PTY without a launch nonce.
openSessionRef.current(launch);
return;
}
- if (visible && !wasVisible && sessions.length === 0) {
- openSessionRef.current(null);
+ const threadLaunchPending =
+ hostThreads &&
+ threadLaunch != null &&
+ threadLaunch.nonce !== lastHandledThreadNonceRef.current;
+ if (visible && !wasVisible && sessions.length === 0 && !threadLaunchPending) {
+ seedOnRevealRef.current();
+ }
+ }, [visible, launch, threadLaunch, sessions.length, rehydrationSettled, hostThreads]);
+
+ // "Start an agent" launch intent (dock variant): resolve the agent (concrete /
+ // default-registered) and start a thread. Each new nonce opens its own thread
+ // tab; the store reconcile + auto-reveal bring it to front + reveal. When no
+ // agent resolves (nothing enabled yet), open Configure agents so the user can
+ // enable one — the retired agent catalog's replacement.
+ useEffect(() => {
+ if (!hostThreads) return;
+ if (threadLaunch == null || threadLaunch.nonce === lastHandledThreadNonceRef.current) return;
+ lastHandledThreadNonceRef.current = threadLaunch.nonce;
+ let agent: { source: 'registry' | 'custom'; id: string } | null =
+ threadLaunch.agentId === ''
+ ? null
+ : { source: threadLaunch.agentSource, id: threadLaunch.agentId };
+ if (agent === null) {
+ const fallback = getDefaultRegisteredAgent();
+ if (fallback !== null) agent = { source: fallback.source, id: fallback.id };
+ }
+ if (agent === null) {
+ openAgentSettings();
+ return;
}
- }, [visible, launch, sessions.length, rehydrationSettled]);
-
- // Reload rehydration (capable bridge only): on mount ask main which PTY sessions
- // survived the reload and rebuild one tab per survivor, each carrying the
- // surviving ptyId so its panel adopts the live shell rather than spawning a fresh
- // one. Run-once (ref-guarded). With no survivors it simply settles and lets the
- // open/launch effect own cold-start seeding. A throw resolves to "no survivors"
- // so a bridge hiccup degrades to a normal cold start, never a crash.
+ launchAgentThread(agent, threadLaunch.prompt, threadLaunch.docName, threadLaunch.titleHint);
+ }, [threadLaunch, hostThreads]);
+
+ // Reload rehydration (capable bridge only): rebuild one terminal tab per PTY
+ // survivor and read the persisted unified order + active key, so restored tabs
+ // land in place and the active tab is restored across kinds.
useEffect(() => {
- if (typeof bridge.terminal?.list !== 'function') return;
+ if (typeof bridge?.terminal?.list !== 'function') return;
if (rehydratedRef.current) return;
rehydratedRef.current = true;
let cancelled = false;
void (async () => {
+ // Read the persisted unified order first so terminal survivors are placed by
+ // it (and threads, arriving async, land at their persisted slots too).
+ const persisted = await readDockSessionOrder(bridge).catch(() => null);
+ if (!cancelled && persisted != null) {
+ reloadOrderRef.current = persisted.order;
+ pendingActiveKeyRef.current = persisted.activeKey;
+ }
let survivors: readonly {
ptyId: string;
customLabel: string | null;
@@ -508,90 +899,98 @@ export function TerminalSessionsHost({
try {
survivors = (await bridge.terminal.list()) ?? [];
} catch (err) {
- // Degrade to a normal cold start, but leave a breadcrumb: a transient
- // list() failure is otherwise indistinguishable from "no survivors", so
- // any surviving PTYs stay orphaned while the dock starts fresh.
console.error('[terminal] reload session list() failed; cold-starting:', err);
survivors = [];
}
if (cancelled) return;
if (survivors.length > 0) {
- const recovered = survivors.map((entry, index) => ({
- id: makeSessionId(index + 1),
- launch: null,
- title: null,
- // Restored from main so a rename + reorder survive a renderer reload;
- // ordinal falls back to positional for a session main never received one
- // for (created in the reload gap).
- customLabel: entry.customLabel ?? null,
- ordinal: entry.ordinal ?? index + 1,
- adoptPtyId: entry.ptyId,
- }));
- // Continue numbering above the highest restored ordinal so a new tab can't
- // collide with a survivor's sticky number.
+ const order = reloadOrderRef.current;
+ const rankOf = (ptyId: string) => {
+ const i = order.indexOf(ptyId);
+ return i === -1 ? Number.POSITIVE_INFINITY : i;
+ };
+ const recovered: TerminalSessionDescriptor[] = survivors
+ .map((entry, index) => ({
+ kind: 'terminal' as const,
+ id: makeSessionId(index + 1),
+ launch: null,
+ title: null,
+ customLabel: entry.customLabel ?? null,
+ ordinal: entry.ordinal ?? index + 1,
+ adoptPtyId: entry.ptyId,
+ }))
+ // Restore the persisted cross-kind order for terminals; survivors absent
+ // from it (created in the reload gap, or when no unified order was
+ // persisted) keep their `list()` order — which already reflects the
+ // terminal-only reorder — via the stable sort's 0 tie-break.
+ .sort((a, b) => {
+ const ra = rankOf(a.adoptPtyId);
+ const rb = rankOf(b.adoptPtyId);
+ return ra === rb ? 0 : ra - rb;
+ });
sessionCounterRef.current = Math.max(recovered.length, ...recovered.map((r) => r.ordinal));
setSessions(recovered);
- setActiveSessionId(recovered[0]?.id ?? '');
}
setRehydrationSettled(true);
+ // Bound the reload-active wait: if the restored active tab never materializes
+ // (its session died), stop blocking live activation so the guard picks a
+ // fallback. Threads have had CHANNEL_WAIT to arrive by now.
+ window.setTimeout(() => {
+ if (!cancelled) pendingActiveKeyRef.current = null;
+ }, 9_000);
})();
return () => {
cancelled = true;
// Reset the run-once guard so React StrictMode's dev double-mount re-runs
- // rehydration on the second mount; the first mount's in-flight list() is
- // discarded via `cancelled`. The reset is load-bearing, NOT removable: the
- // first StrictMode pass is cancelled before it settles `rehydrationSettled`,
- // so without the reset the second pass would skip and the gate would never
- // settle (the terminal would never seed). This depends on `bridge` being
- // referentially stable in production — it is `window.okDesktop`, captured
- // once in EditorPane — so the effect only re-runs under StrictMode, never on
- // a live bridge churn that could re-seed over an active session set.
+ // rehydration on the second mount (see the original terminal host rationale).
rehydratedRef.current = false;
};
}, [bridge]);
- // The editor's "Ask AI" selection affordance routes here. Live PTY → write
- // the composed prompt into the active shell (e.g. a running claude TUI); no
- // trailing newline so the user reviews/sends. No PTY → launch a fresh Claude
- // tab pre-loaded with the same prompt (mirrors the "Open in terminal" path
- // used by menu surfaces). The host is mounted whenever the desktop bridge
- // exists (even with zero sessions), so this subscription is always live.
+ // Web reload: no bridge to rehydrate, but a persisted active key may still be
+ // pending — bound its wait the same way so a stale key never blocks activation.
+ useEffect(() => {
+ if (canRehydrate) return;
+ if (pendingActiveKeyRef.current == null) return;
+ const timer = window.setTimeout(() => {
+ pendingActiveKeyRef.current = null;
+ }, 9_000);
+ return () => window.clearTimeout(timer);
+ }, [canRehydrate]);
+
+ // The editor's "Ask AI" selection affordance routes here. Live PTY → write the
+ // composed prompt into the active shell (e.g. a running claude TUI); no trailing
+ // newline so the user reviews/sends. No live PTY → launch a fresh Claude tab
+ // pre-loaded with the same prompt (mirrors the "Open in terminal" path).
useEffect(() => {
+ if (!terminalAvailable || bridge?.terminal == null) return;
+ const terminal = bridge.terminal;
return subscribeToActiveTerminalInput((text) => {
const activeId = activeSessionIdRef.current;
- const livePtyId = activeId === '' ? undefined : ptyIdBySessionRef.current.get(activeId);
+ const active = sessionsRef.current.find((s) => s.id === activeId);
+ const livePtyId =
+ active?.kind === 'terminal' ? ptyIdBySessionRef.current.get(active.id) : undefined;
if (livePtyId != null) {
- bridge.terminal.input(livePtyId, text);
+ terminal.input(livePtyId, text);
queueMicrotask(() => focusTerminalSession(activeId));
} else {
requestTerminalLaunch(text, 'claude');
}
});
- }, [bridge]);
+ }, [bridge, terminalAvailable]);
- // The Terminal application menu's per-session items act on the tab collection:
- // "New Terminal" opens a fresh tab, "Kill Terminal" closes the active one —
- // reusing the strip's own open/close paths so menu and strip stay identical.
- // ⌘W (`close-active-tab-or-window`) closes the active tab in the WINDOW
- // variant only — every BrowserWindow type must subscribe to it (menu.ts
- // contract), and in the terminal window this host is the only subscriber
- // (close-last then closes the window via the close-last report). In the
- // editor window the doc tree owns ⌘W (DocumentContext closes the active doc
- // tab); handling it here too would double-close.
+ // Terminal application-menu actions act on the tab collection.
useEffect(() => {
return subscribeLocalMenuAction((action) => {
- if (action === 'new-terminal') openSessionRef.current(null);
- else if (action === 'kill-terminal') closeActiveRef.current();
+ if (action === 'new-terminal') {
+ if (terminalAvailable) openSessionRef.current(null);
+ } else if (action === 'kill-terminal') closeActiveRef.current();
else if (action === 'close-active-tab-or-window' && variant === 'window')
closeActiveRef.current();
});
- }, [variant]);
+ }, [variant, terminalAvailable]);
- // ⌘1–⌘9 jump straight to the Nth tab. Capture phase so a focused xterm can't
- // swallow the chord; scoped to focus inside the stable host div (which follows
- // the terminal to whichever dock) so the digit chord stays free everywhere else.
- // The window variant skips the scope gate — the whole window is the terminal,
- // so there is nothing else the digit chord could mean there.
+ // ⌘1–⌘9 jump straight to the Nth tab (capture phase, focus-scoped in the dock).
useEffect(() => {
function onKeyDown(event: KeyboardEvent) {
if (!event.metaKey || event.ctrlKey || event.altKey || event.shiftKey) return;
@@ -602,20 +1001,13 @@ export function TerminalSessionsHost({
event.preventDefault();
event.stopPropagation();
setActiveSessionId(target.id);
- queueMicrotask(() => focusTerminalSession(target.id));
+ queueMicrotask(() => focusSession(target));
}
window.addEventListener('keydown', onKeyDown, { capture: true });
return () => window.removeEventListener('keydown', onKeyDown, { capture: true });
}, [hostEl, variant]);
- // ⌘⇧← / ⌘⇧→ move the ACTIVE tab one slot. Same capture-phase + focus-gate shape
- // as ⌘1–9 (so a focused xterm doesn't swallow it, and the chord stays free
- // outside the terminal in the dock). Meta+Shift only — a focused xterm encodes
- // ⌃/⌥-arrows into the PTY, but leaves meta-modified arrows to the app. Suppressed
- // while the rename input is focused (event target is an <input> — xterm's focus
- // sink is a <textarea>, so the chord still works while typing in the shell) and
- // while a pointer drag is lifted. Keyboard reorders announce via the sr-only
- // region; pointer drags keep dnd-kit's own announcements.
+ // ⌘⇧← / ⌘⇧→ move the ACTIVE tab one slot (capture phase + focus-gate).
useEffect(() => {
function onKeyDown(event: KeyboardEvent) {
if (!event.metaKey || !event.shiftKey || event.ctrlKey || event.altKey) return;
@@ -626,12 +1018,12 @@ export function TerminalSessionsHost({
const target = event.target as HTMLElement | null;
if (target?.tagName === 'INPUT' || target?.isContentEditable) return;
const moved = moveActiveSessionRef.current(direction);
- if (moved == null) return; // no-op at the edges
+ if (moved == null) return;
event.preventDefault();
event.stopPropagation();
- queueMicrotask(() => focusTerminalSession(activeSessionIdRef.current));
- // Announce via the sr-only region (stable refs only; trailing debounce so
- // rapid repeats don't flood — React batching would swallow direct updates).
+ const activeId = activeSessionIdRef.current;
+ const active = sessionsRef.current.find((s) => s.id === activeId);
+ if (active != null) queueMicrotask(() => focusSession(active));
const message = t`Moved ${moved.label} to position ${moved.position} of ${moved.total}`;
if (announceTimerRef.current != null) window.clearTimeout(announceTimerRef.current);
announceTimerRef.current = window.setTimeout(() => {
@@ -642,9 +1034,6 @@ export function TerminalSessionsHost({
window.addEventListener('keydown', onKeyDown, { capture: true });
return () => {
window.removeEventListener('keydown', onKeyDown, { capture: true });
- // Cancel any in-flight announce debounce: this effect re-runs on locale
- // change and tears down on unmount, and a pending 60 ms timer would
- // otherwise fire a stale-closure message against the old `t`/a dead node.
if (announceTimerRef.current != null) {
window.clearTimeout(announceTimerRef.current);
announceTimerRef.current = null;
@@ -652,16 +1041,15 @@ export function TerminalSessionsHost({
};
}, [hostEl, variant, t]);
- // Reflect PTY liveness to main so the Terminal menu's "Kill Terminal" item
- // enables only while at least one session is live. A collapsed-but-alive
- // terminal still counts: the session list tracks the latch, not visibility.
+ // Reflect terminal liveness to main so the Terminal menu's "Kill Terminal"
+ // enables only while at least one TERMINAL session is live.
useEffect(() => {
- const terminalLive = sessions.length > 0;
+ const terminalLive = sessions.some((s) => s.kind === 'terminal');
// Mirror into the renderer store so the Cmd+K palette can gate "Kill
// terminal" on a live session (the bridge push below is main-only).
setViewMenuState({ terminalLive });
- bridge.editor.notifyViewMenuStateChanged({ terminalLive });
- }, [bridge, sessions.length]);
+ bridge?.editor.notifyViewMenuStateChanged({ terminalLive });
+ }, [bridge, sessions]);
useEffect(() => {
onHasSessionsChange?.(sessions.length > 0);
@@ -670,16 +1058,18 @@ export function TerminalSessionsHost({
// Report whether the active tab is a CLI session (see the prop doc). Derived in
// render so the effect fires only on actual transitions, not on every session-
// list mutation. EditorPane's ⌘J read decides inject-vs-launch off this.
- const activeSessionIsCli = sessions.find((s) => s.id === activeSessionId)?.launch?.cli != null;
+ const activeSession = sessions.find((s) => s.id === activeSessionId);
+ const activeSessionIsCli =
+ activeSession?.kind === 'terminal' && activeSession.launch?.cli != null;
useEffect(() => {
onActiveSessionCliChange?.(activeSessionIsCli);
}, [onActiveSessionCliChange, activeSessionIsCli]);
- // Return focus out of the hidden terminal so a keyboard user is never stranded.
- // Only acts when focus is actually inside the terminal.
+ // Return focus out of the hidden dock so a keyboard user is never stranded.
+ // Only acts when focus is actually inside the dock.
//
// Gate on `visible`, not just `isShowing`: a dock move (bottom ↔ right) keeps the
- // terminal `visible` but transiently drops `isShowing` to false for one commit
+ // dock `visible` but transiently drops `isShowing` to false for one commit
// while the destination container's callback ref attaches (`activeTerminalContainer`
// is null until then). Without the `visible` guard, clicking the dock-toggle —
// which lives inside this portaled host, so focus is inside it — would satisfy the
@@ -691,124 +1081,270 @@ export function TerminalSessionsHost({
onRequestEditorFocus();
}, [isShowing, visible, hostEl, onRequestEditorFocus]);
- // Focus the active session's terminal when the terminal is revealed so the user
- // can type immediately. Keyed on the show transition only (active id read from a
- // ref) so switching tabs does not re-fire this.
+ // Focus the active session when the dock is revealed (kind-aware).
useEffect(() => {
if (!isShowing) return;
- focusTerminalSession(activeSessionIdRef.current);
+ const active = sessionsRef.current.find((s) => s.id === activeSessionIdRef.current);
+ if (active != null) focusSession(active);
}, [isShowing]);
- const tabDescriptors = sessions.map((session) => ({
+ const tabDescriptors: TerminalTabDescriptor[] = sessions.map((session) => ({
id: session.id,
- // A user-set custom name pins over the program's OSC title, which pins over
- // the sticky positional default. The default uses the session's immutable
- // ordinal (not its render index) so a reorder never renumbers untitled tabs.
- label: session.customLabel ?? session.title ?? t`Terminal ${session.ordinal}`,
+ label: sessionLabel(session),
+ icon:
+ session.kind === 'terminal'
+ ? terminalTabIcon()
+ : threadTabIcon(threadInfoById.get(session.threadId)),
}));
- // Panels render in a STABLE order (by immutable ordinal), deliberately
- // decoupled from the tab order. A reorder must not move a panel's DOM node:
- // moving an xterm container fires its ResizeObserver refit (SIGWINCH), which
- // makes the running program (e.g. a Claude TUI) repaint and lose its screen —
- // reordering tabs would otherwise reset the live shell. The tabs reorder; the
- // panels stay put. Radix associates each panel with its trigger by `value`,
- // not DOM order, so the active panel still shows regardless of position.
+ // Panels render in STABLE order (by immutable ordinal), decoupled from tab order:
+ // a reorder must not move a panel's DOM node (moving an xterm container fires
+ // SIGWINCH; a thread panel would lose its transcript scroll).
const panelSessions = [...sessions].sort((a, b) => a.ordinal - b.ordinal);
- const sessionViews =
- sessions.length > 0 ? (
- <TerminalTabStrip
- sessions={tabDescriptors}
- activeSessionId={activeSessionId}
- onSelect={setActiveSessionId}
- // Focus the terminal after the activation commits (so the now-shown
- // container is focusable) when a tab is selected by pointer or Enter.
- onTabActivate={(id) => queueMicrotask(() => focusTerminalSession(id))}
- newChatSelected={newChatSelected}
- onNewChatLaunch={launchSelectedNewTab}
- onNewChatPickCli={pickNewChatCli}
- onNewChatPickTerminal={pickNewChatTerminal}
- newChatVisibleClis={newChatVisibleClis}
- onClose={closeSession}
- onRename={setSessionCustomLabel}
- // Pointer-drag reorder: the strip computes the new visual order and the
- // host applies it (keyboard reorder shares reorderSessions). onDragActive
- // gates the ⌘⇧←/→ chord off while a drag is lifted.
- onReorder={reorderSessions}
- onDragActiveChange={(active) => {
- dragActiveRef.current = active;
- }}
- dockPosition={dockPosition}
- onToggleDock={onToggleDock}
- // Collapse hides the terminal but keeps every session alive (hide is not
- // kill), exactly like the ⌘J toggle — the next reveal restores the tabs.
- // The window has no collapse (closing the window is the OS affordance).
- onCollapse={variant === 'window' ? undefined : () => onVisibleChange(false)}
- // Window mode: the tab row doubles as the frameless window's title bar.
- draggable={variant === 'window'}
- className="h-full"
- >
- {panelSessions.map((session) => (
- // forceMount keeps every session mounted (active shown, inactive
- // CSS-hidden) so each retains its xterm scrollback and keeps consuming
- // output — switching tabs is show/hide, never unmount. Iterating
- // `panelSessions` (stable ordinal order), NOT `sessions`, so a tab
- // reorder never moves a panel's DOM node (see panelSessions above).
+ const newButton = (
+ <TerminalNewChatButton
+ selected={newSessionChoice}
+ onLaunchSelected={launchSelectedNewTab}
+ showAgents={hostThreads}
+ registeredAgents={enabledRegisteredAgents}
+ onPickAgent={pickNewChatAgent}
+ onOpenSettings={openAgentSettings}
+ liveThreadCount={liveThreadCount}
+ showClis={terminalAvailable}
+ onPickCli={pickNewChatCli}
+ onPickTerminal={pickNewChatTerminal}
+ // The CLI rows are the ENABLED CLIs (the same set the selection resolver
+ // reads); the selected CLI is always enabled, so no keep-guard is needed.
+ visibleClis={enabledTerminalClis(enabledOverrides, installedClis ?? {})}
+ />
+ );
+
+ // The conversation-history menu rides in the strip's trailing controls, just
+ // left of the dock-toggle/collapse buttons — shown only with archived history to
+ // return to.
+ const trailingControls =
+ hostThreads && archivedThreads.length > 0 ? (
+ <ThreadHistoryMenu archived={archivedThreads} onOpenThread={openArchivedThread} />
+ ) : null;
+
+ // Render the strip (with the + split button + a starting/empty body) whenever
+ // there are sessions, or the dock is visible in the dock variant — so a visible
+ // dock always shows immediate feedback while a session spins up, and an entry
+ // point when idle-empty. The standalone terminal window seeds on mount, so it
+ // shows the strip only once it has a tab (no empty flash).
+ const showStrip = sessions.length > 0 || (visible && hostThreads);
+
+ const sessionViews = showStrip ? (
+ <TerminalTabStrip
+ sessions={tabDescriptors}
+ activeSessionId={activeSessionId}
+ onSelect={(id) => {
+ // A deliberate tab selection is the user taking over the active slot.
+ pendingActiveKeyRef.current = null;
+ setActiveSessionId(id);
+ }}
+ onTabActivate={(id) => {
+ const session = sessionsRef.current.find((s) => s.id === id);
+ if (session != null) queueMicrotask(() => focusSession(session));
+ }}
+ newButton={newButton}
+ trailingControls={trailingControls}
+ onClose={closeSession}
+ onRename={renameSession}
+ onReorder={reorderSessions}
+ onDragActiveChange={(active) => {
+ dragActiveRef.current = active;
+ }}
+ dockPosition={dockPosition}
+ onToggleDock={onToggleDock}
+ onCollapse={variant === 'window' ? undefined : () => onVisibleChange(false)}
+ draggable={variant === 'window'}
+ className="h-full"
+ >
+ {sessions.length === 0 ? (
+ // A terminal surface auto-seeds on reveal, so an empty dock is only ever a
+ // sub-frame transient there — render nothing (the + button suffices) so no
+ // "no sessions" text flashes. On a thread-only surface an empty dock is a
+ // real resting state: offer the reopen-a-past-conversation chooser when
+ // there is history, else the entry-point guidance.
+ terminalAvailable ? null : hostThreads && archivedThreads.length > 0 ? (
+ <ArchivedThreadChooser archived={archivedThreads} onOpen={openArchivedThread} />
+ ) : (
+ <EmptySessionsState />
+ )
+ ) : (
+ panelSessions.map((session) => (
<TabsContent
key={session.id}
value={session.id}
forceMount
- data-terminal-session={session.id}
- // Window mode insets the terminal content by the traffic-light gutter
- // (22px, = trafficLightPosition.x) so its left edge lines up with the
- // bubbles and it isn't glued to the window's edges; the padding shows
- // the window background, framing the xterm. The dock sits flush.
+ data-session-id={session.id}
+ {...(session.kind === 'terminal' ? { 'data-terminal-session': session.id } : {})}
className={cn(
'm-0 flex min-h-0 flex-1 flex-col overflow-hidden data-[state=inactive]:hidden',
variant === 'window' && 'px-[22px] pb-[22px]',
)}
>
- <TerminalGate
- bridge={bridge}
- launch={session.launch}
- // On a renderer reload the session adopts its surviving PTY (live
- // shell + replay) instead of spawning a fresh one; null for new tabs.
- adoptPtyId={session.adoptPtyId}
- // Track this session's live PTY id so the selection-bubble "Ask AI"
- // input can reuse the open terminal (write into the live shell)
- // rather than fall back to the composer. Adopted sessions report
- // their id too, so reuse works for reload survivors.
- onPtyId={(ptyId) => setSessionPtyId(session.id, ptyId)}
- // OSC 0/2 title from the running program → this session's tab label.
- onTitleChange={(title) => setSessionTitle(session.id, title)}
- // The session's "Close terminal" affordance (shown on a refusal/exit
- // notice) closes that tab — hiding the terminal only when it is the
- // last one. The keyboard exit stays ⌘J.
- onClose={() => closeSession(session.id)}
- />
+ {session.kind === 'terminal' ? (
+ bridge != null && terminalAvailable ? (
+ <TerminalGate
+ bridge={bridge}
+ launch={session.launch}
+ adoptPtyId={session.adoptPtyId}
+ onPtyId={(ptyId) => setSessionPtyId(session.id, ptyId)}
+ onTitleChange={(title) => setSessionTitle(session.id, title)}
+ onClose={() => closeSession(session.id)}
+ />
+ ) : null
+ ) : (
+ <ThreadPanel
+ threadId={session.threadId}
+ info={threadInfoById.get(session.threadId)}
+ // The reconnecting banner rides above the ACTIVE thread's
+ // transcript only — never while a terminal (or another thread) is
+ // focused, and never when the channel is healthy.
+ showConnectionBanner={threadConnectionDown && session.id === activeSessionId}
+ />
+ )}
</TabsContent>
- ))}
- </TerminalTabStrip>
- ) : null;
+ ))
+ )}
+ </TerminalTabStrip>
+ ) : null;
- // Render the session subtree into the stable host div (which the relocate effect
- // appends to the active container). A constant portal target = no remount on a
- // dock move. The sr-only announcer rides alongside so keyboard reorders are
- // announced (its textContent is set imperatively; see announceReorder).
- return hostEl != null
- ? createPortal(
- <>
- {sessionViews}
- <span
- ref={announcerRef}
- aria-live="polite"
- aria-atomic="true"
- className="sr-only"
- data-testid="terminal-reorder-announcer"
- />
- </>,
- hostEl,
- )
- : null;
+ return (
+ <>
+ {hostEl != null
+ ? createPortal(
+ <>
+ {sessionViews}
+ <span
+ ref={announcerRef}
+ aria-live="polite"
+ aria-atomic="true"
+ className="sr-only"
+ data-testid="terminal-reorder-announcer"
+ />
+ </>,
+ hostEl,
+ )
+ : null}
+ </>
+ );
+}
+
+/** One thread session's body — the lazy {@link ThreadView}, kept mounted so its
+ * transcript + scroll survive tab switches, with an optional reconnecting banner
+ * above it. Renders nothing until the store first reports its info (a one-render
+ * race on create). */
+function ThreadPanel({
+ threadId,
+ info,
+ showConnectionBanner,
+}: {
+ threadId: string;
+ info: ThreadInfo | undefined;
+ showConnectionBanner: boolean;
+}) {
+ if (info === undefined) return null;
+ return (
+ <>
+ {showConnectionBanner ? <ThreadConnectionBanner /> : null}
+ <Suspense
+ fallback={
+ <div
+ role="status"
+ aria-busy="true"
+ className="flex min-h-0 flex-1 items-center justify-center text-muted-foreground"
+ >
+ <Loader2 className="size-5 animate-spin" aria-hidden="true" />
+ </div>
+ }
+ >
+ <ThreadView key={threadId} info={info} />
+ </Suspense>
+ </>
+ );
+}
+
+/** Thin banner above an active thread's transcript while the agent-thread WS is
+ * reconnecting — the channel recovers + replays automatically (the client owns
+ * that), so this is feedback only. */
+function ThreadConnectionBanner() {
+ const { t } = useLingui();
+ return (
+ <div
+ className="shrink-0 border-amber-500/30 border-b bg-amber-500/5 px-3 py-1 text-amber-700 text-xs dark:text-amber-400"
+ data-testid="agent-thread-reconnecting"
+ >
+ {t`Reconnecting to the agent service…`}
+ </div>
+ );
+}
+
+/** Shown when the dock is open with no sessions — while a launched session spins
+ * up, or when the dock is idle-empty. Phrased as an invitation (not a status) so
+ * it reads fine in both cases; the + split button in the strip is the way in. */
+function EmptySessionsState() {
+ const { t } = useLingui();
+ return (
+ <div
+ className="flex min-h-0 flex-1 items-center justify-center px-6 text-center text-muted-foreground text-sm"
+ data-testid="sessions-dock-empty"
+ >
+ {t`Start a session with the + button, or launch an agent from a page.`}
+ </div>
+ );
+}
+
+/**
+ * The reload-stable key a session persists under (a terminal's ptyId, a thread's
+ * threadId), or null when a fresh terminal has no live PTY yet. Module-pure (takes
+ * the ptyId map explicitly) so effects that consult it keep clean, stable deps.
+ */
+function computePersistKey(
+ session: SessionDescriptor,
+ ptyMap: ReadonlyMap<string, string>,
+): string | null {
+ if (session.kind === 'thread') return session.threadId;
+ return session.adoptPtyId ?? ptyMap.get(session.id) ?? null;
+}
+
+/**
+ * Place freshly-added sessions into `kept`: a session whose reload-stable key is in
+ * the persisted `order` inserts at its ranked slot (restoring the cross-kind reload
+ * arrangement as threads trickle in async); one that is not (live-created after
+ * mount) appends. Existing sessions are never re-sorted, so a user reorder is never
+ * disturbed.
+ */
+function placeSessionAdditions<T extends { readonly id: string }>(
+ kept: readonly T[],
+ additions: readonly T[],
+ order: readonly string[],
+ keyOf: (session: T) => string | null,
+): T[] {
+ const rankOf = (session: T): number => {
+ const key = keyOf(session);
+ if (key == null) return Number.POSITIVE_INFINITY;
+ const i = order.indexOf(key);
+ return i === -1 ? Number.POSITIVE_INFINITY : i;
+ };
+ const result = [...kept];
+ for (const addition of additions) {
+ const addRank = rankOf(addition);
+ if (addRank === Number.POSITIVE_INFINITY) {
+ result.push(addition);
+ continue;
+ }
+ let insertAt = result.length;
+ for (let i = 0; i < result.length; i++) {
+ if (rankOf(result[i]) > addRank) {
+ insertAt = i;
+ break;
+ }
+ }
+ result.splice(insertAt, 0, addition);
+ }
+ return result;
}
diff --git a/packages/app/src/components/TerminalTabStrip.dom.test.tsx b/packages/app/src/components/TerminalTabStrip.dom.test.tsx
index 681d981e7..0a98690bf 100644
--- a/packages/app/src/components/TerminalTabStrip.dom.test.tsx
+++ b/packages/app/src/components/TerminalTabStrip.dom.test.tsx
@@ -1,6 +1,6 @@
-import { afterEach, describe, expect, mock, test } from 'bun:test';
import { act, cleanup, render, screen, within } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
+import { afterEach, describe, expect, test, vi } from 'vitest';
import { TooltipProvider } from '@/components/ui/tooltip';
import { type TerminalTabDescriptor, TerminalTabStrip } from './TerminalTabStrip';
@@ -10,39 +10,52 @@ const SESSIONS: readonly TerminalTabDescriptor[] = [
{ id: 's3', label: 'Terminal 3' },
];
+// A stub for the host-provided New button — the strip renders whatever node the
+// host passes as `newButton` (the real merged split-button has its own test).
+function stubNewButton(onClick: () => void) {
+ return (
+ <button type="button" aria-label="New session" onClick={onClick}>
+ +
+ </button>
+ );
+}
+
function renderStrip(props?: {
sessions?: readonly TerminalTabDescriptor[];
activeSessionId?: string;
dockPosition?: 'bottom' | 'right';
- newChatSelected?: 'claude' | 'codex' | 'opencode' | 'cursor' | 'terminal';
draggable?: boolean;
/** Omit the rename handler to assert the affordance is inert without it. */
renameDisabled?: boolean;
+ /** Render a stub trailing control (stands in for the history menu). */
+ withTrailing?: boolean;
}) {
- const onSelect = mock((_id: string) => {});
- const onTabActivate = mock((_id: string) => {});
- const onNewChatLaunch = mock(() => {});
- const onNewChatPickCli = mock((_cli: string) => {});
- const onNewChatPickTerminal = mock(() => {});
- const onClose = mock((_id: string) => {});
- const onRename = mock((_id: string, _label: string) => {});
- const onToggleDock = mock(() => {});
- const onCollapse = mock(() => {});
+ const onSelect = vi.fn((_id: string) => {});
+ const onTabActivate = vi.fn((_id: string) => {});
+ const onNewButtonClick = vi.fn(() => {});
+ const onClose = vi.fn((_id: string) => {});
+ const onRename = vi.fn((_id: string, _label: string) => {});
+ const onToggleDock = vi.fn(() => {});
+ const onCollapse = vi.fn(() => {});
const view = render(
// The app mounts a root TooltipProvider (main.tsx); the strip's control
// tooltips need that context, so the isolated render supplies its own.
// `draggable` mirrors the standalone terminal window's prop shape (same
- // new-chat model, no dock/collapse controls); the default mirrors the dock.
+ // chrome, no dock/collapse controls); the default mirrors the dock.
<TooltipProvider>
<TerminalTabStrip
sessions={props?.sessions ?? SESSIONS}
activeSessionId={props?.activeSessionId ?? 's1'}
onSelect={onSelect}
onTabActivate={onTabActivate}
- newChatSelected={props?.newChatSelected ?? 'claude'}
- onNewChatLaunch={onNewChatLaunch}
- onNewChatPickCli={onNewChatPickCli}
- onNewChatPickTerminal={onNewChatPickTerminal}
+ newButton={stubNewButton(onNewButtonClick)}
+ trailingControls={
+ props?.withTrailing ? (
+ <button type="button" aria-label="Restore sessions">
+ H
+ </button>
+ ) : undefined
+ }
onClose={onClose}
onRename={props?.renameDisabled ? undefined : onRename}
dockPosition={props?.draggable ? undefined : (props?.dockPosition ?? 'bottom')}
@@ -55,9 +68,7 @@ function renderStrip(props?: {
return {
onSelect,
onTabActivate,
- onNewChatLaunch,
- onNewChatPickCli,
- onNewChatPickTerminal,
+ onNewButtonClick,
onClose,
onRename,
onToggleDock,
@@ -71,7 +82,7 @@ describe('TerminalTabStrip', () => {
test('renders one tab per session inside a labeled tablist', () => {
renderStrip();
- const tablist = screen.getByRole('tablist', { name: 'Terminal sessions' });
+ const tablist = screen.getByRole('tablist', { name: 'Sessions' });
const tabs = within(tablist).getAllByRole('tab');
expect(tabs.map((tab) => tab.textContent)).toEqual(['Terminal 1', 'Terminal 2', 'Terminal 3']);
});
@@ -103,6 +114,25 @@ describe('TerminalTabStrip', () => {
);
});
+ test('scrolls the selected tab into view without changing tab order', () => {
+ const scrolled: Element[] = [];
+ const original = HTMLElement.prototype.scrollIntoView;
+ HTMLElement.prototype.scrollIntoView = function scrollIntoView() {
+ scrolled.push(this);
+ };
+ try {
+ renderStrip({ activeSessionId: 's3' });
+ expect(scrolled.some((element) => element.getAttribute('data-tab-id') === 's3')).toBe(true);
+ expect(
+ within(screen.getByRole('tablist', { name: 'Sessions' }))
+ .getAllByRole('tab')
+ .map((tab) => tab.textContent),
+ ).toEqual(['Terminal 1', 'Terminal 2', 'Terminal 3']);
+ } finally {
+ HTMLElement.prototype.scrollIntoView = original;
+ }
+ });
+
test('is fully controlled: clicking a tab reports onSelect without changing its own selection', async () => {
const user = userEvent.setup();
const { onSelect } = renderStrip({ activeSessionId: 's1' });
@@ -151,92 +181,86 @@ describe('TerminalTabStrip', () => {
expect(onSelect).toHaveBeenCalledWith('s2');
});
- test('the New-chat primary launches the current selection and never onSelect', async () => {
+ test('renders the host-provided New button and forwards its clicks unchanged', async () => {
const user = userEvent.setup();
- const { onNewChatLaunch, onNewChatPickTerminal, onSelect } = renderStrip();
+ const { onNewButtonClick, onSelect } = renderStrip();
- await user.click(screen.getByRole('button', { name: 'New Claude chat' }));
+ await user.click(screen.getByRole('button', { name: 'New session' }));
- expect(onNewChatLaunch).toHaveBeenCalledTimes(1);
- expect(onNewChatPickTerminal).not.toHaveBeenCalled();
+ expect(onNewButtonClick).toHaveBeenCalledTimes(1);
+ // The strip is chrome — it never intercepts the New button's behavior.
expect(onSelect).not.toHaveBeenCalled();
});
- test('the primary reflects a Terminal selection (opens a bare terminal)', async () => {
- const user = userEvent.setup();
- const { onNewChatLaunch } = renderStrip({ newChatSelected: 'terminal' });
-
- await user.click(screen.getByRole('button', { name: 'New terminal' }));
-
- expect(onNewChatLaunch).toHaveBeenCalledTimes(1);
- });
-
- test('the New-chat dropdown picks a bare terminal via its "Terminal" option', async () => {
- const user = userEvent.setup();
- const { onNewChatPickTerminal, onNewChatLaunch } = renderStrip();
-
- await user.click(screen.getByRole('button', { name: 'Choose CLI for new chat' }));
- await user.click(await screen.findByRole('menuitem', { name: 'Terminal' }));
-
- expect(onNewChatPickTerminal).toHaveBeenCalledTimes(1);
- expect(onNewChatLaunch).not.toHaveBeenCalled();
- });
-
- test('New chat hugs the last tab, preceding the trailing dock-toggle / collapse controls', () => {
+ test('the New button hugs the last tab, preceding the trailing dock-toggle / collapse controls', () => {
renderStrip();
- const newChat = screen.getByRole('button', { name: 'New Claude chat' });
- const dockToggle = screen.getByRole('button', { name: 'Dock terminal to the right' });
- const collapse = screen.getByRole('button', { name: 'Collapse terminal' });
- // New chat sits immediately right of the tablist; the spacer pushes the
+ const newButton = screen.getByRole('button', { name: 'New session' });
+ const dockToggle = screen.getByRole('button', { name: 'Dock sessions on the right' });
+ const collapse = screen.getByRole('button', { name: 'Collapse session dock' });
+ // The New button sits immediately right of the tablist; the spacer pushes the
// trailing group (dock-toggle … collapse) to the far right.
expect(
- newChat.compareDocumentPosition(dockToggle) & Node.DOCUMENT_POSITION_FOLLOWING,
+ newButton.compareDocumentPosition(dockToggle) & Node.DOCUMENT_POSITION_FOLLOWING,
).toBeTruthy();
expect(
dockToggle.compareDocumentPosition(collapse) & Node.DOCUMENT_POSITION_FOLLOWING,
).toBeTruthy();
});
+ test('trailing controls render at the far right, immediately left of the dock-toggle', () => {
+ renderStrip({ withTrailing: true });
+ const trailing = screen.getByRole('button', { name: 'Restore sessions' });
+ const newButton = screen.getByRole('button', { name: 'New session' });
+ const dockToggle = screen.getByRole('button', { name: 'Dock sessions on the right' });
+ // The New button hugs the tabs on the left; the trailing control sits in the
+ // far-right cluster, before the dock-toggle.
+ expect(
+ newButton.compareDocumentPosition(trailing) & Node.DOCUMENT_POSITION_FOLLOWING,
+ ).toBeTruthy();
+ expect(
+ trailing.compareDocumentPosition(dockToggle) & Node.DOCUMENT_POSITION_FOLLOWING,
+ ).toBeTruthy();
+ });
+
test('a tab close control reports onClose with that session id only', async () => {
const user = userEvent.setup();
- const { onClose, onSelect, onNewChatLaunch } = renderStrip({ activeSessionId: 's1' });
+ const { onClose, onSelect, onNewButtonClick } = renderStrip({ activeSessionId: 's1' });
await user.click(screen.getByRole('button', { name: 'Close Terminal 2' }));
expect(onClose).toHaveBeenCalledTimes(1);
expect(onClose).toHaveBeenCalledWith('s2');
expect(onSelect).not.toHaveBeenCalled();
- expect(onNewChatLaunch).not.toHaveBeenCalled();
+ expect(onNewButtonClick).not.toHaveBeenCalled();
});
test('the dock-toggle reports onToggleDock and labels the resulting position', async () => {
const user = userEvent.setup();
// Bottom-docked → the toggle moves it to the right.
const bottom = renderStrip({ dockPosition: 'bottom' });
- const toRight = screen.getByRole('button', { name: 'Dock terminal to the right' });
+ const toRight = screen.getByRole('button', { name: 'Dock sessions on the right' });
await user.click(toRight);
expect(bottom.onToggleDock).toHaveBeenCalledTimes(1);
- expect(screen.queryByRole('button', { name: 'Dock terminal to the bottom' })).toBeNull();
+ expect(screen.queryByRole('button', { name: 'Dock sessions at the bottom' })).toBeNull();
cleanup();
// Right-docked → the toggle moves it to the bottom (label flips).
const right = renderStrip({ dockPosition: 'right' });
- const toBottom = screen.getByRole('button', { name: 'Dock terminal to the bottom' });
+ const toBottom = screen.getByRole('button', { name: 'Dock sessions at the bottom' });
await user.click(toBottom);
expect(right.onToggleDock).toHaveBeenCalledTimes(1);
- expect(screen.queryByRole('button', { name: 'Dock terminal to the right' })).toBeNull();
+ expect(screen.queryByRole('button', { name: 'Dock sessions on the right' })).toBeNull();
});
- test('the collapse control reports onCollapse and never onClose / new-chat', async () => {
+ test('the collapse control reports onCollapse and never onClose / new-button', async () => {
const user = userEvent.setup();
- const { onCollapse, onClose, onNewChatLaunch, onNewChatPickTerminal } = renderStrip();
+ const { onCollapse, onClose, onNewButtonClick } = renderStrip();
- await user.click(screen.getByRole('button', { name: 'Collapse terminal' }));
+ await user.click(screen.getByRole('button', { name: 'Collapse session dock' }));
expect(onCollapse).toHaveBeenCalledTimes(1);
expect(onClose).not.toHaveBeenCalled();
- expect(onNewChatLaunch).not.toHaveBeenCalled();
- expect(onNewChatPickTerminal).not.toHaveBeenCalled();
+ expect(onNewButtonClick).not.toHaveBeenCalled();
});
test('no drag-to-dock grip is rendered (dragging was removed)', () => {
@@ -244,12 +268,10 @@ describe('TerminalTabStrip', () => {
expect(screen.queryByRole('button', { name: 'Drag to dock the terminal' })).toBeNull();
});
- test('every icon-only control exposes an accessible name', () => {
+ test('every strip-owned icon-only control exposes an accessible name', () => {
renderStrip();
- expect(screen.getByRole('button', { name: 'New Claude chat' })).toBeDefined();
- expect(screen.getByRole('button', { name: 'Choose CLI for new chat' })).toBeDefined();
- expect(screen.getByRole('button', { name: 'Dock terminal to the right' })).toBeDefined();
- expect(screen.getByRole('button', { name: 'Collapse terminal' })).toBeDefined();
+ expect(screen.getByRole('button', { name: 'Dock sessions on the right' })).toBeDefined();
+ expect(screen.getByRole('button', { name: 'Collapse session dock' })).toBeDefined();
for (const label of ['Terminal 1', 'Terminal 2', 'Terminal 3']) {
expect(screen.getByRole('button', { name: `Close ${label}` })).toBeDefined();
}
@@ -262,10 +284,10 @@ describe('TerminalTabStrip', () => {
renderStrip({ draggable: true });
expect(document.querySelector('[data-electron-drag]')).not.toBeNull();
// The window has no dock-toggle/collapse — window management is the OS
- // title bar's job — but keeps the full new-chat affordance (feature parity).
- expect(screen.queryByRole('button', { name: /Dock terminal/ })).toBeNull();
- expect(screen.queryByRole('button', { name: 'Collapse terminal' })).toBeNull();
- expect(screen.getByRole('button', { name: 'New Claude chat' })).toBeDefined();
+ // title bar's job — but keeps the New button (feature parity).
+ expect(screen.queryByRole('button', { name: /Dock sessions/ })).toBeNull();
+ expect(screen.queryByRole('button', { name: 'Collapse session dock' })).toBeNull();
+ expect(screen.getByRole('button', { name: 'New session' })).toBeDefined();
cleanup();
renderStrip();
expect(document.querySelector('[data-electron-drag]')).toBeNull();
@@ -273,12 +295,12 @@ describe('TerminalTabStrip', () => {
test('window mode keeps the tab controls interactive (no-drag opt-out works)', async () => {
const user = userEvent.setup();
- const { onNewChatLaunch, onClose } = renderStrip({ activeSessionId: 's1', draggable: true });
+ const { onNewButtonClick, onClose } = renderStrip({ activeSessionId: 's1', draggable: true });
- await user.click(screen.getByRole('button', { name: 'New Claude chat' }));
+ await user.click(screen.getByRole('button', { name: 'New session' }));
await user.click(screen.getByRole('button', { name: 'Close Terminal 1' }));
- expect(onNewChatLaunch).toHaveBeenCalledTimes(1);
+ expect(onNewButtonClick).toHaveBeenCalledTimes(1);
expect(onClose).toHaveBeenCalledWith('s1');
});
@@ -426,10 +448,7 @@ describe('TerminalTabStrip', () => {
]}
activeSessionId="s1"
onSelect={() => {}}
- newChatSelected="claude"
- onNewChatLaunch={() => {}}
- onNewChatPickCli={() => {}}
- onNewChatPickTerminal={() => {}}
+ newButton={stubNewButton(() => {})}
onClose={() => {}}
onRename={() => {}}
dockPosition="bottom"
@@ -463,7 +482,7 @@ describe('TerminalTabStrip', () => {
expect(document.querySelectorAll('[data-terminal-tab-sortable]')).toHaveLength(3);
// The dnd-kit wrapper is not focusable and adds no role — the Radix tablist
// still sees exactly three tabs.
- const tablist = screen.getByRole('tablist', { name: 'Terminal sessions' });
+ const tablist = screen.getByRole('tablist', { name: 'Sessions' });
expect(within(tablist).getAllByRole('tab')).toHaveLength(3);
expect(within(tablist).queryAllByRole('button', { name: /^Terminal/ })).toHaveLength(0);
});
diff --git a/packages/app/src/components/TerminalTabStrip.tsx b/packages/app/src/components/TerminalTabStrip.tsx
index de700524b..11320312d 100644
--- a/packages/app/src/components/TerminalTabStrip.tsx
+++ b/packages/app/src/components/TerminalTabStrip.tsx
@@ -5,7 +5,6 @@ import {
SortableContext,
useSortable,
} from '@dnd-kit/sortable';
-import type { TerminalCli } from '@inkeep/open-knowledge-core';
import { Trans, useLingui } from '@lingui/react/macro';
import {
ChevronDownIcon,
@@ -29,7 +28,7 @@ import {
type TabReorderBounds,
tabRunCollisionDetection,
} from './editor-tabs-chrome';
-import { TerminalNewChatButton, type TerminalNewTabChoice } from './TerminalNewChatButton';
+import { scrollTabStripOnWheel } from './tab-strip-wheel';
/** Attribute marking a terminal tab's sortable node — the surface-neutral chrome
* module measures the reorder bounds against this (editor tabs use their own). */
@@ -84,14 +83,19 @@ function SortableTerminalTab({
);
}
-/** One terminal session as the tab strip sees it: a stable id and a display label. */
+/** One session as the tab strip sees it: a stable id, a display label, and an
+ * optional leading icon. The strip is kind-agnostic — the host bakes the kind
+ * glyph (a shell icon for a terminal, an agent avatar + status dot for a thread)
+ * into {@link icon} so the strip never learns about session kinds. */
export interface TerminalTabDescriptor {
readonly id: string;
readonly label: string;
+ /** Leading icon rendered before the label (host-provided, kind-specific). */
+ readonly icon?: ReactNode;
}
interface TerminalTabStripProps {
- /** Open sessions, in tab order. */
+ /** Sessions in tab order. */
readonly sessions: readonly TerminalTabDescriptor[];
/** Currently active session id (controlled — the strip keeps no selection state). */
readonly activeSessionId: string;
@@ -104,20 +108,13 @@ interface TerminalTabStripProps {
* caret stays in the tablist while arrowing.
*/
readonly onTabActivate?: (id: string) => void;
- /** The New-chat split button's current pick — a CLI (resolved by the host from
- * the sticky pick + installed set) or `'terminal'` (a bare shell). Drives the
- * primary icon/label + the dropdown checkmark. */
- readonly newChatSelected: TerminalNewTabChoice;
- /** Primary New-chat click — open a new tab in the current pick, no persist. */
- readonly onNewChatLaunch: () => void;
- /** Dropdown CLI pick — persist it as the new default AND open a tab in it. */
- readonly onNewChatPickCli: (cli: TerminalCli) => void;
- /** Dropdown "Terminal" — persist a bare shell as the default AND open one. */
- readonly onNewChatPickTerminal: () => void;
- /** CLIs to list in the New-chat dropdown — Claude plus PATH-detected CLIs
- * (resolved by the host), so an uninstalled CLI doesn't appear unless
- * detected. Optional: the button falls back to the full list. */
- readonly newChatVisibleClis?: readonly TerminalCli[];
+ /** The "new session" split button, built by the host (it owns the pick model +
+ * the agent/CLI menus). Rendered hugging the last tab, outside the scroll
+ * container so the fade mask never clips it. */
+ readonly newButton?: ReactNode;
+ /** Host-provided trailing control(s), rendered at the far right immediately
+ * before the dock-toggle/collapse buttons (e.g. the conversation-history menu). */
+ readonly trailingControls?: ReactNode;
/** Fires with the session id when the user closes a tab. */
readonly onClose: (id: string) => void;
/**
@@ -201,11 +198,8 @@ export function TerminalTabStrip({
activeSessionId,
onSelect,
onTabActivate,
- newChatSelected,
- onNewChatLaunch,
- onNewChatPickCli,
- onNewChatPickTerminal,
- newChatVisibleClis,
+ newButton,
+ trailingControls,
onClose,
onRename,
onReorder,
@@ -285,10 +279,27 @@ export function TerminalTabStrip({
// with editor tabs) supplies the horizontal clamp, edge-snap collision, and
// width stabilization; bounds are measured against the row on drag start.
const rowRef = useRef<HTMLDivElement>(null);
+ const tabListRef = useRef<HTMLDivElement>(null);
const [tabReorderBounds, setTabReorderBounds] = useState<TabReorderBounds | null>(null);
const sensors = useSensors(useSensor(PointerSensor, { activationConstraint: { distance: 8 } }));
const reorderEnabled = onReorder != null;
const reorderModifiers = [createTabReorderModifier(tabReorderBounds)];
+ const activeTabScrollKey =
+ activeSessionId === ''
+ ? null
+ : `${activeSessionId}\u0000${sessions.map((session) => session.id).join('\u0000')}`;
+
+ // Selection can change through click, arrow keys, shortcuts, close-neighbor
+ // fallback, reload restore, or a newly appended session. Keep the selected tab
+ // visible for every path without moving it in the user's chosen tab order.
+ useEffect(() => {
+ if (activeTabScrollKey === null) return;
+ const [activeId] = activeTabScrollKey.split('\u0000', 1);
+ const safeId = typeof CSS !== 'undefined' && CSS.escape ? CSS.escape(activeId) : activeId;
+ tabListRef.current
+ ?.querySelector<HTMLElement>(`[data-tab-id="${safeId}"]`)
+ ?.scrollIntoView({ block: 'nearest', inline: 'nearest' });
+ }, [activeTabScrollKey]);
function handleDragStart() {
setTabReorderBounds(measureTabReorderBounds(rowRef.current, TERMINAL_TAB_SORTABLE_SELECTOR));
@@ -343,16 +354,24 @@ export function TerminalTabStrip({
)}
>
<TabsList
+ ref={tabListRef}
variant="line"
- aria-label={t`Terminal sessions`}
+ aria-label={t`Sessions`}
+ // Remap a vertical wheel to horizontal scroll so the main scroll wheel
+ // moves the tabs sideways, matching the editor tab strip (which native
+ // overflow-x alone doesn't do for a plain vertical wheel).
+ onWheel={scrollTabStripOnWheel}
// No `flex-1`: the list sizes to its tabs so "New chat" can hug the
// last one. `min-w-0` + `overflow-x-auto` keep the tabs scrolling
// internally when they overflow the space the trailing controls leave.
+ // `overflow-y-hidden` is load-bearing: `overflow-x: auto` alone computes
+ // the y-axis from `visible` to `auto`, so the tab status-dot's 2px
+ // `-bottom-0.5` bleed becomes a stray couple-pixel vertical scroll.
// Window mode: the whole tab run (incl. inter-tab gaps) is `no-drag` so
// a pointer drag crossing a gap reorders instead of moving the window;
// the row's empty space outside the run stays a drag region.
className={cn(
- 'flex h-auto min-w-0 items-center justify-start gap-0.5 overflow-x-auto bg-transparent p-0 [scrollbar-width:none] scroll-fade-mask-x',
+ 'flex h-auto min-w-0 items-center justify-start gap-0.5 overflow-x-auto overflow-y-hidden bg-transparent p-0 [scrollbar-width:none] scroll-fade-mask-x',
draggable && '[-webkit-app-region:no-drag]',
)}
>
@@ -451,10 +470,11 @@ export function TerminalTabStrip({
}
}}
className={cn(
- 'h-7 flex-none rounded-md px-2 text-xs',
+ 'h-7 flex-none gap-1.5 rounded-md px-2 text-xs',
draggable && '[-webkit-app-region:no-drag]',
)}
>
+ {session.icon}
<span className="max-w-40 truncate">{session.label}</span>
</TabsTrigger>
</TooltipTrigger>
@@ -496,19 +516,23 @@ export function TerminalTabStrip({
</SortableContext>
</DndContext>
</TabsList>
- {/* New-chat split button hugs the last tab (outside the tablist's
- scroll+fade so it is never clipped): the primary launches the default
- CLI, the carat switches CLI or opens a bare terminal. */}
- <TerminalNewChatButton
- selected={newChatSelected}
- onLaunchSelected={onNewChatLaunch}
- onPickCli={onNewChatPickCli}
- onPickTerminal={onNewChatPickTerminal}
- visibleClis={newChatVisibleClis}
- className={cn('shrink-0', draggable && '[-webkit-app-region:no-drag]')}
- />
+ {/* The host's "new session" split button hugs the last tab (outside the
+ tablist's scroll+fade so it is never clipped). Wrapped so window mode
+ can opt it out of the title-bar drag region. */}
+ {newButton != null ? (
+ <div className={cn('shrink-0', draggable && '[-webkit-app-region:no-drag]')}>
+ {newButton}
+ </div>
+ ) : null}
{/* Spacer pushes the trailing controls to the far right. */}
<div className="flex-1" />
+ {/* Host-provided trailing controls (e.g. conversation history), just left
+ of the dock-toggle/collapse buttons. */}
+ {trailingControls != null ? (
+ <div className={cn('shrink-0', draggable && '[-webkit-app-region:no-drag]')}>
+ {trailingControls}
+ </div>
+ ) : null}
{onToggleDock != null ? (
<Tooltip>
<TooltipTrigger asChild>
@@ -519,7 +543,7 @@ export function TerminalTabStrip({
// Label names the resulting position, not the current one, so the
// action reads as "move it there" to a screen-reader user.
aria-label={
- rightDocked ? t`Dock terminal to the bottom` : t`Dock terminal to the right`
+ rightDocked ? t`Dock sessions at the bottom` : t`Dock sessions on the right`
}
className="shrink-0 cursor-pointer text-muted-foreground hover:text-foreground"
onClick={onToggleDock}
@@ -533,9 +557,9 @@ export function TerminalTabStrip({
</TooltipTrigger>
<TooltipContent side="bottom" sideOffset={8}>
{rightDocked ? (
- <Trans>Dock terminal to the bottom</Trans>
+ <Trans>Dock sessions at the bottom</Trans>
) : (
- <Trans>Dock terminal to the right</Trans>
+ <Trans>Dock sessions on the right</Trans>
)}
</TooltipContent>
</Tooltip>
@@ -547,7 +571,7 @@ export function TerminalTabStrip({
type="button"
variant="ghost"
size="icon-xs"
- aria-label={t`Collapse terminal`}
+ aria-label={t`Collapse session dock`}
className="shrink-0 cursor-pointer text-muted-foreground hover:text-foreground"
onClick={onCollapse}
>
@@ -561,7 +585,7 @@ export function TerminalTabStrip({
</Button>
</TooltipTrigger>
<TooltipContent side="bottom" sideOffset={8}>
- <Trans>Collapse terminal</Trans>
+ <Trans>Collapse session dock</Trans>
</TooltipContent>
</Tooltip>
) : null}
diff --git a/packages/app/src/components/TerminalWindowApp.config-provider.dom.test.tsx b/packages/app/src/components/TerminalWindowApp.config-provider.dom.test.tsx
index da6c8c1fb..6a298ff29 100644
--- a/packages/app/src/components/TerminalWindowApp.config-provider.dom.test.tsx
+++ b/packages/app/src/components/TerminalWindowApp.config-provider.dom.test.tsx
@@ -12,15 +12,21 @@
* provider wrapping removed, this render throws; with it, the child mounts.
*/
-import { afterEach, describe, expect, mock, test } from 'bun:test';
import { cleanup, render, screen } from '@testing-library/react';
+import { afterEach, describe, expect, test, vi } from 'vitest';
import { TooltipProvider } from '@/components/ui/tooltip';
import { useConfigContext } from '@/lib/config-provider';
import type { OkDesktopBridge } from '@/lib/desktop-bridge-types';
+// The New split-button calls react-query's useQuery; stub it so this test needs
+// no QueryClientProvider.
+vi.doMock('@tanstack/react-query', () => ({
+ useQuery: () => ({ data: undefined, isLoading: false, isError: false }),
+}));
+
// Stand in for the real TerminalGate: read the same context the terminal-consent
// hooks read. Throws (and blanks the root) if no ConfigProvider is above it.
-mock.module('./TerminalGate', () => ({
+vi.doMock('./TerminalGate', () => ({
TerminalGate: () => {
const { projectLocalSynced } = useConfigContext();
return (
diff --git a/packages/app/src/components/TerminalWindowApp.dom.test.tsx b/packages/app/src/components/TerminalWindowApp.dom.test.tsx
index b94401ff0..0df54675d 100644
--- a/packages/app/src/components/TerminalWindowApp.dom.test.tsx
+++ b/packages/app/src/components/TerminalWindowApp.dom.test.tsx
@@ -13,10 +13,10 @@
* trees.
*/
-import { afterEach, beforeEach, describe, expect, mock, spyOn, test } from 'bun:test';
import { act, cleanup, render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { useEffect, useRef } from 'react';
+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
import { TooltipProvider } from '@/components/ui/tooltip';
import type { OkDesktopBridge, OkMenuAction } from '@/lib/desktop-bridge-types';
import {
@@ -24,7 +24,13 @@ import {
emitLocalMenuAction,
} from '@/lib/local-menu-action-bus';
-mock.module('./TerminalGate', () => ({
+// The New split-button calls react-query's useQuery; stub it so the window tests
+// need no QueryClientProvider (the window variant hides agent rows anyway).
+vi.doMock('@tanstack/react-query', () => ({
+ useQuery: () => ({ data: undefined, isLoading: false, isError: false }),
+}));
+
+vi.doMock('./TerminalGate', () => ({
// biome-ignore lint/suspicious/noExplicitAny: test stub
TerminalGate: ({ bridge }: any) => {
const ptyIdRef = useRef<string | null>(null);
@@ -47,8 +53,8 @@ mock.module('./TerminalGate', () => ({
},
}));
-mock.module('@/App', () => ({ App: () => <div data-testid="editor-app" /> }));
-mock.module('@/components/NavigatorApp', () => ({
+vi.doMock('@/App', () => ({ App: () => <div data-testid="editor-app" /> }));
+vi.doMock('@/components/NavigatorApp', () => ({
NavigatorApp: () => <div data-testid="navigator-app" />,
}));
@@ -58,11 +64,11 @@ const { selectDesktopRootApp } = await import('./desktop-root-app');
function makeBridge() {
const viewMenuPushes: Array<{ terminalLive?: boolean }> = [];
let ptyCounter = 0;
- const create = mock(async () => {
+ const create = vi.fn(async () => {
ptyCounter += 1;
return { ok: true as const, ptyId: `pty-${ptyCounter}` };
});
- const kill = mock(async (_id: string) => {});
+ const kill = vi.fn(async (_id: string) => {});
const bridge = {
config: { mode: 'terminal' },
onMenuAction: () => () => {},
@@ -95,7 +101,7 @@ function bridgeWithMode(mode: string): OkDesktopBridge {
// the same affordance the dock has (the window holds feature parity; only the
// placement differs).
async function addTerminalTab(user: ReturnType<typeof userEvent.setup>) {
- await user.click(screen.getByRole('button', { name: 'Choose CLI for new chat' }));
+ await user.click(screen.getByRole('button', { name: 'Choose what a new session starts' }));
await user.click(await screen.findByRole('menuitem', { name: 'Terminal' }));
}
@@ -202,7 +208,7 @@ describe('TerminalWindowApp', () => {
test('closing the last tab closes the window instead of leaving an empty surface', async () => {
const user = userEvent.setup();
- const closeSpy = spyOn(window, 'close').mockImplementation(() => {});
+ const closeSpy = vi.spyOn(window, 'close').mockImplementation(() => {});
try {
const { bridge } = makeBridge();
render(
@@ -256,7 +262,7 @@ describe('TerminalWindowApp', () => {
test('⌘W (close-active-tab-or-window) closes the active tab; the last tab closes the window', async () => {
const user = userEvent.setup();
- const closeSpy = spyOn(window, 'close').mockImplementation(() => {});
+ const closeSpy = vi.spyOn(window, 'close').mockImplementation(() => {});
try {
const view = makeBridge();
render(
@@ -303,14 +309,20 @@ describe('selectDesktopRootApp routing', () => {
__resetLocalMenuActionBusForTests();
});
- test('mode=terminal selects the terminal window app', () => {
- expect(selectDesktopRootApp(bridgeWithMode('terminal')).type).toBe(TerminalWindowApp);
- });
-
- test('mounting the terminal-mode selection renders the full-window terminal', () => {
+ test('mounting the terminal-mode selection renders the full-window terminal', async () => {
+ // The terminal window app is lazy-loaded (it drags the sessions-dock +
+ // thread-client chain, which must stay out of the entry chunk), so
+ // mode=terminal routing is asserted through the mounted result — the
+ // element type is a Suspense wrapper, and the lazy chunk needs awaiting.
+ // The `findByRole` timeout is raised past the 1000 ms default: this mount
+ // resolves the whole sessions-dock + thread-client chain, which can settle
+ // slowly on loaded CI runners (the default flaked the full test:dom suite
+ // while passing locally + in isolation).
const { bridge } = makeBridge();
render(<TooltipProvider>{selectDesktopRootApp(bridge)}</TooltipProvider>);
- expect(screen.getByRole('tablist', { name: 'Terminal sessions' })).toBeTruthy();
+ expect(
+ await screen.findByRole('tablist', { name: 'Sessions' }, { timeout: 5000 }),
+ ).toBeTruthy();
expect(screen.getAllByTestId('terminal-session')).toHaveLength(1);
});
diff --git a/packages/app/src/components/TrashFailureModal.dom.test.tsx b/packages/app/src/components/TrashFailureModal.dom.test.tsx
index 4c82909e2..326c976ff 100644
--- a/packages/app/src/components/TrashFailureModal.dom.test.tsx
+++ b/packages/app/src/components/TrashFailureModal.dom.test.tsx
@@ -1,13 +1,13 @@
-import { afterEach, describe, expect, mock, test } from 'bun:test';
import * as actualLinguiMacro from '@lingui/react/macro';
import { cleanup, render, screen, within } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import type { ReactNode } from 'react';
+import { afterEach, describe, expect, test, vi } from 'vitest';
import { renderLinguiTemplate } from '@/test-utils/lingui-mock';
import { expectVisualClassTokens } from '@/test-utils/visual-contract';
import type { TrashFailedTarget } from './TrashFailureModal';
-mock.module('@lingui/core/macro', () => ({
+vi.doMock('@lingui/core/macro', () => ({
...actualLinguiMacro,
plural: (
count: number,
@@ -17,9 +17,10 @@ mock.module('@lingui/core/macro', () => ({
},
) => (count === 1 ? (forms.one ?? forms.other) : forms.other).replace('#', String(count)),
t: renderLinguiTemplate,
+ msg: renderLinguiTemplate,
}));
-mock.module('@lingui/react/macro', () => ({
+vi.doMock('@lingui/react/macro', () => ({
...actualLinguiMacro,
Trans: ({ children }: { children: ReactNode }) => <>{children}</>,
}));
@@ -50,9 +51,9 @@ async function renderTrashFailureModal({
import('@/components/ui/dialog'),
import('./TrashFailureModal'),
]);
- const onCancel = mock(() => {});
- const onRetry = mock(() => {});
- const onDeletePermanently = mock(() => {});
+ const onCancel = vi.fn(() => {});
+ const onRetry = vi.fn(() => {});
+ const onDeletePermanently = vi.fn(() => {});
render(
<Dialog open={true}>
diff --git a/packages/app/src/components/acp/AcpHarnessAgentDetection.tsx b/packages/app/src/components/acp/AcpHarnessAgentDetection.tsx
new file mode 100644
index 000000000..5e2143033
--- /dev/null
+++ b/packages/app/src/components/acp/AcpHarnessAgentDetection.tsx
@@ -0,0 +1,29 @@
+import { useQuery } from '@tanstack/react-query';
+import { useEffect } from 'react';
+import { detectedHarnessAgents, fetchAgentCatalog } from '@/lib/acp/catalog';
+import { setDetectedRegisteredAgentSuggestions } from '@/lib/acp/registered-agents';
+
+/**
+ * Projects server-host harness detection into every registered-agent picker.
+ * Suggestions remain non-persistent and never become the explicit default.
+ */
+export function AcpHarnessAgentDetection() {
+ const catalog = useQuery({
+ queryKey: ['acp-catalog'],
+ queryFn: ({ signal }) => fetchAgentCatalog(signal),
+ staleTime: 5 * 60 * 1000,
+ });
+
+ useEffect(() => {
+ const suggestions = detectedHarnessAgents(catalog.data?.agents ?? []).map((agent) => ({
+ source: agent.source,
+ id: agent.id,
+ name: agent.name,
+ ...(agent.iconUrl !== undefined ? { iconUrl: agent.iconUrl } : {}),
+ }));
+ setDetectedRegisteredAgentSuggestions(suggestions);
+ return () => setDetectedRegisteredAgentSuggestions([]);
+ }, [catalog.data]);
+
+ return null;
+}
diff --git a/packages/app/src/components/acp/AgentBetaBadge.tsx b/packages/app/src/components/acp/AgentBetaBadge.tsx
new file mode 100644
index 000000000..ebeaf9e0e
--- /dev/null
+++ b/packages/app/src/components/acp/AgentBetaBadge.tsx
@@ -0,0 +1,21 @@
+/**
+ * Small "Beta" tag marking the in-app ACP agent feature as beta. Rendered beside
+ * the "In this app" section header in every agent picker + the catalog dialog
+ * title, scoping the beta signal to the agent-thread rows (not the pre-existing
+ * Terminal / Desktop handoff paths in the same menus).
+ *
+ * Always visible — unlike {@link BetaBadge}, which renders only on the beta
+ * auto-update channel. This one is about the feature's maturity, not the build.
+ */
+
+import { Trans } from '@lingui/react/macro';
+import { Badge } from '@/components/ui/badge';
+import { cn } from '@/lib/utils';
+
+export function AgentBetaBadge({ className }: { readonly className?: string }) {
+ return (
+ <Badge variant="gray" className={cn('h-4 px-1 text-[10px]', className)}>
+ <Trans>Beta</Trans>
+ </Badge>
+ );
+}
diff --git a/packages/app/src/components/acp/AgentMarkdown.dom.test.tsx b/packages/app/src/components/acp/AgentMarkdown.dom.test.tsx
new file mode 100644
index 000000000..9c5e498be
--- /dev/null
+++ b/packages/app/src/components/acp/AgentMarkdown.dom.test.tsx
@@ -0,0 +1,73 @@
+/**
+ * RTL mount tests for AgentMarkdown: streamed ACP agent text renders as
+ * markdown (not raw source), incomplete mid-stream constructs display
+ * without leaking delimiter syntax, raw HTML from the agent is sanitized,
+ * and links are hardened against opener hijacking. Invocation via
+ * `bun run test:dom`.
+ */
+
+import { cleanup, render, waitFor } from '@testing-library/react';
+import { afterEach, describe, expect, test } from 'vitest';
+import { AgentMarkdown } from './AgentMarkdown';
+
+describe('AgentMarkdown', () => {
+ afterEach(cleanup);
+
+ test('renders emphasis and inline code as elements, not raw delimiters', () => {
+ const { container } = render(<AgentMarkdown text={'**bold** and `inline`'} />);
+ expect(container.querySelector('[data-streamdown="strong"]')?.textContent).toBe('bold');
+ expect(container.querySelector('code')?.textContent).toBe('inline');
+ expect(container.textContent).not.toContain('**');
+ });
+
+ test('renders fenced code blocks', async () => {
+ const { container } = render(<AgentMarkdown text={'```ts\nconst x = 1;\n```'} />);
+ await waitFor(() => {
+ expect(container.querySelector('pre')?.textContent).toContain('const x = 1;');
+ });
+ });
+
+ test('code blocks keep one wrapper span per line', async () => {
+ // AgentMarkdown's `[&_pre_code>span]:block` rule is what stacks code
+ // lines when line numbers are off — Streamdown only applies per-line
+ // block display through its line-number classes. This pins the DOM
+ // shape that rule targets; if a Streamdown upgrade changes it,
+ // multi-line code silently collapses onto one visual line.
+ const { container } = render(
+ <AgentMarkdown text={'```ts\nconst a = 1;\nconst b = 2;\nconst c = 3;\n```'} />,
+ );
+ await waitFor(() => {
+ expect(container.querySelectorAll('pre code > span')).toHaveLength(3);
+ });
+ });
+
+ test('renders lists and headings structurally', () => {
+ const { container } = render(<AgentMarkdown text={'## Title\n\n- one\n- two'} />);
+ expect(container.querySelector('h2')?.textContent).toBe('Title');
+ expect(container.querySelectorAll('li')).toHaveLength(2);
+ });
+
+ test('an unterminated construct mid-stream shows text without delimiter noise', () => {
+ const { container } = render(<AgentMarkdown text={'streaming **partial'} />);
+ expect(container.textContent).toContain('partial');
+ expect(container.textContent).not.toContain('**');
+ });
+
+ test('sanitizes raw HTML from the agent', () => {
+ const { container } = render(
+ <AgentMarkdown text={'before <img src="x" onerror="window.__pwned = true"> after'} />,
+ );
+ for (const img of container.querySelectorAll('img')) {
+ expect(img.getAttribute('onerror')).toBeNull();
+ }
+ expect(container.querySelector('script')).toBeNull();
+ });
+
+ test('hardens links to open in a new context', () => {
+ const { container } = render(<AgentMarkdown text={'[docs](https://example.com/)'} />);
+ const anchor = container.querySelector('a');
+ expect(anchor?.getAttribute('href')).toBe('https://example.com/');
+ expect(anchor?.getAttribute('target')).toBe('_blank');
+ expect(anchor?.getAttribute('rel')).toContain('noreferrer');
+ });
+});
diff --git a/packages/app/src/components/acp/AgentMarkdown.tsx b/packages/app/src/components/acp/AgentMarkdown.tsx
new file mode 100644
index 000000000..8a3f864f4
--- /dev/null
+++ b/packages/app/src/components/acp/AgentMarkdown.tsx
@@ -0,0 +1,41 @@
+/**
+ * Streamed agent markdown for the thread transcript. Streamdown closes
+ * unterminated constructs (emphasis, fences, links) so partial stream chunks
+ * render cleanly mid-turn, and sanitizes the rendered tree — agent output is
+ * not trusted HTML. The boundary drops to plain text if the renderer throws
+ * on a malformed partial and retries via `resetKeys` when the next chunk
+ * changes the text.
+ */
+
+import type { ReactNode } from 'react';
+import { ErrorBoundary } from 'react-error-boundary';
+import { Streamdown } from 'streamdown';
+
+export function AgentMarkdown({ text }: { text: string }): ReactNode {
+ return (
+ <ErrorBoundary
+ resetKeys={[text]}
+ fallbackRender={() => <span className="whitespace-pre-wrap">{text}</span>}
+ onError={(error) => {
+ console.warn('[AgentMarkdown] markdown render failed, falling back to plain text', error);
+ }}
+ >
+ <Streamdown
+ // The `pre code>span` rule restores per-line block display in code
+ // blocks: Streamdown bundles it into the line-number counter classes,
+ // so `lineNumbers={false}` alone collapses multi-line code onto one
+ // visual line.
+ className="[&>*:first-child]:mt-0 [&>*:last-child]:mb-0 [&_pre_code>span]:block"
+ lineNumbers={false}
+ controls={{ code: { copy: true, download: false }, table: false, mermaid: false }}
+ // Plain hardened anchors instead of Streamdown's confirm-modal flow:
+ // both shells already gate external opens (web: target=_blank +
+ // noreferrer; desktop: the asset-safety-net window-open handler with
+ // scheme allowlisting), matching every other external link in the app.
+ linkSafety={{ enabled: false }}
+ >
+ {text}
+ </Streamdown>
+ </ErrorBoundary>
+ );
+}
diff --git a/packages/app/src/components/acp/AgentThreadClientBinder.tsx b/packages/app/src/components/acp/AgentThreadClientBinder.tsx
new file mode 100644
index 000000000..0945eb204
--- /dev/null
+++ b/packages/app/src/components/acp/AgentThreadClientBinder.tsx
@@ -0,0 +1,25 @@
+/**
+ * Binds the resolved collab URL onto the module-scope agent-thread client (swapping
+ * `/collab` → `/collab/thread`). Mounted once in EditorPane so the client connects,
+ * lists, and replays regardless of whether the sessions dock is open — thread
+ * liveness is independent of the dock's visibility.
+ *
+ * Lifted out of the retired `AgentThreadRegion`, which used to own this binding
+ * alongside the standalone agent dock. Renders nothing.
+ */
+
+import { useEffect } from 'react';
+import { getAgentThreadClient, threadUrlFromCollabUrl } from '@/lib/acp/thread-client';
+import { useCollabUrl } from '@/lib/use-collab-url';
+
+export function AgentThreadClientBinder(): null {
+ const { collabUrl } = useCollabUrl();
+
+ // The client reconnects when the URL changes and replays any missed events per
+ // thread, so a mid-session project switch (Electron) or a reconnect is transparent.
+ useEffect(() => {
+ getAgentThreadClient().setUrl(threadUrlFromCollabUrl(collabUrl));
+ }, [collabUrl]);
+
+ return null;
+}
diff --git a/packages/app/src/components/acp/RegisteredAgentIcon.dom.test.tsx b/packages/app/src/components/acp/RegisteredAgentIcon.dom.test.tsx
new file mode 100644
index 000000000..0e73a0921
--- /dev/null
+++ b/packages/app/src/components/acp/RegisteredAgentIcon.dom.test.tsx
@@ -0,0 +1,68 @@
+import { cleanup, render } from '@testing-library/react';
+import { afterEach, describe, expect, test } from 'vitest';
+import { RegisteredAgentIcon } from './RegisteredAgentIcon';
+
+describe('RegisteredAgentIcon', () => {
+ afterEach(cleanup);
+
+ test('uses the local colorized Claude icon instead of the registry image', () => {
+ const { container } = render(
+ <RegisteredAgentIcon
+ agentId="claude-acp"
+ iconUrl="https://example.com/claude.svg"
+ className="size-4"
+ />,
+ );
+
+ expect(container.querySelector('img')).toBeNull();
+ const icon = container.querySelector('svg');
+ expect(icon?.getAttribute('class')).toContain('text-[#D97757]');
+ expect(icon?.getAttribute('aria-hidden')).toBe('true');
+ });
+
+ test('uses the local Codex brand gradient instead of the registry image', () => {
+ const { container } = render(
+ <RegisteredAgentIcon
+ agentId="codex-acp"
+ iconUrl="https://example.com/codex.svg"
+ className="size-4"
+ />,
+ );
+
+ expect(container.querySelector('img')).toBeNull();
+ expect(container.querySelector('linearGradient')).toBeTruthy();
+ expect(
+ [...container.querySelectorAll('stop')].map((stop) => stop.getAttribute('stop-color')),
+ ).toEqual(['#B1A7FF', '#7A9DFF', '#3941FF']);
+ });
+
+ test('uses the local adaptive Cursor brand icon instead of the registry image', () => {
+ const { container } = render(
+ <RegisteredAgentIcon
+ agentId="cursor"
+ iconUrl="https://example.com/cursor.svg"
+ className="size-4"
+ />,
+ );
+
+ expect(container.querySelector('img')).toBeNull();
+ const icon = container.querySelector('svg');
+ expect(icon?.getAttribute('class')).toContain('text-[#1B1912]');
+ expect(icon?.getAttribute('class')).toContain('dark:text-white');
+ });
+
+ test('keeps the registry image for agents without a local treatment', () => {
+ const { container } = render(
+ <RegisteredAgentIcon
+ agentId="gemini"
+ iconUrl="https://example.com/gemini.svg"
+ className="size-4"
+ />,
+ );
+
+ expect(container.querySelector('svg')).toBeNull();
+ expect(container.querySelector('img')?.getAttribute('src')).toBe(
+ 'https://example.com/gemini.svg',
+ );
+ });
+});
diff --git a/packages/app/src/components/acp/RegisteredAgentIcon.tsx b/packages/app/src/components/acp/RegisteredAgentIcon.tsx
new file mode 100644
index 000000000..7da4dab1a
--- /dev/null
+++ b/packages/app/src/components/acp/RegisteredAgentIcon.tsx
@@ -0,0 +1,62 @@
+/**
+ * Registered-agent brand icon shared by every ACP surface. First-party agents
+ * use the app's local brand treatment; every other registry/custom agent keeps
+ * its manifest SVG with a neutral-glyph fallback on load failure.
+ */
+
+import { Bot } from 'lucide-react';
+import { type ReactNode, useState } from 'react';
+import { ClaudeIcon } from '@/components/icons/claude';
+import { CodexBrandIcon } from '@/components/icons/codex';
+import { CursorIcon } from '@/components/icons/cursor';
+import { cn } from '@/lib/utils';
+
+export function RegisteredAgentIcon({
+ agentId,
+ iconUrl,
+ className,
+}: {
+ agentId: string;
+ iconUrl?: string;
+ className?: string;
+}): ReactNode {
+ const [failed, setFailed] = useState(false);
+ const brandClassName = cn('shrink-0', className);
+ if (agentId === 'claude-acp') {
+ return (
+ <ClaudeIcon
+ className={cn(
+ 'text-[#D97757] [--ok-brand-color:#D97757] [&_*]:![color:var(--ok-brand-color)]',
+ brandClassName,
+ )}
+ aria-hidden="true"
+ />
+ );
+ }
+ if (agentId === 'codex-acp') {
+ return <CodexBrandIcon className={brandClassName} aria-hidden="true" />;
+ }
+ if (agentId === 'cursor') {
+ return (
+ <CursorIcon
+ className={cn(
+ 'text-[#1B1912] [--ok-brand-color:#1B1912] [&_*]:![color:var(--ok-brand-color)] dark:text-white dark:[--ok-brand-color:#FFFFFF]',
+ brandClassName,
+ )}
+ aria-hidden="true"
+ />
+ );
+ }
+ if (iconUrl === undefined || failed) {
+ return <Bot className={cn('shrink-0 text-muted-foreground', className)} aria-hidden="true" />;
+ }
+ return (
+ <img
+ src={iconUrl}
+ alt=""
+ aria-hidden="true"
+ className={cn('shrink-0 rounded', className)}
+ onError={() => setFailed(true)}
+ />
+ );
+}
diff --git a/packages/app/src/components/acp/ThreadHistoryMenu.tsx b/packages/app/src/components/acp/ThreadHistoryMenu.tsx
new file mode 100644
index 000000000..23e1c5ddf
--- /dev/null
+++ b/packages/app/src/components/acp/ThreadHistoryMenu.tsx
@@ -0,0 +1,224 @@
+/**
+ * Conversation-history surfaces for the sessions dock's agent threads: the
+ * history popover (reopen or delete an archived conversation) and the empty-dock
+ * chooser (reopen a past conversation instead of facing a dead end).
+ *
+ * Closing a thread tab archives it (or discards it when it never received a
+ * message); these are the only ways back to an archived conversation, and the
+ * only place a permanent delete lives. Lifted out of the retired AgentThreadDock
+ * so the unified dock keeps the recover-from-history contract.
+ */
+
+import type { ThreadInfo } from '@inkeep/open-knowledge-core/acp/thread-protocol';
+import { t as tStatic } from '@lingui/core/macro';
+import { useLingui } from '@lingui/react/macro';
+import { History, Trash2 } from 'lucide-react';
+import { type ReactNode, useEffect, useState } from 'react';
+import { RegisteredAgentIcon } from '@/components/acp/RegisteredAgentIcon';
+import { Button } from '@/components/ui/button';
+import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';
+import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip';
+import { getAgentThreadClient } from '@/lib/acp/thread-client';
+
+/**
+ * The past-conversations menu: archived threads, latest activity first, each
+ * reopenable as a tab. Permanent delete lives here (and only here — a tab X
+ * archives a conversation, or discards it when it never received a message),
+ * behind a per-row inline confirm since there is no undo.
+ */
+export function ThreadHistoryMenu({
+ archived,
+ onOpenThread,
+}: {
+ archived: readonly ThreadInfo[];
+ onOpenThread: (threadId: string) => void;
+}): ReactNode {
+ const { t } = useLingui();
+ const client = getAgentThreadClient();
+ const [open, setOpen] = useState(false);
+ const [confirmingId, setConfirmingId] = useState<string | null>(null);
+ // Captured on open (event handler, not render) — React Compiler forbids
+ // impure Date.now() during render. Relative labels only show while open, so
+ // refreshing the reference time on each open is both correct and sufficient.
+ const [now, setNow] = useState(0);
+ return (
+ <Popover
+ open={open}
+ onOpenChange={(next) => {
+ setOpen(next);
+ if (next) setNow(Date.now());
+ else setConfirmingId(null);
+ }}
+ >
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <PopoverTrigger asChild>
+ <Button
+ type="button"
+ variant="ghost"
+ size="icon-xs"
+ className="shrink-0 cursor-pointer text-muted-foreground hover:text-foreground"
+ aria-label={t`Restore sessions`}
+ data-testid="agent-thread-history"
+ >
+ <History aria-hidden="true" />
+ </Button>
+ </PopoverTrigger>
+ </TooltipTrigger>
+ <TooltipContent side="bottom" sideOffset={8}>
+ {t`Restore sessions`}
+ </TooltipContent>
+ </Tooltip>
+ <PopoverContent align="end" className="w-72 p-1">
+ <div className="max-h-80 overflow-y-auto">
+ {archived.map((thread) =>
+ confirmingId === thread.threadId ? (
+ <div
+ key={thread.threadId}
+ className="flex items-center gap-1.5 rounded-md bg-destructive/5 px-2 py-1"
+ data-testid="agent-thread-history-confirm"
+ >
+ <span className="min-w-0 flex-1 truncate text-xs">
+ {t`Delete this conversation?`}
+ </span>
+ <Button
+ type="button"
+ size="sm"
+ variant="destructive"
+ className="h-6 px-2 text-xs"
+ onClick={() => {
+ client.deleteThread(thread.threadId);
+ setConfirmingId(null);
+ }}
+ data-testid="agent-thread-history-confirm-delete"
+ >
+ {t`Delete`}
+ </Button>
+ <Button
+ type="button"
+ size="sm"
+ variant="ghost"
+ className="h-6 px-2 text-xs"
+ onClick={() => setConfirmingId(null)}
+ >
+ {t`Cancel`}
+ </Button>
+ </div>
+ ) : (
+ <div key={thread.threadId} className="group flex items-center gap-0.5">
+ <Button
+ type="button"
+ variant="ghost"
+ className="h-auto min-w-0 flex-1 justify-start gap-2 px-2 py-1.5"
+ onClick={() => {
+ onOpenThread(thread.threadId);
+ setOpen(false);
+ }}
+ data-testid={`agent-thread-history-open-${thread.threadId}`}
+ >
+ <RegisteredAgentIcon
+ agentId={thread.agent.id}
+ iconUrl={thread.agent.iconUrl}
+ className="size-4 shrink-0"
+ />
+ <span className="min-w-0 flex-1 truncate text-left text-xs">{thread.title}</span>
+ <span className="shrink-0 text-[10px] text-muted-foreground">
+ {formatRelative(thread.lastActivityAt, now)}
+ </span>
+ </Button>
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <Button
+ type="button"
+ variant="ghost"
+ size="icon-xs"
+ aria-label={t`Delete ${thread.title}`}
+ className="text-muted-foreground opacity-0 transition-opacity hover:text-destructive group-focus-within:opacity-100 group-hover:opacity-100"
+ onClick={() => setConfirmingId(thread.threadId)}
+ data-testid={`agent-thread-history-delete-${thread.threadId}`}
+ >
+ <Trash2 className="size-3" aria-hidden="true" />
+ </Button>
+ </TooltipTrigger>
+ <TooltipContent side="bottom" sideOffset={8}>
+ {t`Delete ${thread.title}`}
+ </TooltipContent>
+ </Tooltip>
+ </div>
+ ),
+ )}
+ </div>
+ </PopoverContent>
+ </Popover>
+ );
+}
+
+/**
+ * The empty-dock chooser: past conversations, latest first, each reopenable in
+ * one click — so an empty dock with history is a way back in, not a dead end.
+ * The caller renders this only when there is archived history.
+ */
+export function ArchivedThreadChooser({
+ archived,
+ onOpen,
+}: {
+ archived: readonly ThreadInfo[];
+ onOpen: (threadId: string) => void;
+}): ReactNode {
+ const { t } = useLingui();
+ // Date.now() is impure — capture it in an effect (React Compiler forbids it in
+ // render). Refreshed each time the chooser mounts (the dock reaching zero open
+ // sessions), which is exactly when the relative labels below are shown.
+ const [now, setNow] = useState(0);
+ useEffect(() => {
+ setNow(Date.now());
+ }, []);
+ return (
+ <div
+ className="flex min-h-0 flex-1 flex-col gap-2 overflow-y-auto p-3"
+ data-testid="agent-thread-empty-chooser"
+ >
+ <p className="px-1 text-muted-foreground text-xs">
+ {t`No open conversations. Reopen a past one, or start a session with the + button.`}
+ </p>
+ <div className="flex flex-col gap-0.5">
+ {archived.map((thread) => (
+ <Button
+ key={thread.threadId}
+ type="button"
+ variant="ghost"
+ className="h-auto w-full min-w-0 justify-start gap-2 px-2 py-1.5"
+ onClick={() => onOpen(thread.threadId)}
+ data-testid={`agent-thread-empty-open-${thread.threadId}`}
+ >
+ <RegisteredAgentIcon
+ agentId={thread.agent.id}
+ iconUrl={thread.agent.iconUrl}
+ className="size-4 shrink-0"
+ />
+ <span className="min-w-0 flex-1 truncate text-left text-xs">{thread.title}</span>
+ <span className="shrink-0 text-[10px] text-muted-foreground">
+ {formatRelative(thread.lastActivityAt, now)}
+ </span>
+ </Button>
+ ))}
+ </div>
+ </div>
+ );
+}
+
+/** Coarse relative-time label for a conversation's last activity. */
+function formatRelative(ms: number, now: number): string {
+ const diff = Math.max(0, now - ms);
+ if (diff < 60_000) return tStatic`just now`;
+ if (diff < 3_600_000) {
+ const minutes = Math.round(diff / 60_000);
+ return tStatic`${minutes}m ago`;
+ }
+ if (diff < 86_400_000) {
+ const hours = Math.round(diff / 3_600_000);
+ return tStatic`${hours}h ago`;
+ }
+ const days = Math.round(diff / 86_400_000);
+ return tStatic`${days}d ago`;
+}
diff --git a/packages/app/src/components/acp/ThreadView.dom.test.tsx b/packages/app/src/components/acp/ThreadView.dom.test.tsx
new file mode 100644
index 000000000..eceeed8e9
--- /dev/null
+++ b/packages/app/src/components/acp/ThreadView.dom.test.tsx
@@ -0,0 +1,474 @@
+/**
+ * RTL mount tests for the thread-rendering parity surfaces: the terminal
+ * card (command + output + exit badge), the genuine line diff, the explicit
+ * Deny path and kind-aware resolution summaries, dead-turn permission
+ * gating, the awaiting-permission transcript line, the context-usage ring
+ * (shown only once a percentage is computable), and the raw tool-input block.
+ * Invocation via `bun run test:dom`.
+ */
+
+import type { ThreadInfo } from '@inkeep/open-knowledge-core/acp/thread-protocol';
+import { cleanup, fireEvent, render as rtlRender, screen, within } from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
+import { afterEach, describe, expect, test, vi } from 'vitest';
+import { TooltipProvider } from '@/components/ui/tooltip';
+import type {
+ RenderedItem,
+ RenderedTerminal,
+ ThreadRenderModel,
+} from '@/lib/acp/thread-event-model';
+
+// ThreadView renders Radix Tooltips (the context-usage ring, the follow
+// toggle). The app installs the single TooltipProvider at its root (main.tsx),
+// so mount tests must supply one or Radix throws "`Tooltip` must be used
+// within `TooltipProvider`".
+const render = (ui: Parameters<typeof rtlRender>[0]) => rtlRender(ui, { wrapper: TooltipProvider });
+
+let model: ThreadRenderModel | null = null;
+const respondPermission = vi.fn((_threadId: string, _requestId: string, _outcome: unknown) => {});
+const setConfigOption = vi.fn(
+ (_threadId: string, _configId: string, _value: string | boolean) => {},
+);
+const setMode = vi.fn((_threadId: string, _modeId: string) => {});
+
+vi.doMock('@/lib/acp/thread-client', () => ({
+ getAgentThreadClient: () => ({
+ respondPermission,
+ respondRuntimeConsent: () => {},
+ cancel: () => {},
+ prompt: () => {},
+ setMode,
+ setConfigOption,
+ closeThread: () => {},
+ createThread: async () => {
+ throw new Error('unused');
+ },
+ resumeThread: async () => {
+ throw new Error('unused');
+ },
+ }),
+ ThreadResumeError: class ThreadResumeError extends Error {
+ readonly code: string;
+ constructor(code: string, message: string) {
+ super(message);
+ this.code = code;
+ }
+ },
+ useAgentThread: () => ({ info: undefined, events: [], lastSeq: 5 }),
+ useAgentThreadModel: () => model,
+}));
+
+vi.doMock('@/editor/DocumentContext', () => ({
+ useDocumentContext: () => ({ systemProvider: null }),
+}));
+
+vi.doMock('@/lib/use-workspace', () => ({
+ useWorkspace: () => null,
+}));
+
+// Markdown rendering is covered by AgentMarkdown.dom.test.tsx; keep this
+// suite off the streamdown pipeline.
+vi.doMock('@/components/acp/AgentMarkdown', () => ({
+ AgentMarkdown: ({ text }: { text: string }) => <div>{text}</div>,
+}));
+
+const { ThreadView } = await import('./ThreadView');
+
+function makeInfo(overrides?: Partial<ThreadInfo>): ThreadInfo {
+ return {
+ threadId: 'thread-1',
+ agent: { id: 'claude', name: 'Claude Agent', source: 'registry' },
+ title: 'Test thread',
+ status: 'running',
+ createdAt: 1,
+ lastActivityAt: 2,
+ lastSeq: 5,
+ archived: false,
+ ...overrides,
+ };
+}
+
+function makeModel(overrides?: Partial<ThreadRenderModel>): ThreadRenderModel {
+ return {
+ items: [],
+ plan: [],
+ turnActive: true,
+ tokenUsage: null,
+ terminals: {},
+ ...overrides,
+ };
+}
+
+function toolCall(overrides?: Partial<Extract<RenderedItem, { kind: 'tool_call' }>>) {
+ return {
+ kind: 'tool_call' as const,
+ toolCallId: 'c1',
+ title: 'Run tests',
+ toolKind: 'execute',
+ status: 'in_progress' as const,
+ diffs: [],
+ terminalIds: [],
+ content: [],
+ locations: [],
+ rawInput: undefined,
+ ...overrides,
+ };
+}
+
+function permission(overrides?: Partial<Extract<RenderedItem, { kind: 'permission' }>>) {
+ return {
+ kind: 'permission' as const,
+ requestId: 'r1',
+ title: 'Run npm test?',
+ toolKind: 'execute',
+ options: [{ optionId: 'yes', name: 'Allow', kind: 'allow_once' }],
+ resolved: null,
+ ...overrides,
+ };
+}
+
+afterEach(() => {
+ cleanup();
+ respondPermission.mockClear();
+ setConfigOption.mockClear();
+ setMode.mockClear();
+ model = null;
+});
+
+describe('ThreadView agent settings', () => {
+ test('groups agent-advertised selectors and booleans into one settings menu', async () => {
+ render(
+ <ThreadView
+ info={makeInfo({
+ status: 'ready',
+ configOptions: [
+ {
+ id: 'model',
+ name: 'Model',
+ category: 'model',
+ type: 'select',
+ currentValue: 'sonnet',
+ options: [
+ { value: 'sonnet', name: 'Sonnet' },
+ { value: 'opus', name: 'Opus' },
+ ],
+ },
+ {
+ id: 'effort',
+ name: 'Reasoning effort',
+ category: 'thought_level',
+ type: 'select',
+ currentValue: 'medium',
+ options: [
+ { value: 'medium', name: 'Medium' },
+ { value: 'high', name: 'High' },
+ ],
+ },
+ {
+ id: 'fast',
+ name: 'Fast mode',
+ category: 'model_config',
+ type: 'boolean',
+ currentValue: false,
+ },
+ ],
+ })}
+ />,
+ );
+
+ const trigger = screen.getByRole('button', { name: 'Agent settings' });
+ const follow = screen.getByRole('button', { name: "Follow the agent's edits" });
+ expect(screen.queryByTestId('agent-thread-agent-name')).toBeNull();
+ expect(trigger.textContent).toContain('Sonnet');
+ // The settings trigger now lives in the composer's bottom bar, after the
+ // header's follow toggle in document order.
+ expect(follow.compareDocumentPosition(trigger) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();
+ // The menu (and its submenu rows) mount only once the menu is opened.
+ expect(screen.queryByTestId('agent-thread-config-model')).toBeNull();
+
+ await userEvent.click(trigger);
+ // Each multi-value select is a submenu row summarizing its current value
+ // (testids key off option.id); the boolean is an inline menuitemcheckbox.
+ const modelRow = screen.getByTestId('agent-thread-config-model');
+ expect(modelRow.textContent).toContain('Sonnet');
+ const effortRow = screen.getByTestId('agent-thread-config-effort');
+ expect(effortRow.textContent).toContain('Medium');
+
+ // Fast mode is an inline checkbox row — clicking it toggles (menu stays open).
+ const fastRow = screen.getByTestId('agent-thread-config-fast');
+ expect(fastRow.textContent).toContain('Fast mode');
+ expect(fastRow.getAttribute('aria-checked')).toBe('false');
+ await userEvent.click(fastRow);
+ expect(setConfigOption).toHaveBeenCalledWith('thread-1', 'fast', true);
+
+ // Open the Model submenu and pick Opus. Radix menu items select on the
+ // `click` event (handleSelect), which fireEvent dispatches directly;
+ // userEvent's pointer sequence instead trips Radix's submenu grace logic
+ // and never fires the RadioGroup's onValueChange.
+ await userEvent.click(modelRow);
+ fireEvent.click(await screen.findByTestId('agent-thread-config-option-opus'));
+ expect(setConfigOption).toHaveBeenCalledWith('thread-1', 'model', 'opus');
+ });
+
+ test('includes the legacy ACP mode selector when no mode config option is advertised', async () => {
+ render(
+ <ThreadView
+ info={makeInfo({
+ status: 'ready',
+ modes: {
+ currentModeId: 'code',
+ availableModes: [
+ { id: 'ask', name: 'Ask' },
+ { id: 'code', name: 'Code' },
+ ],
+ },
+ })}
+ />,
+ );
+
+ await userEvent.click(screen.getByRole('button', { name: 'Agent settings' }));
+ // Legacy modes render as an "Agent mode" submenu (synthetic id 'legacy-mode');
+ // open it and pick Ask. fireEvent for the radio select — see the Model
+ // submenu note above on why userEvent doesn't fire onValueChange.
+ await userEvent.click(screen.getByTestId('agent-thread-config-legacy-mode'));
+ fireEvent.click(await screen.findByTestId('agent-thread-config-option-ask'));
+ expect(setMode).toHaveBeenCalledWith('thread-1', 'ask');
+ });
+});
+
+describe('ThreadView terminal card', () => {
+ const terminal = (overrides?: Partial<RenderedTerminal>): RenderedTerminal => ({
+ terminalId: 't1',
+ command: 'npm',
+ args: ['test'],
+ output: 'ok 12 tests\n',
+ truncated: false,
+ exit: { exitCode: 0, signal: null },
+ ...overrides,
+ });
+
+ test('renders command line, output, and a neutral exit-0 badge', async () => {
+ model = makeModel({
+ items: [toolCall({ terminalIds: ['t1'], status: 'completed' })],
+ terminals: { t1: terminal() },
+ turnActive: false,
+ });
+ render(<ThreadView info={makeInfo({ status: 'ready' })} />);
+ // Completed cards start collapsed — expand to reach the body.
+ await userEvent.click(screen.getByRole('button', { name: /Run tests/ }));
+ const card = screen.getByTestId('agent-thread-terminal');
+ expect(card.textContent).toContain('npm test');
+ expect(card.textContent).toContain('ok 12 tests');
+ expect(screen.getByTestId('agent-thread-terminal-exit').textContent).toBe('exit 0');
+ });
+
+ test('a failing command shows a destructive exit badge; ANSI is stripped', () => {
+ model = makeModel({
+ items: [toolCall({ terminalIds: ['t1'] })],
+ terminals: {
+ t1: terminal({
+ output: '\x1b[31mFAIL\x1b[0m assertion',
+ exit: { exitCode: 3, signal: null },
+ }),
+ },
+ });
+ render(<ThreadView info={makeInfo()} />);
+ const badge = screen.getByTestId('agent-thread-terminal-exit');
+ expect(badge.textContent).toBe('exit 3');
+ const card = screen.getByTestId('agent-thread-terminal');
+ expect(card.textContent).toContain('FAIL assertion');
+ expect(card.textContent).not.toContain('[31m');
+ });
+
+ test('a still-running terminal shows no exit badge', () => {
+ model = makeModel({
+ items: [toolCall({ terminalIds: ['t1'] })],
+ terminals: { t1: terminal({ exit: null }) },
+ });
+ render(<ThreadView info={makeInfo()} />);
+ expect(screen.getByTestId('agent-thread-terminal').textContent).toContain('running');
+ expect(screen.queryByTestId('agent-thread-terminal-exit')).toBeNull();
+ });
+});
+
+describe('ThreadView inline diff', () => {
+ test('unchanged lines render once as context, not as remove+add pairs', () => {
+ model = makeModel({
+ items: [
+ toolCall({
+ status: 'in_progress',
+ diffs: [{ path: 'notes.md', oldText: 'same\nold\n', newText: 'same\nnew\n' }],
+ }),
+ ],
+ });
+ render(<ThreadView info={makeInfo()} />);
+ const transcript = screen.getByTestId('agent-thread-transcript');
+ const occurrences = (transcript.textContent?.match(/same/g) ?? []).length;
+ expect(occurrences).toBe(1);
+ expect(transcript.textContent).toContain('- old');
+ expect(transcript.textContent).toContain('+ new');
+ });
+
+ test('long unchanged runs collapse into a gap row', () => {
+ const lines = Array.from({ length: 30 }, (_, i) => `line ${i}`).join('\n');
+ model = makeModel({
+ items: [
+ toolCall({
+ status: 'in_progress',
+ diffs: [{ path: 'big.md', oldText: `${lines}\nend`, newText: `${lines}\nEND` }],
+ }),
+ ],
+ });
+ render(<ThreadView info={makeInfo()} />);
+ expect(screen.getByTestId('agent-thread-transcript').textContent).toContain('unchanged lines');
+ });
+});
+
+describe('ThreadView permissions', () => {
+ test('stacks choices in least-privilege order with one primary action', () => {
+ model = makeModel({
+ items: [
+ permission({
+ options: [
+ {
+ optionId: 'always',
+ name: 'Always allow all mcp__open-knowledge__exec',
+ kind: 'allow_always',
+ },
+ { optionId: 'yes', name: 'Allow', kind: 'allow_once' },
+ { optionId: 'no', name: 'Reject', kind: 'reject_once' },
+ ],
+ }),
+ ],
+ });
+ render(<ThreadView info={makeInfo({ status: 'awaiting_permission' })} />);
+
+ const card = screen.getByTestId('agent-thread-permission');
+ const buttons = within(card).getAllByRole('button');
+ expect(buttons.map((button) => button.textContent)).toEqual([
+ 'Allow',
+ 'Always allow all mcp__open-knowledge__exec',
+ 'Deny',
+ ]);
+ expect(buttons.map((button) => button.getAttribute('data-variant'))).toEqual([
+ 'default',
+ 'outline',
+ 'outline',
+ ]);
+ });
+
+ test('clicking an offered option approves with that optionId (selected outcome)', async () => {
+ model = makeModel({ items: [permission()] });
+ render(<ThreadView info={makeInfo({ status: 'awaiting_permission' })} />);
+ await userEvent.click(screen.getByRole('button', { name: 'Allow' }));
+ expect(respondPermission).toHaveBeenCalledWith('thread-1', 'r1', {
+ kind: 'selected',
+ optionId: 'yes',
+ });
+ });
+
+ test('adds an explicit Deny when the agent offers no reject option, wired to the cancelled outcome', async () => {
+ model = makeModel({ items: [permission()] });
+ render(<ThreadView info={makeInfo({ status: 'awaiting_permission' })} />);
+ await userEvent.click(screen.getByTestId('agent-thread-permission-deny'));
+ expect(respondPermission).toHaveBeenCalledWith('thread-1', 'r1', { kind: 'cancelled' });
+ });
+
+ test('offers no extra Deny when the agent already has a reject option', () => {
+ model = makeModel({
+ items: [
+ permission({
+ options: [
+ { optionId: 'yes', name: 'Allow', kind: 'allow_once' },
+ { optionId: 'no', name: 'Reject', kind: 'reject_once' },
+ ],
+ }),
+ ],
+ });
+ render(<ThreadView info={makeInfo({ status: 'awaiting_permission' })} />);
+ expect(screen.queryByTestId('agent-thread-permission-deny')).toBeNull();
+ });
+
+ test("summarizes a chosen reject option as denied, never 'Approved'", () => {
+ model = makeModel({
+ items: [
+ permission({
+ options: [
+ { optionId: 'yes', name: 'Allow', kind: 'allow_once' },
+ { optionId: 'no', name: 'Reject', kind: 'reject_once' },
+ ],
+ resolved: { optionId: 'no', auto: false },
+ }),
+ ],
+ turnActive: false,
+ });
+ render(<ThreadView info={makeInfo({ status: 'ready' })} />);
+ const outcome = screen.getByTestId('agent-thread-permission-outcome');
+ expect(outcome.textContent).toContain('Denied');
+ expect(outcome.textContent).not.toContain('Approved');
+ });
+
+ test('an unresolved request on a dead turn renders inert (no buttons)', () => {
+ model = makeModel({ items: [permission()], turnActive: false });
+ render(<ThreadView info={makeInfo({ status: 'exited' })} />);
+ const card = screen.getByTestId('agent-thread-permission');
+ expect(card.querySelector('button')).toBeNull();
+ expect(card.textContent).toContain('no longer active');
+ });
+});
+
+describe('ThreadView status + usage', () => {
+ test("shows 'Waiting for your approval' instead of the working spinner while parked", () => {
+ model = makeModel({ items: [permission()] });
+ render(<ThreadView info={makeInfo({ status: 'awaiting_permission' })} />);
+ expect(screen.getByTestId('agent-thread-awaiting-permission').textContent).toContain(
+ 'Waiting for your approval',
+ );
+ });
+
+ test('renders the context-usage ring with a percentage and compact token counts in its label', () => {
+ model = makeModel({ tokenUsage: { used: 12_345, size: 200_000 } });
+ render(<ThreadView info={makeInfo({ status: 'ready' })} />);
+ const usage = screen.getByTestId('agent-thread-usage');
+ const label = usage.getAttribute('aria-label') ?? '';
+ expect(label).toContain('6%');
+ expect(label).toContain('12k');
+ expect(label).toContain('200k');
+ });
+
+ test('shows no usage ring when the agent reports usage but no context size', () => {
+ // Without a size there is no fill to draw — the ring is meaningless.
+ model = makeModel({ tokenUsage: { used: 500, size: undefined } });
+ render(<ThreadView info={makeInfo({ status: 'ready' })} />);
+ expect(screen.queryByTestId('agent-thread-usage')).toBeNull();
+ });
+
+ test('no ring at all until the agent reports usage', () => {
+ model = makeModel();
+ render(<ThreadView info={makeInfo({ status: 'ready' })} />);
+ expect(screen.queryByTestId('agent-thread-usage')).toBeNull();
+ });
+});
+
+describe('ThreadView raw input', () => {
+ test('collapses raw tool input by default and reveals it on request', async () => {
+ model = makeModel({
+ items: [toolCall({ rawInput: { docName: 'notes/today', position: 'append' } })],
+ });
+ render(<ThreadView info={makeInfo()} />);
+ const block = screen.getByTestId('agent-thread-tool-raw-input');
+ const trigger = screen.getByRole('button', { name: 'Input' });
+ expect(trigger.getAttribute('aria-expanded')).toBe('false');
+ expect(block.textContent).not.toContain('notes/today');
+
+ await userEvent.click(trigger);
+ expect(trigger.getAttribute('aria-expanded')).toBe('true');
+ expect(block.textContent).toContain('notes/today');
+ });
+
+ test('an empty rawInput object renders no input block', () => {
+ model = makeModel({ items: [toolCall({ rawInput: {} })] });
+ render(<ThreadView info={makeInfo()} />);
+ expect(screen.queryByTestId('agent-thread-tool-raw-input')).toBeNull();
+ });
+});
diff --git a/packages/app/src/components/acp/ThreadView.tsx b/packages/app/src/components/acp/ThreadView.tsx
new file mode 100644
index 000000000..49e6d2615
--- /dev/null
+++ b/packages/app/src/components/acp/ThreadView.tsx
@@ -0,0 +1,1669 @@
+/**
+ * Renders one ACP agent thread: the message/tool-call transcript, the live
+ * plan checklist, inline permission prompts, a mode picker, and the prompt
+ * composer with cancel. UX reference: Zed's agent panel — a single scrolling
+ * transcript of turns with tool calls shown as collapsible cards.
+ *
+ * All copy routes through Lingui; every interactive primitive is a shadcn
+ * component (this subtree is NOT the ProseMirror-exempt editor tree).
+ */
+
+import type {
+ SessionConfigOption,
+ ThreadInfo,
+} from '@inkeep/open-knowledge-core/acp/thread-protocol';
+import { useLingui } from '@lingui/react/macro';
+import {
+ ArrowUp,
+ Check,
+ ChevronDown,
+ ChevronRight,
+ CircleDot,
+ Download,
+ FileText,
+ Loader2,
+ MousePointer2,
+ Search,
+ Sparkles,
+ Square,
+ SquarePen,
+ Terminal as TerminalIcon,
+ Trash2,
+ Wrench,
+} from 'lucide-react';
+import {
+ Fragment,
+ type ReactNode,
+ useEffect,
+ useId,
+ useLayoutEffect,
+ useRef,
+ useState,
+} from 'react';
+import { focusComposerInputOnCardPointer } from '@/components/focus-composer-on-card-pointer';
+import { useOptionalPageList } from '@/components/PageListContext';
+import { Badge } from '@/components/ui/badge';
+import { Button } from '@/components/ui/button';
+import { Checkbox } from '@/components/ui/checkbox';
+import {
+ DropdownMenu,
+ DropdownMenuCheckboxItem,
+ DropdownMenuContent,
+ DropdownMenuLabel,
+ DropdownMenuRadioGroup,
+ DropdownMenuRadioItem,
+ DropdownMenuSub,
+ DropdownMenuSubContent,
+ DropdownMenuSubTrigger,
+ DropdownMenuTrigger,
+} from '@/components/ui/dropdown-menu';
+import { Skeleton } from '@/components/ui/skeleton';
+import { Switch } from '@/components/ui/switch';
+import { Textarea } from '@/components/ui/textarea';
+import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip';
+import { useDocumentContext } from '@/editor/DocumentContext';
+import { computeDiffRows } from '@/lib/acp/inline-diff';
+import { renderTerminalText } from '@/lib/acp/terminal-text';
+import {
+ getAgentThreadClient,
+ ThreadResumeError,
+ useAgentThread,
+ useAgentThreadModel,
+} from '@/lib/acp/thread-client';
+import {
+ type RenderedItem,
+ type RenderedTerminal,
+ type RenderedToolCall,
+ resolvePermissionOutcome,
+} from '@/lib/acp/thread-event-model';
+import { docNameFromHash, hashFromDocName } from '@/lib/doc-hash';
+import { useWorkspace } from '@/lib/use-workspace';
+import { cn } from '@/lib/utils';
+import { AgentMarkdown } from './AgentMarkdown';
+import { latestFollowTarget, loadFollowFilePref, saveFollowFilePref } from './follow-file';
+import { appendPresenceWrite, latestAgentWrite, type PresenceWrite } from './presence-follow';
+import { RegisteredAgentIcon } from './RegisteredAgentIcon';
+
+/**
+ * Stop sends ACP `session/cancel` — a courtesy the agent may ignore while it
+ * keeps generating (and billing). Past this window the view stops pretending
+ * and offers the force-quit escape hatch.
+ */
+const CANCEL_STALL_MS = 10_000;
+
+const TOOL_ICONS: Record<string, typeof Wrench> = {
+ read: FileText,
+ edit: SquarePen,
+ delete: Trash2,
+ search: Search,
+ execute: TerminalIcon,
+ fetch: Search,
+ think: Sparkles,
+};
+
+/** Display name for an agent — drops a trailing "Agent" so it reads as the brand
+ * ("Claude Agent" → "Claude"). */
+function agentDisplayName(name: string): string {
+ return name.replace(/\s+Agent$/i, '');
+}
+
+export function ThreadView({ info }: { info: ThreadInfo }): ReactNode {
+ const { t } = useLingui();
+ const state = useAgentThread(info.threadId);
+ const client = getAgentThreadClient();
+ const workspace = useWorkspace();
+ const [draft, setDraft] = useState('');
+ const [followFile, setFollowFile] = useState(loadFollowFilePref);
+ const scrollRef = useRef<HTMLDivElement>(null);
+ const atBottomRef = useRef(true);
+ // Follow-the-file bookkeeping: `initialSeqRef` marks the event log position
+ // at mount so a replayed history (reload, tab switch) never yanks the
+ // editor around — only events that arrive live do. `lastFollowedRef`
+ // dedupes so each target navigates once.
+ const initialSeqRef = useRef<number | null>(null);
+ const lastFollowedRef = useRef<string | null>(null);
+
+ // Incrementally folded in the store — never re-fold `state.events` here;
+ // the per-render full fold was O(transcript) per streamed chunk.
+ const model = useAgentThreadModel(info.threadId);
+ const status = info.status;
+ const archived = info.archived === true;
+ // An archived transcript can end mid-turn (server crash while streaming) —
+ // never let the fold's stale turn state drive the running UI.
+ const turnActive = model?.turnActive === true && !archived;
+ const [resumePending, setResumePending] = useState(false);
+ const [resumeError, setResumeError] = useState<ThreadResumeError | null>(null);
+ const canPrompt = archived ? !resumePending : status === 'ready' && !turnActive;
+ // Command-derived follow targets (exec `cat foo.md`) only navigate to docs
+ // that exist — a read of a missing file would open a blank create-on-open
+ // tab. Skipped while the page list is still loading (unknown ≠ missing).
+ // Optional variant: the dock renders in hosts/tests without the provider.
+ const pageList = useOptionalPageList();
+ const pages = pageList !== null && !pageList.loading ? pageList.pages : null;
+ const followOptions =
+ pages !== null ? { commandTargetExists: (docName: string) => pages.has(docName) } : {};
+ const transcriptFollowTarget =
+ model !== null ? latestFollowTarget(model.items, workspace, followOptions) : null;
+
+ // Presence-derived write stream — the fallback when the transcript is
+ // informationally empty (some adapters send rawInput {} and no locations
+ // for every call; observed live with Cursor). The server refreshes
+ // `agentPresence.currentDoc` on every MCP write it executes, so this stream
+ // is authoritative regardless of what the adapter reports. Collected only
+ // while a turn is streaming; reset per turn.
+ const { systemProvider } = useDocumentContext();
+ const [presenceWrites, setPresenceWrites] = useState<ReadonlyArray<PresenceWrite>>([]);
+ useEffect(() => {
+ if (!turnActive) {
+ setPresenceWrites([]);
+ return;
+ }
+ const awareness: unknown = systemProvider?.awareness;
+ const observe = () => {
+ const write = latestAgentWrite(awareness, Date.now());
+ if (write !== null) setPresenceWrites((previous) => appendPresenceWrite(previous, write));
+ };
+ observe();
+ const listenable =
+ typeof awareness === 'object' &&
+ awareness !== null &&
+ typeof (awareness as { on?: unknown }).on === 'function' &&
+ typeof (awareness as { off?: unknown }).off === 'function'
+ ? (awareness as {
+ on(event: 'change', handler: () => void): void;
+ off(event: 'change', handler: () => void): void;
+ })
+ : null;
+ listenable?.on('change', observe);
+ return () => listenable?.off('change', observe);
+ }, [turnActive, systemProvider]);
+
+ // The transcript wins when it carries targets at all (richer + proven for
+ // adapters that populate rawInput/locations); presence covers the rest.
+ const followTarget =
+ transcriptFollowTarget ??
+ (presenceWrites.length > 0 ? (presenceWrites[presenceWrites.length - 1]?.doc ?? null) : null);
+ const lastSeq = state?.lastSeq ?? null;
+ const [cancelPending, setCancelPending] = useState(false);
+ const [cancelStalled, setCancelStalled] = useState(false);
+
+ // The turn actually ended — Stop worked (or the thread died with it).
+ useEffect(() => {
+ if (!turnActive) {
+ setCancelPending(false);
+ setCancelStalled(false);
+ }
+ }, [turnActive]);
+
+ useEffect(() => {
+ if (!cancelPending || !turnActive) return;
+ const timer = setTimeout(() => setCancelStalled(true), CANCEL_STALL_MS);
+ return () => clearTimeout(timer);
+ }, [cancelPending, turnActive]);
+
+ const requestCancel = (): void => {
+ client.cancel(info.threadId);
+ setCancelPending(true);
+ };
+
+ useEffect(() => {
+ if (lastSeq !== null && initialSeqRef.current === null) initialSeqRef.current = lastSeq;
+ }, [lastSeq]);
+
+ // Follow the agent's file: navigate the editor to the doc the agent is
+ // working on, as it works. Live events only (see initialSeqRef above), and
+ // only while a turn is streaming — an idle thread never steals navigation.
+ useEffect(() => {
+ if (!followFile || followTarget === null) return;
+ if (!turnActive) return;
+ if (initialSeqRef.current === null || lastSeq === null || lastSeq <= initialSeqRef.current) {
+ return;
+ }
+ if (lastFollowedRef.current === followTarget) return;
+ lastFollowedRef.current = followTarget;
+ if (docNameFromHash(window.location.hash) === followTarget) return;
+ window.location.assign(hashFromDocName(followTarget));
+ }, [followFile, followTarget, turnActive, lastSeq]);
+
+ const toggleFollow = (): void => {
+ const next = !followFile;
+ setFollowFile(next);
+ saveFollowFilePref(next);
+ // Re-arm on re-enable so the current target is navigated to immediately.
+ if (next) {
+ lastFollowedRef.current = null;
+ }
+ };
+
+ // Keep the transcript pinned to the bottom while the user hasn't scrolled up.
+ // `lastSeq` is the trigger (a new event landed), not a value read in the body,
+ // so it reads as an "unnecessary" dep to the analyzer — but dropping it makes
+ // auto-scroll stop firing on new output.
+ // biome-ignore lint/correctness/useExhaustiveDependencies: lastSeq is the render trigger for the scroll, not a body dependency
+ useLayoutEffect(() => {
+ const el = scrollRef.current;
+ if (el === null || !atBottomRef.current) return;
+ el.scrollTop = el.scrollHeight;
+ }, [state?.lastSeq]);
+
+ const onScroll = (): void => {
+ const el = scrollRef.current;
+ if (el === null) return;
+ atBottomRef.current = el.scrollHeight - el.scrollTop - el.clientHeight < 40;
+ };
+
+ // The last resume-carried message that failed — the "new thread" fallback
+ // re-sends it there. Kept out of the draft: the server's optimistic echo
+ // already shows it in the transcript, so putting it back in the composer
+ // would read as two copies.
+ const [failedPrompt, setFailedPrompt] = useState<string | null>(null);
+
+ const submit = (): void => {
+ const text = draft.trim();
+ if (text === '' || !canPrompt) return;
+ if (archived) {
+ // Type-to-resume: the send respawns the agent and reconnects the
+ // stored session; the message rides the resume op as its first turn
+ // (the server echoes it into the transcript immediately).
+ setResumePending(true);
+ setResumeError(null);
+ setFailedPrompt(null);
+ client
+ .resumeThread(info.threadId, text)
+ .catch((err) => {
+ setResumeError(
+ err instanceof ThreadResumeError
+ ? err
+ : new ThreadResumeError('internal', err instanceof Error ? err.message : String(err)),
+ );
+ setFailedPrompt(text);
+ })
+ .finally(() => setResumePending(false));
+ setDraft('');
+ atBottomRef.current = true;
+ return;
+ }
+ client.prompt(info.threadId, text);
+ setDraft('');
+ atBottomRef.current = true;
+ };
+
+ const startFreshThread = (): void => {
+ const prompt = failedPrompt ?? (draft.trim() === '' ? undefined : draft.trim());
+ setResumeError(null);
+ setFailedPrompt(null);
+ void client
+ .createThread({
+ agent: { source: info.agent.source, id: info.agent.id },
+ prompt,
+ })
+ .catch((err) => {
+ // This create bypasses launchAgentThread, so no launch toast fires —
+ // surface the failure inline the same way the resume path does, and
+ // restore the prompt so the retry keeps the user's text.
+ setResumeError(
+ err instanceof ThreadResumeError
+ ? err
+ : new ThreadResumeError('internal', err instanceof Error ? err.message : String(err)),
+ );
+ setFailedPrompt(prompt ?? null);
+ });
+ };
+
+ return (
+ <div
+ className="flex min-h-0 flex-1 flex-col text-gray-800 dark:text-gray-200"
+ data-agent-thread-root=""
+ >
+ <ThreadHeader info={info} followFile={followFile} onToggleFollow={toggleFollow} />
+ {model !== null && model.plan.length > 0 ? <PlanChecklist plan={model.plan} /> : null}
+ <div
+ ref={scrollRef}
+ onScroll={onScroll}
+ className="min-h-0 flex-1 overflow-y-auto px-3 py-2 subtle-scrollbar scroll-fade-mask"
+ data-testid="agent-thread-transcript"
+ >
+ {model === null || model.items.length === 0 ? (
+ <ThreadEmptyState status={status} archived={archived} agent={info.agent} />
+ ) : (
+ <div className="flex flex-col gap-2">
+ {model.items.map((item, index) => (
+ <ThreadItem
+ // biome-ignore lint/suspicious/noArrayIndexKey: transcript is append-only; index is stable
+ key={index}
+ item={item}
+ threadId={info.threadId}
+ // Thread liveness, not turn liveness: the server keeps an
+ // unanswered request answerable until its timeout even after
+ // the prompt settles (and some agents ask outside a turn) —
+ // only a dead thread makes answering impossible.
+ actionable={!archived && status !== 'exited' && status !== 'error'}
+ terminals={model.terminals}
+ />
+ ))}
+ {turnActive ? (
+ status === 'awaiting_permission' ? (
+ <div
+ className="flex items-center gap-2 px-1 py-1 text-amber-700 text-sm dark:text-amber-400"
+ data-testid="agent-thread-awaiting-permission"
+ >
+ <CircleDot className="size-3.5" aria-hidden="true" />
+ <span>{t`Waiting for your approval`}</span>
+ </div>
+ ) : (
+ <div
+ className="flex items-center gap-2 px-1 py-1 text-muted-foreground text-sm"
+ data-testid="agent-thread-working"
+ >
+ <Loader2 className="size-3.5 animate-spin" aria-hidden="true" />
+ <span>{t`Working…`}</span>
+ </div>
+ )
+ ) : status === 'installing' || status === 'spawning' ? (
+ // A resume respawning its agent: the optimistic message echo is
+ // already in the transcript above — show that the agent is on
+ // its way rather than a silent gap until the turn opens.
+ <div
+ className="flex items-center gap-2 px-1 py-1 text-muted-foreground text-sm"
+ data-testid="agent-thread-starting"
+ >
+ <Loader2 className="size-3.5 animate-spin" aria-hidden="true" />
+ <span>{t`Starting the agent…`}</span>
+ </div>
+ ) : null}
+ </div>
+ )}
+ </div>
+ {cancelStalled && turnActive ? (
+ <div
+ className="flex items-center gap-2 border-amber-500/30 border-t bg-amber-500/5 px-3 py-1.5 text-amber-700 text-xs dark:text-amber-400"
+ data-testid="agent-thread-cancel-stalled"
+ >
+ <span className="flex-1">
+ {t`The agent isn't stopping. Force stop closes this thread and quits the agent.`}
+ </span>
+ <Button
+ type="button"
+ size="sm"
+ variant="destructive"
+ className="h-6 text-xs"
+ onClick={() => client.closeThread(info.threadId)}
+ data-testid="agent-thread-force-stop"
+ >
+ {t`Force stop`}
+ </Button>
+ </div>
+ ) : null}
+ {archived && resumeError !== null ? (
+ <div
+ className="flex items-center gap-2 border-amber-500/30 border-t bg-amber-500/5 px-3 py-1.5 text-amber-700 text-xs dark:text-amber-400"
+ data-testid="agent-thread-resume-failed"
+ >
+ <span className="flex-1">
+ {resumeError.code === 'resume-unsupported'
+ ? t`${info.agent.name} can't continue this conversation — the transcript is kept, but the agent session is gone.`
+ : t`Couldn't resume this conversation: ${resumeError.message}`}
+ </span>
+ <Button
+ type="button"
+ size="sm"
+ variant="outline"
+ className="h-6 shrink-0 text-xs"
+ onClick={startFreshThread}
+ data-testid="agent-thread-resume-fallback-new"
+ >
+ {t`New thread with ${info.agent.name}`}
+ </Button>
+ </div>
+ ) : null}
+ <ThreadComposer
+ info={info}
+ draft={draft}
+ onDraftChange={setDraft}
+ onSubmit={submit}
+ canPrompt={canPrompt}
+ turnActive={turnActive}
+ cancelPending={cancelPending}
+ onCancel={requestCancel}
+ status={status}
+ archived={archived}
+ resumePending={resumePending}
+ usage={model?.tokenUsage ?? null}
+ />
+ </div>
+ );
+}
+
+function ThreadHeader({
+ info,
+ followFile,
+ onToggleFollow,
+}: {
+ info: ThreadInfo;
+ followFile: boolean;
+ onToggleFollow: () => void;
+}): ReactNode {
+ const { t } = useLingui();
+ return (
+ <div className="flex items-center gap-2 px-3 pb-1.5 pt-0">
+ <span className="min-w-0 truncate font-medium text-1sm">{info.title}</span>
+ {info.archived === true ? (
+ <Badge variant="gray" className="shrink-0 px-1.5 py-0 text-[10px]">
+ {t`Archived`}
+ </Badge>
+ ) : null}
+ <div className="ml-auto flex shrink-0 items-center gap-1.5">
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <Button
+ type="button"
+ variant="ghost"
+ size="icon-xs"
+ // On/off is carried by the pressed-looking accent fill (not a subtle
+ // gray shift), so the icon stays constant and just fills when active.
+ className={cn(
+ 'rounded-md',
+ followFile
+ ? 'bg-primary/10 text-primary hover:bg-primary/15 hover:text-primary'
+ : 'text-muted-foreground',
+ )}
+ aria-pressed={followFile}
+ aria-label={t`Follow the agent's edits`}
+ onClick={onToggleFollow}
+ data-testid="agent-thread-follow-toggle"
+ >
+ <MousePointer2 className="size-3.5" aria-hidden="true" />
+ </Button>
+ </TooltipTrigger>
+ <TooltipContent side="bottom">
+ {followFile ? t`Following the agent's edits` : t`Follow the agent's edits`}
+ </TooltipContent>
+ </Tooltip>
+ </div>
+ </div>
+ );
+}
+
+type SelectConfigOption = Extract<SessionConfigOption, { type: 'select' }>;
+
+function selectOptionName(option: SelectConfigOption): string {
+ for (const entry of option.options) {
+ if ('value' in entry) {
+ if (entry.value === option.currentValue) return entry.name;
+ continue;
+ }
+ const current = entry.options.find((candidate) => candidate.value === option.currentValue);
+ if (current !== undefined) return current.name;
+ }
+ return option.currentValue;
+}
+
+function hasSelectValues(option: SelectConfigOption): boolean {
+ return option.options.some((entry) => ('value' in entry ? true : entry.options.length > 0));
+}
+
+/** One stable trigger for every setting an ACP agent advertises. */
+function AgentSettingsPopover({ info }: { info: ThreadInfo }): ReactNode {
+ const { t } = useLingui();
+ const client = getAgentThreadClient();
+ const configOptions = (info.configOptions ?? []).filter(
+ (option) => option.type === 'boolean' || hasSelectValues(option),
+ );
+ const modes = info.modes;
+ // `modes` predates generalized config options. Keep it as a fallback, but
+ // never duplicate a mode the agent already exposes in `configOptions`.
+ const showLegacyModes =
+ modes != null &&
+ modes.availableModes.length > 1 &&
+ !configOptions.some((option) => option.category === 'mode');
+ if (configOptions.length === 0 && !showLegacyModes) return null;
+
+ const primarySelect =
+ configOptions.find(
+ (option): option is SelectConfigOption =>
+ option.type === 'select' && option.category === 'model',
+ ) ?? configOptions.find((option): option is SelectConfigOption => option.type === 'select');
+ const legacyModeName = showLegacyModes
+ ? modes?.availableModes.find((mode) => mode.id === modes.currentModeId)?.name
+ : undefined;
+ const triggerText =
+ primarySelect !== undefined ? selectOptionName(primarySelect) : (legacyModeName ?? t`Settings`);
+
+ return (
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <Button
+ type="button"
+ variant="ghost"
+ className="h-6 max-w-48 gap-1 rounded-md px-2 text-xs"
+ aria-label={t`Agent settings`}
+ data-testid="agent-thread-settings"
+ >
+ <span className="truncate">{triggerText}</span>
+ <ChevronDown className="size-3.5" data-icon="inline-end" aria-hidden="true" />
+ </Button>
+ </DropdownMenuTrigger>
+ {/* Hybrid menu: each multi-value select is a submenu row summarizing its
+ current value; a lone boolean stays inline. The compact top level scales
+ as agents expose more (and longer-described) options — the sprawl lives
+ in the submenus instead of stretching one flat panel. */}
+ <DropdownMenuContent align="end" className="w-60" data-testid="agent-thread-settings-popover">
+ {configOptions.map((option) =>
+ option.type === 'select' ? (
+ <ConfigSelectSub
+ key={option.id}
+ option={option}
+ onSelect={(value) => client.setConfigOption(info.threadId, option.id, value)}
+ />
+ ) : (
+ <ConfigBooleanItem
+ key={option.id}
+ option={option}
+ onCheckedChange={(value) => client.setConfigOption(info.threadId, option.id, value)}
+ />
+ ),
+ )}
+ {showLegacyModes && modes != null ? (
+ <ConfigSelectSub
+ option={{
+ id: 'legacy-mode',
+ name: t`Agent mode`,
+ category: 'mode',
+ type: 'select',
+ currentValue: modes.currentModeId,
+ options: modes.availableModes.map((mode) => ({ value: mode.id, name: mode.name })),
+ }}
+ onSelect={(modeId) => client.setMode(info.threadId, modeId)}
+ />
+ ) : null}
+ </DropdownMenuContent>
+ </DropdownMenu>
+ );
+}
+
+function ConfigSelectSub({
+ option,
+ onSelect,
+}: {
+ option: SelectConfigOption;
+ onSelect: (valueId: string) => void;
+}): ReactNode {
+ const entries: ReadonlyArray<(typeof option.options)[number]> = option.options;
+ const flat = entries.filter(
+ (entry): entry is Extract<(typeof entries)[number], { value: string }> => 'value' in entry,
+ );
+ const groups = entries.filter(
+ (entry): entry is Extract<(typeof entries)[number], { group: string }> => 'group' in entry,
+ );
+ return (
+ <DropdownMenuSub>
+ <DropdownMenuSubTrigger className="gap-2" data-testid={`agent-thread-config-${option.id}`}>
+ <span className="min-w-0 flex-1 truncate">{option.name}</span>
+ <span className="max-w-[11rem] truncate text-1sm text-muted-foreground">
+ {selectOptionName(option)}
+ </span>
+ </DropdownMenuSubTrigger>
+ {/* Cap the height so a long option list (e.g. the pr-review personas)
+ scrolls instead of spanning the whole window; still never exceeds the
+ viewport-fit height Radix computes. overscroll-contain stops the scroll
+ from chaining to the page at the list boundaries. */}
+ <DropdownMenuSubContent className="max-h-[min(22rem,var(--radix-dropdown-menu-content-available-height))] max-w-72 overscroll-contain">
+ {/* Name the flyout — orients you once a long list scrolls the parent row
+ out of view. Skip a group label that just repeats it. */}
+ <DropdownMenuLabel>{option.name}</DropdownMenuLabel>
+ <DropdownMenuRadioGroup value={option.currentValue} onValueChange={onSelect}>
+ {flat.map((entry) => (
+ <ConfigRadioItem key={entry.value} entry={entry} />
+ ))}
+ {groups.map((group) => (
+ <Fragment key={group.group}>
+ {group.name !== option.name ? (
+ <DropdownMenuLabel className="font-normal text-muted-foreground">
+ {group.name}
+ </DropdownMenuLabel>
+ ) : null}
+ {group.options.map((entry) => (
+ <ConfigRadioItem key={entry.value} entry={entry} />
+ ))}
+ </Fragment>
+ ))}
+ </DropdownMenuRadioGroup>
+ </DropdownMenuSubContent>
+ </DropdownMenuSub>
+ );
+}
+
+function ConfigRadioItem({
+ entry,
+}: {
+ entry: { value: string; name: string; description?: string | null };
+}): ReactNode {
+ return (
+ <DropdownMenuRadioItem
+ value={entry.value}
+ className="items-start"
+ data-testid={`agent-thread-config-option-${entry.value}`}
+ >
+ {/* min-w-0 lets the column shrink below the name's intrinsic width so the
+ truncate/clamp actually clip instead of stretching the submenu. */}
+ <div className="flex min-w-0 flex-col">
+ <span className="truncate">{entry.name}</span>
+ {entry.description ? (
+ // Persona descriptions are long agent-routing prompts (spawn rules,
+ // example blocks); clamp as a safety net so a verbose entry can't
+ // stretch the submenu — the gist is front-loaded anyway.
+ <span className="line-clamp-2 text-1sm text-muted-foreground">{entry.description}</span>
+ ) : null}
+ </div>
+ </DropdownMenuRadioItem>
+ );
+}
+
+function ConfigBooleanItem({
+ option,
+ onCheckedChange,
+}: {
+ option: Extract<SessionConfigOption, { type: 'boolean' }>;
+ onCheckedChange: (value: boolean) => void;
+}): ReactNode {
+ // A real `menuitemcheckbox` (keyboard-roving, `aria-checked`) owns the toggle,
+ // so the row is fully accessible. The default checkmark is hidden and a
+ // decorative Switch stands in for it — the Switch is `aria-hidden` +
+ // pointer-events-none, so it never becomes a second (invalid) menu control.
+ return (
+ <DropdownMenuCheckboxItem
+ checked={option.currentValue}
+ onCheckedChange={onCheckedChange}
+ // Keep the menu open on toggle so several settings can be flipped in one visit.
+ onSelect={(event) => event.preventDefault()}
+ className="items-start justify-between gap-4 pr-2 [&_[data-slot=dropdown-menu-checkbox-item-indicator]]:hidden"
+ data-testid={`agent-thread-config-${option.id}`}
+ >
+ <div className="flex min-w-0 flex-col">
+ <span>{option.name}</span>
+ {option.description ? (
+ <span className="text-1sm text-muted-foreground">{option.description}</span>
+ ) : null}
+ </div>
+ <Switch
+ checked={option.currentValue}
+ size="sm"
+ aria-hidden="true"
+ tabIndex={-1}
+ className="pointer-events-none mt-0.5"
+ />
+ </DropdownMenuCheckboxItem>
+ );
+}
+
+/**
+ * A minimal chat-shaped placeholder shown while a stored conversation resumes:
+ * a sent bubble on the right, an agent reply block on the left, twice over.
+ * Mirrors the transcript's real structure (skeleton-for-structured-content)
+ * without faking avatars, timestamps, or tool cards. The visible bars are
+ * decorative; a screen-reader status announces the load separately.
+ */
+function ThreadTranscriptSkeleton(): ReactNode {
+ const { t } = useLingui();
+ // Populate the live region AFTER mount so the status reads as a *change* — a
+ // region that already holds its text on first render is often not announced.
+ const [announced, setAnnounced] = useState('');
+ useEffect(() => {
+ setAnnounced(t`Loading the conversation`);
+ }, [t]);
+ return (
+ <div className="flex flex-col gap-6 pt-2">
+ <div aria-live="polite" className="sr-only" role="status">
+ {announced}
+ </div>
+ <div aria-hidden="true" className="flex flex-col gap-6">
+ <div className="flex justify-end">
+ <Skeleton className="h-12 w-3/5 rounded-2xl rounded-br-xs" />
+ </div>
+ <div className="flex flex-col gap-2">
+ <Skeleton className="h-3.5 w-11/12" />
+ <Skeleton className="h-3.5 w-4/5" />
+ <Skeleton className="h-3.5 w-2/3" />
+ </div>
+ <div className="flex justify-end">
+ <Skeleton className="h-8 w-2/5 rounded-2xl rounded-br-xs" />
+ </div>
+ <div className="flex flex-col gap-2">
+ <Skeleton className="h-3.5 w-5/6" />
+ <Skeleton className="h-3.5 w-3/4" />
+ </div>
+ </div>
+ </div>
+ );
+}
+
+function ThreadEmptyState({
+ status,
+ archived,
+ agent,
+}: {
+ status: ThreadInfo['status'];
+ archived: boolean;
+ agent: ThreadInfo['agent'];
+}): ReactNode {
+ const { t } = useLingui();
+ const agentName = agentDisplayName(agent.name);
+
+ // Resuming a stored conversation: show the transcript's shape, not a bare line.
+ if (archived) {
+ return <ThreadTranscriptSkeleton />;
+ }
+
+ // Ready and idle: a quiet, faded agent mark + "Ask <agent>". Deliberately
+ // minimal — no starter-prompt scaffolding (project shapes vary too much to
+ // suggest reliably) and no illustration (chat surfaces stay text/icon-first).
+ if (status === 'ready') {
+ return (
+ <div className="flex h-full flex-col items-center justify-center gap-3 px-6 text-center">
+ <RegisteredAgentIcon
+ agentId={agent.id}
+ iconUrl={agent.iconUrl}
+ className="size-12 opacity-25 grayscale"
+ />
+ <p className="text-muted-foreground text-sm">{t`Ask ${agentName}`}</p>
+ </div>
+ );
+ }
+
+ // Auth is an action prompt, not a wait — keep a plain line pointing at the
+ // sign-in notice rendered below the transcript.
+ if (status === 'auth_required') {
+ return (
+ <div className="flex h-full items-center justify-center px-6 text-center text-muted-foreground text-sm">
+ {t`This agent needs you to sign in first — see the notice below.`}
+ </div>
+ );
+ }
+
+ // Agent still coming up: the faded agent mark with a shimmering status line so
+ // the wait reads as "working". `shimmer` is a text-clipped gradient sweep, so
+ // it animates the label; the icon stays faded (an SVG has no text to clip).
+ const loadingMessage =
+ status === 'installing'
+ ? t`Installing ${agentName}…`
+ : status === 'spawning'
+ ? t`Starting ${agentName}…`
+ : t`Connecting to ${agentName}…`;
+ return (
+ <div className="flex h-full flex-col items-center justify-center gap-3 px-6 text-center">
+ <RegisteredAgentIcon
+ agentId={agent.id}
+ iconUrl={agent.iconUrl}
+ className="size-12 opacity-25 grayscale"
+ />
+ <p className="shimmer text-sm">{loadingMessage}</p>
+ </div>
+ );
+}
+
+function PlanChecklist({ plan }: { plan: { content: string; status?: string }[] }): ReactNode {
+ const { t } = useLingui();
+ const [open, setOpen] = useState(true);
+ const done = plan.filter((p) => p.status === 'completed').length;
+ return (
+ <div className="border-border/60 border-b bg-muted/30 px-3 py-1.5">
+ <Button
+ type="button"
+ variant="ghost"
+ size="sm"
+ className="h-auto w-full justify-start gap-1.5 p-0 font-medium text-muted-foreground text-xs hover:bg-transparent"
+ onClick={() => setOpen((o) => !o)}
+ aria-expanded={open}
+ >
+ {open ? (
+ <ChevronDown className="size-3.5" aria-hidden="true" />
+ ) : (
+ <ChevronRight className="size-3.5" aria-hidden="true" />
+ )}
+ <span>{t`Plan (${done}/${plan.length})`}</span>
+ </Button>
+ {open ? (
+ <ul className="mt-1 flex flex-col gap-0.5">
+ {plan.map((entry, index) => (
+ <li
+ // biome-ignore lint/suspicious/noArrayIndexKey: plan is a positional list
+ key={index}
+ className={cn(
+ 'flex items-start gap-1.5 text-xs',
+ entry.status === 'completed' && 'text-muted-foreground line-through',
+ )}
+ >
+ <span aria-hidden="true">{entry.status === 'completed' ? '☑' : '☐'}</span>
+ <span>{entry.content}</span>
+ </li>
+ ))}
+ </ul>
+ ) : null}
+ </div>
+ );
+}
+
+function ThreadItem({
+ item,
+ threadId,
+ actionable,
+ terminals,
+}: {
+ item: RenderedItem;
+ threadId: string;
+ /** The thread can still take answers (live agent, not archived/dead). */
+ actionable: boolean;
+ terminals: Record<string, RenderedTerminal>;
+}): ReactNode {
+ switch (item.kind) {
+ case 'message':
+ return <MessageBubble item={item} />;
+ case 'tool_call':
+ return <ToolCallCard call={item} terminals={terminals} />;
+ case 'permission':
+ return <PermissionPrompt item={item} threadId={threadId} actionable={actionable} />;
+ case 'runtime_consent':
+ return <RuntimeConsentPrompt item={item} threadId={threadId} />;
+ case 'notice':
+ return (
+ <div
+ className={cn(
+ 'rounded-md border px-2 py-1.5 text-xs',
+ item.tone === 'error'
+ ? 'border-red-500/30 bg-red-500/5 text-red-600 dark:text-red-400'
+ : 'border-amber-500/30 bg-amber-500/5 text-amber-700 dark:text-amber-400',
+ )}
+ data-testid="agent-thread-notice"
+ >
+ {item.text}
+ </div>
+ );
+ }
+}
+
+function MessageBubble({ item }: { item: Extract<RenderedItem, { kind: 'message' }> }): ReactNode {
+ if (item.role === 'thought') {
+ return <div className="px-1 text-muted-foreground text-xs italic">{item.text}</div>;
+ }
+ const isUser = item.role === 'user';
+ return (
+ <div
+ className={cn(
+ 'wrap-break-word text-sm text-foreground',
+ isUser
+ ? // Sent-message bubble: light-gray fill, right-aligned, with the
+ // squared bottom-right corner (the sender-side "tail"). Extra bottom
+ // margin (on top of the transcript's gap-2) enlarges only the turn
+ // boundary — the gap before the agent's response starts — while the
+ // response's own items (reply text + its tool calls) stay tight.
+ 'my-3 ml-auto max-w-[85%] whitespace-pre-wrap rounded-2xl rounded-br-xs bg-muted px-3 py-1.5'
+ : // Agent reply reads as full-width prose — no bubble, no fill.
+ 'w-full',
+ )}
+ data-testid={isUser ? 'agent-thread-user-message' : 'agent-thread-agent-message'}
+ >
+ {isUser ? item.text : <AgentMarkdown text={item.text} />}
+ </div>
+ );
+}
+
+/**
+ * The adapter-reported raw tool input, pretty-printed for the card body —
+ * "what exactly is it about to run". Null for absent/empty inputs (nothing
+ * worth a block) and bounded so a huge argument can't flood the transcript.
+ */
+function formatRawInput(rawInput: unknown): string | null {
+ if (rawInput === undefined || rawInput === null) return null;
+ if (
+ typeof rawInput === 'object' &&
+ !Array.isArray(rawInput) &&
+ Object.keys(rawInput).length === 0
+ ) {
+ return null;
+ }
+ let text: string | undefined;
+ try {
+ text = JSON.stringify(rawInput, null, 1);
+ } catch {
+ return null;
+ }
+ if (text === undefined) return null;
+ return text.length > 2_000 ? `${text.slice(0, 2_000)}…` : text;
+}
+
+function ToolCallCard({
+ call,
+ terminals,
+}: {
+ call: RenderedToolCall;
+ terminals: Record<string, RenderedTerminal>;
+}): ReactNode {
+ const [open, setOpen] = useState(call.status !== 'completed');
+ const Icon = TOOL_ICONS[call.toolKind] ?? Wrench;
+ const callTerminals = call.terminalIds
+ .map((id) => terminals[id])
+ .filter((terminal): terminal is RenderedTerminal => terminal !== undefined);
+ const rawInput = formatRawInput(call.rawInput);
+ const hasBody =
+ call.diffs.length > 0 ||
+ call.content.length > 0 ||
+ call.locations.length > 0 ||
+ callTerminals.length > 0 ||
+ rawInput !== null;
+ return (
+ <div
+ className="rounded-md border border-border/60 text-xs"
+ data-testid="agent-thread-tool-call"
+ >
+ <Button
+ type="button"
+ variant="ghost"
+ size="sm"
+ className="h-auto w-full justify-start gap-1.5 rounded-md px-2 py-1.5 font-normal"
+ onClick={() => setOpen((o) => !o)}
+ disabled={!hasBody}
+ aria-expanded={open}
+ >
+ <Icon className="size-3.5 shrink-0 text-muted-foreground" aria-hidden="true" />
+ <span className="truncate">{call.title}</span>
+ <ToolStatusBadge status={call.status} />
+ </Button>
+ {open && hasBody ? (
+ <div className="flex flex-col gap-1.5 border-border/60 border-t px-2 py-1.5">
+ {call.diffs.map((diff, index) => (
+ // biome-ignore lint/suspicious/noArrayIndexKey: diffs are positional within a card
+ <InlineDiff key={index} diff={diff} />
+ ))}
+ {callTerminals.map((terminal) => (
+ <TerminalBlock key={terminal.terminalId} terminal={terminal} />
+ ))}
+ {call.content.map((text, index) => (
+ <pre
+ // biome-ignore lint/suspicious/noArrayIndexKey: content blocks are positional
+ key={index}
+ className="overflow-x-auto whitespace-pre-wrap break-words rounded bg-muted/50 px-2 py-1 font-mono text-[11px]"
+ >
+ {text}
+ </pre>
+ ))}
+ {rawInput !== null ? <RawInputBlock text={rawInput} /> : null}
+ {call.locations.length > 0 ? (
+ <div className="flex flex-wrap gap-1 text-muted-foreground">
+ {call.locations.map((loc, index) => (
+ <span
+ // biome-ignore lint/suspicious/noArrayIndexKey: locations are positional
+ key={index}
+ className="rounded bg-muted/50 px-1 py-0.5 font-mono text-[11px]"
+ >
+ {loc.path}
+ {loc.line !== undefined ? `:${loc.line}` : ''}
+ </span>
+ ))}
+ </div>
+ ) : null}
+ </div>
+ ) : null}
+ </div>
+ );
+}
+
+function ToolStatusBadge({ status }: { status: RenderedToolCall['status'] }): ReactNode {
+ const { t } = useLingui();
+ const label =
+ status === 'completed'
+ ? t`done`
+ : status === 'failed'
+ ? t`failed`
+ : status === 'in_progress'
+ ? t`running`
+ : t`pending`;
+ return (
+ <Badge
+ variant={status === 'failed' ? 'destructive' : 'secondary'}
+ className="ml-auto shrink-0 px-1.5 py-0 text-[10px]"
+ >
+ {label}
+ </Badge>
+ );
+}
+
+/** A genuine line diff (jsdiff) with long unchanged runs collapsed — enough to
+ * read a tool-call diff without the full CodeMirror MergeView (reserved for
+ * the conflict/history surfaces). */
+function InlineDiff({
+ diff,
+}: {
+ diff: { path: string; oldText: string | null; newText: string };
+}): ReactNode {
+ const { t } = useLingui();
+ const rows = computeDiffRows(diff.oldText, diff.newText);
+ return (
+ <div className="overflow-hidden rounded border border-border/60">
+ <div className="bg-muted/50 px-2 py-0.5 font-mono text-[11px] text-muted-foreground">
+ {diff.path}
+ </div>
+ <pre className="overflow-x-auto font-mono text-[11px] leading-snug">
+ {rows.map((row, index) =>
+ row.type === 'gap' ? (
+ <div
+ // biome-ignore lint/suspicious/noArrayIndexKey: diff rows are positional
+ key={index}
+ className="select-none px-2 text-muted-foreground/70"
+ >
+ {t`⋯ ${row.count} unchanged lines`}
+ </div>
+ ) : (
+ <div
+ // biome-ignore lint/suspicious/noArrayIndexKey: diff rows are positional
+ key={index}
+ className={cn(
+ 'px-2',
+ row.type === 'add' && 'bg-green-500/10 text-green-700 dark:text-green-400',
+ row.type === 'del' && 'bg-red-500/10 text-red-700 dark:text-red-400',
+ row.type === 'ctx' && 'text-muted-foreground',
+ )}
+ >
+ <span aria-hidden="true">
+ {row.type === 'add' ? '+ ' : row.type === 'del' ? '- ' : ' '}
+ </span>
+ {row.text}
+ </div>
+ ),
+ )}
+ </pre>
+ </div>
+ );
+}
+
+/** One ACP terminal embedded in a tool call: the command OK ran for the
+ * agent, its (ANSI-stripped) output, and a live/exit status badge. */
+function TerminalBlock({ terminal }: { terminal: RenderedTerminal }): ReactNode {
+ const { t } = useLingui();
+ const commandLine = [terminal.command, ...terminal.args].join(' ');
+ const text = renderTerminalText(terminal.output);
+ const exit = terminal.exit;
+ const failed = exit !== null && (exit.signal !== null || exit.exitCode !== 0);
+ return (
+ <div
+ className="overflow-hidden rounded border border-border/60"
+ data-testid="agent-thread-terminal"
+ >
+ <div className="flex items-center gap-1.5 bg-muted/50 px-2 py-0.5">
+ <TerminalIcon className="size-3 shrink-0 text-muted-foreground" aria-hidden="true" />
+ <span className="truncate font-mono text-[11px] text-muted-foreground" title={commandLine}>
+ {commandLine}
+ </span>
+ <span className="ml-auto shrink-0">
+ {exit === null ? (
+ <span className="flex items-center gap-1 text-[10px] text-muted-foreground">
+ <Loader2 className="size-3 animate-spin" aria-hidden="true" />
+ {t`running`}
+ </span>
+ ) : (
+ <Badge
+ variant={failed ? 'destructive' : 'secondary'}
+ className="px-1.5 py-0 font-mono text-[10px]"
+ data-testid="agent-thread-terminal-exit"
+ >
+ {exit.signal !== null ? exit.signal : t`exit ${exit.exitCode ?? 0}`}
+ </Badge>
+ )}
+ </span>
+ </div>
+ {text.trim() !== '' || terminal.truncated ? (
+ <pre className="max-h-64 overflow-auto whitespace-pre-wrap break-words px-2 py-1 font-mono text-[11px] leading-snug">
+ {terminal.truncated ? `${t`… earlier output trimmed`}\n` : null}
+ {text}
+ </pre>
+ ) : null}
+ </div>
+ );
+}
+
+/** The tool call's raw input — shown so the user can see what the tool was
+ * actually asked to do, not just the adapter's title for it. */
+function RawInputBlock({ text }: { text: string }): ReactNode {
+ const { t } = useLingui();
+ const [open, setOpen] = useState(false);
+ const contentId = useId();
+ return (
+ <div data-testid="agent-thread-tool-raw-input">
+ <Button
+ type="button"
+ variant="ghost"
+ size="sm"
+ className="h-auto w-full justify-start gap-1 px-0 py-0.5 text-[10px] text-muted-foreground uppercase tracking-wide hover:bg-transparent"
+ onClick={() => setOpen((value) => !value)}
+ aria-expanded={open}
+ aria-controls={contentId}
+ >
+ {open ? (
+ <ChevronDown className="size-3" aria-hidden="true" />
+ ) : (
+ <ChevronRight className="size-3" aria-hidden="true" />
+ )}
+ {t`Input`}
+ </Button>
+ {open ? (
+ <pre
+ id={contentId}
+ className="overflow-x-auto whitespace-pre-wrap break-words rounded bg-muted/30 px-2 py-1 font-mono text-[11px] text-muted-foreground"
+ >
+ {text}
+ </pre>
+ ) : null}
+ </div>
+ );
+}
+
+function PermissionPrompt({
+ item,
+ threadId,
+ actionable,
+}: {
+ item: Extract<RenderedItem, { kind: 'permission' }>;
+ threadId: string;
+ /** The thread is still live — a dead thread's prompt must not invite an answer. */
+ actionable: boolean;
+}): ReactNode {
+ const { t } = useLingui();
+ const client = getAgentThreadClient();
+ const outcome = resolvePermissionOutcome(item);
+ const pending = outcome === null;
+ const cardRef = useRef<HTMLDivElement>(null);
+ const primaryRef = useRef<HTMLButtonElement>(null);
+ // The agent's own choices may already include a refusal; only add our
+ // explicit Deny (the ACP `cancelled` outcome) when they don't — without it
+ // "no" exists only when the agent thinks to offer one.
+ const hasRejectOption = item.options.some((option) => option.kind.startsWith('reject'));
+ const options = [...item.options].sort(
+ (a, b) => permissionOptionRank(a.kind) - permissionOptionRank(b.kind),
+ );
+ // The safest useful default is a one-time grant. A persistent grant is the
+ // final focus fallback, after any refusal the agent exposes.
+ const defaultOptionId =
+ options.find((option) => option.kind === 'allow_once')?.optionId ??
+ options.find((option) => option.kind.startsWith('reject'))?.optionId ??
+ (hasRejectOption
+ ? (options.find((option) => option.kind === 'allow_always')?.optionId ?? options[0]?.optionId)
+ : undefined);
+
+ const optionVariant = (kind: (typeof options)[number]['kind']) =>
+ kind === 'allow_once' ? 'default' : 'outline';
+ const optionLabel = (option: (typeof options)[number]) =>
+ option.kind === 'reject_once' && option.name.trim().toLocaleLowerCase() === 'reject'
+ ? t`Deny`
+ : option.name;
+
+ const optionButtons = options.map((option) => (
+ <Button
+ key={option.optionId}
+ ref={option.optionId === defaultOptionId ? primaryRef : undefined}
+ type="button"
+ size="sm"
+ variant={optionVariant(option.kind)}
+ className="h-auto min-h-7 max-w-full self-start whitespace-normal text-left text-xs"
+ onClick={() =>
+ client.respondPermission(threadId, item.requestId, {
+ kind: 'selected',
+ optionId: option.optionId,
+ })
+ }
+ data-permission-kind={option.kind}
+ >
+ {optionLabel(option)}
+ </Button>
+ ));
+
+ const denyButton = !hasRejectOption ? (
+ // ACP has no first-class per-tool deny beyond the agent's own reject
+ // options; `cancelled` is the protocol's only refusal channel, and agents
+ // may treat it as cancelling the whole turn. Shown only when the agent
+ // offered no reject option, so "no" exists at all.
+ <Button
+ ref={defaultOptionId === undefined ? primaryRef : undefined}
+ type="button"
+ size="sm"
+ variant="outline"
+ className="h-7 self-start text-xs"
+ onClick={() => client.respondPermission(threadId, item.requestId, { kind: 'cancelled' })}
+ data-testid="agent-thread-permission-deny"
+ >
+ {t`Deny`}
+ </Button>
+ ) : null;
+
+ // Move focus onto the primary option when a live prompt appears — but only
+ // if focus is already inside this thread's panel (e.g. on the composer the
+ // user just typed in). A prompt landing while the user works in the editor
+ // must not steal focus from it.
+ useEffect(() => {
+ if (!pending || !actionable) return;
+ const root = cardRef.current?.closest('[data-agent-thread-root]');
+ if (root == null || !root.contains(document.activeElement)) return;
+ primaryRef.current?.focus();
+ }, [pending, actionable]);
+
+ const resolvedLabel =
+ outcome === null
+ ? null
+ : outcome.kind === 'dismissed'
+ ? // Covers timeout, Stop-cancel, and agent exit alike — don't claim a
+ // specific cause the event doesn't carry.
+ t`Not answered`
+ : outcome.kind === 'approved'
+ ? outcome.auto
+ ? t`Auto-approved`
+ : outcome.optionName !== null
+ ? t`Approved — ${outcome.optionName}`
+ : t`Approved`
+ : outcome.auto
+ ? t`Auto-denied`
+ : outcome.optionName !== null
+ ? t`Denied — ${outcome.optionName}`
+ : t`Denied`;
+
+ return (
+ <div
+ ref={cardRef}
+ className={cn(
+ 'rounded-md border px-2.5 py-2 text-sm',
+ pending && actionable
+ ? 'border-amber-500/40 bg-amber-500/5'
+ : 'border-border/60 bg-muted/20',
+ )}
+ data-testid="agent-thread-permission"
+ >
+ <div className="mb-1.5 font-medium">{item.title}</div>
+ {!pending ? (
+ <div
+ className="text-muted-foreground text-xs"
+ data-testid="agent-thread-permission-outcome"
+ >
+ {resolvedLabel}
+ </div>
+ ) : !actionable ? (
+ // Unresolved on a dead turn (crash-mid-stream archive): answering is
+ // impossible, so don't render buttons that would silently no-op.
+ <div className="text-muted-foreground text-xs">{t`This request is no longer active.`}</div>
+ ) : (
+ <div className="flex flex-col items-start gap-1.5">
+ {optionButtons}
+ {denyButton}
+ </div>
+ )}
+ </div>
+ );
+}
+
+function permissionOptionRank(
+ kind: Extract<RenderedItem, { kind: 'permission' }>['options'][number]['kind'],
+): number {
+ if (kind === 'allow_once') return 0;
+ if (kind === 'allow_always') return 1;
+ return 2;
+}
+
+/**
+ * Prompt (and progress) for OK downloading a language runtime an agent needs
+ * but the machine lacks (npx→Node.js, uvx→uv). Modeled on {@link
+ * PermissionPrompt}: the card is a retained transcript item, so it renders the
+ * same on live launch and on replay of an archived thread.
+ */
+function RuntimeConsentPrompt({
+ item,
+ threadId,
+}: {
+ item: Extract<RenderedItem, { kind: 'runtime_consent' }>;
+ threadId: string;
+}): ReactNode {
+ const { t } = useLingui();
+ const client = getAgentThreadClient();
+ const [remember, setRemember] = useState(true);
+
+ if (item.resolved === 'declined' || item.resolved === 'timeout') {
+ return (
+ <div
+ className="rounded-md border border-border/60 bg-muted/20 px-2.5 py-2 text-muted-foreground text-xs"
+ data-testid="agent-thread-runtime-consent"
+ >
+ {item.resolved === 'declined'
+ ? t`Skipped downloading ${item.displayName}.`
+ : t`The ${item.displayName} download request timed out.`}
+ </div>
+ );
+ }
+
+ if (item.resolved === 'granted') {
+ if (item.install === 'done') {
+ return (
+ <div
+ className="flex items-center gap-1.5 rounded-md border border-border/60 bg-muted/20 px-2.5 py-2 text-muted-foreground text-xs"
+ data-testid="agent-thread-runtime-consent"
+ >
+ <Check
+ className="size-3.5 shrink-0 text-green-600 dark:text-green-400"
+ aria-hidden="true"
+ />
+ <span>{t`Installed ${item.displayName} ${item.version}`}</span>
+ </div>
+ );
+ }
+ if (item.install === 'failed') {
+ return (
+ <div
+ className="rounded-md border border-border/60 bg-muted/20 px-2.5 py-2 text-muted-foreground text-xs"
+ data-testid="agent-thread-runtime-consent"
+ >
+ {t`Couldn't finish installing ${item.displayName} — see below.`}
+ </div>
+ );
+ }
+ const pct = consentPercent(item.progress);
+ return (
+ <div
+ className="rounded-md border border-border/60 bg-muted/30 px-2.5 py-2 text-xs"
+ data-testid="agent-thread-runtime-consent"
+ >
+ <div className="mb-1.5 flex items-center gap-1.5 text-muted-foreground">
+ <Loader2 className="size-3.5 shrink-0 animate-spin" aria-hidden="true" />
+ <span>{t`Downloading ${item.displayName} ${item.version}…`}</span>
+ </div>
+ <div className="h-1.5 w-full overflow-hidden rounded-full bg-muted">
+ <div
+ className="h-full rounded-full bg-primary transition-[width] duration-200"
+ style={{ width: pct !== null ? `${pct}%` : '40%' }}
+ />
+ </div>
+ {pct !== null ? (
+ <div className="mt-1 text-[11px] text-muted-foreground">{`${pct}%`}</div>
+ ) : null}
+ </div>
+ );
+ }
+
+ return (
+ <div
+ className="rounded-md border border-blue-500/40 bg-blue-500/5 px-2.5 py-2 text-sm"
+ data-testid="agent-thread-runtime-consent"
+ >
+ <div className="mb-1 flex items-center gap-1.5 font-medium">
+ <Download className="size-4 shrink-0" aria-hidden="true" />
+ <span>{t`${item.agentName} needs ${item.displayName}`}</span>
+ </div>
+ <p className="mb-2 text-muted-foreground text-xs">
+ {t`This agent runs through ${item.provides}, which isn't installed. Open Knowledge can download a private copy of ${item.displayName} ${item.version} (about ${item.approxSizeMB} MB from ${item.sourceHost}) that won't touch the rest of your system.`}
+ </p>
+ <label
+ htmlFor={`runtime-consent-remember-${item.requestId}`}
+ className="mb-2 flex w-fit items-center gap-1.5 text-muted-foreground text-xs"
+ >
+ <Checkbox
+ id={`runtime-consent-remember-${item.requestId}`}
+ checked={remember}
+ onCheckedChange={(value) => setRemember(value === true)}
+ data-testid="agent-thread-runtime-consent-remember"
+ />
+ {t`Remember this for future agents`}
+ </label>
+ <div className="flex flex-wrap gap-1.5">
+ <Button
+ type="button"
+ size="sm"
+ className="h-7 text-xs"
+ onClick={() =>
+ client.respondRuntimeConsent(threadId, item.requestId, { kind: 'granted', remember })
+ }
+ data-testid="agent-thread-runtime-consent-allow"
+ >
+ {t`Download ${item.displayName}`}
+ </Button>
+ <Button
+ type="button"
+ size="sm"
+ variant="outline"
+ className="h-7 text-xs"
+ onClick={() =>
+ client.respondRuntimeConsent(threadId, item.requestId, { kind: 'declined', remember })
+ }
+ data-testid="agent-thread-runtime-consent-decline"
+ >
+ {t`Not now`}
+ </Button>
+ </div>
+ </div>
+ );
+}
+
+function consentPercent(
+ progress: { receivedBytes: number; totalBytes: number | null } | null,
+): number | null {
+ if (progress === null || progress.totalBytes === null || progress.totalBytes <= 0) return null;
+ return Math.min(100, Math.round((progress.receivedBytes / progress.totalBytes) * 100));
+}
+
+/** Compact token count for the usage tooltip: `108k`, `1.5M`, `950`. */
+function formatCompactTokens(value: number): string {
+ const thousands = Math.round(value / 1_000);
+ // Promote to M once the rounded k would read as 1000k (e.g. 999,600 → 1M).
+ if (thousands >= 1_000) {
+ const millions = value / 1_000_000;
+ return `${millions % 1 === 0 ? millions.toFixed(0) : millions.toFixed(1)}M`;
+ }
+ if (value >= 1_000) return `${thousands}k`;
+ return String(value);
+}
+
+/**
+ * Context-window fill as a mini progress ring — the whole point is "how full",
+ * which a ring conveys at a glance where the token counts read as noise. The
+ * exact numbers move to a tooltip. Tone escalates as the window fills (amber
+ * ≥75%, red ≥90%) so "almost out of room" reads without opening the tooltip.
+ * The trigger is a real focusable button so keyboard + screen-reader users get
+ * the same figures hover users do (`label` is its accessible name).
+ */
+function ContextUsageRing({
+ used,
+ size,
+ percent,
+}: {
+ used: number;
+ size: number;
+ percent: number;
+}): ReactNode {
+ const { t } = useLingui();
+ const radius = 6;
+ const circumference = 2 * Math.PI * radius;
+ const tone =
+ percent >= 90 ? 'text-red-500' : percent >= 75 ? 'text-amber-500' : 'text-muted-foreground/60';
+ const left = 100 - percent;
+ const usedLabel = formatCompactTokens(used);
+ const sizeLabel = formatCompactTokens(size);
+ return (
+ <Tooltip>
+ <TooltipTrigger
+ aria-label={t`Context window: ${percent}% used, ${usedLabel} of ${sizeLabel} tokens`}
+ className="flex size-5 items-center justify-center rounded-full outline-none focus-visible:ring-2 focus-visible:ring-ring/50"
+ data-testid="agent-thread-usage"
+ >
+ <svg viewBox="0 0 16 16" className="size-4 -rotate-90" aria-hidden="true">
+ <circle
+ cx="8"
+ cy="8"
+ r={radius}
+ fill="none"
+ strokeWidth="2"
+ className="stroke-current text-muted-foreground/10"
+ />
+ <circle
+ cx="8"
+ cy="8"
+ r={radius}
+ fill="none"
+ strokeWidth="2"
+ strokeLinecap="round"
+ strokeDasharray={circumference}
+ strokeDashoffset={circumference * (1 - percent / 100)}
+ className={cn('stroke-current transition-[stroke-dashoffset]', tone)}
+ />
+ </svg>
+ </TooltipTrigger>
+ <TooltipContent side="top">
+ {/* Wrap the lines: the base TooltipContent is inline-flex (a row), so
+ sibling spans would render side by side without a column wrapper. */}
+ <div className="flex flex-col items-center gap-0.5 text-center">
+ <span className="text-background/60">{t`Context window:`}</span>
+ <span>{t`${percent}% used (${left}% left)`}</span>
+ <span className="tabular-nums">{t`${usedLabel} / ${sizeLabel} tokens used`}</span>
+ </div>
+ </TooltipContent>
+ </Tooltip>
+ );
+}
+
+function ThreadComposer({
+ info,
+ draft,
+ onDraftChange,
+ onSubmit,
+ canPrompt,
+ turnActive,
+ cancelPending,
+ onCancel,
+ status,
+ archived,
+ resumePending,
+ usage,
+}: {
+ info: ThreadInfo;
+ draft: string;
+ onDraftChange: (value: string) => void;
+ onSubmit: () => void;
+ canPrompt: boolean;
+ turnActive: boolean;
+ /** Stop was pressed and the turn hasn't ended yet. */
+ cancelPending: boolean;
+ onCancel: () => void;
+ status: ThreadInfo['status'];
+ archived: boolean;
+ /** A resume op is in flight (archived thread, message queued on it). */
+ resumePending: boolean;
+ /** Context-window fill the agent reported; null until it reports any. */
+ usage: { used?: number; size?: number } | null;
+}): ReactNode {
+ const { t } = useLingui();
+ const ref = useRef<HTMLTextAreaElement>(null);
+ // Naming the agent in the placeholder ("Message Claude") beats a generic
+ // "Message the agent"; strip the "Agent" suffix so it reads as the brand.
+ const agentName = agentDisplayName(info.agent.name);
+
+ // Grow with content up to a cap. `draft` is the trigger, not read in the
+ // body (the element's own scrollHeight is), so the analyzer sees it as
+ // redundant — but it is exactly what should re-run the resize.
+ // biome-ignore lint/correctness/useExhaustiveDependencies: draft is the resize trigger, not a body dependency
+ useEffect(() => {
+ const el = ref.current;
+ if (el === null) return;
+ el.style.height = 'auto';
+ el.style.height = `${Math.min(el.scrollHeight, 160)}px`;
+ }, [draft]);
+
+ const usagePercent =
+ usage !== null && usage.used !== undefined && usage.size !== undefined && usage.size > 0
+ ? Math.min(100, Math.round((usage.used / usage.size) * 100))
+ : null;
+
+ return (
+ <div className="p-2">
+ {/* Two-row field: the textarea fills the full width on top; a bottom bar
+ holds the model/agent settings (left) and the context ring + send/stop
+ (right). The wrapper owns the border + focus ring so the whole box lights
+ up on focus. Every control is a real in-flow sibling (natural Tab order,
+ own focus ring) and the send button lives on its own row, so there's no
+ reserved text gutter narrowing the input on multi-line drafts. */}
+ {/* biome-ignore lint/a11y/noStaticElementInteractions: pointer-only affordance — pressing the card's whitespace focuses the textarea; keyboard/AT users reach it via Tab. See focus-composer-on-card-pointer.ts. */}
+ <div
+ onMouseDown={(event) => focusComposerInputOnCardPointer(event, ref)}
+ className="cursor-text rounded-lg border border-input bg-transparent transition-colors focus-within:border-ring focus-within:ring-3 focus-within:ring-ring/50 dark:bg-input/30"
+ >
+ <Textarea
+ ref={ref}
+ value={draft}
+ onChange={(event) => onDraftChange(event.target.value)}
+ onKeyDown={(event) => {
+ if (event.key === 'Enter' && !event.shiftKey) {
+ event.preventDefault();
+ onSubmit();
+ }
+ }}
+ rows={1}
+ // Stable accessible name — the placeholder is situational (and a
+ // placeholder alone isn't a reliable label for screen readers).
+ aria-label={t`Message ${agentName}`}
+ placeholder={
+ archived
+ ? resumePending
+ ? t`Resuming the conversation`
+ : t`Pick up where you left off`
+ : status === 'auth_required'
+ ? t`Sign in to ${agentName} first`
+ : t`Message ${agentName}`
+ }
+ disabled={
+ archived
+ ? resumePending
+ : status !== 'ready' && status !== 'running' && status !== 'awaiting_permission'
+ }
+ // Borderless + transparent so the wrapper alone renders the field chrome
+ // and focus ring (no doubled border/ring). Full width — the action bar
+ // sits on its own row below, so no right-padding gutter is reserved.
+ className="max-h-40 min-h-9 resize-none border-0 bg-transparent pb-0 shadow-none focus-visible:border-0 focus-visible:ring-0 disabled:bg-transparent dark:bg-transparent dark:disabled:bg-transparent placeholder:text-muted-foreground/60"
+ data-testid="agent-thread-composer"
+ />
+ {/* Action bar: model/agent settings on the left, context ring + send/stop
+ on the right. The send cluster uses `ml-auto` (not the row's
+ justify-between) so it stays hard-right even when the settings popover
+ renders nothing — while the agent is loading / errored / auth-required
+ it exposes no config options, and justify-between would then float the
+ lone send button to the left. */}
+ <div className="flex items-center gap-2 px-1.5 pt-1 pb-1.5">
+ <AgentSettingsPopover info={info} />
+ <div className="ml-auto flex items-center gap-1.5">
+ {usagePercent !== null && usage?.used !== undefined && usage?.size !== undefined ? (
+ <ContextUsageRing used={usage.used} size={usage.size} percent={usagePercent} />
+ ) : null}
+ {turnActive ? (
+ <Button
+ type="button"
+ size="icon-sm"
+ className="rounded-lg"
+ disabled={cancelPending}
+ onClick={onCancel}
+ aria-label={cancelPending ? t`Stopping` : t`Stop`}
+ data-testid="agent-thread-cancel"
+ >
+ {cancelPending ? (
+ <Loader2 className="size-3.5 animate-spin" aria-hidden="true" />
+ ) : (
+ <Square className="size-3 fill-current" aria-hidden="true" />
+ )}
+ </Button>
+ ) : (
+ <Button
+ type="button"
+ size="icon-sm"
+ className="rounded-lg"
+ disabled={!canPrompt || draft.trim() === ''}
+ onClick={onSubmit}
+ aria-label={t`Send`}
+ data-testid="agent-thread-send"
+ >
+ <ArrowUp className="size-4" aria-hidden="true" />
+ </Button>
+ )}
+ </div>
+ </div>
+ </div>
+ </div>
+ );
+}
diff --git a/packages/app/src/components/acp/follow-file.test.ts b/packages/app/src/components/acp/follow-file.test.ts
new file mode 100644
index 000000000..5b4ef6bed
--- /dev/null
+++ b/packages/app/src/components/acp/follow-file.test.ts
@@ -0,0 +1,456 @@
+import { describe, expect, test } from 'vitest';
+import type { RenderedToolCall } from '@/lib/acp/thread-event-model';
+import type { Workspace } from '@/lib/workspace-paths';
+import {
+ docNameFromAbsolutePath,
+ followTargetFromToolCall,
+ latestFollowTarget,
+} from './follow-file';
+
+const posix: Workspace = { contentDir: '/home/me/notes', pathSeparator: '/' };
+const windows: Workspace = { contentDir: 'C:\\Users\\me\\notes', pathSeparator: '\\' };
+
+function call(overrides: Partial<RenderedToolCall>): RenderedToolCall {
+ return {
+ kind: 'tool_call',
+ toolCallId: 'c1',
+ title: 'Tool',
+ toolKind: 'edit',
+ status: 'in_progress',
+ diffs: [],
+ terminalIds: [],
+ content: [],
+ locations: [],
+ rawInput: undefined,
+ ...overrides,
+ };
+}
+
+describe('docNameFromAbsolutePath', () => {
+ test('maps markdown files inside the workspace to docNames', () => {
+ expect(docNameFromAbsolutePath('/home/me/notes/plans/launch.md', posix)).toBe('plans/launch');
+ expect(docNameFromAbsolutePath('/home/me/notes/intro.mdx', posix)).toBe('intro');
+ });
+
+ test('rejects paths outside the workspace and non-markdown files', () => {
+ expect(docNameFromAbsolutePath('/etc/passwd', posix)).toBeNull();
+ expect(docNameFromAbsolutePath('/home/me/notes-other/x.md', posix)).toBeNull();
+ expect(docNameFromAbsolutePath('/home/me/notes/image.png', posix)).toBeNull();
+ });
+
+ test('handles Windows separators', () => {
+ expect(docNameFromAbsolutePath('C:\\Users\\me\\notes\\a\\b.md', windows)).toBe('a/b');
+ });
+});
+
+describe('followTargetFromToolCall', () => {
+ test('OK MCP write (real Codex rawInput shape: arguments.document.path) resolves', () => {
+ const target = followTargetFromToolCall(
+ call({
+ toolKind: 'execute',
+ rawInput: {
+ server: 'open-knowledge',
+ tool: 'write',
+ arguments: {
+ cwd: '/somewhere',
+ document: { path: 'orbit/plan', frontmatter: { title: 'Plan' } },
+ },
+ },
+ }),
+ posix,
+ );
+ expect(target).toBe('orbit/plan');
+ });
+
+ test('an .md-suffixed MCP doc path normalizes to the extension-less docName', () => {
+ const target = followTargetFromToolCall(
+ call({
+ rawInput: {
+ server: 'open-knowledge',
+ tool: 'edit',
+ arguments: { document: { path: 'orbit/plan.md', find: 'a', replace: 'b' } },
+ },
+ }),
+ posix,
+ );
+ expect(target).toBe('orbit/plan');
+ });
+
+ test('batch write (documents[]) follows the LAST entry — the most recent write', () => {
+ // Real Codex rawInput shape from a live run: one `write` call carrying a
+ // 12-page batch under `documents: [...]`. Before the batch branch existed
+ // this resolved to null and the editor never followed the build.
+ const target = followTargetFromToolCall(
+ call({
+ toolKind: 'execute',
+ rawInput: {
+ server: 'open-knowledge',
+ tool: 'write',
+ arguments: {
+ cwd: '/somewhere',
+ documents: [
+ { path: 'articles/coffee/espresso', frontmatter: { title: 'Espresso' } },
+ { path: 'articles/coffee/latte', frontmatter: { title: 'Latte' } },
+ { path: 'articles/coffee/french-press', frontmatter: { title: 'French Press' } },
+ ],
+ },
+ },
+ }),
+ posix,
+ );
+ expect(target).toBe('articles/coffee/french-press');
+ });
+
+ test('batch write skips non-object trailing entries; an empty batch is no target', () => {
+ // The last OBJECT entry wins — a stray non-object tail (adapter quirk)
+ // must not blank the whole batch.
+ expect(
+ followTargetFromToolCall(
+ call({
+ rawInput: {
+ server: 'open-knowledge',
+ tool: 'write',
+ arguments: {
+ documents: [{ path: 'articles/coffee/beans.md' }, 'junk'],
+ },
+ },
+ }),
+ posix,
+ ),
+ ).toBe('articles/coffee/beans');
+ expect(
+ followTargetFromToolCall(
+ call({
+ rawInput: {
+ server: 'open-knowledge',
+ tool: 'write',
+ arguments: { documents: [] },
+ },
+ }),
+ posix,
+ ),
+ ).toBeNull();
+ });
+
+ test('folder-creation write (folder.path, no documents) is not a doc target', () => {
+ // Real shape from the same live run: `write` with `folder: {path}` creates
+ // a folder — there is no document to follow.
+ expect(
+ followTargetFromToolCall(
+ call({
+ rawInput: {
+ server: 'open-knowledge',
+ tool: 'write',
+ arguments: {
+ cwd: '/somewhere',
+ folder: { path: 'articles/coffee', frontmatter: { title: 'Coffee Wiki' } },
+ },
+ },
+ }),
+ posix,
+ ),
+ ).toBeNull();
+ });
+
+ test('flat docName argument shape also resolves', () => {
+ const target = followTargetFromToolCall(
+ call({
+ toolKind: 'other',
+ rawInput: {
+ server: 'open-knowledge',
+ tool: 'write',
+ arguments: { docName: 'demo/plan', content: '# hi' },
+ },
+ }),
+ posix,
+ );
+ expect(target).toBe('demo/plan');
+ });
+
+ test('arguments-direct rawInput shape also resolves', () => {
+ expect(followTargetFromToolCall(call({ rawInput: { docName: 'notes/today' } }), null)).toBe(
+ 'notes/today',
+ );
+ });
+
+ test('move follows the destination', () => {
+ expect(
+ followTargetFromToolCall(
+ call({ rawInput: { tool: 'move', arguments: { from: 'a', to: 'b' } } }),
+ posix,
+ ),
+ ).toBe('b');
+ });
+
+ test('deletions never navigate', () => {
+ expect(
+ followTargetFromToolCall(
+ call({ rawInput: { tool: 'delete', arguments: { docName: 'gone' } } }),
+ posix,
+ ),
+ ).toBeNull();
+ expect(
+ followTargetFromToolCall(
+ call({ toolKind: 'delete', locations: [{ path: '/home/me/notes/x.md' }] }),
+ posix,
+ ),
+ ).toBeNull();
+ });
+
+ test('falls back to the newest resolvable location', () => {
+ const target = followTargetFromToolCall(
+ call({
+ locations: [
+ { path: '/home/me/notes/first.md' },
+ { path: '/elsewhere/skip.md' },
+ { path: '/home/me/notes/deep/second.md', line: 4 },
+ ],
+ }),
+ posix,
+ );
+ expect(target).toBe('deep/second');
+ });
+
+ test('sanitizes hostile docNames', () => {
+ expect(
+ followTargetFromToolCall(call({ rawInput: { docName: '../escape' } }), posix),
+ ).toBeNull();
+ expect(followTargetFromToolCall(call({ rawInput: { docName: '/abs' } }), posix)).toBeNull();
+ expect(followTargetFromToolCall(call({ rawInput: { docName: '' } }), posix)).toBeNull();
+ });
+
+ test('skips dot-segment plumbing docs (agent skills, .ok config)', () => {
+ expect(
+ followTargetFromToolCall(
+ call({
+ toolKind: 'read',
+ locations: [{ path: '/home/me/notes/.codex/skills/open-knowledge/SKILL.md' }],
+ }),
+ posix,
+ ),
+ ).toBeNull();
+ expect(
+ followTargetFromToolCall(call({ rawInput: { docName: '.ok/config' } }), posix),
+ ).toBeNull();
+ });
+
+ test('JSON-string arguments (adapter-serialized) resolve like object arguments', () => {
+ const target = followTargetFromToolCall(
+ call({
+ rawInput: {
+ tool: 'write',
+ arguments: JSON.stringify({ document: { path: 'wiki/tea', content: '# Tea' } }),
+ },
+ }),
+ posix,
+ );
+ expect(target).toBe('wiki/tea');
+ });
+
+ test('tool name at `name` (adapter-dependent) still gates deletions', () => {
+ expect(
+ followTargetFromToolCall(
+ call({ rawInput: { name: 'delete', arguments: { document: { path: 'wiki/tea' } } } }),
+ posix,
+ ),
+ ).toBeNull();
+ });
+
+ test('bare-arguments delete is guarded by the call title', () => {
+ expect(
+ followTargetFromToolCall(
+ call({
+ title: 'open-knowledge - delete',
+ rawInput: { document: { path: 'wiki/tea' } },
+ }),
+ posix,
+ ),
+ ).toBeNull();
+ });
+
+ test('template move (nested from/to) is not a document target', () => {
+ expect(
+ followTargetFromToolCall(
+ call({
+ rawInput: { tool: 'move', arguments: { template: { from: 'log/a', to: 'log/b' } } },
+ }),
+ posix,
+ ),
+ ).toBeNull();
+ });
+});
+
+describe('followTargetFromToolCall — exec command strings', () => {
+ test('command reads of MISSING docs never navigate; write targets are not gated', () => {
+ // Live-run regression: the agent ran `cat log.md` on a doc that was never
+ // created, and follow parked the editor on a blank create-on-open tab.
+ const missingRead = call({
+ rawInput: { tool: 'exec', arguments: { command: 'cat log.md' } },
+ });
+ const exists = (docName: string) => docName !== 'log';
+ expect(
+ followTargetFromToolCall(missingRead, posix, { commandTargetExists: exists }),
+ ).toBeNull();
+ // The same read WITH the doc present follows normally.
+ expect(followTargetFromToolCall(missingRead, posix, { commandTargetExists: () => true })).toBe(
+ 'log',
+ );
+ // No predicate (page list still loading) → ungated, previous behavior.
+ expect(followTargetFromToolCall(missingRead, posix)).toBe('log');
+ // Write targets may name docs that don't exist YET — never gated.
+ expect(
+ followTargetFromToolCall(
+ call({
+ rawInput: {
+ tool: 'write',
+ arguments: { document: { path: 'brand/new-page' } },
+ },
+ }),
+ posix,
+ { commandTargetExists: () => false },
+ ),
+ ).toBe('brand/new-page');
+ });
+
+ test('latestFollowTarget falls back past a gated command read to the last write', () => {
+ const items = [
+ {
+ kind: 'tool_call',
+ toolKind: 'execute',
+ title: 'write',
+ locations: [],
+ rawInput: { tool: 'write', arguments: { documents: [{ path: 'articles/caffeine' }] } },
+ },
+ {
+ kind: 'tool_call',
+ toolKind: 'execute',
+ title: 'exec',
+ locations: [],
+ rawInput: { tool: 'exec', arguments: { command: 'cat log.md' } },
+ },
+ ];
+ expect(latestFollowTarget(items, posix, { commandTargetExists: (d) => d !== 'log' })).toBe(
+ 'articles/caffeine',
+ );
+ });
+
+ test('cat with a relative markdown path', () => {
+ expect(
+ followTargetFromToolCall(
+ call({ rawInput: { tool: 'exec', arguments: { command: 'cat specs/foo/SPEC.md' } } }),
+ posix,
+ ),
+ ).toBe('specs/foo/SPEC');
+ });
+
+ test('quoted paths with spaces', () => {
+ expect(
+ followTargetFromToolCall(
+ call({ rawInput: { tool: 'exec', arguments: { command: 'cat "my notes/plan.md"' } } }),
+ posix,
+ ),
+ ).toBe('my notes/plan');
+ });
+
+ test('leading ./ is normalized', () => {
+ expect(
+ followTargetFromToolCall(
+ call({ rawInput: { tool: 'exec', arguments: { command: 'head -25 ./readme.md' } } }),
+ posix,
+ ),
+ ).toBe('readme');
+ });
+
+ test('flags are skipped; the first md operand wins', () => {
+ expect(
+ followTargetFromToolCall(
+ call({
+ rawInput: { tool: 'exec', arguments: { command: 'grep -rn oauth articles/auth.md' } },
+ }),
+ posix,
+ ),
+ ).toBe('articles/auth');
+ });
+
+ test('globs carry no single target', () => {
+ expect(
+ followTargetFromToolCall(
+ call({ rawInput: { tool: 'exec', arguments: { command: 'head -25 specs/*/SPEC.md' } } }),
+ posix,
+ ),
+ ).toBeNull();
+ });
+
+ test('directory listings carry no doc target', () => {
+ expect(
+ followTargetFromToolCall(
+ call({ rawInput: { tool: 'exec', arguments: { command: 'ls specs/' } } }),
+ posix,
+ ),
+ ).toBeNull();
+ });
+
+ test('non-read command heads never navigate', () => {
+ expect(
+ followTargetFromToolCall(
+ call({ rawInput: { tool: 'exec', arguments: { command: 'rm wiki/tea.md' } } }),
+ posix,
+ ),
+ ).toBeNull();
+ });
+
+ test('absolute in-workspace paths map through the workspace root', () => {
+ expect(
+ followTargetFromToolCall(
+ call({
+ rawInput: { tool: 'exec', arguments: { command: 'cat /home/me/notes/wiki/tea.md' } },
+ }),
+ posix,
+ ),
+ ).toBe('wiki/tea');
+ });
+
+ test('absolute out-of-workspace paths resolve to null', () => {
+ expect(
+ followTargetFromToolCall(
+ call({ rawInput: { tool: 'exec', arguments: { command: 'cat /etc/motd.md' } } }),
+ posix,
+ ),
+ ).toBeNull();
+ });
+
+ test('pipes: an md operand anywhere in the pipeline is found', () => {
+ expect(
+ followTargetFromToolCall(
+ call({ rawInput: { tool: 'exec', arguments: { command: 'cat notes.md | head -5' } } }),
+ posix,
+ ),
+ ).toBe('notes');
+ });
+
+ test('a native terminal command (bare command field) also follows', () => {
+ expect(
+ followTargetFromToolCall(
+ call({ toolKind: 'execute', rawInput: { command: 'cat wiki/tea.md' } }),
+ posix,
+ ),
+ ).toBe('wiki/tea');
+ });
+});
+
+describe('latestFollowTarget', () => {
+ test('the last tool call with a resolvable target wins', () => {
+ const items = [
+ { kind: 'message' },
+ call({ rawInput: { docName: 'one' } }),
+ call({ rawInput: { tool: 'exec', arguments: { command: 'ls' } } }),
+ call({ rawInput: { docName: 'two' } }),
+ { kind: 'notice' },
+ ];
+ expect(latestFollowTarget(items, posix)).toBe('two');
+ });
+
+ test('null when nothing followable happened', () => {
+ expect(latestFollowTarget([{ kind: 'message' }], posix)).toBeNull();
+ });
+});
diff --git a/packages/app/src/components/acp/follow-file.ts b/packages/app/src/components/acp/follow-file.ts
new file mode 100644
index 000000000..d119e4a72
--- /dev/null
+++ b/packages/app/src/components/acp/follow-file.ts
@@ -0,0 +1,278 @@
+/**
+ * Follow-the-file: derive which document the agent is currently working on
+ * from a thread's tool calls, so the editor can navigate along while the
+ * agent creates and edits files (the ACP `locations` contract, plus the
+ * OpenKnowledge MCP tools' argument shapes).
+ *
+ * Two signal shapes, in priority order:
+ * 1. OK MCP tool calls — adapters report them with
+ * `rawInput: { server, tool, arguments: {…} }` (Codex), with `arguments`
+ * as a JSON string (adapter-dependent), or as the arguments object
+ * directly. The doc target is wherever the verb vocabulary puts it:
+ * `document.path` (write / edit), flat `to` (move), flat `docName`
+ * (links / history), or a `.md`/`.mdx` path referenced inside an `exec`
+ * / shell `command` string.
+ * 2. `locations[]` — absolute file paths (native read/edit tools). Mapped to
+ * a docName by stripping the workspace `contentDir` prefix and the
+ * `.md`/`.mdx` extension; non-markdown paths are not editor documents and
+ * resolve to null.
+ */
+
+import type { RenderedToolCall } from '@/lib/acp/thread-event-model';
+import type { Workspace } from '@/lib/workspace-paths';
+
+const FOLLOW_PREF_KEY = 'ok-acp-follow-file-v1';
+
+/** Persisted follow toggle; defaults ON (the launch-demo behavior). */
+export function loadFollowFilePref(): boolean {
+ try {
+ return localStorage.getItem(FOLLOW_PREF_KEY) !== '0';
+ } catch {
+ return true;
+ }
+}
+
+export function saveFollowFilePref(enabled: boolean): void {
+ try {
+ localStorage.setItem(FOLLOW_PREF_KEY, enabled ? '1' : '0');
+ } catch {
+ // Privacy mode / no storage — the in-session toggle still works.
+ }
+}
+
+/**
+ * A docName is only navigable when it is a plain relative identifier.
+ * Dot-segment docs (`.codex/skills/…`, `.ok/…`) are agent/config plumbing,
+ * not user content — following them would open the transcript with a jump to
+ * the agent's own skill file instead of the user's documents.
+ */
+export function sanitizeDocName(docName: string): string | null {
+ if (docName === '' || docName.startsWith('/') || docName.startsWith('\\')) return null;
+ const segments = docName.split('/');
+ if (segments.some((s) => s === '' || s.startsWith('.'))) return null;
+ return docName;
+}
+
+/** Map an absolute file path to a docName relative to `contentDir`. */
+export function docNameFromAbsolutePath(path: string, workspace: Workspace): string | null {
+ const sep = workspace.pathSeparator;
+ const normalize = (p: string): string => (sep === '\\' ? p.replaceAll('\\', '/') : p);
+ const root = normalize(workspace.contentDir).replace(/\/$/, '');
+ const normalized = normalize(path);
+ if (!normalized.startsWith(`${root}/`)) return null;
+ const relative = normalized.slice(root.length + 1);
+ const match = /\.(md|mdx)$/.exec(relative);
+ if (match === null) return null;
+ return sanitizeDocName(relative.slice(0, -match[0].length));
+}
+
+function stringField(obj: Record<string, unknown>, key: string): string | null {
+ const value = obj[key];
+ return typeof value === 'string' && value !== '' ? value : null;
+}
+
+/**
+ * Read-only command heads worth following (mirrors the OK `exec` tool's
+ * allowlist, plus common read-only lookalikes). A command whose head is not
+ * listed — `rm`, `mv`, arbitrary scripts — never drives navigation: following
+ * a file that a command is deleting or renaming is not what follow means.
+ */
+const FOLLOWABLE_COMMAND_HEADS = new Set([
+ 'cat',
+ 'ls',
+ 'grep',
+ 'rg',
+ 'find',
+ 'head',
+ 'tail',
+ 'wc',
+ 'sort',
+ 'uniq',
+ 'cut',
+ 'sed',
+ 'awk',
+ 'bat',
+ 'less',
+ 'more',
+]);
+
+/**
+ * DocName referenced by a shell-ish `command` string (the OK `exec` tool, or
+ * a native terminal tool). First `.md`/`.mdx` token wins — the primary
+ * operand. Globs carry no single target; flags are skipped; absolute paths
+ * map through the workspace root like `locations[]` entries do.
+ */
+function docTargetFromCommand(command: string, workspace: Workspace | null): string | null {
+ const tokens: string[] = [];
+ const tokenizer = /"([^"]*)"|'([^']*)'|(\S+)/g;
+ let match: RegExpExecArray | null = tokenizer.exec(command);
+ while (match !== null) {
+ tokens.push(match[1] ?? match[2] ?? match[3] ?? '');
+ match = tokenizer.exec(command);
+ }
+ const head = tokens[0];
+ if (head === undefined || !FOLLOWABLE_COMMAND_HEADS.has(head)) return null;
+ for (const token of tokens.slice(1)) {
+ if (token.startsWith('-')) continue;
+ if (/[*?[\]]/.test(token)) continue;
+ const mdMatch = /\.(md|mdx)$/i.exec(token);
+ if (mdMatch === null) continue;
+ if (token.startsWith('/') || /^[A-Za-z]:[\\/]/.test(token)) {
+ if (workspace !== null) {
+ const doc = docNameFromAbsolutePath(token, workspace);
+ if (doc !== null) return doc;
+ }
+ continue;
+ }
+ const doc = sanitizeDocName(token.replace(/^\.\//, '').slice(0, -mdMatch[0].length));
+ if (doc !== null) return doc;
+ }
+ return null;
+}
+
+/**
+ * Follow-target options. `commandTargetExists` gates COMMAND-derived targets
+ * (the `exec`/shell `command` string path) on the doc actually existing: a
+ * read of a missing file (`cat log.md` on a doc that was never created) must
+ * not navigate — the editor would open a blank create-on-open tab, which is
+ * exactly how a live build ended parked on an empty "log" page. Write-shaped
+ * targets (`document`/`documents`/`to`/`docName`) are deliberately NOT gated:
+ * they routinely name docs that don't exist YET (the write creates them).
+ */
+export interface FollowTargetOptions {
+ commandTargetExists?: (docName: string) => boolean;
+}
+
+/**
+ * DocName from an OK MCP tool call's rawInput, or null when the call is not
+ * an OK MCP doc operation. Deletions return null — navigating to a document
+ * that is being removed is never what follow mode means.
+ */
+/**
+ * Unwrap an OK MCP call's rawInput into `{ tool, args }`. Codex reports
+ * `{ server, tool, arguments }`; other adapters name the tool at `name`, pass
+ * `arguments` as a serialized JSON string, or pass the arguments object bare
+ * with no tool name at all.
+ */
+function unwrapMcpInput(
+ rawInput: unknown,
+): { tool: string | null; args: Record<string, unknown> } | null {
+ if (typeof rawInput !== 'object' || rawInput === null) return null;
+ const input = rawInput as Record<string, unknown>;
+ const tool = stringField(input, 'tool') ?? stringField(input, 'name');
+ let args: Record<string, unknown> = input;
+ if (typeof input.arguments === 'object' && input.arguments !== null) {
+ args = input.arguments as Record<string, unknown>;
+ } else if (typeof input.arguments === 'string') {
+ try {
+ const parsed: unknown = JSON.parse(input.arguments);
+ if (typeof parsed === 'object' && parsed !== null) {
+ args = parsed as Record<string, unknown>;
+ }
+ } catch {
+ // Not JSON — treat the input itself as the args object.
+ }
+ }
+ return { tool, args };
+}
+
+function mcpDocTarget(
+ rawInput: unknown,
+ title: string,
+ workspace: Workspace | null,
+ options: FollowTargetOptions,
+): string | null {
+ const unwrapped = unwrapMcpInput(rawInput);
+ if (unwrapped === null) return null;
+ const { tool, args } = unwrapped;
+ // Deletion guard: by tool name when the adapter reports one, by the call
+ // title otherwise (the bare-arguments shape of `delete` is otherwise
+ // indistinguishable from `write`'s).
+ if (tool === 'delete' || (tool === null && /\bdelete\b/i.test(title))) return null;
+ // The OK MCP write/edit schema nests the target at `document.path`
+ // (observed from real Codex tool_call rawInput); batch writes carry
+ // `documents: [...]` instead — the LAST entry is the most recent write, so
+ // that's the one to follow (observed live: a 12-page batch produced no
+ // follow target at all before this branch existed); `move` lands the doc at
+ // flat `to` (template/skill moves nest theirs — those are not documents);
+ // `docName` is the flat fallback shape.
+ const document =
+ typeof args.document === 'object' && args.document !== null
+ ? (args.document as Record<string, unknown>)
+ : null;
+ let lastBatchEntry: Record<string, unknown> | null = null;
+ if (Array.isArray(args.documents)) {
+ for (let i = args.documents.length - 1; i >= 0; i--) {
+ const entry: unknown = args.documents[i];
+ if (typeof entry === 'object' && entry !== null) {
+ lastBatchEntry = entry as Record<string, unknown>;
+ break;
+ }
+ }
+ }
+ const docName =
+ (document !== null ? stringField(document, 'path') : null) ??
+ (lastBatchEntry !== null ? stringField(lastBatchEntry, 'path') : null) ??
+ stringField(args, 'to') ??
+ stringField(args, 'docName');
+ if (docName !== null) {
+ // Agents sometimes pass the on-disk form (`orbit/plan.md`); the navigable
+ // docName is extension-less.
+ return sanitizeDocName(docName.replace(/\.(md|mdx)$/, ''));
+ }
+ const command = stringField(args, 'command');
+ if (command !== null) {
+ const target = docTargetFromCommand(command, workspace);
+ if (
+ target !== null &&
+ options.commandTargetExists !== undefined &&
+ !options.commandTargetExists(target)
+ ) {
+ return null;
+ }
+ return target;
+ }
+ return null;
+}
+
+/**
+ * The document a tool call is working on, or null when it has none (shell
+ * commands, searches, deletions, files outside the workspace).
+ */
+export function followTargetFromToolCall(
+ call: Pick<RenderedToolCall, 'toolKind' | 'title' | 'locations' | 'rawInput'>,
+ workspace: Workspace | null,
+ options: FollowTargetOptions = {},
+): string | null {
+ if (call.toolKind === 'delete') return null;
+ const mcp = mcpDocTarget(call.rawInput, call.title, workspace, options);
+ if (mcp !== null) return mcp;
+ if (workspace === null) return null;
+ // Newest location wins — long calls append locations as they progress.
+ for (let i = call.locations.length - 1; i >= 0; i--) {
+ const location = call.locations[i];
+ if (location === undefined) continue;
+ const docName = docNameFromAbsolutePath(location.path, workspace);
+ if (docName !== null) return docName;
+ }
+ return null;
+}
+
+/**
+ * The latest followable document across a transcript's items (last tool call
+ * with a resolvable target wins — that is what the agent touched most
+ * recently).
+ */
+export function latestFollowTarget(
+ items: ReadonlyArray<{ kind: string }>,
+ workspace: Workspace | null,
+ options: FollowTargetOptions = {},
+): string | null {
+ let target: string | null = null;
+ for (const item of items) {
+ if (item.kind !== 'tool_call') continue;
+ const resolved = followTargetFromToolCall(item as RenderedToolCall, workspace, options);
+ if (resolved !== null) target = resolved;
+ }
+ return target;
+}
diff --git a/packages/app/src/components/acp/presence-follow.test.ts b/packages/app/src/components/acp/presence-follow.test.ts
new file mode 100644
index 000000000..4d623c369
--- /dev/null
+++ b/packages/app/src/components/acp/presence-follow.test.ts
@@ -0,0 +1,82 @@
+import { describe, expect, test } from 'vitest';
+import { appendPresenceWrite, latestAgentWrite } from './presence-follow';
+
+function awarenessWith(entries: Record<string, { currentDoc: string | null; ts: number }>) {
+ return {
+ getStates: () =>
+ new Map([
+ [
+ 1,
+ {
+ agentPresence: Object.fromEntries(
+ Object.entries(entries).map(([id, e]) => [
+ id,
+ { displayName: id, icon: 'claude', color: '#000', mode: 'writing', ...e },
+ ]),
+ ),
+ },
+ ],
+ ]),
+ };
+}
+
+describe('latestAgentWrite', () => {
+ const NOW = 1_000_000;
+
+ test('freshest write across agents wins; stale and doc-less entries are skipped', () => {
+ const awareness = awarenessWith({
+ 'agent-a': { currentDoc: 'articles/wine/tannins', ts: NOW - 100 },
+ 'agent-b': { currentDoc: 'articles/wine/terroir', ts: NOW - 50 },
+ 'agent-idle': { currentDoc: null, ts: NOW },
+ 'agent-stale': { currentDoc: 'old/doc', ts: NOW - 60_000 },
+ });
+ expect(latestAgentWrite(awareness, NOW)).toEqual({
+ doc: 'articles/wine/terroir',
+ ts: NOW - 50,
+ });
+ });
+
+ test('dot-segment plumbing targets never become follow targets', () => {
+ const awareness = awarenessWith({
+ 'agent-a': { currentDoc: '.ok/skills/foo/SKILL', ts: NOW - 10 },
+ });
+ expect(latestAgentWrite(awareness, NOW)).toBeNull();
+ });
+
+ test('presence sentinels never become follow targets', () => {
+ // The server publishes these to keep an idle agent visible in the presence
+ // bar — following them opens a phantom tab and, at turn end, drags the
+ // editor off the last real page.
+ expect(
+ latestAgentWrite(awarenessWith({ a: { currentDoc: '(agent thread)', ts: NOW } }), NOW),
+ ).toBeNull();
+ expect(
+ latestAgentWrite(awarenessWith({ a: { currentDoc: '(connected)', ts: NOW } }), NOW),
+ ).toBeNull();
+ });
+
+ test('a real write still wins over a fresher sentinel from another agent', () => {
+ const awareness = awarenessWith({
+ writer: { currentDoc: 'articles/tea/terroir', ts: NOW - 100 },
+ idler: { currentDoc: '(agent thread)', ts: NOW },
+ });
+ expect(latestAgentWrite(awareness, NOW)).toEqual({
+ doc: 'articles/tea/terroir',
+ ts: NOW - 100,
+ });
+ });
+
+ test('non-awareness values return null', () => {
+ expect(latestAgentWrite(null, NOW)).toBeNull();
+ expect(latestAgentWrite({}, NOW)).toBeNull();
+ });
+});
+
+describe('appendPresenceWrite', () => {
+ test('re-observations of the same (doc, ts) do not extend the stream', () => {
+ const first = appendPresenceWrite([], { doc: 'a', ts: 1 });
+ expect(appendPresenceWrite(first, { doc: 'a', ts: 1 })).toBe(first);
+ expect(appendPresenceWrite(first, { doc: 'a', ts: 2 })).toHaveLength(2);
+ expect(appendPresenceWrite(first, { doc: 'b', ts: 1 })).toHaveLength(2);
+ });
+});
diff --git a/packages/app/src/components/acp/presence-follow.ts b/packages/app/src/components/acp/presence-follow.ts
new file mode 100644
index 000000000..8e23ba7af
--- /dev/null
+++ b/packages/app/src/components/acp/presence-follow.ts
@@ -0,0 +1,67 @@
+/**
+ * Presence-derived write stream — the adapter-independent fallback signal for
+ * follow-the-file and the content-phase detector.
+ *
+ * Some ACP adapters report tool calls with EMPTY rawInput and no locations
+ * (observed live: Cursor sends `rawInput: {}` + title "MCP: tool" for every
+ * call), so the transcript carries nothing to derive follow targets from. But
+ * the OK server EXECUTES every MCP write and refreshes the writing agent's
+ * `agentPresence.currentDoc` on `__system__` awareness per write — an
+ * authoritative, adapter-independent stream of write targets. ThreadView
+ * consumes it when (and only when) the transcript yields no targets at all.
+ *
+ * Multi-agent caveat: presence entries are not tied to a specific thread; the
+ * stream reads "the doc most recently written by ANY agent." While a turn is
+ * streaming that is overwhelmingly this thread's agent — the same
+ * approximation the agent-build showcase's gate makes.
+ */
+
+import { isPresenceSentinelDocName } from '@inkeep/open-knowledge-core';
+import { AGENT_PRESENCE_STALE_MS, hasAgentPresenceShape } from '@/lib/agent-presence';
+import { sanitizeDocName } from './follow-file';
+
+export interface PresenceWrite {
+ doc: string;
+ ts: number;
+}
+
+/**
+ * The freshest agent write visible on `__system__` awareness right now, or
+ * null. Dot-segment targets (`.ok/…` skill/config writes) are not user
+ * documents and never become follow targets.
+ */
+export function latestAgentWrite(awareness: unknown, now: number): PresenceWrite | null {
+ if (!hasAgentPresenceShape(awareness)) return null;
+ let latest: PresenceWrite | null = null;
+ for (const state of awareness.getStates().values()) {
+ const presence = state.agentPresence;
+ if (!presence) continue;
+ for (const entry of Object.values(presence)) {
+ if (!entry.currentDoc) continue;
+ // Sentinels ('(connected)', '(agent thread)') keep an idle agent visible
+ // in the presence bar but are NOT docs — following them opens a phantom
+ // tab and, at turn end, drags the editor off the last real page.
+ if (isPresenceSentinelDocName(entry.currentDoc)) continue;
+ if (now - entry.ts >= AGENT_PRESENCE_STALE_MS) continue;
+ if (latest !== null && entry.ts <= latest.ts) continue;
+ const doc = sanitizeDocName(entry.currentDoc);
+ if (doc === null) continue;
+ latest = { doc, ts: entry.ts };
+ }
+ }
+ return latest;
+}
+
+/**
+ * Append an observed write to the per-turn stream. Same (doc, ts) is the same
+ * write re-observed (awareness redelivers state on unrelated changes) — only
+ * a new ts or a new doc extends the stream.
+ */
+export function appendPresenceWrite(
+ stream: ReadonlyArray<PresenceWrite>,
+ write: PresenceWrite,
+): ReadonlyArray<PresenceWrite> {
+ const last = stream[stream.length - 1];
+ if (last !== undefined && last.doc === write.doc && last.ts === write.ts) return stream;
+ return [...stream, write];
+}
diff --git a/packages/app/src/components/composer-shared-draft.dom.test.tsx b/packages/app/src/components/composer-shared-draft.dom.test.tsx
index 7c1e2a06d..c519a5dad 100644
--- a/packages/app/src/components/composer-shared-draft.dom.test.tsx
+++ b/packages/app/src/components/composer-shared-draft.dom.test.tsx
@@ -18,15 +18,15 @@
* `ComposerMentionInput.dom.test.tsx`).
*/
-import { afterEach, beforeEach, describe, expect, mock, test } from 'bun:test';
import type { CreateScenario, InstallState } from '@inkeep/open-knowledge-core';
import * as actualLinguiMacro from '@lingui/react/macro';
import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
import type { JSONContent } from '@tiptap/core';
import { type ReactNode, type Ref, useImperativeHandle, useRef, useState } from 'react';
+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
import { __resetComposerDraftForTests } from './composer-draft-store';
-mock.module('@lingui/react/macro', () => ({
+vi.doMock('@lingui/react/macro', () => ({
...actualLinguiMacro,
Trans: ({ children }: { children: ReactNode }) => <>{children}</>,
useLingui: () => ({
@@ -35,15 +35,15 @@ mock.module('@lingui/react/macro', () => ({
}),
}));
-mock.module('@/lib/config-context', () => ({
+vi.doMock('@/lib/config-context', () => ({
useConfigContext: () => ({ merged: { appearance: { preview: { autoOpen: true } } } }),
}));
-mock.module('@/components/PageListContext', () => ({
+vi.doMock('@/components/PageListContext', () => ({
usePageList: () => ({ pageMeta: new Map() }),
}));
-mock.module('@/components/handoff/OpenInAgentMenuItem', () => ({
+vi.doMock('@/components/handoff/OpenInAgentMenuItem', () => ({
TargetIcon: ({ id }: { id: string }) => <span data-testid={`target-icon-${id}`} />,
}));
@@ -53,7 +53,7 @@ type MenuChild = {
onSelect?: () => void;
[key: string]: unknown;
};
-mock.module('@/components/ui/dropdown-menu', () => ({
+vi.doMock('@/components/ui/dropdown-menu', () => ({
DropdownMenu: ({ children }: MenuChild) => <div>{children}</div>,
DropdownMenuTrigger: ({ children }: MenuChild) => <>{children}</>,
DropdownMenuContent: ({ children, ...props }: MenuChild) => (
@@ -77,23 +77,24 @@ const installedAll: Record<string, InstallState> = {
codex: { installed: true },
cursor: { installed: true },
};
-mock.module('@/components/handoff/useInstalledAgents', () => ({
+vi.doMock('@/components/handoff/useInstalledAgents', () => ({
useInstalledAgents: () => ({ states: installedAll, refresh: () => Promise.resolve() }),
}));
-mock.module('@/lib/use-workspace', () => ({
+vi.doMock('@/lib/use-workspace', () => ({
useWorkspace: () => ({ contentDir: '/tmp/project', pathSeparator: '/' }),
}));
-mock.module('@/hooks/use-selection-context', () => ({
+vi.doMock('@/hooks/use-selection-context', () => ({
useSelectionContext: () => null,
}));
-mock.module('@/components/handoff/useHandoffDispatch', () => ({
+vi.doMock('@/components/handoff/useHandoffDispatch', () => ({
useHandoffDispatch: () => ({ dispatch: () => Promise.resolve({ ok: true }) }),
buildComposerHandoffInput: (args: { instruction: string }) => ({
compose: { instruction: args.instruction },
}),
+ startAgentThreadForInput: () => {},
buildCreateHandoffInput: (args: { description: string }) => ({
createDescription: args.description,
}),
@@ -101,7 +102,7 @@ mock.module('@/components/handoff/useHandoffDispatch', () => ({
openInstallUrl: () => Promise.resolve(),
}));
-mock.module('sonner', () => ({ toast: { error: () => {}, success: () => {} } }));
+vi.doMock('sonner', () => ({ toast: { error: () => {}, success: () => {} } }));
// ---------------------------------------------------------------------------
// Doc-faithful input double. It honors the SHARED-DRAFT contract additions:
@@ -144,7 +145,7 @@ function textToDoc(value: string): JSONContent {
};
}
-mock.module('@/editor/ComposerMentionInput', () => ({
+vi.doMock('@/editor/ComposerMentionInput', () => ({
ComposerMentionInput: ({
ref,
ariaLabel,
@@ -250,6 +251,7 @@ mock.module('@/editor/ComposerMentionInput', () => ({
const { BottomComposer } = await import('./BottomComposer');
const { CreatePromptComposer } = await import('./empty-state/CreatePromptComposer');
+const { registerAgent } = await import('@/lib/acp/registered-agents');
beforeEach(() => {
try {
@@ -258,6 +260,10 @@ beforeEach(() => {
/* guarded */
}
__resetComposerDraftForTests();
+ // Seed one enabled in-app agent — production hydrates this on boot; without it
+ // the create composer collapses to the "Turn on an agent" nudge (no input),
+ // which these draft tests aren't exercising.
+ registerAgent({ source: 'registry', id: 'claude-acp', name: 'Claude' }, { makeDefault: true });
});
afterEach(() => {
diff --git a/packages/app/src/components/desktop-root-app.tsx b/packages/app/src/components/desktop-root-app.tsx
index cfb8a88e9..a960758f7 100644
--- a/packages/app/src/components/desktop-root-app.tsx
+++ b/packages/app/src/components/desktop-root-app.tsx
@@ -1,9 +1,15 @@
-import type { ReactElement } from 'react';
+import { lazy, type ReactElement, Suspense } from 'react';
import { App } from '@/App';
import { NavigatorApp } from '@/components/NavigatorApp';
-import { TerminalWindowApp } from '@/components/TerminalWindowApp';
import type { OkDesktopBridge } from '@/lib/desktop-bridge-types';
+// Lazy-loaded: the terminal window statically imports TerminalSessionsHost
+// (and through it the ACP thread-client chain), which must stay out of the
+// entry chunk — editor windows and the web distribution never render it.
+const TerminalWindowApp = lazy(() =>
+ import('@/components/TerminalWindowApp').then((mod) => ({ default: mod.TerminalWindowApp })),
+);
+
/**
* Pick the root surface for the current window from the desktop bridge's mode.
* `terminal` and `navigator` are dedicated Electron window types; everything
@@ -11,7 +17,13 @@ import type { OkDesktopBridge } from '@/lib/desktop-bridge-types';
* undefined — renders the full editor shell.
*/
export function selectDesktopRootApp(bridge: OkDesktopBridge | undefined): ReactElement {
- if (bridge?.config.mode === 'terminal') return <TerminalWindowApp bridge={bridge} />;
+ if (bridge?.config.mode === 'terminal') {
+ return (
+ <Suspense fallback={null}>
+ <TerminalWindowApp bridge={bridge} />
+ </Suspense>
+ );
+ }
if (bridge?.config.mode === 'navigator') return <NavigatorApp bridge={bridge} />;
return <App />;
}
diff --git a/packages/app/src/components/empty-state/CreatePromptComposer.dom.test.tsx b/packages/app/src/components/empty-state/CreatePromptComposer.dom.test.tsx
index 4de309bbf..9223bd7eb 100644
--- a/packages/app/src/components/empty-state/CreatePromptComposer.dom.test.tsx
+++ b/packages/app/src/components/empty-state/CreatePromptComposer.dom.test.tsx
@@ -9,15 +9,25 @@
* accessible-name split.
*/
-import { afterEach, describe, expect, mock, test } from 'bun:test';
import type { CreateScenario, InstallState } from '@inkeep/open-knowledge-core';
import * as actualLinguiMacro from '@lingui/react/macro';
import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
import { type ReactNode, type Ref, useImperativeHandle, useRef } from 'react';
+import { afterEach, describe, expect, test, vi } from 'vitest';
import type { HandoffDispatchInput } from '@/components/handoff/useHandoffDispatch';
+// Real namespace, captured before the mock below replaces the module — lets the
+// mock keep the real `buildCreateHandoffInput` (whose exact output shape the CLI
+// tests assert) while spying on the thread-launch + app-dispatch entry points.
+import * as handoffModule from '@/components/handoff/useHandoffDispatch';
+import {
+ desktopEnabledKey,
+ reloadEnabledAgentsFromStorage,
+ setAgentEnabled,
+} from '@/lib/acp/enabled-agents';
+import { registerAgent, reloadRegisteredAgentsFromStorage } from '@/lib/acp/registered-agents';
import type { Workspace } from '@/lib/workspace-paths';
-mock.module('@lingui/react/macro', () => ({
+vi.doMock('@lingui/react/macro', () => ({
...actualLinguiMacro,
Trans: ({ children }: { children: ReactNode }) => <>{children}</>,
useLingui: () => ({
@@ -26,23 +36,23 @@ mock.module('@lingui/react/macro', () => ({
}),
}));
-mock.module('@/lib/config-context', () => ({
+vi.doMock('@/lib/config-context', () => ({
useConfigContext: () => ({ merged: { appearance: { preview: { autoOpen: true } } } }),
}));
let states: Record<string, InstallState> = {};
-mock.module('@/components/handoff/useInstalledAgents', () => ({
+vi.doMock('@/components/handoff/useInstalledAgents', () => ({
useInstalledAgents: () => ({ states, refresh: () => Promise.resolve() }),
}));
let workspaceValue: Workspace | null = null;
-mock.module('@/lib/use-workspace', () => ({
+vi.doMock('@/lib/use-workspace', () => ({
useWorkspace: () => workspaceValue,
}));
// Stub the brand-icon helper so the test doesn't pull next-themes / SVG vendor
// icons — the composer only needs *an* icon per row, not the themed artwork.
-mock.module('@/components/handoff/OpenInAgentMenuItem', () => ({
+vi.doMock('@/components/handoff/OpenInAgentMenuItem', () => ({
TargetIcon: ({ id }: { id: string }) => (
<svg data-testid={`target-icon-${id}`} aria-hidden="true" />
),
@@ -57,7 +67,7 @@ type MenuChild = {
onSelect?: () => void;
[key: string]: unknown;
};
-mock.module('@/components/ui/dropdown-menu', () => ({
+vi.doMock('@/components/ui/dropdown-menu', () => ({
DropdownMenu: ({ children }: MenuChild) => <div>{children}</div>,
DropdownMenuTrigger: ({ children }: MenuChild) => <>{children}</>,
DropdownMenuContent: ({ children, ...props }: MenuChild) => (
@@ -78,6 +88,27 @@ mock.module('@/components/ui/dropdown-menu', () => ({
DropdownMenuSeparator: () => <hr data-testid="menu-separator" />,
}));
+// Spy on the two handoff entry points the create composer can reach on submit,
+// keeping every other export (notably the real `buildCreateHandoffInput`) intact
+// so the CLI tests still assert its true output. `startAgentThreadForInput` =
+// the in-app thread path; `useHandoffDispatch().dispatch` = the app-agent
+// deep-link path. Which one fires on Enter is exactly what the thread-mode
+// keyboard test below pins.
+const threadLaunchCalls: unknown[] = [];
+const dispatchCalls: Array<{ id: string; input: unknown }> = [];
+vi.doMock('@/components/handoff/useHandoffDispatch', () => ({
+ ...handoffModule,
+ startAgentThreadForInput: (input: unknown) => {
+ threadLaunchCalls.push(input);
+ },
+ useHandoffDispatch: () => ({
+ dispatch: (id: string, input: unknown) => {
+ dispatchCalls.push({ id, input });
+ return Promise.resolve({ ok: true });
+ },
+ }),
+}));
+
// Mentions the mock input returns from getContent(); reset per test.
let mockMentions: string[] = [];
// Textarea double for the rich `@`-mention input: exposes the same imperative
@@ -92,7 +123,7 @@ type MentionHandle = {
setText: (text: string) => void;
getContent: () => { instruction: string; mentions: string[] };
};
-mock.module('@/editor/ComposerMentionInput', () => ({
+vi.doMock('@/editor/ComposerMentionInput', () => ({
ComposerMentionInput: ({
ref,
ariaLabel,
@@ -151,9 +182,18 @@ const launchCalls: HandoffDispatchInput[] = [];
const { CreatePromptComposer } = await import('./CreatePromptComposer');
const { TerminalLaunchProvider } = await import('@/components/handoff/TerminalLaunchContext');
+// Desktop is enablement-gated now (off by default); these tests express Desktop
+// visibility via `states`, so translate installed → enabled at render.
+function enableInstalledDesktopTargets() {
+ for (const [id, state] of Object.entries(states)) {
+ if (state?.installed === true) setAgentEnabled(desktopEnabledKey(id), true);
+ }
+}
+
async function renderComposer(
opts: { withTerminal: boolean; scenario?: CreateScenario } = { withTerminal: true },
) {
+ enableInstalledDesktopTargets();
const value = opts.withTerminal
? { launchInTerminal: (i: HandoffDispatchInput) => launchCalls.push(i), installedClis: {} }
: null;
@@ -173,9 +213,14 @@ describe('CreatePromptComposer Desktop / Terminal sections', () => {
afterEach(() => {
cleanup();
launchCalls.length = 0;
+ threadLaunchCalls.length = 0;
+ dispatchCalls.length = 0;
states = {};
workspaceValue = null;
mockMentions = [];
+ if (typeof localStorage !== 'undefined') localStorage.clear();
+ reloadRegisteredAgentsFromStorage();
+ reloadEnabledAgentsFromStorage();
});
test('renders Desktop and Terminal sections with the CLI launch row when a launcher is present', async () => {
@@ -191,10 +236,13 @@ describe('CreatePromptComposer Desktop / Terminal sections', () => {
Node.DOCUMENT_POSITION_FOLLOWING,
).toBeTruthy();
expect(screen.getByTestId('create-with-cli-claude')).toBeTruthy();
- expect(screen.queryByTestId('menu-separator')).not.toBeNull();
+ // Two separators: Terminal | Desktop, and the Configure agents footer. No
+ // In-app section here (no enabled in-app agents), so no generic thread row.
+ expect(screen.queryAllByTestId('menu-separator')).toHaveLength(2);
+ expect(screen.queryByTestId('create-agent-option-thread')).toBeNull();
});
- test('omits the Terminal section (label, row, separator) on the web host while keeping Desktop', async () => {
+ test('omits the Terminal section (label, row) on the web host while keeping Desktop', async () => {
states = { ...installedAll };
workspaceValue = { contentDir: '/tmp/project', pathSeparator: '/' };
await renderComposer({ withTerminal: false });
@@ -202,7 +250,47 @@ describe('CreatePromptComposer Desktop / Terminal sections', () => {
expect(screen.getByText('Desktop')).toBeTruthy();
expect(screen.queryByText('Terminal')).toBeNull();
expect(screen.queryByTestId('create-with-cli-claude')).toBeNull();
- expect(screen.queryByTestId('menu-separator')).toBeNull();
+ // One separator remains: In-this-app | Desktop (Terminal absent on web).
+ expect(screen.queryAllByTestId('menu-separator')).toHaveLength(1);
+ });
+
+ test('picking an in-app agent row switches the Create button to that agent', async () => {
+ registerAgent({ source: 'registry', id: 'claude-acp', name: 'Claude Agent' });
+ states = { ...installedAll };
+ workspaceValue = { contentDir: '/tmp/project', pathSeparator: '/' };
+ await renderComposer({ withTerminal: true });
+
+ const row = screen.getByTestId('create-agent-option-thread-registry:claude-acp');
+ fireEvent.click(row);
+
+ await waitFor(() => {
+ expect(screen.getByTestId('create-with-agent').textContent).toContain('Start Claude Agent');
+ });
+ // Selecting thread mode does not launch the terminal.
+ expect(launchCalls).toEqual([]);
+ });
+
+ test('Enter in thread mode starts the in-app agent — not an app-agent dispatch', async () => {
+ registerAgent({ source: 'registry', id: 'claude-acp', name: 'Claude Agent' });
+ states = { ...installedAll };
+ workspaceValue = { contentDir: '/tmp/project', pathSeparator: '/' };
+ await renderComposer({ withTerminal: true, scenario: 'new-project' });
+
+ const field = screen.getByLabelText('Describe the project you want to create');
+ fireEvent.change(field, { target: { value: 'Build a coffee wiki' } });
+ fireEvent.click(screen.getByTestId('create-agent-option-thread-registry:claude-acp')); // thread mode
+ await waitFor(() => {
+ expect(screen.getByTestId('create-with-agent').textContent).toContain('Start Claude Agent');
+ });
+
+ // Enter must perform the SAME action as the Create button — launch the in-app
+ // thread — instead of falling through to the app-agent deep-link dispatch (the
+ // regression when handleSubmit lacked the thread branch the button had).
+ fireEvent.keyDown(field, { key: 'Enter' });
+ expect(threadLaunchCalls).toHaveLength(1);
+ expect(threadLaunchCalls[0]).toMatchObject({ createDescription: 'Build a coffee wiki' });
+ expect(dispatchCalls).toEqual([]);
+ expect(launchCalls).toEqual([]);
});
test('selecting the Terminal Claude row switches the button to CLI mode; Create launches with the typed brief', async () => {
diff --git a/packages/app/src/components/empty-state/CreatePromptComposer.tsx b/packages/app/src/components/empty-state/CreatePromptComposer.tsx
index 966bd8c66..35910395c 100644
--- a/packages/app/src/components/empty-state/CreatePromptComposer.tsx
+++ b/packages/app/src/components/empty-state/CreatePromptComposer.tsx
@@ -1,7 +1,9 @@
import { type HandoffTarget, TERMINAL_CLIS, type TerminalCli } from '@inkeep/open-knowledge-core';
import { Trans, useLingui } from '@lingui/react/macro';
-import { ArrowUpRight, Check, ChevronDown, Sparkles } from 'lucide-react';
-import { useEffect, useRef, useState } from 'react';
+import { Check, ChevronDown, SlidersHorizontal, Sparkles } from 'lucide-react';
+import { type ReactNode, useRef, useState } from 'react';
+import { AgentBetaBadge } from '@/components/acp/AgentBetaBadge';
+import { RegisteredAgentIcon } from '@/components/acp/RegisteredAgentIcon';
import {
clearComposerDraft,
getComposerDraft,
@@ -14,11 +16,12 @@ import {
import { focusComposerInputOnCardPointer } from '@/components/focus-composer-on-card-pointer';
import { TargetIcon } from '@/components/handoff/OpenInAgentMenuItem';
import { useTerminalLaunch } from '@/components/handoff/TerminalLaunchContext';
-import { cliIconTargetId, visibleTerminalClis } from '@/components/handoff/terminal-cli-display';
+import { cliIconTargetId } from '@/components/handoff/terminal-cli-display';
import {
buildCreateHandoffInput,
getDisplayNameDefault,
openInstallUrl,
+ startAgentThreadForInput,
useHandoffDispatch,
} from '@/components/handoff/useHandoffDispatch';
import { useInstalledAgents } from '@/components/handoff/useInstalledAgents';
@@ -37,13 +40,30 @@ import {
ComposerMentionInput,
type ComposerMentionInputHandle,
} from '@/editor/ComposerMentionInput';
+import { isDesktopTargetEnabled, isInAppAgentEnabled } from '@/lib/acp/agent-visibility';
+import { useEnabledOverrides } from '@/lib/acp/enabled-agents';
+import {
+ enabledDesktopTargets,
+ enabledTerminalClis,
+ resolveLauncherSelection,
+} from '@/lib/acp/launcher-selection';
+import {
+ pickEffectiveDefaultAgent,
+ type RegisteredAgent,
+ registerAgent,
+ useDefaultRegisteredAgent,
+ useRegisteredAgents,
+} from '@/lib/acp/registered-agents';
import { VISIBLE_TARGETS } from '@/lib/handoff/targets';
import { hasValidPromptInput } from '@/lib/has-valid-prompt-input';
+import { writePreferredAgent } from '@/lib/preferred-agent-store';
import {
- readPreferredAgent,
- resolvePreferredAgent,
- writePreferredAgent,
-} from '@/lib/preferred-agent-store';
+ IN_APP_THREAD_ID,
+ loadStickyAgent,
+ saveStickyAgent,
+ terminalCliId,
+} from '@/lib/unified-agent-store';
+import { openAgentSettings } from '@/lib/use-settings-route';
import { useWorkspace } from '@/lib/use-workspace';
import { cn } from '@/lib/utils';
@@ -52,6 +72,15 @@ interface CreatePromptComposerProps {
readonly className?: string;
}
+/**
+ * "Start {agentName}" with the named placeholder — keeps the catalog message
+ * shared with the launcher menus' t-macro form (`t\`Start ${agentName}\``);
+ * inlining a member expression would emit a positional `{0}` and fork it.
+ */
+function StartAgentNameLabel({ agentName }: { agentName: string }): ReactNode {
+ return <Trans>Start {agentName}</Trans>;
+}
+
/**
* Empty-state prompt composer — a free-form `@`-mention input (the shared
* `ComposerMentionInput`, so the brief can reference existing docs/files as
@@ -80,28 +109,48 @@ interface CreatePromptComposerProps {
export function CreatePromptComposer({ scenario, className }: CreatePromptComposerProps) {
const { t } = useLingui();
const { states, refresh } = useInstalledAgents();
+ const overrides = useEnabledOverrides();
const { dispatch } = useHandoffDispatch();
const workspace = useWorkspace();
// Null on the web host (no docked terminal); non-null only on desktop. Gates
// the chevron menu's "Terminal" launch section.
const terminalLaunch = useTerminalLaunch();
- // Optimistic sync init from device-local memory (no cold-start flash); the
- // probe-reconcile effect below corrects it once install state resolves. `null`
- // means "no agent chosen yet" (first run) or "no installed agent" (post-probe).
- const [selectedAgentId, setSelectedAgentId] = useState<HandoffTarget | null>(() =>
- readPreferredAgent(),
+ // The remembered pick as reactive session state — a unified-agent-store sticky
+ // id, seeded from device-local memory and updated by the picks below. The
+ // effective SELECTION is DERIVED from it every render (never snapshotted at
+ // mount), so enabling/disabling agents in Settings takes effect immediately.
+ const [selectedId, setSelectedId] = useState<string | null>(() => loadStickyAgent());
+
+ const defaultRegisteredAgent = useDefaultRegisteredAgent();
+ // Every registered agent gets a picker row; only the ENABLED ones show.
+ const registeredThreadAgents = useRegisteredAgents();
+ const enabledThreadAgents = registeredThreadAgents.filter((agent) =>
+ isInAppAgentEnabled(overrides, agent.source, agent.id, true, agent.supported),
);
- // Once the user explicitly picks an agent this session, stop auto-reconciling
- // — their choice is authoritative even if the probe later disagrees.
- const userPickedRef = useRef(false);
- // Which docked-terminal CLI is the chosen create target (vs an installed app
- // agent); null when an app agent is selected. Session-only — the
- // preferred-agent store is app-only.
- const [selectedCli, setSelectedCli] = useState<TerminalCli | null>(null);
- // The CLI is the active create target only when one is selected AND the
- // docked terminal is available (the web host has no shell).
- const cliSelected = selectedCli !== null && terminalLaunch !== null;
+ // The in-app agent the primary launches + names: the registered default when
+ // still enabled, else the first enabled one.
+ const defaultThreadAgent = pickEffectiveDefaultAgent(enabledThreadAgents, defaultRegisteredAgent);
+
+ // One selection decision, enablement-aware for every category — the SAME
+ // `resolveLauncherSelection` the footer composer + sessions dock use, so a
+ // disabled agent / CLI / app is never the Create target on any surface.
+ const selection = resolveLauncherSelection({
+ sticky: selectedId,
+ effectiveThreadAgent: defaultThreadAgent,
+ enabledClis:
+ terminalLaunch !== null ? enabledTerminalClis(overrides, terminalLaunch.installedClis) : [],
+ enabledDesktopTargets: enabledDesktopTargets(overrides),
+ installedClis: terminalLaunch?.installedClis ?? {},
+ terminalAvailable: terminalLaunch !== null,
+ threadsAvailable: true,
+ desktopSelectable: true,
+ });
+ const threadSelected = selection.kind === 'thread';
+ const selectedCli: TerminalCli | null = selection.kind === 'cli' ? selection.cli : null;
+ const selectedAgentId: HandoffTarget | null =
+ selection.kind === 'desktop' ? selection.target : null;
+ const cliSelected = selectedCli !== null;
const inputRef = useRef<ComposerMentionInputHandle>(null);
@@ -136,37 +185,75 @@ export function CreatePromptComposer({ scenario, className }: CreatePromptCompos
// Starter-brief chips, per surface — shared with the embedded CopyablePromptList.
const suggestions = useCreateSuggestions(scenario);
- // Installed agents only — there's no web fallback, so an agent that can't be
- // launched is never offered (mirrors the "Open with AI" menu).
- const selectableTargets = VISIBLE_TARGETS.filter(
- (target) => states[target.id]?.installed === true,
+ // Desktop rows are the agents the user ENABLED in Configure agents (Desktop is
+ // off by default; enabling is opt-in). An enabled-but-not-installed agent
+ // still shows and routes to its installer on Create.
+ const selectableTargets = VISIBLE_TARGETS.filter((target) =>
+ isDesktopTargetEnabled(overrides, target.id),
);
const probeSettled = VISIBLE_TARGETS.every((target) => states[target.id]?.installed != null);
- // Probe done with nothing installed → the composer has nothing to launch.
- const noAgentsInstalled = probeSettled && selectableTargets.length === 0;
-
- // Smart default: once the install probe settles, resolve last-used → first
- // installed → null (see `resolvePreferredAgent`). Gated on `userPickedRef` so
- // it never overrides a manual selection, and on the probe being fully resolved
- // so a partial result doesn't bounce the button mid-probe.
- useEffect(() => {
- if (!probeSettled || userPickedRef.current) return;
- const resolved = resolvePreferredAgent({ lastUsed: readPreferredAgent(), states });
- setSelectedAgentId((current) => (resolved === current ? current : resolved));
- }, [probeSettled, states]);
+ const hasEnabledTerminalCli =
+ terminalLaunch !== null &&
+ enabledTerminalClis(overrides, terminalLaunch.installedClis).length > 0;
+ // Collapse to the install nudge only when the user has nothing enabled at all
+ // (in-app agents are seeded on by default, so this is rare). Otherwise the
+ // composer defaults to in-app thread mode.
+ const noAgentsInstalled =
+ probeSettled &&
+ selectableTargets.length === 0 &&
+ enabledThreadAgents.length === 0 &&
+ !hasEnabledTerminalCli;
+ // Every pick just updates the one sticky id (persisted + reactive); the
+ // selection re-derives above. No probe-reconcile effect and no `userPickedRef`
+ // — an explicit pick simply wins because it IS the sticky value, and a stale
+ // pick (a disabled agent/CLI/app) degrades through `resolveLauncherSelection`.
function chooseAgent(targetId: HandoffTarget) {
- userPickedRef.current = true;
- setSelectedCli(null);
- setSelectedAgentId(targetId);
- writePreferredAgent(targetId);
+ setSelectedId(targetId);
+ saveStickyAgent(targetId);
+ writePreferredAgent(targetId); // legacy key, kept for cross-surface back-compat
}
- // Select a docked-terminal CLI as the create target. Session-only; the Create
- // button performs the launch, parallel to chooseAgent setting the app default.
function chooseCli(cli: TerminalCli) {
- userPickedRef.current = true;
- setSelectedCli(cli);
+ setSelectedId(terminalCliId(cli));
+ saveStickyAgent(terminalCliId(cli));
+ }
+
+ // Picking a specific registered agent makes it the launch default and selects
+ // in-app thread mode.
+ function chooseThreadAgent(agent: RegisteredAgent) {
+ registerAgent(agent);
+ setSelectedId(IN_APP_THREAD_ID);
+ saveStickyAgent(IN_APP_THREAD_ID);
+ }
+
+ // Open a server-hosted in-app agent thread with the composed brief, mirroring
+ // handleCreate's validation + draft-clear. No deep-link dispatch.
+ function launchThread() {
+ const { instruction, mentions } = inputRef.current?.getContent() ?? {
+ instruction: '',
+ mentions: [],
+ };
+ if (!hasValidPromptInput(instruction, mentions, false)) {
+ setShowRequiredError(true);
+ return;
+ }
+ const input = buildCreateHandoffInput({
+ workspace,
+ description: instruction,
+ scenario,
+ mentions,
+ });
+ if (input === null) return;
+ // Launch the effective (enabled) agent explicitly, never a disabled default.
+ startAgentThreadForInput(
+ input,
+ defaultThreadAgent !== null
+ ? { agent: { source: defaultThreadAgent.source, id: defaultThreadAgent.id } }
+ : undefined,
+ );
+ inputRef.current?.clear();
+ clearComposerDraft();
}
function launchCli() {
@@ -210,6 +297,13 @@ export function CreatePromptComposer({ scenario, className }: CreatePromptCompos
}
// Remember what was launched so the next visit defaults to it.
writePreferredAgent(targetId);
+ // An enabled-but-not-installed Desktop agent routes to its installer
+ // rather than a failing deep-link dispatch.
+ if (states[targetId]?.installed !== true) {
+ const target = VISIBLE_TARGETS.find((candidate) => candidate.id === targetId);
+ if (target) void openInstallUrl(target);
+ return;
+ }
const input = buildCreateHandoffInput({
workspace,
description: instruction,
@@ -224,11 +318,16 @@ export function CreatePromptComposer({ scenario, className }: CreatePromptCompos
clearComposerDraft();
}
- // Enter (handled inside ComposerMentionInput) creates with the resolved target
- // — the docked-terminal CLI when selected, else the chosen app agent. A null
- // agent (probe still settling) is a no-op, matching the disabled Create button.
+ // Enter (handled inside ComposerMentionInput) must perform the SAME action as
+ // the primary Create button so keyboard and pointer never diverge: launch the
+ // in-app agent thread when thread mode is selected, else the docked-terminal
+ // CLI, else the chosen app agent. The branch ORDER mirrors the button's onClick
+ // (thread → CLI → app agent). A null agent with none of those selected (probe
+ // still settling) is a no-op, matching the disabled Create button.
function handleSubmit() {
- if (cliSelected) {
+ if (threadSelected) {
+ launchThread();
+ } else if (cliSelected) {
launchCli();
} else if (selectedAgentId !== null) {
handleCreate(selectedAgentId);
@@ -245,10 +344,10 @@ export function CreatePromptComposer({ scenario, className }: CreatePromptCompos
inputRef.current?.focus();
}
- // No agent to launch → the composer can't do anything, so collapse it to a
- // compact "install an agent" nudge instead of a dead input. Keeps the AI
- // capability discoverable + funnels to install, without the layout pop of
- // hiding the surface entirely.
+ // Nothing enabled to launch → the composer can't do anything, so collapse it
+ // to a compact nudge that points at Configure agents instead of a dead input.
+ // We no longer pitch desktop-app installs here: Desktop is opt-in and the
+ // in-app agents are the first-class path, so "turn one on" is the honest CTA.
if (noAgentsInstalled) {
return (
<div
@@ -261,40 +360,36 @@ export function CreatePromptComposer({ scenario, className }: CreatePromptCompos
<div className="flex min-w-0 items-center gap-2.5">
<Sparkles aria-hidden="true" className="size-4 shrink-0 text-muted-foreground" />
<span className="text-1sm text-muted-foreground">
- <Trans>Install an AI agent to create with AI</Trans>
+ <Trans>Turn on an agent to create with AI</Trans>
</span>
</div>
- <div className="flex flex-wrap items-center gap-1.5">
- {VISIBLE_TARGETS.map((target) => (
- <Button
- key={target.id}
- type="button"
- variant="outline"
- size="sm"
- onClick={() => void openInstallUrl(target)}
- className="gap-1.5"
- data-testid={`install-agent-${target.id}`}
- >
- <TargetIcon id={target.id} aria-hidden="true" className="size-3.5" />
- {target.displayName}
- <ArrowUpRight aria-hidden="true" className="size-3" />
- </Button>
- ))}
- </div>
+ <Button
+ type="button"
+ variant="outline"
+ size="sm"
+ onClick={openAgentSettings}
+ className="gap-1.5"
+ data-testid="create-configure-agents"
+ >
+ <SlidersHorizontal aria-hidden="true" className="size-3.5" />
+ <Trans>Configure agents</Trans>
+ </Button>
</div>
);
}
- // Chevron-menu sections: installed app agents under "Desktop", the docked CLIs
- // under "Terminal". The separator sits between them only when both render.
- const showDesktopSection = selectableTargets.length > 0;
- const showTerminalSection = terminalLaunch !== null;
- // Claude plus every CLI the probe hasn't ruled out (fail-open), and always the
- // current pick (`selectedCli`) so this composer's own Create target can't be
- // gated out of its own dropdown.
+ // Chevron-menu sections. Each renders only when it has rows, so an empty
+ // section header never shows. The Terminal CLIs are the ones enabled in
+ // Configure agents.
const terminalClis = terminalLaunch
- ? visibleTerminalClis(terminalLaunch.installedClis, selectedCli)
+ ? enabledTerminalClis(overrides, terminalLaunch.installedClis)
: [];
+ const showDesktopSection = selectableTargets.length > 0;
+ const showTerminalSection = terminalClis.length > 0;
+ const showThreadSection = enabledThreadAgents.length > 0;
+ // The Create button is actionable whenever the resolver found something enabled
+ // to launch (an in-app thread, a CLI, or a picked desktop app).
+ const canCreate = selection.kind !== 'none';
return (
<div className={cn('flex w-full flex-col gap-3', className)}>
@@ -338,8 +433,8 @@ export function CreatePromptComposer({ scenario, className }: CreatePromptCompos
) : (
<span />
)}
- {selectedAgentId === null ? (
- // No agent resolved yet (probe still settling) — nothing to launch.
+ {!canCreate ? (
+ // Nothing enabled to launch yet — a disabled affordance.
<Button
type="button"
variant="outline"
@@ -356,12 +451,29 @@ export function CreatePromptComposer({ scenario, className }: CreatePromptCompos
<ButtonGroup>
<Button
type="button"
- onClick={() => (cliSelected ? launchCli() : handleCreate(selectedAgentId))}
+ onClick={() =>
+ threadSelected
+ ? launchThread()
+ : cliSelected
+ ? launchCli()
+ : selectedAgentId !== null
+ ? handleCreate(selectedAgentId)
+ : undefined
+ }
variant="outline"
className="gap-1.5"
data-testid="create-with-agent"
>
- {cliSelected && selectedCli !== null ? (
+ {threadSelected && defaultThreadAgent !== null ? (
+ <>
+ <RegisteredAgentIcon
+ agentId={defaultThreadAgent.id}
+ iconUrl={defaultThreadAgent.iconUrl}
+ className="size-3.5"
+ />
+ <StartAgentNameLabel agentName={defaultThreadAgent.name} />
+ </>
+ ) : cliSelected && selectedCli !== null ? (
<>
<TargetIcon
id={cliIconTargetId(selectedCli)}
@@ -370,12 +482,12 @@ export function CreatePromptComposer({ scenario, className }: CreatePromptCompos
/>
<Trans>Create with {TERMINAL_CLIS[selectedCli].displayName} CLI</Trans>
</>
- ) : (
+ ) : selectedAgentId !== null ? (
<>
<TargetIcon id={selectedAgentId} aria-hidden="true" className="size-3.5" />
<Trans>Create with {getDisplayNameDefault(selectedAgentId)}</Trans>
</>
- )}
+ ) : null}
</Button>
<DropdownMenu
onOpenChange={(open) => {
@@ -393,7 +505,40 @@ export function CreatePromptComposer({ scenario, className }: CreatePromptCompos
<ChevronDown aria-hidden="true" className="size-3.5" />
</Button>
</DropdownMenuTrigger>
- <DropdownMenuContent align="end" className="min-w-[200px]">
+ <DropdownMenuContent align="end" className="max-h-80 min-w-[200px]">
+ {/* In-app agent threads lead the menu when any is enabled;
+ an empty section (all disabled) is hidden entirely. */}
+ {showThreadSection ? (
+ <DropdownMenuGroup aria-label={t`In app (beta)`}>
+ <DropdownMenuLabel className="flex items-center gap-1.5">
+ <Trans>In app</Trans>
+ <AgentBetaBadge />
+ </DropdownMenuLabel>
+ {enabledThreadAgents.map((agent) => (
+ <DropdownMenuItem
+ key={`${agent.source}:${agent.id}`}
+ onSelect={() => chooseThreadAgent(agent)}
+ data-testid={`create-agent-option-thread-${agent.source}:${agent.id}`}
+ >
+ <RegisteredAgentIcon
+ agentId={agent.id}
+ iconUrl={agent.iconUrl}
+ className="size-4"
+ />
+ <span className="flex-1 truncate">{agent.name}</span>
+ {threadSelected &&
+ defaultThreadAgent !== null &&
+ defaultThreadAgent.source === agent.source &&
+ defaultThreadAgent.id === agent.id ? (
+ <Check aria-hidden="true" className="size-4 text-muted-foreground" />
+ ) : null}
+ </DropdownMenuItem>
+ ))}
+ </DropdownMenuGroup>
+ ) : null}
+ {showThreadSection && (showTerminalSection || showDesktopSection) ? (
+ <DropdownMenuSeparator />
+ ) : null}
{showTerminalSection ? (
// Terminal section leads (the in-app terminal is the
// first-class path). Labeled `role="group"` so assistive tech
@@ -455,6 +600,22 @@ export function CreatePromptComposer({ scenario, className }: CreatePromptCompos
</DropdownMenuGroup>
</>
) : null}
+ {/* Settings row — always last. Opens Configure agents so the
+ user manages which agents appear here (replaces the former
+ "Choose another agent" catalog affordance). */}
+ <DropdownMenuSeparator />
+ <DropdownMenuItem
+ onSelect={openAgentSettings}
+ data-testid="create-agent-option-settings"
+ >
+ <SlidersHorizontal
+ aria-hidden="true"
+ className="size-4 text-muted-foreground"
+ />
+ <span className="flex-1">
+ <Trans>Configure agents</Trans>
+ </span>
+ </DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
</ButtonGroup>
diff --git a/packages/app/src/components/focus-composer-on-card-pointer.ts b/packages/app/src/components/focus-composer-on-card-pointer.ts
index 240556d00..bc71e3f37 100644
--- a/packages/app/src/components/focus-composer-on-card-pointer.ts
+++ b/packages/app/src/components/focus-composer-on-card-pointer.ts
@@ -1,14 +1,15 @@
/**
- * Shared "click the card, focus the field" affordance for the two Ask AI
- * composers (the bottom docked composer and the empty-state create composer).
+ * Shared "click the card, focus the field" affordance for the composer cards:
+ * the two Ask AI composers (ProseMirror `ComposerMentionInput` contentEditable)
+ * and the agent-thread composer (native `<textarea>`).
*
- * Both wrap a ProseMirror `contentEditable` (`ComposerMentionInput`), not a
- * native `<input>`/`<textarea>`. A contentEditable focuses on click only within
- * its OWN box, and — unlike a labelable form control — a wrapping `<label>`
- * cannot forward a click into it (CSS/HTML can't move focus into a
- * contentEditable). So the standard chat-composer affordance (ChatGPT / Claude /
- * Cursor: click anywhere in the field's card to focus the input) needs this
- * pointer handler on the card.
+ * A contentEditable focuses on click only within its OWN box, and — unlike a
+ * labelable form control — a wrapping `<label>` cannot forward a click into it,
+ * so the standard chat-composer affordance (ChatGPT / Claude / Cursor: click
+ * anywhere in the field's card to focus the input) needs this pointer handler.
+ * The agent-thread composer's chrome (wrapper padding, the whitespace in the
+ * action bar between the settings menu and the send button) isn't wrapped in a
+ * label either, so it reuses the same handler against its textarea ref.
*
* a11y: this is a pointer-only progressive enhancement. The card keeps passive
* semantics (no `role`/`tabindex`) — the real control is the inner textbox,
@@ -17,7 +18,6 @@
*/
import type { RefObject } from 'react';
-import type { ComposerMentionInputHandle } from '@/editor/ComposerMentionInput';
// Interactive descendants that own their own click: real buttons/links, menu
// items, native form fields, and the editable itself (let the browser place the
@@ -36,7 +36,10 @@ const INTERACTIVE_TARGET_SELECTOR =
*/
export function focusComposerInputOnCardPointer(
event: { target: EventTarget | null; preventDefault: () => void },
- inputRef: RefObject<ComposerMentionInputHandle | null>,
+ // Any focusable input handle — the ProseMirror `ComposerMentionInputHandle`
+ // (Ask AI composers) or a native `HTMLTextAreaElement` (the agent-thread
+ // composer). Both expose `focus()`.
+ inputRef: RefObject<{ focus: () => void } | null>,
): void {
if (!(event.target instanceof HTMLElement) || event.target.closest(INTERACTIVE_TARGET_SELECTOR)) {
return;
diff --git a/packages/app/src/components/graph-view-utils.test.ts b/packages/app/src/components/graph-view-utils.test.ts
index 1a9c67287..e9ce20f48 100644
--- a/packages/app/src/components/graph-view-utils.test.ts
+++ b/packages/app/src/components/graph-view-utils.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import {
buildGraphLinkSignature,
@@ -552,3 +552,114 @@ describe('buildGraphLinkSignature', () => {
).toBe('notes/alpha>notes/beta,notes/beta>notes/gamma');
});
});
+
+describe('reconcileGraphData — staged entrance (showcase)', () => {
+ const doc = (id: string) => ({
+ kind: 'doc' as const,
+ id,
+ label: id,
+ docName: id,
+ anchor: null,
+ });
+ const NOW = 1_000_000;
+ const entrance = { nodeStepMs: 140, linkExtraMs: 260 };
+
+ test('a clump of new nodes staggers sequentially; links wait for both endpoints', () => {
+ const merged = reconcileGraphData(
+ { nodes: [doc('hub')], links: [] },
+ {
+ nodes: [doc('hub'), doc('a'), doc('b'), doc('c')],
+ links: [
+ { source: 'hub', target: 'a' },
+ { source: 'a', target: 'c' },
+ ],
+ },
+ NOW,
+ entrance,
+ );
+ const bornById = new Map(merged.nodes.map((node) => [node.id, node.bornAt]));
+ expect(bornById.get('a')).toBe(NOW);
+ expect(bornById.get('b')).toBe(NOW + 140);
+ expect(bornById.get('c')).toBe(NOW + 280);
+ // hub pre-existed with no bornAt → stamped now (no stagger for survivors).
+ expect(bornById.get('hub')).toBe(NOW);
+ // hub>a waits for a; a>c waits for c (the later endpoint).
+ expect(merged.links[0]?.bornAt).toBe(NOW + 260);
+ expect(merged.links[1]?.bornAt).toBe(NOW + 280 + 260);
+ });
+
+ test('a lone arrival gets no artificial delay', () => {
+ const merged = reconcileGraphData(
+ { nodes: [doc('hub')], links: [] },
+ { nodes: [doc('hub'), doc('solo')], links: [{ source: 'hub', target: 'solo' }] },
+ NOW,
+ entrance,
+ );
+ expect(merged.nodes.find((node) => node.id === 'solo')?.bornAt).toBe(NOW);
+ expect(merged.links[0]?.bornAt).toBe(NOW + 260);
+ });
+
+ test('surviving links keep their original bornAt across staggered applies', () => {
+ const first = reconcileGraphData(
+ { nodes: [], links: [] },
+ { nodes: [doc('a'), doc('b')], links: [{ source: 'a', target: 'b' }] },
+ NOW,
+ entrance,
+ );
+ const second = reconcileGraphData(
+ first,
+ { nodes: [doc('a'), doc('b'), doc('c'), doc('d')], links: [{ source: 'a', target: 'b' }] },
+ NOW + 5_000,
+ entrance,
+ );
+ expect(second.links[0]?.bornAt).toBe(first.links[0]?.bornAt);
+ });
+
+ test('without entrance options behavior is unchanged (everything born now)', () => {
+ const merged = reconcileGraphData(
+ { nodes: [], links: [] },
+ { nodes: [doc('a'), doc('b')], links: [{ source: 'a', target: 'b' }] },
+ NOW,
+ );
+ expect(merged.nodes.every((node) => node.bornAt === NOW)).toBe(true);
+ expect(merged.links[0]?.bornAt).toBe(NOW);
+ });
+});
+
+describe('reconcileGraphData — instant baseline (pre-build content)', () => {
+ const doc = (id: string) => ({
+ kind: 'doc' as const,
+ id,
+ label: id,
+ docName: id,
+ anchor: null,
+ });
+ const NOW = 2_000_000;
+
+ test('fresh mount: baseline nodes/links are instantly present; only additions stagger', () => {
+ const merged = reconcileGraphData(
+ { nodes: [], links: [] },
+ {
+ nodes: [doc('old-1'), doc('old-2'), doc('new-1'), doc('new-2')],
+ links: [
+ { source: 'old-1', target: 'old-2' },
+ { source: 'new-1', target: 'new-2' },
+ ],
+ },
+ NOW,
+ {
+ nodeStepMs: 140,
+ linkExtraMs: 260,
+ instantNodeIds: new Set(['old-1', 'old-2']),
+ instantLinkKeys: new Set(['old-1>old-2']),
+ },
+ );
+ const bornById = new Map(merged.nodes.map((node) => [node.id, node.bornAt]));
+ expect(bornById.get('old-1')).toBe(0);
+ expect(bornById.get('old-2')).toBe(0);
+ expect(bornById.get('new-1')).toBe(NOW);
+ expect(bornById.get('new-2')).toBe(NOW + 140);
+ expect(merged.links[0]?.bornAt).toBe(0);
+ expect(merged.links[1]?.bornAt).toBe(NOW + 140 + 260);
+ });
+});
diff --git a/packages/app/src/components/graph-view-utils.ts b/packages/app/src/components/graph-view-utils.ts
index 6bfbe77a8..b7647b813 100644
--- a/packages/app/src/components/graph-view-utils.ts
+++ b/packages/app/src/components/graph-view-utils.ts
@@ -9,6 +9,8 @@ interface DocGraphNode {
cluster?: string | null;
category?: string | null;
tags?: string[] | null;
+ /** Wall-clock ms this node first entered the rendered graph (birth animation). */
+ bornAt?: number;
}
interface ExternalGraphNode {
@@ -16,6 +18,8 @@ interface ExternalGraphNode {
id: string;
label: string;
url: string;
+ /** Wall-clock ms this node first entered the rendered graph (birth animation). */
+ bornAt?: number;
}
export type GraphNode = DocGraphNode | ExternalGraphNode;
@@ -23,6 +27,8 @@ export type GraphNode = DocGraphNode | ExternalGraphNode;
export interface GraphLink {
source: string;
target: string;
+ /** Wall-clock ms this link first entered the rendered graph (fade-in). */
+ bornAt?: number;
}
export interface GraphData {
@@ -122,18 +128,67 @@ export function buildGraphLinkSignature(links: GraphLink[]): string {
.join(',');
}
-export function reconcileGraphData(previous: GraphData, next: GraphData): GraphData {
+/**
+ * Staged-entrance pacing for `reconcileGraphData`. Agents deliver a whole
+ * page batch in one CC1 push, so every new node would otherwise stamp the
+ * same `bornAt` and bloom simultaneously. With entrance options, the i-th
+ * new node of an apply is born `i * nodeStepMs` later (a sequential pop-in
+ * replay of the build), and each new link waits for BOTH endpoints plus
+ * `linkExtraMs`, so edges draw between nodes that are already visible.
+ */
+export interface ReconcileEntranceOptions {
+ nodeStepMs: number;
+ linkExtraMs: number;
+ /**
+ * Pre-build content (the showcase's build-start baseline): these nodes and
+ * links materialize INSTANTLY (`bornAt: 0`, no birth animation) even on a
+ * fresh mount — the staged replay is for what the agent ADDED, not for
+ * re-birthing everything that already existed.
+ */
+ instantNodeIds?: ReadonlySet<string>;
+ instantLinkKeys?: ReadonlySet<string>;
+}
+
+/**
+ * Merge a fresh API graph into the rendered one, preserving force-layout
+ * physics for surviving nodes and stamping `bornAt` on first appearance so the
+ * canvas can fade/scale new nodes and links in. `now` is injectable for tests.
+ * `entrance` (showcase mode) staggers same-apply arrivals — see
+ * {@link ReconcileEntranceOptions}.
+ */
+export function reconcileGraphData(
+ previous: GraphData,
+ next: GraphData,
+ now: number = Date.now(),
+ entrance?: ReconcileEntranceOptions,
+): GraphData {
const previousNodesById = new Map(
(previous.nodes as MutableGraphNode[]).map((node) => [node.id, node] as const),
);
+ const newNodes: MutableGraphNode[] = [];
const nextNodes = next.nodes.map((node) => {
const mergedNode = { ...node } as MutableGraphNode;
const previousNode = previousNodesById.get(node.id);
if (previousNode) {
copyGraphNodePhysics(mergedNode, previousNode);
+ mergedNode.bornAt = previousNode.bornAt ?? now;
+ } else if (entrance?.instantNodeIds?.has(node.id)) {
+ // Pre-build content on a fresh mount — present, not born.
+ mergedNode.bornAt = 0;
+ } else {
+ mergedNode.bornAt = now;
+ newNodes.push(mergedNode);
}
return mergedNode as GraphNode;
});
+ // A lone arrival needs no pacing; a clump gets the sequential entrance.
+ // API order approximates creation order (the write batch is ordered).
+ if (entrance !== undefined && newNodes.length > 1) {
+ newNodes.forEach((node, index) => {
+ node.bornAt = now + index * entrance.nodeStepMs;
+ });
+ }
+ const nodeBornById = new Map(nextNodes.map((node) => [node.id, node.bornAt] as const));
const previousLinksByKey = new Map(
(previous.links as MutableGraphLink[]).map((link) => [
@@ -143,15 +198,27 @@ export function reconcileGraphData(previous: GraphData, next: GraphData): GraphD
);
const nextLinks = next.links.map((link) => {
const mergedLink = { ...link } as MutableGraphLink;
- const previousLink = previousLinksByKey.get(
- `${getGraphLinkEndpointId(link.source)}>${getGraphLinkEndpointId(link.target)}`,
- );
+ const sourceId = getGraphLinkEndpointId(link.source);
+ const targetId = getGraphLinkEndpointId(link.target);
+ const previousLink = previousLinksByKey.get(`${sourceId}>${targetId}`);
// __indexColor is force-graph's internal canvas hit-test identifier.
// The map is keyed by source>target, so this only copies the color when
// the exact same endpoint pair reappears — never leaks across different links.
if (previousLink?.__indexColor) {
mergedLink.__indexColor = previousLink.__indexColor;
}
+ if (previousLink?.bornAt !== undefined) {
+ mergedLink.bornAt = previousLink.bornAt;
+ } else if (entrance?.instantLinkKeys?.has(`${sourceId}>${targetId}`)) {
+ // Pre-build link on a fresh mount — present, not born.
+ mergedLink.bornAt = 0;
+ } else if (entrance !== undefined) {
+ mergedLink.bornAt =
+ Math.max(now, nodeBornById.get(sourceId) ?? now, nodeBornById.get(targetId) ?? now) +
+ entrance.linkExtraMs;
+ } else {
+ mergedLink.bornAt = now;
+ }
return mergedLink as GraphLink;
});
diff --git a/packages/app/src/components/handoff/AgentSplitButton.non-modal.dom.test.tsx b/packages/app/src/components/handoff/AgentSplitButton.non-modal.dom.test.tsx
new file mode 100644
index 000000000..6e725a415
--- /dev/null
+++ b/packages/app/src/components/handoff/AgentSplitButton.non-modal.dom.test.tsx
@@ -0,0 +1,73 @@
+/**
+ * The composer agent picker can hand directly to the modal agent catalog.
+ * Keeping the picker non-modal prevents Radix's dropdown pointer lock from
+ * surviving that surface transition and making the app appear frozen.
+ */
+
+import { cleanup, render, screen } from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
+import { afterEach, describe, expect, test } from 'vitest';
+import { AgentSplitButton } from './AgentSplitButton';
+
+type WindowGlobals = { NodeFilter?: typeof NodeFilter };
+type GlobalWithDomShims = typeof globalThis &
+ WindowGlobals & { window?: WindowGlobals; ResizeObserver?: unknown };
+const globalWithDomShims = globalThis as GlobalWithDomShims;
+if (
+ globalWithDomShims.NodeFilter === undefined &&
+ globalWithDomShims.window?.NodeFilter !== undefined
+) {
+ globalWithDomShims.NodeFilter = globalWithDomShims.window.NodeFilter;
+}
+if (globalWithDomShims.ResizeObserver === undefined) {
+ class NoopResizeObserver {
+ observe() {}
+ unobserve() {}
+ disconnect() {}
+ }
+ globalWithDomShims.ResizeObserver = NoopResizeObserver;
+}
+
+describe('AgentSplitButton non-modal contract', () => {
+ afterEach(() => {
+ cleanup();
+ document.body.style.pointerEvents = '';
+ });
+
+ test('opening the composer picker leaves the rest of the app interactive', async () => {
+ const user = userEvent.setup();
+ render(
+ <AgentSplitButton
+ primary="Ask Claude"
+ onPrimary={() => {}}
+ installedTargets={[]}
+ selectedTargetId={null}
+ onSelectTarget={() => {}}
+ thread={{ selected: true, onSelect: () => {} }}
+ threadAgents={[
+ {
+ key: 'registry:claude-acp',
+ id: 'claude-acp',
+ name: 'Claude',
+ selected: true,
+ onSelect: () => {},
+ },
+ ]}
+ onBrowseThreadAgents={() => {}}
+ triggerAriaLabel="Choose agent"
+ testIds={{
+ primary: 'primary',
+ trigger: 'trigger',
+ menu: 'menu',
+ option: (id) => `option-${id}`,
+ terminal: 'terminal',
+ threadBrowse: 'browse',
+ }}
+ />,
+ );
+
+ await user.click(screen.getByTestId('trigger'));
+ expect(screen.getByTestId('menu')).toBeDefined();
+ expect(document.body.style.pointerEvents).not.toBe('none');
+ });
+});
diff --git a/packages/app/src/components/handoff/AgentSplitButton.tsx b/packages/app/src/components/handoff/AgentSplitButton.tsx
index a89aeebb7..0cea7a45f 100644
--- a/packages/app/src/components/handoff/AgentSplitButton.tsx
+++ b/packages/app/src/components/handoff/AgentSplitButton.tsx
@@ -1,7 +1,9 @@
import type { HandoffTarget, TargetData, TerminalCli } from '@inkeep/open-knowledge-core';
import { Trans, useLingui } from '@lingui/react/macro';
-import { Check, ChevronDown } from 'lucide-react';
+import { Check, ChevronDown, SlidersHorizontal } from 'lucide-react';
import type { ReactNode } from 'react';
+import { AgentBetaBadge } from '@/components/acp/AgentBetaBadge';
+import { RegisteredAgentIcon } from '@/components/acp/RegisteredAgentIcon';
import { TargetIcon } from '@/components/handoff/OpenInAgentMenuItem';
import { cliIconTargetId } from '@/components/handoff/terminal-cli-display';
import { Button } from '@/components/ui/button';
@@ -30,10 +32,10 @@ import {
* caller decides whether to render this at all (e.g. the empty-state swaps in a
* disabled standalone button until an agent resolves).
*
- * Uses a DropdownMenu (not a Popover): the Electron pointerdown hazard only
- * bites Radix triggers inside `-webkit-app-region: drag` chrome, and both
- * consumers sit in the content area. See ProjectSwitcher for the drag-region
- * case that genuinely needs the workaround.
+ * Uses a non-modal DropdownMenu (not a Popover): these are menu actions, but
+ * "Choose another agent" hands directly to a modal dialog. A modal dropdown
+ * would leave Radix's body pointer lock active during that handoff and make the
+ * catalog appear frozen.
*/
/**
* One CLI row in the "Terminal" section — a docked-terminal launcher for a
@@ -51,6 +53,25 @@ export interface TerminalCliRow {
readonly onSelect: () => void;
}
+/**
+ * One registered in-app agent in the "In this app" section — selecting it
+ * makes that agent the thread target (the parent owns registration/default
+ * bumping). When any of these exist, they replace the single generic
+ * "Start an agent" row so the first registration never locks the choice in.
+ */
+export interface ThreadAgentRow {
+ /** Stable row key (`<source>:<id>`). */
+ readonly key: string;
+ /** Registry/custom agent id used to select a known local brand icon. */
+ readonly id: string;
+ /** Agent display name ("Claude Agent"). */
+ readonly name: string;
+ /** Registry-manifest icon URL, when any. */
+ readonly iconUrl?: string;
+ readonly selected: boolean;
+ readonly onSelect: () => void;
+}
+
export interface AgentSplitButtonTestIds {
/** The primary action button. */
primary: string;
@@ -65,6 +86,10 @@ export interface AgentSplitButtonTestIds {
* `terminal` slot; a function keys each row of the `terminals` array by CLI.
*/
terminal: string | ((cli: TerminalCli) => string);
+ /** Per-registered-agent thread row testid, keyed by the row key. */
+ threadAgent?: (key: string) => string;
+ /** The "Settings" row testid — opens Configure agents. */
+ settings?: string;
}
export function AgentSplitButton({
@@ -74,6 +99,8 @@ export function AgentSplitButton({
installedTargets,
selectedTargetId,
onSelectTarget,
+ threadAgents,
+ onOpenSettings,
terminal,
terminals,
menuEmptyState,
@@ -103,6 +130,17 @@ export function AgentSplitButton({
* renders these rows instead of the legacy single {@link terminal} slot.
*/
terminals?: readonly TerminalCliRow[];
+ /**
+ * Enabled in-app agents, one selectable row each. When empty, the "In app"
+ * group is hidden entirely (no generic fallback row).
+ */
+ threadAgents?: readonly ThreadAgentRow[];
+ /**
+ * Opens Settings → Configure agents — rendered as the last row of the menu so
+ * the user manages which agents appear here. Replaces the former catalog
+ * "Choose another agent…" affordance.
+ */
+ onOpenSettings: () => void;
/** Rendered inside the menu when there are no app agents and no terminal. */
menuEmptyState?: ReactNode;
onMenuOpenChange?: (open: boolean) => void;
@@ -115,6 +153,7 @@ export function AgentSplitButton({
const cliRows = terminals && terminals.length > 0 ? terminals : null;
const showTerminal = cliRows != null || terminal != null;
const hasOptions = showDesktop || showTerminal;
+ const showThreadAgents = threadAgents !== undefined && threadAgents.length > 0;
// The terminal-row testid is either a static string (legacy slot) or a
// per-CLI function (N-row mode); normalize to a per-CLI resolver here.
const terminalTestId = (cli: TerminalCli): string =>
@@ -135,7 +174,7 @@ export function AgentSplitButton({
>
{primary}
</Button>
- <DropdownMenu onOpenChange={onMenuOpenChange}>
+ <DropdownMenu modal={false} onOpenChange={onMenuOpenChange}>
<DropdownMenuTrigger asChild>
<Button
type="button"
@@ -147,7 +186,41 @@ export function AgentSplitButton({
<ChevronDown aria-hidden="true" className="size-3.5 text-muted-foreground" />
</Button>
</DropdownMenuTrigger>
- <DropdownMenuContent align={menuAlign} className="min-w-[200px]" data-testid={testIds.menu}>
+ <DropdownMenuContent
+ align={menuAlign}
+ className="max-h-80 min-w-[200px]"
+ data-testid={testIds.menu}
+ >
+ {showThreadAgents ? (
+ // In-app agent threads lead the menu when any is enabled; an empty
+ // section (all disabled) is hidden entirely.
+ <>
+ <DropdownMenuGroup aria-label={t`In app (beta)`}>
+ <DropdownMenuLabel className="flex items-center gap-1.5">
+ <Trans>In app</Trans>
+ <AgentBetaBadge />
+ </DropdownMenuLabel>
+ {threadAgents?.map((row) => (
+ <DropdownMenuItem
+ key={row.key}
+ onSelect={row.onSelect}
+ data-testid={testIds.threadAgent?.(row.key)}
+ >
+ <RegisteredAgentIcon
+ agentId={row.id}
+ iconUrl={row.iconUrl}
+ className="size-4"
+ />
+ <span className="flex-1 truncate">{row.name}</span>
+ {row.selected ? (
+ <Check aria-hidden="true" className="size-4 text-muted-foreground" />
+ ) : null}
+ </DropdownMenuItem>
+ ))}
+ </DropdownMenuGroup>
+ {hasOptions ? <DropdownMenuSeparator /> : null}
+ </>
+ ) : null}
{hasOptions ? (
<>
{showTerminal ? (
@@ -234,9 +307,22 @@ export function AgentSplitButton({
</>
) : null}
</>
- ) : (
- menuEmptyState
- )}
+ ) : null}
+ {/* Empty state only when nothing at all is enabled (no in-app agents,
+ no terminal, no desktop) — an empty section header never shows. */}
+ {!showThreadAgents && !hasOptions ? menuEmptyState : null}
+ {/* Settings row — always last. Opens Configure agents so the user
+ manages which agents appear in this menu (replaces the former
+ "Choose another agent" catalog affordance). The separator only
+ renders when a section sits above it — when nothing is enabled the
+ empty state reads with the footer as one unit, no lone rule. */}
+ {showThreadAgents || hasOptions ? <DropdownMenuSeparator /> : null}
+ <DropdownMenuItem onSelect={onOpenSettings} data-testid={testIds.settings}>
+ <SlidersHorizontal aria-hidden="true" className="size-4 text-muted-foreground" />
+ <span className="flex-1">
+ <Trans>Configure agents</Trans>
+ </span>
+ </DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
</ButtonGroup>
diff --git a/packages/app/src/components/handoff/OpenInAgentContextSubmenu.dom.test.tsx b/packages/app/src/components/handoff/OpenInAgentContextSubmenu.dom.test.tsx
index c93ef2cb2..5d30a22a2 100644
--- a/packages/app/src/components/handoff/OpenInAgentContextSubmenu.dom.test.tsx
+++ b/packages/app/src/components/handoff/OpenInAgentContextSubmenu.dom.test.tsx
@@ -1,43 +1,74 @@
-import { afterEach, describe, expect, mock, test } from 'bun:test';
import type { HandoffTarget, InstallState } from '@inkeep/open-knowledge-core';
import * as actualLinguiMacro from '@lingui/react/macro';
import { cleanup, render, screen, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import type { ReactNode } from 'react';
+import { afterEach, describe, expect, test, vi } from 'vitest';
import { DropdownMenu, DropdownMenuContent } from '@/components/ui/dropdown-menu';
+import {
+ desktopEnabledKey,
+ reloadEnabledAgentsFromStorage,
+ setAgentEnabled,
+} from '@/lib/acp/enabled-agents';
+import { registerAgent, reloadRegisteredAgentsFromStorage } from '@/lib/acp/registered-agents';
import { renderLinguiTemplate } from '@/test-utils/lingui-mock';
import { TerminalLaunchProvider } from './TerminalLaunchContext';
import type { HandoffDispatchInput } from './useHandoffDispatch';
-mock.module('@lingui/core/macro', () => ({ ...actualLinguiMacro, t: renderLinguiTemplate }));
+vi.doMock('@lingui/core/macro', () => ({
+ ...actualLinguiMacro,
+ t: renderLinguiTemplate,
+ // A transitively-imported module uses the `msg` macro; the whole-module mock
+ // must expose it too or the file fails to link.
+ msg: renderLinguiTemplate,
+}));
-mock.module('@lingui/react/macro', () => ({
+vi.doMock('@lingui/react/macro', () => ({
...actualLinguiMacro,
Trans: ({ children }: { children: ReactNode }) => <>{children}</>,
useLingui: () => ({ t: renderLinguiTemplate }),
}));
-mock.module('next-themes', () => ({
+vi.doMock('next-themes', () => ({
useTheme: () => ({ resolvedTheme: 'light' }),
}));
-mock.module('@/lib/config-provider', () => ({
+vi.doMock('@/lib/config-provider', () => ({
useConfigContext: () => ({
merged: { appearance: { preview: { autoOpen: true } } },
}),
}));
-mock.module('@/lib/config-context', () => ({
+vi.doMock('@/lib/config-context', () => ({
useConfigContext: () => ({
merged: { appearance: { preview: { autoOpen: true } } },
}),
}));
-mock.module('sonner', () => ({
+vi.doMock('sonner', () => ({
toast: {
- error: mock(() => {}),
- success: mock(() => {}),
+ error: vi.fn(() => {}),
+ success: vi.fn(() => {}),
+ },
+}));
+
+const threadLaunchCalls: HandoffDispatchInput[] = [];
+const threadLaunchOpts: Array<
+ { agent?: { source: string; id: string }; chooseAgent?: boolean } | undefined
+> = [];
+/** Ordered trace of menu-dismiss vs launch, in call order. See the
+ * "dismisses the host menu before launching" test for why order matters. */
+const callOrder: string[] = [];
+vi.doMock('./useHandoffDispatch', () => ({
+ startAgentThreadForInput: (
+ input: HandoffDispatchInput,
+ opts?: { agent?: { source: string; id: string }; chooseAgent?: boolean },
+ ) => {
+ callOrder.push('launch');
+ threadLaunchCalls.push(input);
+ threadLaunchOpts.push(opts);
},
+ openInstallUrl: () => Promise.resolve(),
}));
const readyInput: HandoffDispatchInput = {
@@ -64,14 +95,22 @@ async function renderSubmenu({
input = readyInput,
states = installStates(),
withTerminal = false,
+ onBeforeLaunch,
}: {
input?: HandoffDispatchInput | null;
states?: Record<HandoffTarget, InstallState>;
withTerminal?: boolean;
+ onBeforeLaunch?: () => void;
} = {}) {
+ // Desktop is enablement-gated now (off by default); these tests express
+ // Desktop visibility via install state, so enable the installed targets to
+ // preserve that intent.
+ for (const [id, state] of Object.entries(states)) {
+ if (state?.installed === true) setAgentEnabled(desktopEnabledKey(id), true);
+ }
const { OpenInAgentContextSubmenu } = await import('./OpenInAgentContextSubmenu');
const dispatchCalls: Array<{ input: HandoffDispatchInput; target: HandoffTarget }> = [];
- const dispatch = mock(async (target: HandoffTarget, nextInput: HandoffDispatchInput) => {
+ const dispatch = vi.fn(async (target: HandoffTarget, nextInput: HandoffDispatchInput) => {
dispatchCalls.push({ input: nextInput, target });
return { ok: true as const };
});
@@ -84,6 +123,7 @@ async function renderSubmenu({
input={input}
installStates={states}
isElectronHost={true}
+ onBeforeLaunch={onBeforeLaunch}
/>
</DropdownMenuContent>
</DropdownMenu>
@@ -120,6 +160,15 @@ describe('OpenInAgentContextSubmenu runtime behavior', () => {
afterEach(() => {
cleanup();
launchCalls.length = 0;
+ threadLaunchCalls.length = 0;
+ threadLaunchOpts.length = 0;
+ callOrder.length = 0;
+ // jsdom preload exposes no global localStorage — the store falls back to
+ // in-memory state there, so the reload alone resets it; clear the real
+ // storage when an environment provides one.
+ if (typeof localStorage !== 'undefined') localStorage.clear();
+ reloadRegisteredAgentsFromStorage();
+ reloadEnabledAgentsFromStorage();
});
test('renders only installed visible targets and dispatches the selected row', async () => {
@@ -159,7 +208,7 @@ describe('OpenInAgentContextSubmenu runtime behavior', () => {
expect(screen.queryByTestId('file-tree-open-in-claude-web-fallback') === null).toBe(true);
});
- test('shows the empty hint when no targets are installed', async () => {
+ test('hides the In-app section when nothing is enabled, keeping the Configure agents row', async () => {
await renderSubmenu({
states: installStates({
'claude-code': { installed: false, lastChecked: 1 },
@@ -168,21 +217,62 @@ describe('OpenInAgentContextSubmenu runtime behavior', () => {
cursor: { installed: false, lastChecked: 1 },
}),
});
- const empty = screen.getByTestId('file-tree-open-in-empty');
- expect(empty.textContent).toContain('No installed agents found');
+ // No enabled agents (none registered, Desktop off by default) → empty
+ // sections are hidden; the Configure agents footer is still reachable.
+ expect(screen.queryByTestId('file-tree-open-in-thread')).toBeNull();
+ expect(screen.queryByText('No installed agents found')).toBeNull();
+ expect(screen.getByTestId('file-tree-open-in-settings')).toBeTruthy();
});
- test('shows the checking hint while the install probe is pending', async () => {
- await renderSubmenu({
- states: installStates({
- 'claude-code': { installed: null },
- 'claude-cowork': { installed: null },
- codex: { installed: null },
- cursor: { installed: null },
- }),
- });
- const empty = screen.getByTestId('file-tree-open-in-empty');
- expect(empty.textContent).toContain('Checking for installed agents');
+ test('a per-agent row is disabled with a No workspace hint while input is missing', async () => {
+ registerAgent({ source: 'registry', id: 'claude-acp', name: 'Claude Agent' });
+ await renderSubmenu({ input: null });
+ const row = screen.getByTestId('file-tree-open-in-thread-claude-acp');
+ expect(row.getAttribute('data-disabled')).toBe('');
+ expect(row.getAttribute('aria-label')).toBe('Start Claude Agent, No workspace');
+ await userEvent.click(row);
+ expect(threadLaunchCalls).toEqual([]);
+ });
+
+ test('registered agents render as one-click rows that launch that agent directly', async () => {
+ registerAgent({ source: 'registry', id: 'claude-acp', name: 'Claude Agent' });
+ registerAgent({ source: 'registry', id: 'codex-acp', name: 'Codex' });
+ await renderSubmenu();
+
+ // The generic picker row is replaced by per-agent rows (+ the Settings row).
+ expect(screen.queryByTestId('file-tree-open-in-thread')).toBeNull();
+ expect(screen.getByTestId('file-tree-open-in-thread-codex-acp').textContent).toContain(
+ 'Start Codex',
+ );
+
+ await userEvent.click(screen.getByTestId('file-tree-open-in-thread-claude-acp'));
+ expect(threadLaunchCalls).toEqual([readyInput]);
+ expect(threadLaunchOpts).toEqual([{ agent: { source: 'registry', id: 'claude-acp' } }]);
+ });
+
+ test('the Settings row opens Configure agents', async () => {
+ registerAgent({ source: 'registry', id: 'claude-acp', name: 'Claude Agent' });
+ await renderSubmenu();
+
+ window.location.hash = '';
+ await userEvent.click(screen.getByTestId('file-tree-open-in-settings'));
+ expect(window.location.hash).toBe('#settings/configure-agents');
+ // No thread launch — the Settings row only navigates.
+ expect(threadLaunchCalls).toEqual([]);
+ });
+
+ // Regression: FileTree's menu is pinned `open` and is torn down only by
+ // Pierre's `context.close()`. Launching first leaves that layer alive while
+ // the modal catalog mounts, and the resulting focus-restore/dismiss cascade
+ // recurses until the renderer hangs (a hard freeze, reproduced in-app). Every
+ // launch row must dismiss first, so ORDER is the contract under test — not
+ // merely that the callback fired.
+ test('dismisses the host menu before launching a registered-agent row', async () => {
+ registerAgent({ source: 'registry', id: 'claude-acp', name: 'Claude Agent' });
+ await renderSubmenu({ onBeforeLaunch: () => callOrder.push('dismiss') });
+
+ await userEvent.click(screen.getByTestId('file-tree-open-in-thread-claude-acp'));
+ expect(callOrder).toEqual(['dismiss', 'launch']);
});
test('groups installed agents under Desktop and the CLI launch under Terminal', async () => {
@@ -242,7 +332,7 @@ describe('OpenInAgentContextSubmenu runtime behavior', () => {
expect(screen.queryByTestId('file-tree-open-in-terminal-claude')).toBeNull();
});
- test('renders only the Terminal section (no Desktop label, no separator) when no agents are installed', async () => {
+ test('renders only the Terminal section (no In app, no Desktop) when nothing else is enabled', async () => {
await renderSubmenu({
withTerminal: true,
states: installStates({
@@ -255,7 +345,10 @@ describe('OpenInAgentContextSubmenu runtime behavior', () => {
expect(screen.getByText('Terminal')).toBeTruthy();
expect(screen.queryByText('Desktop')).toBeNull();
+ // No enabled in-app agents → the In app section is hidden.
+ expect(screen.queryByText('In app')).toBeNull();
expect(screen.getByTestId('file-tree-open-in-terminal-claude')).toBeTruthy();
- expect(document.querySelector('[data-slot="dropdown-menu-separator"]')).toBeNull();
+ // A single separator sits before the Configure agents footer.
+ expect(document.querySelectorAll('[data-slot="dropdown-menu-separator"]').length).toBe(1);
});
});
diff --git a/packages/app/src/components/handoff/OpenInAgentContextSubmenu.tsx b/packages/app/src/components/handoff/OpenInAgentContextSubmenu.tsx
index a951e7be9..d98fca495 100644
--- a/packages/app/src/components/handoff/OpenInAgentContextSubmenu.tsx
+++ b/packages/app/src/components/handoff/OpenInAgentContextSubmenu.tsx
@@ -5,8 +5,8 @@
* Behavior:
* - Render only targets where `installStates[t.id].installed === true`.
* - Installed app launchers sit under a "Desktop" section label; the docked
- * terminal launchers — one row per PATH-gated CLI (`visibleTerminalClis`:
- * Claude plus CLIs the probe hasn't ruled out) — sit under a "Terminal"
+ * terminal launchers — one row per enabled CLI (`isTerminalCliEnabled`:
+ * CLIs the probe hasn't ruled out) — sit under a "Terminal"
* section label, gated on a desktop terminal bridge.
* - Empty state: when no targets are install-detected and there is no
* terminal launcher, render a disabled "No installed agents found" item
@@ -31,12 +31,15 @@ import {
type HandoffOutcome,
type HandoffTarget,
type InstallState,
+ TERMINAL_CLI_IDS,
TERMINAL_CLIS,
} from '@inkeep/open-knowledge-core';
import { t } from '@lingui/core/macro';
import { Trans, useLingui } from '@lingui/react/macro';
-import { Sparkles } from 'lucide-react';
+import { SlidersHorizontal, Sparkles } from 'lucide-react';
import type { ReactNode } from 'react';
+import { AgentBetaBadge } from '@/components/acp/AgentBetaBadge';
+import { RegisteredAgentIcon } from '@/components/acp/RegisteredAgentIcon';
import {
DropdownMenuGroup,
DropdownMenuItem,
@@ -47,11 +50,23 @@ import {
DropdownMenuSubTrigger,
} from '@/components/ui/dropdown-menu.tsx';
import { useIsEmbedded } from '@/hooks/use-is-embedded';
+import {
+ isDesktopTargetEnabled,
+ isInAppAgentEnabled,
+ isTerminalCliEnabled,
+} from '@/lib/acp/agent-visibility';
+import { useEnabledOverrides } from '@/lib/acp/enabled-agents';
+import { useRegisteredAgents } from '@/lib/acp/registered-agents';
import { VISIBLE_TARGETS } from '@/lib/handoff/targets';
+import { openAgentSettings } from '@/lib/use-settings-route';
import { TargetIcon } from './OpenInAgentMenuItem';
import { useTerminalLaunch } from './TerminalLaunchContext';
-import { cliIconTargetId, visibleTerminalClis } from './terminal-cli-display';
-import type { HandoffDispatchInput } from './useHandoffDispatch';
+import { cliIconTargetId } from './terminal-cli-display';
+import {
+ type HandoffDispatchInput,
+ openInstallUrl,
+ startAgentThreadForInput,
+} from './useHandoffDispatch';
/**
* Status hint shown on the trigger row when the right-clicked node has no
@@ -82,36 +97,41 @@ interface OpenInAgentContextSubmenuProps {
target: HandoffTarget,
input: HandoffDispatchInput,
) => Promise<HandoffOutcome>;
+ /** Fired right before any launch/dispatch — lets the FileTree caller dismiss
+ * its context menu before the agent surface takes over. */
+ readonly onBeforeLaunch?: () => void;
}
export function OpenInAgentContextSubmenu(props: OpenInAgentContextSubmenuProps): ReactNode {
const { t } = useLingui();
const isEmbedded = useIsEmbedded();
const terminalLaunch = useTerminalLaunch();
+ const registeredAgents = useRegisteredAgents();
+ const overrides = useEnabledOverrides();
if (isEmbedded) return null;
- const { input, installStates, dispatch } = props;
+ const { input, installStates, dispatch, onBeforeLaunch } = props;
const inputMissing = input === null;
const hint = contextRowHint(inputMissing);
- // Filter: render only installed targets. Web-host Cursor is already forced
- // to `installed: false` upstream in `useInstalledAgents`, so the filter
- // subsumes that case too.
- const installedTargets = VISIBLE_TARGETS.filter(
- (target) => installStates[target.id]?.installed === true,
+ // Rows are the agents the user ENABLED in Configure agents (source of truth),
+ // not just install-detected ones — an enabled-but-not-installed Desktop agent
+ // still shows and routes to its installer on select.
+ const installedTargets = VISIBLE_TARGETS.filter((target) =>
+ isDesktopTargetEnabled(overrides, target.id),
);
- const probePending = VISIBLE_TARGETS.some(
- (target) => installStates[target.id]?.installed == null,
+ const enabledRegisteredAgents = registeredAgents.filter((agent) =>
+ isInAppAgentEnabled(overrides, agent.source, agent.id, true, agent.supported),
);
-
+ const terminalClis = terminalLaunch
+ ? TERMINAL_CLI_IDS.filter((cli) =>
+ isTerminalCliEnabled(overrides, cli, terminalLaunch.installedClis),
+ )
+ : [];
+ // Each section renders only when it has rows, so an empty header never shows.
const showDesktopSection = installedTargets.length > 0;
- // Desktop-only: `useTerminalLaunch()` is null on the web host (no shell).
- const showTerminalSection = terminalLaunch !== null;
- // When nothing is install-detected and there's no terminal launcher to fall
- // back on, surface a disabled hint rather than an empty flyout.
- const showEmptyHint = !showDesktopSection && !showTerminalSection;
- // Claude plus every CLI the probe hasn't ruled out (fail-open); no "current
- // pick" to preserve on this launch-only submenu, so no `keep`.
- const terminalClis = terminalLaunch ? visibleTerminalClis(terminalLaunch.installedClis) : [];
+ // Keep the `terminalLaunch !== null` alias so TS narrows it inside the section.
+ const showTerminalSection = terminalLaunch !== null && terminalClis.length > 0;
+ const showThreadSection = enabledRegisteredAgents.length > 0;
return (
<DropdownMenuSub>
@@ -119,7 +139,52 @@ export function OpenInAgentContextSubmenu(props: OpenInAgentContextSubmenuProps)
<Sparkles aria-hidden="true" />
<Trans>Open with AI</Trans>
</DropdownMenuSubTrigger>
- <DropdownMenuSubContent>
+ <DropdownMenuSubContent className="max-h-80">
+ {/* In-app agents — shown only when any is enabled; an empty section is
+ hidden. Enablement is managed in Configure agents (footer). */}
+ {showThreadSection ? (
+ <DropdownMenuGroup aria-label={t`In app (beta)`}>
+ <DropdownMenuLabel className="flex items-center gap-1.5">
+ <Trans>In app</Trans>
+ <AgentBetaBadge />
+ </DropdownMenuLabel>
+ {enabledRegisteredAgents.map((agent) => {
+ const agentName = agent.name;
+ return (
+ <DropdownMenuItem
+ key={`${agent.source}:${agent.id}`}
+ onSelect={() => {
+ if (input === null) return;
+ onBeforeLaunch?.();
+ startAgentThreadForInput(input, {
+ agent: { source: agent.source, id: agent.id },
+ });
+ }}
+ disabled={inputMissing}
+ data-testid={`file-tree-open-in-thread-${agent.id}`}
+ aria-label={hint ? t`Start ${agentName}, ${hint}` : undefined}
+ >
+ <RegisteredAgentIcon
+ agentId={agent.id}
+ iconUrl={agent.iconUrl}
+ className="size-4"
+ />
+ <span className="flex-1">
+ <Trans>Start {agentName}</Trans>
+ </span>
+ {hint ? (
+ <span aria-hidden="true" className="ml-2 text-muted-foreground text-xs">
+ {hint}
+ </span>
+ ) : null}
+ </DropdownMenuItem>
+ );
+ })}
+ </DropdownMenuGroup>
+ ) : null}
+ {showThreadSection && (showTerminalSection || showDesktopSection) ? (
+ <DropdownMenuSeparator />
+ ) : null}
{showTerminalSection ? (
// Terminal section leads (the in-app terminal is the first-class path).
// Labeled `role="group"` so assistive tech announces the section the
@@ -141,6 +206,7 @@ export function OpenInAgentContextSubmenu(props: OpenInAgentContextSubmenuProps)
key={cli}
onSelect={() => {
if (input === null) return;
+ onBeforeLaunch?.();
terminalLaunch.launchInTerminal(input, cli);
}}
disabled={inputMissing}
@@ -180,6 +246,12 @@ export function OpenInAgentContextSubmenu(props: OpenInAgentContextSubmenuProps)
disabled={!enabled}
onSelect={() => {
if (!input) return;
+ onBeforeLaunch?.();
+ // Enabled-but-not-installed → open the installer.
+ if (installStates[target.id]?.installed !== true) {
+ void openInstallUrl(target);
+ return;
+ }
void dispatch(target.id, input);
}}
data-testid={`file-tree-open-in-${target.id}`}
@@ -198,15 +270,19 @@ export function OpenInAgentContextSubmenu(props: OpenInAgentContextSubmenuProps)
</DropdownMenuGroup>
</>
) : null}
- {showEmptyHint ? (
- <DropdownMenuItem disabled data-testid="file-tree-open-in-empty">
- {probePending ? (
- <Trans>Checking for installed agents</Trans>
- ) : (
- <Trans>No installed agents found</Trans>
- )}
- </DropdownMenuItem>
+ {/* Settings row — always last, always actionable. Opens Configure agents
+ so the user manages which agents appear here (replaces the former
+ "Choose another agent" catalog affordance). The separator only renders
+ when a section sits above it, so the all-disabled menu isn't a lone rule. */}
+ {showThreadSection || showTerminalSection || showDesktopSection ? (
+ <DropdownMenuSeparator />
) : null}
+ <DropdownMenuItem onSelect={openAgentSettings} data-testid="file-tree-open-in-settings">
+ <SlidersHorizontal aria-hidden="true" />
+ <span className="flex-1">
+ <Trans>Configure agents</Trans>
+ </span>
+ </DropdownMenuItem>
</DropdownMenuSubContent>
</DropdownMenuSub>
);
diff --git a/packages/app/src/components/handoff/OpenInAgentEmptySpaceSubmenu.dom.test.tsx b/packages/app/src/components/handoff/OpenInAgentEmptySpaceSubmenu.dom.test.tsx
index 3231e1fb8..49f512d34 100644
--- a/packages/app/src/components/handoff/OpenInAgentEmptySpaceSubmenu.dom.test.tsx
+++ b/packages/app/src/components/handoff/OpenInAgentEmptySpaceSubmenu.dom.test.tsx
@@ -1,44 +1,71 @@
-import { afterEach, describe, expect, mock, test } from 'bun:test';
import type { HandoffTarget, InstallState } from '@inkeep/open-knowledge-core';
import * as actualLinguiMacro from '@lingui/react/macro';
import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import type { ReactNode } from 'react';
import { act } from 'react';
+import { afterEach, describe, expect, test, vi } from 'vitest';
import { ContextMenu, ContextMenuContent, ContextMenuTrigger } from '@/components/ui/context-menu';
+import {
+ desktopEnabledKey,
+ reloadEnabledAgentsFromStorage,
+ setAgentEnabled,
+} from '@/lib/acp/enabled-agents';
+import { registerAgent, reloadRegisteredAgentsFromStorage } from '@/lib/acp/registered-agents';
import { renderLinguiTemplate } from '@/test-utils/lingui-mock';
import { TerminalLaunchProvider } from './TerminalLaunchContext';
import type { HandoffDispatchInput } from './useHandoffDispatch';
-mock.module('@lingui/core/macro', () => ({ ...actualLinguiMacro, t: renderLinguiTemplate }));
+vi.doMock('@lingui/core/macro', () => ({
+ ...actualLinguiMacro,
+ t: renderLinguiTemplate,
+ // A transitively-imported module uses the `msg` macro; the whole-module mock
+ // must expose it too or the file fails to link.
+ msg: renderLinguiTemplate,
+}));
-mock.module('@lingui/react/macro', () => ({
+vi.doMock('@lingui/react/macro', () => ({
...actualLinguiMacro,
Trans: ({ children }: { children: ReactNode }) => <>{children}</>,
useLingui: () => ({ t: renderLinguiTemplate }),
}));
-mock.module('next-themes', () => ({
+vi.doMock('next-themes', () => ({
useTheme: () => ({ resolvedTheme: 'light' }),
}));
-mock.module('sonner', () => ({
+vi.doMock('sonner', () => ({
toast: {
- error: mock(() => {}),
- success: mock(() => {}),
+ error: vi.fn(() => {}),
+ success: vi.fn(() => {}),
},
}));
-mock.module('@/lib/config-context', () => ({
+vi.doMock('@/lib/config-context', () => ({
useConfigContext: () => ({
merged: { appearance: { preview: { autoOpen: true } } },
}),
}));
-mock.module('@/hooks/use-is-embedded', () => ({
+vi.doMock('@/hooks/use-is-embedded', () => ({
useIsEmbedded: () => false,
}));
+const threadLaunchCalls: HandoffDispatchInput[] = [];
+const threadLaunchOpts: Array<
+ { agent?: { source: string; id: string }; chooseAgent?: boolean } | undefined
+> = [];
+vi.doMock('./useHandoffDispatch', () => ({
+ startAgentThreadForInput: (
+ input: HandoffDispatchInput,
+ opts?: { agent?: { source: string; id: string }; chooseAgent?: boolean },
+ ) => {
+ threadLaunchCalls.push(input);
+ threadLaunchOpts.push(opts);
+ },
+ openInstallUrl: () => Promise.resolve(),
+}));
+
const readyInput: HandoffDispatchInput = {
docContext: null,
docPath: '',
@@ -68,9 +95,12 @@ async function renderSubmenu({
states?: Record<HandoffTarget, InstallState>;
withTerminal?: boolean;
} = {}) {
+ for (const [id, state] of Object.entries(states)) {
+ if (state?.installed === true) setAgentEnabled(desktopEnabledKey(id), true);
+ }
const { OpenInAgentEmptySpaceSubmenu } = await import('./OpenInAgentEmptySpaceSubmenu');
const dispatchCalls: Array<{ input: HandoffDispatchInput; target: HandoffTarget }> = [];
- const dispatch = mock(async (target: HandoffTarget, nextInput: HandoffDispatchInput) => {
+ const dispatch = vi.fn(async (target: HandoffTarget, nextInput: HandoffDispatchInput) => {
dispatchCalls.push({ input: nextInput, target });
return { ok: true as const };
});
@@ -125,6 +155,14 @@ describe('OpenInAgentEmptySpaceSubmenu runtime behavior', () => {
afterEach(() => {
cleanup();
launchCalls.length = 0;
+ threadLaunchCalls.length = 0;
+ threadLaunchOpts.length = 0;
+ // jsdom preload exposes no global localStorage — the store falls back to
+ // in-memory state there, so the reload alone resets it; clear the real
+ // storage when an environment provides one.
+ if (typeof localStorage !== 'undefined') localStorage.clear();
+ reloadRegisteredAgentsFromStorage();
+ reloadEnabledAgentsFromStorage();
});
test('renders as a ContextMenu submenu, filters visible installed targets, and dispatches rows', async () => {
@@ -156,11 +194,9 @@ describe('OpenInAgentEmptySpaceSubmenu runtime behavior', () => {
expect(dispatch).not.toHaveBeenCalled();
});
- test('hides the whole submenu when nothing can render (no installed targets, no terminal launcher)', async () => {
- // No TerminalLaunchContext provider in the test → `useTerminalLaunch()` is
- // null (web-host path). With every visible target uninstalled there is
- // nothing to launch, so the submenu (and its trigger) must not render — and
- // there is no claude.ai fallback to keep it alive anymore.
+ test('hides the In-app section when nothing is enabled, keeping the Configure agents row', async () => {
+ // Web-host path (no terminal), everything uninstalled, no agents enabled:
+ // empty sections are hidden and the Configure agents footer stays reachable.
await renderSubmenu({
states: installStates({
'claude-code': { installed: false, lastChecked: 1 },
@@ -169,7 +205,43 @@ describe('OpenInAgentEmptySpaceSubmenu runtime behavior', () => {
cursor: { installed: false, lastChecked: 1 },
}),
});
- expect(screen.queryByRole('menuitem', { name: 'Open with AI' }) === null).toBe(true);
+ await openEmptySpaceSubmenu();
+ expect(screen.queryByTestId('empty-space-open-in-thread')).toBeNull();
+ expect(screen.getByTestId('empty-space-open-in-settings')).toBeTruthy();
+ });
+
+ test('a per-agent row is disabled with a No workspace hint while input is missing', async () => {
+ registerAgent({ source: 'registry', id: 'claude-acp', name: 'Claude Agent' });
+ await renderSubmenu({ input: null });
+ await openEmptySpaceSubmenu();
+ const row = screen.getByTestId('empty-space-open-in-thread-claude-acp');
+ expect(row.getAttribute('data-disabled')).toBe('');
+ expect(row.getAttribute('aria-label')).toBe('Start Claude Agent, No workspace');
+ await userEvent.click(row);
+ expect(threadLaunchCalls).toEqual([]);
+ });
+
+ test('registered agents render as one-click rows that launch that agent directly', async () => {
+ registerAgent({ source: 'registry', id: 'claude-acp', name: 'Claude Agent' });
+ await renderSubmenu();
+ await openEmptySpaceSubmenu();
+
+ expect(screen.queryByTestId('empty-space-open-in-thread')).toBeNull();
+ await userEvent.click(screen.getByTestId('empty-space-open-in-thread-claude-acp'));
+ expect(threadLaunchCalls).toEqual([readyInput]);
+ expect(threadLaunchOpts).toEqual([{ agent: { source: 'registry', id: 'claude-acp' } }]);
+ });
+
+ test('the Settings row opens Configure agents', async () => {
+ registerAgent({ source: 'registry', id: 'claude-acp', name: 'Claude Agent' });
+ await renderSubmenu();
+ await openEmptySpaceSubmenu();
+
+ window.location.hash = '';
+ await userEvent.click(screen.getByTestId('empty-space-open-in-settings'));
+ expect(window.location.hash).toBe('#settings/configure-agents');
+ // No thread launch — the Settings row only navigates.
+ expect(threadLaunchCalls).toEqual([]);
});
test('groups installed agents under Desktop and the CLI launch under Terminal', async () => {
@@ -233,7 +305,7 @@ describe('OpenInAgentEmptySpaceSubmenu runtime behavior', () => {
expect(screen.queryByTestId('empty-space-open-in-terminal-claude')).toBeNull();
});
- test('renders only the Terminal section (no Desktop label, no separator) when no agents are installed', async () => {
+ test('renders only the Terminal section (no In app, no Desktop) when nothing else is enabled', async () => {
await renderSubmenu({
withTerminal: true,
states: installStates({
@@ -247,7 +319,9 @@ describe('OpenInAgentEmptySpaceSubmenu runtime behavior', () => {
expect(screen.getByText('Terminal')).toBeTruthy();
expect(screen.queryByText('Desktop')).toBeNull();
+ expect(screen.queryByText('In app')).toBeNull();
expect(screen.getByTestId('empty-space-open-in-terminal-claude')).toBeTruthy();
- expect(document.querySelector('[data-slot="context-menu-separator"]')).toBeNull();
+ // A single separator sits before the Configure agents footer.
+ expect(document.querySelectorAll('[data-slot="context-menu-separator"]').length).toBe(1);
});
});
diff --git a/packages/app/src/components/handoff/OpenInAgentEmptySpaceSubmenu.tsx b/packages/app/src/components/handoff/OpenInAgentEmptySpaceSubmenu.tsx
index efc88b2be..7d3710e28 100644
--- a/packages/app/src/components/handoff/OpenInAgentEmptySpaceSubmenu.tsx
+++ b/packages/app/src/components/handoff/OpenInAgentEmptySpaceSubmenu.tsx
@@ -11,8 +11,8 @@
* because Radix submenus inherit roving focus from their parent root primitive.
*
* Installed app launchers sit under a "Desktop" section label; the docked
- * terminal launchers — one row per PATH-gated CLI (`visibleTerminalClis`: Claude
- * plus CLIs the probe hasn't ruled out) — sit under a "Terminal" section label.
+ * terminal launchers — one row per enabled CLI (`isTerminalCliEnabled`: CLIs the
+ * probe hasn't ruled out) — sit under a "Terminal" section label.
*
* When there is nothing to render (no installed targets and no terminal
* launcher), the entire submenu is hidden so the user doesn't land on an empty
@@ -23,12 +23,15 @@ import {
type HandoffOutcome,
type HandoffTarget,
type InstallState,
+ TERMINAL_CLI_IDS,
TERMINAL_CLIS,
} from '@inkeep/open-knowledge-core';
import { t } from '@lingui/core/macro';
import { Trans, useLingui } from '@lingui/react/macro';
-import { Sparkles } from 'lucide-react';
+import { SlidersHorizontal, Sparkles } from 'lucide-react';
import type { ReactNode } from 'react';
+import { AgentBetaBadge } from '@/components/acp/AgentBetaBadge';
+import { RegisteredAgentIcon } from '@/components/acp/RegisteredAgentIcon';
import {
ContextMenuGroup,
ContextMenuItem,
@@ -39,11 +42,23 @@ import {
ContextMenuSubTrigger,
} from '@/components/ui/context-menu';
import { useIsEmbedded } from '@/hooks/use-is-embedded';
+import {
+ isDesktopTargetEnabled,
+ isInAppAgentEnabled,
+ isTerminalCliEnabled,
+} from '@/lib/acp/agent-visibility';
+import { useEnabledOverrides } from '@/lib/acp/enabled-agents';
+import { useRegisteredAgents } from '@/lib/acp/registered-agents';
import { VISIBLE_TARGETS } from '@/lib/handoff/targets';
+import { openAgentSettings } from '@/lib/use-settings-route';
import { TargetIcon } from './OpenInAgentMenuItem';
import { useTerminalLaunch } from './TerminalLaunchContext';
-import { cliIconTargetId, visibleTerminalClis } from './terminal-cli-display';
-import type { HandoffDispatchInput } from './useHandoffDispatch';
+import { cliIconTargetId } from './terminal-cli-display';
+import {
+ type HandoffDispatchInput,
+ openInstallUrl,
+ startAgentThreadForInput,
+} from './useHandoffDispatch';
/** Status hint shown alongside per-target rows when the input is not ready
* (workspace not resolved yet). Mirrors `contextRowHint` in the sibling
@@ -73,33 +88,33 @@ export function OpenInAgentEmptySpaceSubmenu(props: OpenInAgentEmptySpaceSubmenu
const { t } = useLingui();
const isEmbedded = useIsEmbedded();
const terminalLaunch = useTerminalLaunch();
+ const registeredAgents = useRegisteredAgents();
+ const overrides = useEnabledOverrides();
if (isEmbedded) return null;
const { input, installStates, dispatch } = props;
const inputMissing = input === null;
const hint = emptySpaceRowHint(inputMissing);
- // Install-state filter: render only targets we know are installed. Web-host
- // Cursor forces `installed: false` upstream in `useInstalledAgents`, so the
- // filter subsumes that case.
- const installedTargets = VISIBLE_TARGETS.filter(
- (target) => installStates[target.id]?.installed === true,
+ // Rows are the agents the user ENABLED in Configure agents (source of truth),
+ // not just install-detected ones — an enabled-but-not-installed Desktop agent
+ // still shows and routes to its installer on select.
+ const installedTargets = VISIBLE_TARGETS.filter((target) =>
+ isDesktopTargetEnabled(overrides, target.id),
+ );
+ const enabledRegisteredAgents = registeredAgents.filter((agent) =>
+ isInAppAgentEnabled(overrides, agent.source, agent.id, true, agent.supported),
);
+ const terminalClis = terminalLaunch
+ ? TERMINAL_CLI_IDS.filter((cli) =>
+ isTerminalCliEnabled(overrides, cli, terminalLaunch.installedClis),
+ )
+ : [];
+ // Each section renders only when it has rows, so an empty header never shows.
const showDesktopSection = installedTargets.length > 0;
- // Desktop-only: `useTerminalLaunch()` is null on the web host (no shell).
- const showTerminalSection = terminalLaunch !== null;
-
- // Discoverability gate: if there's nothing to render — no installed agents
- // AND no terminal launcher row — hide the entire submenu so the user doesn't
- // land on an empty flyout (a dead end). Common in web/remote-web mode where
- // install probing returns all-false and there is no docked terminal. A stub
- // item adds noise without a recovery affordance, so absence is the signal.
- if (!showDesktopSection && !showTerminalSection) {
- return null;
- }
- // Claude plus every CLI the probe hasn't ruled out (fail-open); launch-only
- // submenu with no "current pick" to preserve, so no `keep`.
- const terminalClis = terminalLaunch ? visibleTerminalClis(terminalLaunch.installedClis) : [];
+ // Keep the `terminalLaunch !== null` alias so TS narrows it inside the section.
+ const showTerminalSection = terminalLaunch !== null && terminalClis.length > 0;
+ const showThreadSection = enabledRegisteredAgents.length > 0;
return (
<ContextMenuSub>
@@ -107,7 +122,51 @@ export function OpenInAgentEmptySpaceSubmenu(props: OpenInAgentEmptySpaceSubmenu
<Sparkles aria-hidden="true" />
<Trans>Open with AI</Trans>
</ContextMenuSubTrigger>
- <ContextMenuSubContent>
+ <ContextMenuSubContent className="max-h-80">
+ {/* In-app agents — shown only when any is enabled; an empty section is
+ hidden. Enablement is managed in Configure agents (footer). */}
+ {showThreadSection ? (
+ <ContextMenuGroup aria-label={t`In app (beta)`}>
+ <ContextMenuLabel className="flex items-center gap-1.5">
+ <Trans>In app</Trans>
+ <AgentBetaBadge />
+ </ContextMenuLabel>
+ {enabledRegisteredAgents.map((agent) => {
+ const agentName = agent.name;
+ return (
+ <ContextMenuItem
+ key={`${agent.source}:${agent.id}`}
+ onSelect={() => {
+ if (input === null) return;
+ startAgentThreadForInput(input, {
+ agent: { source: agent.source, id: agent.id },
+ });
+ }}
+ disabled={inputMissing}
+ data-testid={`empty-space-open-in-thread-${agent.id}`}
+ aria-label={hint ? t`Start ${agentName}, ${hint}` : undefined}
+ >
+ <RegisteredAgentIcon
+ agentId={agent.id}
+ iconUrl={agent.iconUrl}
+ className="size-4"
+ />
+ <span className="flex-1">
+ <Trans>Start {agentName}</Trans>
+ </span>
+ {hint ? (
+ <span aria-hidden="true" className="ml-2 text-muted-foreground text-xs">
+ {hint}
+ </span>
+ ) : null}
+ </ContextMenuItem>
+ );
+ })}
+ </ContextMenuGroup>
+ ) : null}
+ {showThreadSection && (showTerminalSection || showDesktopSection) ? (
+ <ContextMenuSeparator />
+ ) : null}
{showTerminalSection ? (
// Terminal section leads (the in-app terminal is the first-class path).
// Labeled `role="group"` so assistive tech announces the section the
@@ -168,6 +227,11 @@ export function OpenInAgentEmptySpaceSubmenu(props: OpenInAgentEmptySpaceSubmenu
disabled={!enabled}
onSelect={() => {
if (!input) return;
+ // Enabled-but-not-installed → open the installer.
+ if (installStates[target.id]?.installed !== true) {
+ void openInstallUrl(target);
+ return;
+ }
void dispatch(target.id, input);
}}
data-testid={`empty-space-open-in-${target.id}`}
@@ -186,6 +250,19 @@ export function OpenInAgentEmptySpaceSubmenu(props: OpenInAgentEmptySpaceSubmenu
</ContextMenuGroup>
</>
) : null}
+ {/* Settings row — always last, always actionable. Opens Configure agents
+ so the user manages which agents appear here (replaces the former
+ "Choose another agent" catalog affordance). The separator only renders
+ when a section sits above it, so the all-disabled menu isn't a lone rule. */}
+ {showThreadSection || showTerminalSection || showDesktopSection ? (
+ <ContextMenuSeparator />
+ ) : null}
+ <ContextMenuItem onSelect={openAgentSettings} data-testid="empty-space-open-in-settings">
+ <SlidersHorizontal aria-hidden="true" />
+ <span className="flex-1">
+ <Trans>Configure agents</Trans>
+ </span>
+ </ContextMenuItem>
</ContextMenuSubContent>
</ContextMenuSub>
);
diff --git a/packages/app/src/components/handoff/OpenInAgentMenu.dom.test.tsx b/packages/app/src/components/handoff/OpenInAgentMenu.dom.test.tsx
index 1ca117250..9aa68b88b 100644
--- a/packages/app/src/components/handoff/OpenInAgentMenu.dom.test.tsx
+++ b/packages/app/src/components/handoff/OpenInAgentMenu.dom.test.tsx
@@ -1,13 +1,27 @@
-import { afterEach, describe, expect, mock, test } from 'bun:test';
import * as actualLinguiMacro from '@lingui/react/macro';
import { cleanup, render, screen, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import type { ReactNode } from 'react';
+import { afterEach, describe, expect, test, vi } from 'vitest';
import { TooltipProvider } from '@/components/ui/tooltip';
+import {
+ desktopEnabledKey,
+ reloadEnabledAgentsFromStorage,
+ setAgentEnabled,
+} from '@/lib/acp/enabled-agents';
+import { registerAgent, reloadRegisteredAgentsFromStorage } from '@/lib/acp/registered-agents';
import { TerminalLaunchProvider } from './TerminalLaunchContext';
import type { HandoffDispatchInput } from './useHandoffDispatch';
-mock.module('@lingui/react/macro', () => ({
+// Desktop is enablement-gated now (off by default); these tests express Desktop
+// visibility via `states` install flags, so translate installed → enabled.
+function enableInstalledDesktop(): void {
+ for (const [id, state] of Object.entries(states)) {
+ if (state?.installed === true) setAgentEnabled(desktopEnabledKey(id), true);
+ }
+}
+
+vi.doMock('@lingui/react/macro', () => ({
...actualLinguiMacro,
Trans: ({ children }: { children: ReactNode }) => <>{children}</>,
useLingui: () => ({
@@ -21,7 +35,7 @@ const dispatchCalls: Array<{ target: string; input: HandoffDispatchInput }> = []
const launchCalls: Array<{ input: HandoffDispatchInput; cli: string }> = [];
let states: Record<string, { installed: boolean | null; lastChecked?: number }> = {};
-mock.module('./useInstalledAgents', () => ({
+vi.doMock('./useInstalledAgents', () => ({
useInstalledAgents: () => ({
states,
refresh: () => {
@@ -31,29 +45,35 @@ mock.module('./useInstalledAgents', () => ({
}),
}));
-mock.module('./useHandoffDispatch', () => ({
+vi.doMock('./useHandoffDispatch', () => ({
useHandoffDispatch: () => ({
dispatch: (target: string, input: HandoffDispatchInput) => {
dispatchCalls.push({ target, input });
return Promise.resolve({ ok: true as const });
},
}),
+ composeThreadLaunchPrompt: (input: HandoffDispatchInput) =>
+ `thread-prompt:${input.docContext?.relativePath ?? 'none'}`,
+ startAgentThreadForInput: () => {},
+ // Present so the whole-module mock still exposes every named export the
+ // component imports (the install nudge), or the file fails to link.
+ openInstallUrl: () => Promise.resolve(),
}));
-mock.module('@/lib/config-context', () => ({
+vi.doMock('@/lib/config-context', () => ({
useConfigContext: () => ({
merged: { appearance: { preview: { autoOpen: true } } },
}),
}));
-mock.module('@/hooks/use-is-embedded', () => ({
+vi.doMock('@/hooks/use-is-embedded', () => ({
useIsEmbedded: () => false,
}));
// The popover renders its own agent rows now and only pulls `TargetIcon` from
// this module (which transitively imports `next-themes`); stub it so the mount
// stays provider-free.
-mock.module('./OpenInAgentMenuItem', () => ({
+vi.doMock('./OpenInAgentMenuItem', () => ({
TargetIcon: () => null,
}));
@@ -64,6 +84,7 @@ const input: HandoffDispatchInput = {
};
async function renderMenu(menuInput: HandoffDispatchInput | null = input) {
+ enableInstalledDesktop();
const { OpenInAgentMenu } = await import('./OpenInAgentMenu');
render(
<TooltipProvider>
@@ -73,6 +94,7 @@ async function renderMenu(menuInput: HandoffDispatchInput | null = input) {
}
async function renderMenuWithTerminal(menuInput: HandoffDispatchInput | null = input) {
+ enableInstalledDesktop();
const { OpenInAgentMenu } = await import('./OpenInAgentMenu');
render(
<TooltipProvider>
@@ -102,6 +124,9 @@ describe('OpenInAgentMenu runtime behavior', () => {
dispatchCalls.length = 0;
launchCalls.length = 0;
states = {};
+ if (typeof localStorage !== 'undefined') localStorage.clear();
+ reloadRegisteredAgentsFromStorage();
+ reloadEnabledAgentsFromStorage();
});
test('exports the shell component', async () => {
@@ -214,7 +239,8 @@ describe('OpenInAgentMenu runtime behavior', () => {
expect(dispatchCalls).toStrictEqual([{ target: 'codex', input }]);
});
- test('shows the empty hint (no claude.ai fallback) when nothing is installed', async () => {
+ test('shows an enabled in-app agent (no claude.ai fallback) when nothing is installed', async () => {
+ registerAgent({ source: 'registry', id: 'claude-acp', name: 'Claude Agent' });
states = {
'claude-cowork': { installed: false, lastChecked: 1 },
'claude-code': { installed: false, lastChecked: 1 },
@@ -224,14 +250,16 @@ describe('OpenInAgentMenu runtime behavior', () => {
await renderMenu();
await openMenu();
- // No terminal launcher in the test (no provider → web-host path), so the
- // disabled empty hint renders. The removed claude.ai web fallback must not.
- const empty = screen.getByTestId('open-in-agent-empty');
- expect(empty.textContent).toContain('No installed agents found');
+ // The enabled in-app agent renders; no desktop apps (Desktop off) and no
+ // terminal provider (web-host path), and the removed claude.ai web fallback
+ // must not render.
+ expect(screen.getByTestId('open-in-agent-thread-start-claude-acp')).toBeTruthy();
+ expect(screen.queryByTestId('open-in-agent-desktop-label')).toBeNull();
+ expect(screen.queryByTestId('open-in-agent-terminal-label')).toBeNull();
expect(screen.queryByTestId('open-in-agent-claude-web-fallback')).toBeNull();
});
- test('shows the checking hint while the install probe is pending', async () => {
+ test('hides the In-app section when no agent is enabled, keeping Configure agents', async () => {
states = {
'claude-cowork': { installed: null },
'claude-code': { installed: null },
@@ -241,8 +269,8 @@ describe('OpenInAgentMenu runtime behavior', () => {
await renderMenu();
await openMenu();
- const empty = screen.getByTestId('open-in-agent-empty');
- expect(empty.textContent).toContain('Checking for installed agents');
+ expect(screen.queryByTestId('open-in-agent-thread-label')).toBeNull();
+ expect(screen.getByTestId('open-in-agent-settings')).toBeTruthy();
});
test('groups installed agents under Desktop and the CLI launch under Terminal', async () => {
diff --git a/packages/app/src/components/handoff/OpenInAgentMenu.non-modal.dom.test.tsx b/packages/app/src/components/handoff/OpenInAgentMenu.non-modal.dom.test.tsx
index 44c10df49..36facceaf 100644
--- a/packages/app/src/components/handoff/OpenInAgentMenu.non-modal.dom.test.tsx
+++ b/packages/app/src/components/handoff/OpenInAgentMenu.non-modal.dom.test.tsx
@@ -25,8 +25,9 @@
*
* Substrate: jsdom via `bun run test:dom`.
*/
-import { afterEach, describe, expect, mock, test } from 'bun:test';
+
import { cleanup, render, screen, waitFor } from '@testing-library/react';
+import { afterEach, describe, expect, test, vi } from 'vitest';
import type { HandoffDispatchInput } from './useHandoffDispatch';
// Radix Popover mounts a Popper (react-use-size → ResizeObserver) and a focus
@@ -60,11 +61,15 @@ if (globalWithDomShims.ResizeObserver === undefined) {
// just the disabled "Checking for installed agents" hint, keeping the mount
// surface minimal — the modal/non-modal behavior is
// independent of the rows.
-mock.module('./useInstalledAgents', () => ({
+vi.doMock('./useInstalledAgents', () => ({
useInstalledAgents: () => ({ states: {}, refresh: () => {} }),
}));
-mock.module('./useHandoffDispatch', () => ({
+vi.doMock('./useHandoffDispatch', () => ({
useHandoffDispatch: () => ({ dispatch: async () => {}, reinstallCoworkSkill: async () => {} }),
+ composeThreadLaunchPrompt: (input: HandoffDispatchInput) =>
+ `thread-prompt:${input.docContext?.relativePath ?? 'none'}`,
+ startAgentThreadForInput: () => {},
+ openInstallUrl: () => Promise.resolve(),
}));
const { OpenInAgentMenu } = await import('./OpenInAgentMenu');
diff --git a/packages/app/src/components/handoff/OpenInAgentMenu.tsx b/packages/app/src/components/handoff/OpenInAgentMenu.tsx
index ed175bc53..bc66d4d40 100644
--- a/packages/app/src/components/handoff/OpenInAgentMenu.tsx
+++ b/packages/app/src/components/handoff/OpenInAgentMenu.tsx
@@ -15,8 +15,8 @@
* - Render only targets where `states[t.id]?.installed === true`, scoped to
* `VISIBLE_TARGETS`.
* - Installed app launchers sit under a "Desktop" section label; the docked
- * terminal launchers — one row per PATH-gated CLI (`visibleTerminalClis`:
- * Claude plus CLIs the probe hasn't ruled out), each with a "<Brand> CLI"
+ * terminal launchers — one row per enabled CLI (`isTerminalCliEnabled`:
+ * CLIs the probe hasn't ruled out), each with a "<Brand> CLI"
* accessible name — sit under a "Terminal" section label. The terminal
* section is absent on the web host (`useTerminalLaunch()` is null — no shell).
* - Empty state: when nothing is install-detected and there is no terminal
@@ -27,25 +27,39 @@
*/
import {
- type HandoffTarget,
- type InstallState,
type TargetData,
+ TERMINAL_CLI_IDS,
TERMINAL_CLIS,
type TerminalCli,
} from '@inkeep/open-knowledge-core';
import { Trans, useLingui } from '@lingui/react/macro';
-import { Sparkles } from 'lucide-react';
+import { SlidersHorizontal, Sparkles } from 'lucide-react';
import { type ReactNode, useEffect, useEffectEvent, useRef, useState } from 'react';
+import { AgentBetaBadge } from '@/components/acp/AgentBetaBadge';
+import { RegisteredAgentIcon } from '@/components/acp/RegisteredAgentIcon';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';
import { Separator } from '@/components/ui/separator';
import { useIsEmbedded } from '@/hooks/use-is-embedded';
+import {
+ isDesktopTargetEnabled,
+ isInAppAgentEnabled,
+ isTerminalCliEnabled,
+} from '@/lib/acp/agent-visibility';
+import { type EnabledOverrides, useEnabledOverrides } from '@/lib/acp/enabled-agents';
+import { type RegisteredAgent, useRegisteredAgents } from '@/lib/acp/registered-agents';
import { VISIBLE_TARGETS } from '@/lib/handoff/targets';
+import { openAgentSettings } from '@/lib/use-settings-route';
import { TargetIcon } from './OpenInAgentMenuItem';
import { type TerminalLaunchContextValue, useTerminalLaunch } from './TerminalLaunchContext';
-import { cliIconTargetId, visibleTerminalClis } from './terminal-cli-display';
-import { type HandoffDispatchInput, useHandoffDispatch } from './useHandoffDispatch';
+import { cliIconTargetId } from './terminal-cli-display';
+import {
+ type HandoffDispatchInput,
+ openInstallUrl,
+ startAgentThreadForInput,
+ useHandoffDispatch,
+} from './useHandoffDispatch';
import { useInstalledAgents } from './useInstalledAgents';
interface OpenInAgentMenuProps {
@@ -57,18 +71,29 @@ interface OpenInAgentMenuProps {
}
interface OpenWithAiPanelProps {
- readonly installStates: Record<HandoffTarget, InstallState>;
+ /** User enable/disable overrides — filters the rows to enabled agents. */
+ readonly overrides: EnabledOverrides;
/** Docked-terminal launcher when present (desktop); null on the web host. */
readonly terminalLaunch: TerminalLaunchContextValue | null;
/** Disable every dispatch row — set when there is nothing to dispatch
* (no active doc / workspace not loaded). The trigger is also disabled in
* that state, so this is a defensive guard for the controlled-open path. */
readonly disabled: boolean;
+ /** Registered in-app agents — one launch row each. Empty before the first
+ * catalog registration, where the single "Start an agent" row renders. */
+ readonly registeredAgents: readonly RegisteredAgent[];
/** Fired when the user picks an agent; carries the typed instruction — the
* empty string when the user dispatched without typing one. */
readonly onPick: (target: TargetData, instruction: string) => void;
/** Fired when the user picks a CLI row; carries the chosen CLI + instruction. */
readonly onLaunchTerminal: (cli: TerminalCli, instruction: string) => void;
+ /** Fired when the user picks a registered-agent row. */
+ readonly onStartThreadWith: (
+ agent: { source: 'registry' | 'custom'; id: string },
+ instruction: string,
+ ) => void;
+ /** Fired when the user picks the "Settings" row (opens Configure agents). */
+ readonly onOpenSettings: () => void;
}
/**
@@ -79,31 +104,44 @@ interface OpenWithAiPanelProps {
* because the popover unmounts its content when closed.
*/
function OpenWithAiPanel({
- installStates,
+ overrides,
terminalLaunch,
disabled,
+ registeredAgents,
onPick,
onLaunchTerminal,
+ onStartThreadWith,
+ onOpenSettings,
}: OpenWithAiPanelProps): ReactNode {
const { t } = useLingui();
const [instruction, setInstruction] = useState('');
- const installedTargets = VISIBLE_TARGETS.filter(
- (target) => installStates[target.id]?.installed === true,
+ // Desktop rows are the agents the user ENABLED in Configure agents (source of
+ // truth), not just install-detected ones — a not-installed one still shows
+ // and routes to its installer on launch.
+ const installedTargets = VISIBLE_TARGETS.filter((target) =>
+ isDesktopTargetEnabled(overrides, target.id),
);
- const probePending = VISIBLE_TARGETS.some(
- (target) => installStates[target.id]?.installed == null,
+ // Only the in-app agents the user has enabled appear as rows.
+ const enabledRegisteredAgents = registeredAgents.filter((agent) =>
+ isInAppAgentEnabled(overrides, agent.source, agent.id, true, agent.supported),
);
- // Two labeled sections orient the user: "Desktop" over the installed app
- // launchers, "Terminal" over the docked-terminal CLI rows. Both are
- // hidden in the empty state (no installed agents and no terminal launcher).
+ // Three labeled sections orient the user: "In this app" over the server-
+ // hosted agent-thread launcher (always present — threads work on every
+ // host), "Desktop" over the installed app launchers, "Terminal" over the
+ // docked-terminal CLI rows. The Agents row always shows, so the empty state
+ // never appears while it is present.
+ // The Terminal CLIs the user ENABLED in Configure agents. Each section renders
+ // only when it has rows, so an empty section header never shows.
+ const terminalClis = terminalLaunch
+ ? TERMINAL_CLI_IDS.filter((cli) =>
+ isTerminalCliEnabled(overrides, cli, terminalLaunch.installedClis),
+ )
+ : [];
const showDesktopSection = installedTargets.length > 0;
- const showTerminalSection = terminalLaunch !== null;
- const hasRows = showDesktopSection || showTerminalSection;
- // Claude plus every CLI the probe hasn't ruled out (fail-open). No `keep`:
- // this popover launches, it doesn't show a "current pick" to preserve.
- const terminalClis = terminalLaunch ? visibleTerminalClis(terminalLaunch.installedClis) : [];
+ const showTerminalSection = terminalClis.length > 0;
+ const showThreadSection = enabledRegisteredAgents.length > 0;
return (
<div className="flex flex-col gap-1">
@@ -116,15 +154,56 @@ function OpenWithAiPanel({
data-testid="open-in-agent-instruction"
/>
</div>
- {hasRows ? (
+ {/* The agent sections scroll; the instruction input above and the
+ Configure agents footer below stay put. */}
+ <div className="flex max-h-72 flex-col gap-0.5 overflow-y-auto subtle-scrollbar">
+ {/* In-app agents — shown only when any is enabled; an empty section is
+ hidden entirely. Enablement is managed in Configure agents (footer). */}
+ {showThreadSection ? (
+ <fieldset className="m-0 flex min-w-0 flex-col gap-0.5 border-0 p-0">
+ <legend
+ className="flex items-center gap-1.5 px-1.5 py-1 font-medium text-muted-foreground text-xs"
+ data-testid="open-in-agent-thread-label"
+ >
+ <Trans>In app</Trans>
+ <AgentBetaBadge />
+ </legend>
+ {enabledRegisteredAgents.map((agent) => {
+ const agentName = agent.name;
+ return (
+ <Button
+ key={`${agent.source}:${agent.id}`}
+ type="button"
+ variant="ghost"
+ className="h-auto w-full justify-start gap-1.5 rounded-md px-1.5 py-1 font-normal text-foreground"
+ disabled={disabled}
+ data-testid={`open-in-agent-thread-start-${agent.id}`}
+ onClick={() =>
+ onStartThreadWith({ source: agent.source, id: agent.id }, instruction)
+ }
+ >
+ <RegisteredAgentIcon
+ agentId={agent.id}
+ iconUrl={agent.iconUrl}
+ className="size-4"
+ />
+ <span>{t`Start ${agentName}`}</span>
+ </Button>
+ );
+ })}
+ </fieldset>
+ ) : null}
+ {showThreadSection && (showTerminalSection || showDesktopSection) ? (
+ <Separator className="my-1" />
+ ) : null}
<div className="flex flex-col gap-0.5">
{showTerminalSection ? (
- // Terminal section leads (the in-app terminal is the first-class path).
- // CLI launchers run `claude` / `codex` / `cursor-agent` in the docked
- // terminal with the same scope prompt (plus instruction) the deep-link
- // puts in `q=`. Visible text is the brand name; the accessible name is
- // "<Brand> CLI" so AT users can tell each apart from the matching
- // Desktop row (WCAG 2.5.3 — the name contains the visible label).
+ // Terminal section (desktop only). CLI launchers run `claude` /
+ // `codex` / `cursor-agent` in the docked terminal with the same
+ // scope prompt (plus instruction) the deep-link puts in `q=`.
+ // Visible text is the brand name; the accessible name is "<Brand>
+ // CLI" so AT users can tell each apart from the matching Desktop
+ // row (WCAG 2.5.3 — the name contains the visible label).
<fieldset className="m-0 flex min-w-0 flex-col gap-0.5 border-0 p-0">
<legend
className="px-1.5 py-1 font-medium text-muted-foreground text-xs"
@@ -191,19 +270,24 @@ function OpenWithAiPanel({
</>
) : null}
</div>
- ) : (
- <p
- className="text-muted-foreground text-sm"
- data-testid="open-in-agent-empty"
- aria-live="polite"
+ {/* Settings row — always last. Opens Configure agents so the user
+ manages which agents appear here (replaces the former "Choose
+ another agent" catalog affordance). The separator only renders when a
+ section sits above it, so the all-disabled menu isn't a lone rule. */}
+ {showThreadSection || showTerminalSection || showDesktopSection ? (
+ <Separator className="my-1" />
+ ) : null}
+ <Button
+ type="button"
+ variant="ghost"
+ className="h-auto w-full justify-start gap-1.5 rounded-md px-1.5 py-1 font-normal text-foreground"
+ data-testid="open-in-agent-settings"
+ onClick={onOpenSettings}
>
- {probePending ? (
- <Trans>Checking for installed agents</Trans>
- ) : (
- <Trans>No installed agents found</Trans>
- )}
- </p>
- )}
+ <SlidersHorizontal className="size-4 text-muted-foreground" aria-hidden="true" />
+ <span>{t`Configure agents`}</span>
+ </Button>
+ </div>
</div>
);
}
@@ -218,6 +302,8 @@ export function OpenInAgentMenu({ input, open, onOpenChange }: OpenInAgentMenuPr
const { states, refresh } = useInstalledAgents();
const { dispatch } = useHandoffDispatch();
const terminalLaunch = useTerminalLaunch();
+ const registeredAgents = useRegisteredAgents();
+ const overrides = useEnabledOverrides();
const [internalOpen, setInternalOpen] = useState(false);
// Tracks whether a real `pointerdown` reached the trigger this interaction.
// See the trigger's onPointerDown/onClick below for why this is load-bearing
@@ -266,6 +352,13 @@ export function OpenInAgentMenu({ input, open, onOpenChange }: OpenInAgentMenuPr
const handlePick = (target: TargetData, instruction: string): void => {
const next = inputWith(instruction);
if (next === null) return;
+ // An enabled-but-not-installed Desktop agent routes to its installer
+ // rather than a failing deep-link dispatch.
+ if (states[target.id]?.installed !== true) {
+ void openInstallUrl(target);
+ handleOpenChange(false);
+ return;
+ }
void dispatch(target.id, next);
handleOpenChange(false);
};
@@ -277,6 +370,19 @@ export function OpenInAgentMenu({ input, open, onOpenChange }: OpenInAgentMenuPr
handleOpenChange(false);
};
+ // In-app agent thread: compose the scope prompt (same pipeline as the
+ // terminal/deep-link paths). Per-agent rows name their agent; enablement is
+ // managed in Settings → Configure agents (the "Configure agents" row).
+ const handleStartThreadWith = (
+ agent: { source: 'registry' | 'custom'; id: string },
+ instruction: string,
+ ): void => {
+ const next = inputWith(instruction);
+ if (next === null) return;
+ startAgentThreadForInput(next, { agent });
+ handleOpenChange(false);
+ };
+
return (
// Non-modal (Radix Popover default): keeps the rest of the chrome live and
// never sets `body { pointer-events: none }`. The trigger lives in the
@@ -333,11 +439,14 @@ export function OpenInAgentMenu({ input, open, onOpenChange }: OpenInAgentMenuPr
data-testid="open-in-agent-menu"
>
<OpenWithAiPanel
- installStates={states}
+ overrides={overrides}
terminalLaunch={terminalLaunch}
disabled={input === null}
+ registeredAgents={registeredAgents}
onPick={handlePick}
onLaunchTerminal={handleLaunchTerminal}
+ onStartThreadWith={handleStartThreadWith}
+ onOpenSettings={openAgentSettings}
/>
</PopoverContent>
</Popover>
diff --git a/packages/app/src/components/handoff/OpenInAgentMenuItem.dom.test.tsx b/packages/app/src/components/handoff/OpenInAgentMenuItem.dom.test.tsx
index c6bf27be5..b97f1ac18 100644
--- a/packages/app/src/components/handoff/OpenInAgentMenuItem.dom.test.tsx
+++ b/packages/app/src/components/handoff/OpenInAgentMenuItem.dom.test.tsx
@@ -1,18 +1,20 @@
-import { afterEach, describe, expect, mock, test } from 'bun:test';
import * as actualLinguiMacro from '@lingui/react/macro';
import { cleanup, render, screen, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import type { ReactNode } from 'react';
+import { afterEach, describe, expect, test, vi } from 'vitest';
import { DropdownMenu, DropdownMenuContent } from '@/components/ui/dropdown-menu';
import { KNOWN_TARGETS } from '@/lib/handoff/targets';
-mock.module('@lingui/core/macro', () => ({
+const passthroughLingui = (strings: TemplateStringsArray, ...values: unknown[]) =>
+ strings.reduce((acc, part, index) => `${acc}${part}${values[index] ?? ''}`, '');
+vi.doMock('@lingui/core/macro', () => ({
...actualLinguiMacro,
- t: (strings: TemplateStringsArray, ...values: unknown[]) =>
- strings.reduce((acc, part, index) => `${acc}${part}${values[index] ?? ''}`, ''),
+ t: passthroughLingui,
+ msg: passthroughLingui,
}));
-mock.module('@lingui/react/macro', () => ({
+vi.doMock('@lingui/react/macro', () => ({
...actualLinguiMacro,
Trans: ({ children }: { children: ReactNode }) => <>{children}</>,
useLingui: () => ({
@@ -21,7 +23,7 @@ mock.module('@lingui/react/macro', () => ({
}),
}));
-mock.module('next-themes', () => ({
+vi.doMock('next-themes', () => ({
useTheme: () => ({ resolvedTheme: 'light' }),
}));
diff --git a/packages/app/src/components/handoff/OpenInAgentTerminalRow.dom.test.tsx b/packages/app/src/components/handoff/OpenInAgentTerminalRow.dom.test.tsx
index 0f2db7c70..346db1cbc 100644
--- a/packages/app/src/components/handoff/OpenInAgentTerminalRow.dom.test.tsx
+++ b/packages/app/src/components/handoff/OpenInAgentTerminalRow.dom.test.tsx
@@ -8,11 +8,11 @@
* chosen CLI to the launcher.
*/
-import { afterEach, describe, expect, mock, test } from 'bun:test';
import type { TerminalCli } from '@inkeep/open-knowledge-core';
import { cleanup, render, screen, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import type { ReactNode } from 'react';
+import { afterEach, describe, expect, test, vi } from 'vitest';
import type { HandoffDispatchInput } from './useHandoffDispatch';
const input: HandoffDispatchInput = {
@@ -32,7 +32,7 @@ const installedStates = {
import * as actualLinguiMacro from '@lingui/react/macro';
-mock.module('@lingui/react/macro', () => ({
+vi.doMock('@lingui/react/macro', () => ({
...actualLinguiMacro,
Trans: ({ children }: { children: ReactNode }) => <>{children}</>,
useLingui: () => ({
@@ -41,21 +41,25 @@ mock.module('@lingui/react/macro', () => ({
}),
}));
-mock.module('./useInstalledAgents', () => ({
+vi.doMock('./useInstalledAgents', () => ({
useInstalledAgents: () => ({ states: installedStates, refresh: () => Promise.resolve() }),
}));
-mock.module('./useHandoffDispatch', () => ({
+vi.doMock('./useHandoffDispatch', () => ({
useHandoffDispatch: () => ({ dispatch: () => Promise.resolve({ ok: true as const }) }),
+ composeThreadLaunchPrompt: (dispatchInput: HandoffDispatchInput) =>
+ `thread-prompt:${dispatchInput.docContext?.relativePath ?? 'none'}`,
+ startAgentThreadForInput: () => {},
+ openInstallUrl: () => Promise.resolve(),
}));
-mock.module('@/lib/config-context', () => ({
+vi.doMock('@/lib/config-context', () => ({
useConfigContext: () => ({ merged: { appearance: { preview: { autoOpen: true } } } }),
}));
-mock.module('@/hooks/use-is-embedded', () => ({ useIsEmbedded: () => false }));
+vi.doMock('@/hooks/use-is-embedded', () => ({ useIsEmbedded: () => false }));
-mock.module('./OpenInAgentMenuItem', () => ({ TargetIcon: () => null }));
+vi.doMock('./OpenInAgentMenuItem', () => ({ TargetIcon: () => null }));
const { OpenInAgentMenu } = await import('./OpenInAgentMenu');
const { TerminalLaunchProvider } = await import('./TerminalLaunchContext');
@@ -66,7 +70,7 @@ async function renderMenu(opts: {
launcher: ((input: HandoffDispatchInput, cli: TerminalCli) => void) | null;
menuInput?: HandoffDispatchInput | null;
// The raw PATH-detection map the production provider supplies. The component
- // gates its own rows via `visibleTerminalClis`, so feeding the map here (not a
+ // gates its own rows via `isTerminalCliEnabled`, so feeding the map here (not a
// pre-gated list) exercises that production wiring. Defaults to `{}` (probe
// unresolved → fail-open, every CLI shown).
installedClis?: Partial<Record<TerminalCli, boolean>>;
@@ -105,11 +109,11 @@ describe('Open-with-AI Terminal CLI rows', () => {
expect(screen.getByTestId('open-in-agent-terminal-cursor')).toBeTruthy();
});
- test('gates rows through the real probe map: Claude always, detected shown, probed-absent hidden', async () => {
- // A complete resolved map: only `codex` on PATH. The component runs
- // `visibleTerminalClis` itself, so this exercises the production wiring —
- // Claude (always-visible anchor) plus `codex`; Cursor and Antigravity are
- // probed absent (`false`), so their rows are gone.
+ test('gates rows through the real probe map: probed-absent hidden (Claude included), detected shown', async () => {
+ // A complete resolved map: only `codex` on PATH. Rows gate via
+ // `isTerminalCliEnabled` — codex shows; Claude, Cursor, and Antigravity are
+ // probed absent (`false`), so their rows are gone. Claude is no longer a
+ // special always-visible anchor: an absent Claude CLI hides like any other.
await renderMenu({
launcher: () => {},
installedClis: {
@@ -122,7 +126,7 @@ describe('Open-with-AI Terminal CLI rows', () => {
},
});
await openMenu();
- expect(screen.getByTestId('open-in-agent-terminal-claude')).toBeTruthy();
+ expect(screen.queryByTestId('open-in-agent-terminal-claude')).toBeNull();
expect(screen.getByTestId('open-in-agent-terminal-codex')).toBeTruthy();
expect(screen.queryByTestId('open-in-agent-terminal-antigravity')).toBeNull();
expect(screen.queryByTestId('open-in-agent-terminal-cursor')).toBeNull();
diff --git a/packages/app/src/components/handoff/TerminalLaunchContext.tsx b/packages/app/src/components/handoff/TerminalLaunchContext.tsx
index 6b675970c..8e04eb89c 100644
--- a/packages/app/src/components/handoff/TerminalLaunchContext.tsx
+++ b/packages/app/src/components/handoff/TerminalLaunchContext.tsx
@@ -28,8 +28,8 @@ export interface TerminalLaunchContextValue {
/**
* The PATH-detection map from the desktop probe — which launchable CLIs are on
* PATH. The single source every launch surface gates its rows from: each passes
- * it through {@link visibleTerminalClis} (with its own current pick as `keep`)
- * so gating logic lives in ONE place and can't drift between surfaces. A partial
+ * it through `isTerminalCliEnabled` (keeping its own current pick visible) so
+ * gating logic lives in ONE place and can't drift between surfaces. A partial
* map: `undefined` = unknown/unresolved (shown, fail-open), `false` = probed
* absent (hidden), `true` = detected. Provided by `App.tsx` from the live probe.
*/
diff --git a/packages/app/src/components/handoff/terminal-cli-display.test.ts b/packages/app/src/components/handoff/terminal-cli-display.test.ts
deleted file mode 100644
index b35ac3a44..000000000
--- a/packages/app/src/components/handoff/terminal-cli-display.test.ts
+++ /dev/null
@@ -1,44 +0,0 @@
-import { describe, expect, it } from 'bun:test';
-import { TERMINAL_CLI_IDS } from '@inkeep/open-knowledge-core';
-import { visibleTerminalClis } from './terminal-cli-display';
-
-/** A complete resolved probe map (every CLI keyed), all reported absent. Matches
- * the shape `resolveCliInstalledMap` returns — the renderer only ever sees a
- * complete map or the empty `{}` (unresolved). */
-const allAbsent = Object.fromEntries(TERMINAL_CLI_IDS.map((cli) => [cli, false]));
-
-describe('visibleTerminalClis', () => {
- it('fails open on the empty map (probe unresolved / failed / older bridge)', () => {
- // Regression guard: an empty map is "unknown", NOT "none installed". Hiding
- // here would silently drop genuinely-installed CLIs from every launch surface
- // for the whole session whenever the probe never resolves.
- expect(visibleTerminalClis({})).toEqual([...TERMINAL_CLI_IDS]);
- });
-
- it('hides only CLIs the probe positively reports absent', () => {
- expect(visibleTerminalClis({ ...allAbsent, codex: true, cursor: true })).toEqual([
- 'claude',
- 'codex',
- 'cursor',
- ]);
- });
-
- it('hides GitHub Copilot when the probe confirms it is absent', () => {
- expect(visibleTerminalClis({ ...allAbsent, copilot: false })).not.toContain('copilot');
- });
-
- it('always keeps Claude — the install-nudge anchor — even when probed absent', () => {
- expect(visibleTerminalClis(allAbsent)).toEqual(['claude']);
- });
-
- it('keeps `keep` (the current pick) even when probed absent', () => {
- // A picker's own selected CLI must stay in its dropdown so it can be re-picked
- // and shows its checkmark, even if the probe says it's not on PATH.
- expect(visibleTerminalClis(allAbsent, 'codex')).toEqual(['claude', 'codex']);
- });
-
- it('preserves TERMINAL_CLI_IDS launch order', () => {
- const allInstalled = Object.fromEntries(TERMINAL_CLI_IDS.map((cli) => [cli, true]));
- expect(visibleTerminalClis(allInstalled)).toEqual([...TERMINAL_CLI_IDS]);
- });
-});
diff --git a/packages/app/src/components/handoff/terminal-cli-display.ts b/packages/app/src/components/handoff/terminal-cli-display.ts
index c9450c7f1..81f6096a7 100644
--- a/packages/app/src/components/handoff/terminal-cli-display.ts
+++ b/packages/app/src/components/handoff/terminal-cli-display.ts
@@ -3,7 +3,7 @@
* "Open with AI" / New-chat surface (header popover + the two right-click
* submenus + the empty-state create composer + the composer "Ask" split button +
* the tab-strip New-chat dropdown) renders the CLIs in the same order with the
- * same brand icon and accessible name, gated the same way by {@link visibleTerminalClis}.
+ * same brand icon and accessible name, gated the same way by `isTerminalCliEnabled`.
*/
import {
type HandoffTarget,
@@ -13,45 +13,11 @@ import {
} from '@inkeep/open-knowledge-core';
/** CLIs shown under the "Terminal" section, in launch order — the full set,
- * before PATH-detection gating. Callers pass the installed-CLI map through
- * {@link visibleTerminalClis} to drop CLIs that aren't installed. */
+ * before enablement gating. Launcher surfaces filter this through
+ * `isTerminalCliEnabled` (in `agent-visibility.ts`) to drop CLIs the probe
+ * reports absent. */
export const VISIBLE_CLIS: readonly TerminalCli[] = TERMINAL_CLI_IDS;
-/** Terminal CLIs surfaced as launch rows even when NOT detected on PATH. Claude
- * is the install-nudge anchor: it's the default-CLI fallback (`resolveDefaultCli`)
- * and has a "Get Claude" missing-CLI banner, so keeping its row is a discoverable
- * install affordance rather than a dead end. Every other CLI is offered only once
- * detected — a niche CLI (e.g. Antigravity) shouldn't clutter the menu for users
- * who don't have it. */
-const ALWAYS_VISIBLE_CLIS: ReadonlySet<TerminalCli> = new Set<TerminalCli>(['claude']);
-
-/**
- * The launch-row CLIs to show given the PATH-detection map, in
- * {@link TERMINAL_CLI_IDS} launch order. Fails OPEN: a CLI is hidden only when
- * the probe positively reports it absent (`installed[cli] === false`). Shown
- * otherwise — always-visible anchors (Claude), `keep` (the current pick), any
- * detected CLI, and — critically — any CLI whose state is still UNKNOWN.
- *
- * "Unknown" is `installed[cli] === undefined`. A resolved probe map is complete
- * (every CLI keyed true/false — see `resolveCliInstalledMap`), so an undefined
- * entry means the probe hasn't resolved yet, failed, or the desktop bridge is
- * too old to expose it. Hiding on unknown would make a probe failure or a
- * renderer/main version skew silently drop genuinely-installed CLIs from every
- * launch surface for the whole session; failing open keeps them launchable (the
- * pre-gating behavior) and lets the row settle once the probe confirms absence.
- *
- * @param keep the current pick (sticky/default CLI) — never hidden, even when
- * probed absent, so a picker's dropdown always contains its own selected row.
- */
-export function visibleTerminalClis(
- installed: Partial<Record<TerminalCli, boolean>>,
- keep?: TerminalCli | null,
-): readonly TerminalCli[] {
- return TERMINAL_CLI_IDS.filter(
- (cli) => ALWAYS_VISIBLE_CLIS.has(cli) || cli === keep || installed[cli] !== false,
- );
-}
-
/** CLI id → the handoff target id whose brand icon `TargetIcon` renders. Reads
* the single source of truth on the registry (shared with prompt composition)
* rather than a parallel local map. */
diff --git a/packages/app/src/components/handoff/thread-launch-events.ts b/packages/app/src/components/handoff/thread-launch-events.ts
new file mode 100644
index 000000000..9d7c8cdc4
--- /dev/null
+++ b/packages/app/src/components/handoff/thread-launch-events.ts
@@ -0,0 +1,54 @@
+/**
+ * Window-scoped pub/sub carrying an "open an agent thread" launch from the
+ * handoff menus to the dock (whose open-state + launch intent live in
+ * EditorPane) — the ACP twin of `terminal-launch-events.ts`.
+ *
+ * The payload names a catalog agent (registry manifest id or custom entry id)
+ * plus the composed prompt (never a command). Works on BOTH hosts — agent
+ * threads are server-hosted, so unlike the terminal channel this one has no
+ * desktop gate.
+ */
+
+const THREAD_LAUNCH_EVENT = 'open-knowledge:agent-thread-launch';
+
+export interface AgentThreadLaunchDetail {
+ readonly agentSource: 'registry' | 'custom';
+ readonly agentId: string;
+ /** Composed scope prompt, or null for a promptless "new chat". */
+ readonly prompt: string | null;
+ /** Extension-less docName context the launch came from, when any. */
+ readonly docName: string | null;
+ /**
+ * The user's raw typed text (create brief / instruction) for title
+ * derivation — kept out of `prompt` so the composed handoff preamble never
+ * becomes the tab label. Null when the launch carried no typed text.
+ */
+ readonly titleHint: string | null;
+}
+
+export function requestAgentThreadLaunch(
+ detail: AgentThreadLaunchDetail,
+ target: Pick<Window, 'dispatchEvent'> | EventTarget = typeof window === 'undefined'
+ ? new EventTarget()
+ : window,
+): void {
+ target.dispatchEvent(new CustomEvent<AgentThreadLaunchDetail>(THREAD_LAUNCH_EVENT, { detail }));
+}
+
+export function subscribeToAgentThreadLaunchRequests(
+ onRequest: (detail: AgentThreadLaunchDetail) => void,
+ target: Pick<Window, 'addEventListener' | 'removeEventListener'> | EventTarget = typeof window ===
+ 'undefined'
+ ? new EventTarget()
+ : window,
+): () => void {
+ const listener = (event: Event) => {
+ const detail =
+ event instanceof CustomEvent
+ ? (event as CustomEvent<AgentThreadLaunchDetail>).detail
+ : undefined;
+ if (detail && typeof detail.agentId === 'string') onRequest(detail);
+ };
+ target.addEventListener(THREAD_LAUNCH_EVENT, listener as EventListener);
+ return () => target.removeEventListener(THREAD_LAUNCH_EVENT, listener as EventListener);
+}
diff --git a/packages/app/src/components/handoff/useHandoffDispatch.test.ts b/packages/app/src/components/handoff/useHandoffDispatch.test.ts
index 0d2c0cdd9..90569a45a 100644
--- a/packages/app/src/components/handoff/useHandoffDispatch.test.ts
+++ b/packages/app/src/components/handoff/useHandoffDispatch.test.ts
@@ -14,7 +14,6 @@
* - Default deps wire production bindings without error
*/
-import { describe, expect, mock, test } from 'bun:test';
import { setTimeout as wait } from 'node:timers/promises';
import type { HandoffOutcome, HandoffPayload, HandoffTarget } from '@inkeep/open-knowledge-core';
import {
@@ -22,6 +21,7 @@ import {
OK_TERMINAL_SURFACE_PREAMBLE,
withSkillPointer,
} from '@inkeep/open-knowledge-core';
+import { describe, expect, test, vi } from 'vitest';
import type {
HandoffDispatchDeps,
HandoffDispatchInput,
@@ -68,8 +68,8 @@ function buildDeps(
): HandoffDispatchDeps & { toast: RecordingToast } {
const toast = recordingToast();
const defaults: HandoffDispatchDeps = {
- dispatchHandoff: mock(async (_payload: HandoffPayload) => ({ ok: true }) as HandoffOutcome),
- recordHandoff: mock(async (_line) => {}),
+ dispatchHandoff: vi.fn(async (_payload: HandoffPayload) => ({ ok: true }) as HandoffOutcome),
+ recordHandoff: vi.fn(async (_line) => {}),
toast,
now: () => new Date('2026-04-22T03:00:00.000Z'),
isElectronHost: () => true,
@@ -83,7 +83,7 @@ function buildDeps(
: 'Cursor',
// Default to `already-installed` so existing tests exercise the URL
// dispatch path; install-gate-specific tests override this.
- ensureCoworkSkillInstalled: mock(async () => ({ kind: 'already-installed' }) as const),
+ ensureCoworkSkillInstalled: vi.fn(async () => ({ kind: 'already-installed' }) as const),
// Default true to match `defaultHandoffDispatchDeps()` and the cold-start
// fallback in the hook; tests covering the `false` branch override this.
autoOpen: true,
@@ -208,7 +208,7 @@ describe('runHandoffDispatch — success path', () => {
await runHandoffDispatch('codex', input, deps);
expect(deps.dispatchHandoff).toHaveBeenCalledTimes(1);
- const [payload] = (deps.dispatchHandoff as ReturnType<typeof mock>).mock.calls[0] as [
+ const [payload] = (deps.dispatchHandoff as ReturnType<typeof vi.fn>).mock.calls[0] as [
HandoffPayload,
];
expect(payload.target).toBe('codex');
@@ -260,7 +260,7 @@ describe('runHandoffDispatch — success path', () => {
await runHandoffDispatch('codex', input, deps);
expect(deps.dispatchHandoff).toHaveBeenCalledTimes(1);
- const [payload] = (deps.dispatchHandoff as ReturnType<typeof mock>).mock.calls[0] as [
+ const [payload] = (deps.dispatchHandoff as ReturnType<typeof vi.fn>).mock.calls[0] as [
HandoffPayload,
];
expect(payload.target).toBe('codex');
@@ -294,7 +294,7 @@ describe('runHandoffDispatch — success path', () => {
await runHandoffDispatch('codex', input, deps);
- const [payload] = (deps.dispatchHandoff as ReturnType<typeof mock>).mock.calls[0] as [
+ const [payload] = (deps.dispatchHandoff as ReturnType<typeof vi.fn>).mock.calls[0] as [
HandoffPayload,
];
expect(payload.target).toBe('codex');
@@ -319,7 +319,7 @@ describe('runHandoffDispatch — autoOpen=false honors the user preference', ()
const { runHandoffDispatch } = await import('./useHandoffDispatch');
const deps = buildDeps({ autoOpen: false });
await runHandoffDispatch('codex', sampleInput(), deps);
- const [payload] = (deps.dispatchHandoff as ReturnType<typeof mock>).mock.calls[0] as [
+ const [payload] = (deps.dispatchHandoff as ReturnType<typeof vi.fn>).mock.calls[0] as [
HandoffPayload,
];
expect(payload.prompt).toBe(
@@ -338,7 +338,7 @@ describe('runHandoffDispatch — autoOpen=false honors the user preference', ()
docPath: '',
};
await runHandoffDispatch('codex', input, deps);
- const [payload] = (deps.dispatchHandoff as ReturnType<typeof mock>).mock.calls[0] as [
+ const [payload] = (deps.dispatchHandoff as ReturnType<typeof vi.fn>).mock.calls[0] as [
HandoffPayload,
];
expect(payload.prompt).toBe(
@@ -356,7 +356,7 @@ describe('runHandoffDispatch — autoOpen=false honors the user preference', ()
docPath: '',
};
await runHandoffDispatch('codex', input, deps);
- const [payload] = (deps.dispatchHandoff as ReturnType<typeof mock>).mock.calls[0] as [
+ const [payload] = (deps.dispatchHandoff as ReturnType<typeof vi.fn>).mock.calls[0] as [
HandoffPayload,
];
expect(payload.prompt).toBe(
@@ -370,7 +370,7 @@ describe('runHandoffDispatch — failure path', () => {
test('renders error toast with Retry action and records error stats line', async () => {
const { runHandoffDispatch } = await import('./useHandoffDispatch');
const deps = buildDeps({
- dispatchHandoff: mock(
+ dispatchHandoff: vi.fn(
async (_p: HandoffPayload) => ({ ok: false, reason: 'not-installed' }) as HandoffOutcome,
),
});
@@ -399,7 +399,7 @@ describe('runHandoffDispatch — failure path', () => {
test('retry action re-invokes dispatchHandoff with the same payload', async () => {
const { runHandoffDispatch } = await import('./useHandoffDispatch');
- const dispatch = mock(async (_p: HandoffPayload) => ({ ok: true }) as HandoffOutcome);
+ const dispatch = vi.fn(async (_p: HandoffPayload) => ({ ok: true }) as HandoffOutcome);
// First call returns failure; subsequent retries return success.
let firstCall = true;
(
@@ -429,8 +429,9 @@ describe('runHandoffDispatch — failure path', () => {
await wait(0);
expect(dispatch).toHaveBeenCalledTimes(2);
- const firstPayload = (dispatch as ReturnType<typeof mock>).mock.calls[0]?.[0] as HandoffPayload;
- const secondPayload = (dispatch as ReturnType<typeof mock>).mock
+ const firstPayload = (dispatch as ReturnType<typeof vi.fn>).mock
+ .calls[0]?.[0] as HandoffPayload;
+ const secondPayload = (dispatch as ReturnType<typeof vi.fn>).mock
.calls[1]?.[0] as HandoffPayload;
expect(secondPayload).toEqual(firstPayload);
@@ -446,7 +447,7 @@ describe('runHandoffDispatch — failure path', () => {
// button + "Still couldn't reach" copy. Third failure: distinct
// "please try again later" copy, NO button — user cannot loop further.
const { runHandoffDispatch } = await import('./useHandoffDispatch');
- const dispatch = mock(
+ const dispatch = vi.fn(
async (_p: HandoffPayload) => ({ ok: false, reason: 'dispatch-error' }) as HandoffOutcome,
);
const deps = buildDeps({ dispatchHandoff: dispatch });
@@ -490,7 +491,7 @@ describe('runHandoffDispatch — failure path', () => {
test('web-host-cursor-unsupported reason flows through to telemetry + toast', async () => {
const { runHandoffDispatch } = await import('./useHandoffDispatch');
const deps = buildDeps({
- dispatchHandoff: mock(
+ dispatchHandoff: vi.fn(
async (_p: HandoffPayload) =>
({
ok: false,
@@ -536,7 +537,7 @@ describe('runHandoffDispatch — Cowork install gate', () => {
test('first click + bridge ran: shows install toast and skips URL dispatch', async () => {
const { runHandoffDispatch } = await import('./useHandoffDispatch');
const deps = buildDeps({
- ensureCoworkSkillInstalled: mock(
+ ensureCoworkSkillInstalled: vi.fn(
async () => ({ kind: 'installed-now', path: '/tmp/openknowledge.skill' }) as const,
),
});
@@ -554,7 +555,7 @@ describe('runHandoffDispatch — Cowork install gate', () => {
test('install-failed: surfaces error toast and returns dispatch-error outcome', async () => {
const { runHandoffDispatch } = await import('./useHandoffDispatch');
const deps = buildDeps({
- ensureCoworkSkillInstalled: mock(
+ ensureCoworkSkillInstalled: vi.fn(
async () =>
({
kind: 'install-failed',
@@ -591,7 +592,7 @@ describe('runHandoffDispatch — Cowork install gate', () => {
const { runHandoffDispatch } = await import('./useHandoffDispatch');
const deps = buildDeps({
isElectronHost: () => false,
- ensureCoworkSkillInstalled: mock(async () => ({ kind: 'host-unsupported' }) as const),
+ ensureCoworkSkillInstalled: vi.fn(async () => ({ kind: 'host-unsupported' }) as const),
});
await runHandoffDispatch('claude-cowork', sampleInput(), deps);
@@ -602,7 +603,7 @@ describe('runHandoffDispatch — Cowork install gate', () => {
test('non-Cowork target: install gate is never consulted', async () => {
const { runHandoffDispatch } = await import('./useHandoffDispatch');
- const ensureSpy = mock(async () => ({ kind: 'already-installed' }) as const);
+ const ensureSpy = vi.fn(async () => ({ kind: 'already-installed' }) as const);
const deps = buildDeps({ ensureCoworkSkillInstalled: ensureSpy });
await runHandoffDispatch('codex', sampleInput(), deps);
@@ -614,7 +615,7 @@ describe('runHandoffDispatch — Cowork install gate', () => {
test('retry attempt skips the install gate (only first attempt invokes it)', async () => {
const { runHandoffDispatch } = await import('./useHandoffDispatch');
- const ensureSpy = mock(async () => ({ kind: 'already-installed' }) as const);
+ const ensureSpy = vi.fn(async () => ({ kind: 'already-installed' }) as const);
const deps = buildDeps({ ensureCoworkSkillInstalled: ensureSpy });
// attempt=2 simulates a retry — the install gate must not re-run.
@@ -627,7 +628,7 @@ describe('runHandoffDispatch — Cowork install gate', () => {
test('install gate throws: surfaces error toast + dispatch-error outcome (no unhandled rejection)', async () => {
const { runHandoffDispatch } = await import('./useHandoffDispatch');
const deps = buildDeps({
- ensureCoworkSkillInstalled: mock(async () => {
+ ensureCoworkSkillInstalled: vi.fn(async () => {
throw new Error('IPC channel closed');
}),
});
@@ -1561,7 +1562,7 @@ describe('runHandoffDispatch — selection scope', () => {
await runHandoffDispatch('claude-code', selectionInput(), deps);
expect(deps.dispatchHandoff).toHaveBeenCalledTimes(1);
- const [payload] = (deps.dispatchHandoff as ReturnType<typeof mock>).mock.calls[0] as [
+ const [payload] = (deps.dispatchHandoff as ReturnType<typeof vi.fn>).mock.calls[0] as [
HandoffPayload,
];
expect(payload.target).toBe('claude-code');
@@ -2074,7 +2075,7 @@ describe('runHandoffDispatch — ask scope', () => {
await runHandoffDispatch('claude-code', askInput(), deps);
expect(deps.dispatchHandoff).toHaveBeenCalledTimes(1);
- const [payload] = (deps.dispatchHandoff as ReturnType<typeof mock>).mock.calls[0] as [
+ const [payload] = (deps.dispatchHandoff as ReturnType<typeof vi.fn>).mock.calls[0] as [
HandoffPayload,
];
expect(payload.target).toBe('claude-code');
@@ -2096,7 +2097,7 @@ describe('runHandoffDispatch — ask scope', () => {
deps,
);
- const [payload] = (deps.dispatchHandoff as ReturnType<typeof mock>).mock.calls[0] as [
+ const [payload] = (deps.dispatchHandoff as ReturnType<typeof vi.fn>).mock.calls[0] as [
HandoffPayload,
];
expect(payload.prompt).toContain('research the extinction of flightless birds');
@@ -2125,7 +2126,7 @@ describe('runHandoffDispatch — ask scope', () => {
await runHandoffDispatch('codex', askInput(), deps);
- const [payload] = (deps.dispatchHandoff as ReturnType<typeof mock>).mock.calls[0] as [
+ const [payload] = (deps.dispatchHandoff as ReturnType<typeof vi.fn>).mock.calls[0] as [
HandoffPayload,
];
expect(payload.prompt).toContain('> condense this doc');
@@ -2148,7 +2149,7 @@ describe('runHandoffDispatch — ask scope', () => {
await runHandoffDispatch('cursor', input, deps);
- const [payload] = (deps.dispatchHandoff as ReturnType<typeof mock>).mock.calls[0] as [
+ const [payload] = (deps.dispatchHandoff as ReturnType<typeof vi.fn>).mock.calls[0] as [
HandoffPayload,
];
expect(payload.prompt).toBe(
@@ -2458,7 +2459,7 @@ describe('runHandoffDispatch — compose scope (US-002)', () => {
await runHandoffDispatch('codex', composeProjectInput(), deps);
- const [payload] = (deps.dispatchHandoff as ReturnType<typeof mock>).mock.calls[0] as [
+ const [payload] = (deps.dispatchHandoff as ReturnType<typeof vi.fn>).mock.calls[0] as [
HandoffPayload,
];
expect(payload.docPath).toBe('');
@@ -2492,7 +2493,7 @@ describe('runHandoffDispatch — compose scope (US-002)', () => {
await runHandoffDispatch('claude-code', input, deps);
- const [payload] = (deps.dispatchHandoff as ReturnType<typeof mock>).mock.calls[0] as [
+ const [payload] = (deps.dispatchHandoff as ReturnType<typeof vi.fn>).mock.calls[0] as [
HandoffPayload,
];
expect(payload.prompt).toContain('@specs/foo/SPEC.md');
@@ -2518,7 +2519,7 @@ describe('runHandoffDispatch — compose scope (US-002)', () => {
await runHandoffDispatch('codex', input, deps);
- const [payload] = (deps.dispatchHandoff as ReturnType<typeof mock>).mock.calls[0] as [
+ const [payload] = (deps.dispatchHandoff as ReturnType<typeof vi.fn>).mock.calls[0] as [
HandoffPayload,
];
expect(payload.prompt).toContain('This sentence is wordy.');
@@ -2559,7 +2560,7 @@ describe('runHandoffDispatch — compose scope (US-002)', () => {
await runHandoffDispatch('cursor', input, deps);
- const [payload] = (deps.dispatchHandoff as ReturnType<typeof mock>).mock.calls[0] as [
+ const [payload] = (deps.dispatchHandoff as ReturnType<typeof vi.fn>).mock.calls[0] as [
HandoffPayload,
];
expect(payload.docPath).toBe('');
@@ -2567,3 +2568,43 @@ describe('runHandoffDispatch — compose scope (US-002)', () => {
expect(payload.prompt).not.toContain('@');
});
});
+
+describe('threadTitleHintFromInput — the thread-title source', () => {
+ const base = { docContext: null, projectDir: '/proj', docPath: '' };
+
+ test('returns the create brief so the title skips the handoff preamble', async () => {
+ const { threadTitleHintFromInput } = await import('./useHandoffDispatch');
+ expect(threadTitleHintFromInput({ ...base, createDescription: 'Fix the login bug' })).toBe(
+ 'Fix the login bug',
+ );
+ });
+
+ test('prefers compose instruction over a later scope, in selectScopedPrompt order', async () => {
+ const { threadTitleHintFromInput } = await import('./useHandoffDispatch');
+ expect(
+ threadTitleHintFromInput({
+ ...base,
+ compose: { scope: 'project', instruction: 'summarize the specs', mentions: [] },
+ instruction: 'toolbar text that should lose',
+ }),
+ ).toBe('summarize the specs');
+ });
+
+ test('skips blank candidates and falls back to the toolbar instruction', async () => {
+ const { threadTitleHintFromInput } = await import('./useHandoffDispatch');
+ expect(
+ threadTitleHintFromInput({
+ ...base,
+ createDescription: ' ',
+ instruction: 'rename headings',
+ }),
+ ).toBe('rename headings');
+ });
+
+ test('returns null when no typed text is present (bare launch)', async () => {
+ const { threadTitleHintFromInput } = await import('./useHandoffDispatch');
+ expect(
+ threadTitleHintFromInput({ ...base, docContext: { relativePath: 'notes/today.md' } }),
+ ).toBeNull();
+ });
+});
diff --git a/packages/app/src/components/handoff/useHandoffDispatch.ts b/packages/app/src/components/handoff/useHandoffDispatch.ts
index 5568f2a0c..7a63cb41a 100644
--- a/packages/app/src/components/handoff/useHandoffDispatch.ts
+++ b/packages/app/src/components/handoff/useHandoffDispatch.ts
@@ -27,12 +27,14 @@ import {
composeSelectionPrompt,
composeSkillPrompt,
composeTerminalBareLaunchPrompt,
+ composeThreadBareLaunchPrompt,
type DocContext,
type HandoffOutcome,
type HandoffPayload,
type HandoffScope,
type HandoffTarget,
OK_TERMINAL_SURFACE_PREAMBLE,
+ OK_THREAD_SURFACE_PREAMBLE,
type PromptTransport,
type SkillScope,
type TargetData,
@@ -60,6 +62,7 @@ import {
type HandoffStatsLine,
} from '@/lib/handoff/telemetry';
import { docNameToRelativePath, joinWorkspacePath, type Workspace } from '@/lib/workspace-paths';
+import { requestAgentThreadLaunch } from './thread-launch-events';
// Side-effect import only — loads the `Window.okDesktop?` global augmentation.
import '@/lib/desktop-bridge-types';
@@ -912,6 +915,80 @@ export function composeTerminalLaunchPrompt(input: HandoffDispatchInput, cli: Te
return composeTerminalBareLaunchPrompt(input.docContext?.relativePath ?? null);
}
+/**
+ * Prompt for an in-app agent thread (server-hosted ACP). The thread twin of
+ * {@link composeTerminalLaunchPrompt}: same scope-directive threading, with
+ * the thread-surface preamble instead of the terminal one. Agent-neutral —
+ * threads are not CLI-specific, so scope composition uses the `claude-code`
+ * target purely to reach `selectScopedPrompt` (the composed text is
+ * target-agnostic for the directive scopes).
+ */
+function composeThreadLaunchPrompt(input: HandoffDispatchInput): string {
+ const hasInstruction = typeof input.instruction === 'string' && input.instruction.trim() !== '';
+ if (input.compose !== undefined || input.createDescription !== undefined || hasInstruction) {
+ // Threads deliver the composed prompt straight to the server-hosted agent —
+ // no URL round-trip and no shell quoting — so use the generous `terminal`
+ // byte budget rather than `url`, whose per-target URL budget would trim
+ // thread content that has no URL-length constraint.
+ return `${OK_THREAD_SURFACE_PREAMBLE} ${selectScopedPrompt(input, 'claude-code', false, 'terminal')}`;
+ }
+ return composeThreadBareLaunchPrompt(input.docContext?.relativePath ?? null);
+}
+
+/** Extension-less docName from a handoff input's file context, when any. */
+function docNameFromInput(input: HandoffDispatchInput): string | null {
+ const rel = input.docContext?.relativePath;
+ if (typeof rel !== 'string' || rel === '') return null;
+ return rel.replace(/\.(md|mdx)$/, '');
+}
+
+/**
+ * The user's raw typed text for a launch — the create brief or free-form
+ * instruction, taken in the same scope precedence `selectScopedPrompt` uses.
+ * Carried alongside (not inside) the composed prompt so the thread title
+ * derives from what the user actually typed, never from the handoff preamble
+ * the prompt opens with. Null when the scope carried no typed text (bare
+ * file/folder/project launches) — the server then falls back to the prompt.
+ */
+export function threadTitleHintFromInput(input: HandoffDispatchInput): string | null {
+ const candidates = [
+ input.compose?.instruction,
+ input.selection?.instruction,
+ input.ask?.instruction,
+ input.createDescription,
+ input.instruction,
+ ];
+ for (const candidate of candidates) {
+ if (typeof candidate === 'string' && candidate.trim() !== '') return candidate;
+ }
+ return null;
+}
+
+/**
+ * Fire an "open an in-app agent thread" launch for a handoff input — the shared
+ * entry point behind every "Start an agent" affordance (the sparkles popover,
+ * the file-tree / empty-space right-click submenus, and the composers). Works
+ * on both hosts — threads are server-hosted.
+ *
+ * Without options, the region resolves the target: the default registered
+ * agent launches directly, or (before any registration) Configure agents opens
+ * so the user can enable one. `opts.agent` launches that specific agent.
+ */
+export function startAgentThreadForInput(
+ input: HandoffDispatchInput,
+ opts?: {
+ agent?: { source: 'registry' | 'custom'; id: string };
+ },
+): void {
+ requestAgentThreadLaunch({
+ agentSource: opts?.agent?.source ?? 'registry',
+ agentId: opts?.agent?.id ?? '',
+ prompt: composeThreadLaunchPrompt(input),
+ docName: docNameFromInput(input),
+ titleHint: threadTitleHintFromInput(input),
+ });
+}
+
/**
* Pure test-seam helper. Called by the React hook with production deps; unit
* tests call it directly with recording doubles.
diff --git a/packages/app/src/components/settings/ConfigureAgentsSection.dom.test.tsx b/packages/app/src/components/settings/ConfigureAgentsSection.dom.test.tsx
new file mode 100644
index 000000000..c18575135
--- /dev/null
+++ b/packages/app/src/components/settings/ConfigureAgentsSection.dom.test.tsx
@@ -0,0 +1,260 @@
+/**
+ * Behavioral tests for the Settings → Configure agents section: it renders the
+ * agent groups (In app / Terminal / Desktop) with toggles, and flipping a toggle
+ * persists an enable/disable override to the `enabled-agents` store so the
+ * launcher dropdowns show/hide that agent.
+ */
+
+import type { InstallState } from '@inkeep/open-knowledge-core';
+import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
+import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
+import type { ReactNode } from 'react';
+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
+import type { AgentCatalog } from '@/lib/acp/catalog';
+
+// Minimal localStorage for the enabled-agents store (plain bun test has none).
+const backing = new Map<string, string>();
+if (typeof globalThis.localStorage === 'undefined') {
+ (globalThis as { localStorage?: unknown }).localStorage = {
+ getItem: (key: string) => backing.get(key) ?? null,
+ setItem: (key: string, value: string) => void backing.set(key, value),
+ removeItem: (key: string) => void backing.delete(key),
+ clear: () => backing.clear(),
+ };
+}
+
+vi.doMock('@lingui/react/macro', () => ({
+ Trans: ({ children }: { children: ReactNode }) => <>{children}</>,
+ useLingui: () => ({
+ t: (strings: TemplateStringsArray, ...values: unknown[]) =>
+ strings.reduce((acc, part, index) => `${acc}${part}${values[index] ?? ''}`, ''),
+ }),
+}));
+
+const catalog: AgentCatalog = {
+ agents: [
+ // Harness-mapped agents (agent.harness present) are the default-visible set.
+ {
+ id: 'claude-acp',
+ name: 'Claude Agent',
+ version: '1',
+ source: 'registry',
+ supported: true,
+ featured: true,
+ harness: { cli: 'claude', availability: 'unknown' },
+ },
+ {
+ id: 'opencode-acp',
+ name: 'OpenCode',
+ version: '1',
+ source: 'registry',
+ supported: false,
+ featured: false,
+ harness: { cli: 'opencode', availability: 'not-found' },
+ },
+ // Not harness-mapped and not enabled → collapsed behind "Show more".
+ {
+ id: 'cline',
+ name: 'Cline',
+ version: '1',
+ source: 'registry',
+ supported: true,
+ featured: false,
+ description: 'Autonomous coding agent',
+ },
+ // Supported; harness not found on this host → not auto-detected (defaults
+ // off), but the toggle stays operable. Carries a catalog blurb.
+ {
+ id: 'cursor',
+ name: 'Cursor',
+ version: '1',
+ source: 'registry',
+ supported: true,
+ featured: false,
+ description: 'ACP wrapper for Cursor',
+ license: 'Apache-2.0',
+ harness: { cli: 'cursor', availability: 'not-found' },
+ },
+ // Supported + harness present → detected → defaults on.
+ {
+ id: 'gemini',
+ name: 'Gemini',
+ version: '1',
+ source: 'registry',
+ supported: true,
+ featured: false,
+ description: 'ACP wrapper for Gemini',
+ harness: { cli: 'pi', availability: 'present' },
+ },
+ ],
+ stale: false,
+ maxThreads: 8,
+};
+vi.doMock('@/lib/acp/catalog', () => ({
+ fetchAgentCatalog: () => Promise.resolve(catalog),
+}));
+
+let states: Record<string, InstallState> = {};
+vi.doMock('@/components/handoff/useInstalledAgents', () => ({
+ useInstalledAgents: () => ({ states, refresh: () => Promise.resolve() }),
+}));
+
+// Web-host default: no docked terminal → the Terminal group is absent.
+vi.doMock('@/components/handoff/TerminalLaunchContext', () => ({
+ useTerminalLaunch: () => null,
+}));
+
+vi.doMock('@/components/handoff/OpenInAgentMenuItem', () => ({
+ TargetIcon: ({ id }: { id: string }) => <svg data-testid={`target-icon-${id}`} aria-hidden />,
+}));
+vi.doMock('@/components/acp/RegisteredAgentIcon', () => ({
+ RegisteredAgentIcon: () => <svg data-testid="registered-agent-icon" aria-hidden />,
+}));
+
+import {
+ getDefaultRegisteredAgent,
+ registerAgent,
+ reloadRegisteredAgentsFromStorage,
+} from '@/lib/acp/registered-agents';
+
+// Dynamic import AFTER the mock.module calls above: the shim registers mocks via
+// vitest's runtime `vi.doMock` (no retroactive registry patch like bun), so the
+// component — and its `fetchAgentCatalog` import — must resolve after the mocks.
+const { ConfigureAgentsSection } = await import('./ConfigureAgentsSection');
+
+const STORAGE_KEY = 'ok-acp-enabled-agents-v1';
+
+function overrides(): Record<string, boolean> {
+ return JSON.parse(localStorage.getItem(STORAGE_KEY) ?? '{}');
+}
+
+function renderSection() {
+ const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });
+ render(
+ <QueryClientProvider client={client}>
+ <ConfigureAgentsSection />
+ </QueryClientProvider>,
+ );
+}
+
+beforeEach(() => {
+ localStorage.clear();
+ reloadRegisteredAgentsFromStorage();
+ states = { 'claude-code': { installed: true }, codex: { installed: false } } as Record<
+ string,
+ InstallState
+ >;
+});
+
+afterEach(() => cleanup());
+
+describe('ConfigureAgentsSection', () => {
+ test('renders In app + Desktop groups (no Terminal on the web host)', async () => {
+ renderSection();
+ await waitFor(() => expect(screen.getByText('Claude Agent')).toBeTruthy());
+ expect(screen.getByText('In app')).toBeTruthy();
+ expect(screen.getByText('Desktop')).toBeTruthy();
+ expect(screen.queryByText('Terminal')).toBeNull();
+ });
+
+ test('a platform-unsupported in-app agent renders disabled', async () => {
+ renderSection();
+ const toggle = await screen.findByTestId('configure-agents-in-app-registry:opencode-acp');
+ expect(toggle.getAttribute('data-disabled')).toBe('');
+ });
+
+ test('a row shows the catalog description as its subtitle, never the license or an install signal', async () => {
+ renderSection();
+ // The human blurb, not the SPDX license. (A global "Not installed" check
+ // would hit the Desktop group's own install hint, so scope to the license.)
+ expect(await screen.findByText('ACP wrapper for Cursor')).toBeTruthy();
+ expect(screen.getByText('ACP wrapper for Gemini')).toBeTruthy();
+ expect(screen.queryByText('Apache-2.0')).toBeNull();
+ });
+
+ test('a present harness defaults on and a not-found one defaults off (toggle still operable)', async () => {
+ renderSection();
+ const present = await screen.findByTestId('configure-agents-in-app-registry:gemini');
+ const notFound = await screen.findByTestId('configure-agents-in-app-registry:cursor');
+ expect(present.getAttribute('aria-checked')).toBe('true');
+ expect(notFound.getAttribute('aria-checked')).toBe('false');
+ // Not a platform gate — the not-found row is still enabled to turn on.
+ expect(notFound.getAttribute('data-disabled')).toBeNull();
+ });
+
+ test('collapses to the harness-mapped agents, with a Show more toggle for the rest', async () => {
+ renderSection();
+ // Default view: harness-mapped agents (Claude/OpenCode/Cursor/Gemini) show;
+ // the non-mapped agent (Cline) is hidden behind the toggle.
+ await screen.findByText('Claude Agent');
+ expect(screen.getByText('ACP wrapper for Cursor')).toBeTruthy();
+ expect(screen.queryByText('Cline')).toBeNull();
+ const toggle = screen.getByTestId('configure-agents-in-app-show-more');
+ expect(toggle.textContent).toContain('Show 1 more');
+
+ fireEvent.click(toggle);
+
+ // Expanded: the collapsed agent appears; the toggle flips to Show less.
+ expect(screen.getByText('Cline')).toBeTruthy();
+ expect(toggle.textContent).toContain('Show less');
+ });
+
+ test('enabling an in-app agent is visibility-only and does not change the launch default', async () => {
+ // An explicit pick established a default before Settings is opened.
+ registerAgent({ source: 'registry', id: 'codex-acp', name: 'Codex' });
+ expect(getDefaultRegisteredAgent()?.id).toBe('codex-acp');
+
+ renderSection();
+ const toggle = await screen.findByTestId('configure-agents-in-app-registry:claude-acp');
+ fireEvent.click(toggle);
+
+ // The toggle records the enable override...
+ await waitFor(() => expect(overrides()['in-app:registry:claude-acp']).toBe(true));
+ // ...but the launch default is untouched (enabling is visibility, not a pick).
+ expect(getDefaultRegisteredAgent()?.id).toBe('codex-acp');
+ });
+
+ test('disabling the current default moves the default to the next enabled agent', async () => {
+ // Two registered agents, claude is the launch default; codex is the fallback.
+ registerAgent({ source: 'registry', id: 'codex-acp', name: 'Codex' });
+ registerAgent({ source: 'registry', id: 'claude-acp', name: 'Claude Agent' });
+ expect(getDefaultRegisteredAgent()?.id).toBe('claude-acp');
+
+ renderSection();
+ const toggle = await screen.findByTestId('configure-agents-in-app-registry:claude-acp');
+ fireEvent.click(toggle); // disable the default
+
+ await waitFor(() => expect(overrides()['in-app:registry:claude-acp']).toBe(false));
+ // The default no longer points at the just-disabled agent — it moved to codex,
+ // so the composer won't keep showing the disabled agent as selected.
+ expect(getDefaultRegisteredAgent()?.id).toBe('codex-acp');
+ });
+
+ test('toggling a Desktop agent on persists a true override (Desktop is off by default)', async () => {
+ renderSection();
+ const toggle = await screen.findByTestId('configure-agents-desktop-claude-code');
+ // Desktop is opt-in — off by default with no override yet.
+ expect(overrides()['desktop:claude-code']).toBeUndefined();
+ fireEvent.click(toggle);
+ await waitFor(() => expect(overrides()['desktop:claude-code']).toBe(true));
+ });
+
+ test('search filters agents across groups', async () => {
+ renderSection();
+ await screen.findByText('Claude Agent'); // catalog resolved
+ fireEvent.change(screen.getByTestId('configure-agents-search'), { target: { value: 'codex' } });
+ // In-app 'Claude Agent' no longer matches; the Desktop 'Codex' row does.
+ await waitFor(() => expect(screen.queryByText('Claude Agent')).toBeNull());
+ expect(screen.getByTestId('configure-agents-desktop-codex')).toBeTruthy();
+ expect(screen.queryByTestId('configure-agents-no-results')).toBeNull();
+ });
+
+ test('a query matching nothing shows the no-results line', async () => {
+ renderSection();
+ await screen.findByText('Claude Agent');
+ fireEvent.change(screen.getByTestId('configure-agents-search'), {
+ target: { value: 'zzzznope' },
+ });
+ await waitFor(() => expect(screen.getByTestId('configure-agents-no-results')).toBeTruthy());
+ });
+});
diff --git a/packages/app/src/components/settings/ConfigureAgentsSection.tsx b/packages/app/src/components/settings/ConfigureAgentsSection.tsx
new file mode 100644
index 000000000..ac1eee8a9
--- /dev/null
+++ b/packages/app/src/components/settings/ConfigureAgentsSection.tsx
@@ -0,0 +1,403 @@
+/**
+ * Settings → User → Configure agents.
+ *
+ * The single user-owned surface controlling which agents appear in the agent
+ * launcher menus (footer "Ask", empty-state "Create with", header "Open with
+ * AI", the file-tree right-click submenus, and the dock New-chat picker). Lists
+ * every agent in three groups — In app / Terminal / Desktop — each with a
+ * toggle. The toggle is the source of truth: enabling shows the agent in every
+ * menu, disabling hides it.
+ *
+ * Enablement persists to localStorage via `enabled-agents.ts`; effective state
+ * is `override ?? categoryDefault` resolved through `agent-visibility.ts` so
+ * this list and the menus always agree. Only a platform-unsupported in-app agent
+ * is disabled; every other agent stays toggleable, with the catalog description
+ * as its muted subtitle.
+ */
+
+import { TERMINAL_CLI_IDS, TERMINAL_CLIS, type TerminalCli } from '@inkeep/open-knowledge-core';
+import { useLingui } from '@lingui/react/macro';
+import { useQuery } from '@tanstack/react-query';
+import { Loader2, Search, WifiOff } from 'lucide-react';
+import { type ReactNode, useEffect, useEffectEvent, useState } from 'react';
+import { AgentBetaBadge } from '@/components/acp/AgentBetaBadge';
+import { RegisteredAgentIcon } from '@/components/acp/RegisteredAgentIcon';
+import { TargetIcon } from '@/components/handoff/OpenInAgentMenuItem';
+import { useTerminalLaunch } from '@/components/handoff/TerminalLaunchContext';
+import { cliIconTargetId } from '@/components/handoff/terminal-cli-display';
+import { useInstalledAgents } from '@/components/handoff/useInstalledAgents';
+import { Button } from '@/components/ui/button';
+import { Input } from '@/components/ui/input';
+import { Switch } from '@/components/ui/switch';
+import {
+ isDesktopTargetEnabled,
+ isInAppAgentEnabled,
+ isTerminalCliEnabled,
+} from '@/lib/acp/agent-visibility';
+import { type CatalogAgent, fetchAgentCatalog } from '@/lib/acp/catalog';
+import {
+ desktopEnabledKey,
+ inAppEnabledKey,
+ setAgentEnabled,
+ terminalEnabledKey,
+ useEnabledOverrides,
+} from '@/lib/acp/enabled-agents';
+import {
+ reassignDefaultIfDisabled,
+ registerAgent,
+ useRegisteredAgents,
+} from '@/lib/acp/registered-agents';
+import { VISIBLE_TARGETS } from '@/lib/handoff/targets';
+
+/** One toggle row: icon + name (+ optional muted hint) on the left, Switch on
+ * the right. The icon aligns to the name line only — a two-line row (name +
+ * description hint) keeps the icon centered on the name, not the block. */
+function AgentRow({
+ icon,
+ name,
+ hint,
+ checked,
+ disabled,
+ ariaLabel,
+ testId,
+ onToggle,
+}: {
+ icon: ReactNode;
+ name: ReactNode;
+ hint?: ReactNode;
+ checked: boolean;
+ disabled?: boolean;
+ ariaLabel: string;
+ testId: string;
+ onToggle: (next: boolean) => void;
+}): ReactNode {
+ return (
+ <div className="flex items-center justify-between gap-3 px-3 py-2.5">
+ <div className="flex min-w-0 items-start gap-2.5">
+ {/* h-5 matches the name's leading-5 line box, so the icon centers on the
+ name line whether or not a hint sits below it. */}
+ <span className="flex h-5 shrink-0 items-center">{icon}</span>
+ <div className="flex min-w-0 flex-col">
+ <span className="truncate text-sm leading-5">{name}</span>
+ {hint ? <span className="truncate text-muted-foreground text-1sm">{hint}</span> : null}
+ </div>
+ </div>
+ <Switch
+ checked={checked}
+ disabled={disabled}
+ onCheckedChange={onToggle}
+ aria-label={ariaLabel}
+ data-testid={testId}
+ />
+ </div>
+ );
+}
+
+function AgentGroup({
+ label,
+ children,
+ labelId,
+}: {
+ label: ReactNode;
+ labelId: string;
+ children: ReactNode;
+}): ReactNode {
+ return (
+ <section aria-labelledby={labelId}>
+ <h4
+ id={labelId}
+ className="mb-2 font-mono text-muted-foreground text-xs uppercase tracking-wide"
+ >
+ {label}
+ </h4>
+ <div className="divide-y overflow-hidden rounded-md border">{children}</div>
+ </section>
+ );
+}
+
+export function ConfigureAgentsSection(): ReactNode {
+ const { t } = useLingui();
+ const overrides = useEnabledOverrides();
+ const registered = useRegisteredAgents();
+ const { states, refresh } = useInstalledAgents();
+ // Null on the web host (no docked terminal / shell), so the Terminal group is
+ // absent there — matching the launcher menus.
+ const terminalLaunch = useTerminalLaunch();
+ const [query, setQuery] = useState('');
+ // In app list is collapsed to the harness-mapped agents by default; this
+ // reveals the long tail.
+ const [showInAppOverflow, setShowInAppOverflow] = useState(false);
+
+ const catalog = useQuery({
+ queryKey: ['acp-catalog'],
+ queryFn: ({ signal }) => fetchAgentCatalog(signal),
+ staleTime: 5 * 60 * 1000,
+ });
+
+ // Refresh desktop install detection when the section mounts so a freshly
+ // installed app shows as installed. `useEffectEvent` keeps `refresh` out of
+ // the dependency array; the probe coordinator throttles + dedups.
+ const refreshOnMount = useEffectEvent(() => {
+ void refresh();
+ });
+ useEffect(() => {
+ refreshOnMount();
+ }, []);
+
+ // Registered-agent metadata hydration (name + icon from the catalog) runs once
+ // at app startup via `useHydrateRegisteredAgentMeta` in main.tsx, so it no
+ // longer needs to be gated behind opening this tab; here the catalog just
+ // drives the In app list.
+ const catalogAgents = catalog.data?.agents;
+ const registeredKeys = new Set(registered.map((a) => `${a.source}:${a.id}`));
+ const installedClis = terminalLaunch?.installedClis ?? {};
+
+ // Case-insensitive substring filter over each agent's visible name.
+ const q = query.trim().toLowerCase();
+ const matches = (text: string): boolean => q === '' || text.toLowerCase().includes(q);
+
+ const inAppAgents = (catalogAgents ?? []).filter((agent) => matches(agent.name));
+ const terminalClis =
+ terminalLaunch !== null
+ ? TERMINAL_CLI_IDS.filter((cli) => matches(TERMINAL_CLIS[cli].displayName))
+ : [];
+ const desktopTargets = VISIBLE_TARGETS.filter((target) => matches(target.displayName));
+
+ // With a query active, hide a group that has no matches; when every group is
+ // empty, show a single no-results line instead of three empty boxes.
+ const searching = q !== '';
+ const catalogReady = !catalog.isLoading && !catalog.isError;
+ const noMatches =
+ searching &&
+ catalogReady &&
+ inAppAgents.length === 0 &&
+ terminalClis.length === 0 &&
+ desktopTargets.length === 0;
+ const showInApp = !searching || catalog.isLoading || catalog.isError || inAppAgents.length > 0;
+ const showTerminal = terminalLaunch !== null && (!searching || terminalClis.length > 0);
+ const showDesktop = !searching || desktopTargets.length > 0;
+
+ // Effective on/off for an in-app agent — the SAME predicate the row + menus
+ // use, so this list and every launcher agree.
+ const inAppChecked = (agent: CatalogAgent): boolean => {
+ const isRegistered = registeredKeys.has(`${agent.source}:${agent.id}`);
+ const isDetected = agent.supported === true && agent.harness?.availability === 'present';
+ return isInAppAgentEnabled(
+ overrides,
+ agent.source,
+ agent.id,
+ isRegistered || isDetected,
+ agent.supported,
+ );
+ };
+ // Default view = the harness-mapped agents (the server attaches `harness`
+ // exactly for the `ACP_AGENT_HARNESS_CLIS` set, i.e. the ones that also appear
+ // in the Terminal section), plus any agent the user has turned on so an
+ // enabled agent never hides behind "Show more". Searching or expanding shows
+ // the full list.
+ const inAppPrimary = inAppAgents.filter((a) => a.harness !== undefined || inAppChecked(a));
+ const inAppShown = searching || showInAppOverflow ? inAppAgents : inAppPrimary;
+ const inAppHiddenCount = searching ? 0 : inAppAgents.length - inAppPrimary.length;
+
+ const titleId = 'settings-configure-agents-title';
+
+ return (
+ <section
+ aria-labelledby={titleId}
+ className="space-y-6"
+ data-testid="settings-configure-agents"
+ >
+ <div className="space-y-1">
+ <h3 id={titleId} className="font-semibold text-base">
+ {t`Configure agents`}
+ </h3>
+ <p className="text-muted-foreground text-sm">
+ {t`Choose which agents appear in the agent selector. Turn one off to hide it everywhere.`}
+ </p>
+ </div>
+
+ <div className="relative">
+ <Search
+ className="-translate-y-1/2 absolute top-1/2 left-2.5 size-4 text-muted-foreground"
+ aria-hidden="true"
+ />
+ <Input
+ value={query}
+ onChange={(event) => setQuery(event.target.value)}
+ placeholder={t`Search agents`}
+ aria-label={t`Search agents`}
+ className="pl-8"
+ data-testid="configure-agents-search"
+ />
+ </div>
+
+ {noMatches ? (
+ <p
+ className="py-6 text-center text-muted-foreground text-sm"
+ data-testid="configure-agents-no-results"
+ >
+ {t`No agents match your search.`}
+ </p>
+ ) : null}
+
+ {/* In app — server-hosted agents from the registry catalog. */}
+ {showInApp ? (
+ <AgentGroup
+ label={
+ <span className="inline-flex items-center gap-1.5">
+ {t`In app`}
+ <AgentBetaBadge />
+ </span>
+ }
+ labelId="settings-configure-agents-in-app"
+ >
+ {catalog.isLoading ? (
+ <div className="flex items-center justify-center gap-2 px-3 py-6 text-muted-foreground text-sm">
+ <Loader2 className="size-4 animate-spin" aria-hidden="true" />
+ {t`Loading agents…`}
+ </div>
+ ) : catalog.isError ? (
+ <div className="flex flex-col items-center gap-2 px-3 py-6 text-center text-muted-foreground text-sm">
+ <WifiOff className="size-5" aria-hidden="true" />
+ <span>{t`Couldn't reach the agent registry.`}</span>
+ <Button
+ type="button"
+ variant="outline"
+ size="sm"
+ onClick={() => void catalog.refetch()}
+ >
+ {t`Retry`}
+ </Button>
+ </div>
+ ) : (catalogAgents?.length ?? 0) === 0 ? (
+ <p className="px-3 py-6 text-center text-muted-foreground text-sm">
+ {t`No agents available.`}
+ </p>
+ ) : (
+ <>
+ {inAppShown.map((agent: CatalogAgent) => {
+ // `inAppChecked` folds in registration + present-harness detection,
+ // matching the launcher menus so this toggle and the menus agree.
+ const checked = inAppChecked(agent);
+ // Muted subtitle: the platform gate wins (disabled rows say why),
+ // otherwise the catalog's own blurb (e.g. "ACP wrapper for Cursor").
+ // Deliberately NOT `license` (an SPDX string like "Apache-2.0") and
+ // NOT the harness probe (a flaky server-side PATH check) — only the
+ // human description belongs here.
+ const hint = !agent.supported
+ ? t`Not available on this platform`
+ : agent.description;
+ return (
+ <AgentRow
+ key={`${agent.source}:${agent.id}`}
+ icon={
+ <RegisteredAgentIcon
+ agentId={agent.id}
+ iconUrl={agent.iconUrl}
+ className="size-4"
+ />
+ }
+ name={agent.name}
+ hint={hint}
+ checked={checked}
+ disabled={!agent.supported}
+ ariaLabel={t`Enable ${agent.name}`}
+ testId={`configure-agents-in-app-${agent.source}:${agent.id}`}
+ onToggle={(next) => {
+ if (next) {
+ // Enabling registers the agent for visibility only (caches
+ // name/icon so the menus can render it) and records an
+ // explicit override. `makeDefault: false` keeps the launch
+ // default put — enabling here is a visibility action, not a
+ // pick; only choosing an agent in a launcher sets the default.
+ registerAgent(
+ {
+ source: agent.source,
+ id: agent.id,
+ name: agent.name,
+ supported: agent.supported,
+ ...(agent.iconUrl !== undefined ? { iconUrl: agent.iconUrl } : {}),
+ },
+ { makeDefault: false },
+ );
+ setAgentEnabled(inAppEnabledKey(agent.source, agent.id), true);
+ } else {
+ setAgentEnabled(inAppEnabledKey(agent.source, agent.id), false);
+ // If this agent was the launch default, move the default to
+ // the next still-enabled agent (or clear it) so the composer
+ // stops showing a just-disabled agent as selected. The
+ // disabled agent is excluded by key, so the pre-toggle
+ // `overrides` snapshot is accurate for the remaining agents.
+ reassignDefaultIfDisabled(`${agent.source}:${agent.id}`, (a) =>
+ isInAppAgentEnabled(overrides, a.source, a.id, true, a.supported),
+ );
+ }
+ }}
+ />
+ );
+ })}
+ {inAppHiddenCount > 0 ? (
+ <Button
+ type="button"
+ variant="ghost"
+ onClick={() => setShowInAppOverflow((v) => !v)}
+ className="w-full justify-center rounded-none font-normal text-1sm text-muted-foreground"
+ data-testid="configure-agents-in-app-show-more"
+ >
+ {showInAppOverflow ? t`Show less` : t`Show ${inAppHiddenCount} more`}
+ </Button>
+ ) : null}
+ </>
+ )}
+ </AgentGroup>
+ ) : null}
+
+ {/* Terminal — docked-terminal CLI launchers. Desktop-only (no web shell). */}
+ {showTerminal ? (
+ <AgentGroup label={t`Terminal`} labelId="settings-configure-agents-terminal">
+ {terminalClis.map((cli: TerminalCli) => {
+ const { displayName } = TERMINAL_CLIS[cli];
+ const notInstalled = installedClis[cli] === false;
+ return (
+ <AgentRow
+ key={cli}
+ icon={
+ <TargetIcon id={cliIconTargetId(cli)} className="size-4" aria-hidden="true" />
+ }
+ name={t`${displayName} CLI`}
+ hint={notInstalled ? t`Not installed` : undefined}
+ checked={isTerminalCliEnabled(overrides, cli, installedClis)}
+ ariaLabel={t`Enable ${displayName} CLI`}
+ testId={`configure-agents-terminal-${cli}`}
+ onToggle={(next) => setAgentEnabled(terminalEnabledKey(cli), next)}
+ />
+ );
+ })}
+ </AgentGroup>
+ ) : null}
+
+ {/* Desktop — installed app launchers (deep-link handoff). */}
+ {showDesktop ? (
+ <AgentGroup label={t`Desktop`} labelId="settings-configure-agents-desktop">
+ {desktopTargets.map((target) => {
+ const installed = states[target.id]?.installed ?? null;
+ return (
+ <AgentRow
+ key={target.id}
+ icon={<TargetIcon id={target.id} className="size-4" aria-hidden="true" />}
+ name={target.displayName}
+ // Only show the hint once the probe positively reports absent;
+ // `null` is detection-pending, not "not installed".
+ hint={installed === false ? t`Not installed` : undefined}
+ checked={isDesktopTargetEnabled(overrides, target.id)}
+ ariaLabel={t`Enable ${target.displayName}`}
+ testId={`configure-agents-desktop-${target.id}`}
+ onToggle={(next) => setAgentEnabled(desktopEnabledKey(target.id), next)}
+ />
+ );
+ })}
+ </AgentGroup>
+ ) : null}
+ </section>
+ );
+}
diff --git a/packages/app/src/components/settings/SettingsDialogBody.tsx b/packages/app/src/components/settings/SettingsDialogBody.tsx
index 8a3bb85e9..7ff4aab1c 100644
--- a/packages/app/src/components/settings/SettingsDialogBody.tsx
+++ b/packages/app/src/components/settings/SettingsDialogBody.tsx
@@ -109,6 +109,7 @@ import { cn } from '@/lib/utils';
import { AccountSection } from './AccountSection';
import { AiToolsSection } from './AiToolsSection';
import { ColorThemePicker } from './ColorThemePicker';
+import { ConfigureAgentsSection } from './ConfigureAgentsSection';
import { CustomThemeEditor } from './CustomThemeEditor';
import { EmbeddingsKeySection } from './EmbeddingsKeySection';
import { LinkPreviewsSection } from './LinkPreviewsSection';
@@ -189,6 +190,11 @@ export function SettingsDialogBody({
</div>
);
}
+ if (activeId === 'configure-agents') {
+ // User-owned enable/disable for the launcher agent lists (In app / Terminal
+ // / Desktop). Its own localStorage store, not the config binding.
+ return <ConfigureAgentsSection />;
+ }
if (activeId === 'hotkeys') {
return <HotkeysSection />;
}
diff --git a/packages/app/src/components/settings/SettingsDialogShell.tsx b/packages/app/src/components/settings/SettingsDialogShell.tsx
index ff60908b7..851508b37 100644
--- a/packages/app/src/components/settings/SettingsDialogShell.tsx
+++ b/packages/app/src/components/settings/SettingsDialogShell.tsx
@@ -19,8 +19,8 @@
* the body chunk is cached after the first open.
*
* Sidebar IA:
- * USER → Preferences, Hotkeys, Account, Plugins (user-scope manage),
- * AI tools & CLI (Electron host only)
+ * USER → Preferences, Configure agents, Hotkeys, Account, Plugins
+ * (user-scope manage), AI tools & CLI (Electron host only)
* THIS PROJECT → Sync, Search, Plugins (project-scope manage), Link previews
* (hidden on the packaged file:// renderer), Templates, Ignore
* patterns, Config sharing
@@ -68,19 +68,31 @@ function releaseNotesUrl(version: string): string {
interface SettingsDialogShellProps {
open: boolean;
+ /**
+ * Sidebar section to open on the `open` edge (from a `#settings/<id>` deep
+ * link). Null opens the default (Preferences). An unknown id also falls back
+ * to Preferences via the sidebar's no-match behavior.
+ */
+ initialSection?: string | null;
onOpenChange: (open: boolean) => void;
}
-export function SettingsDialogShell({ open, onOpenChange }: SettingsDialogShellProps) {
+export function SettingsDialogShell({
+ open,
+ initialSection = null,
+ onOpenChange,
+}: SettingsDialogShellProps) {
const { t } = useLingui();
const { collabUrl } = useDocumentContext();
const { userBinding, userSynced, okignoreBinding, okignoreSynced, projectConfig, merged } =
useConfigContext();
const { desktopPresent } = useClaudeDesktopIntegration();
- // Always default to USER → Preferences on each fresh open. No
- // in-session memory of last-viewed section.
- const [activeId, setActiveId] = useState('preferences');
+ // On each fresh open, honor the deep-link section (`#settings/<id>`) if one
+ // was given, else default to USER → Preferences. No in-session memory of
+ // last-viewed section beyond the open edge; sidebar clicks update activeId
+ // locally without touching the hash.
+ const [activeId, setActiveId] = useState(initialSection ?? 'preferences');
const [searchQuery, setSearchQuery] = useState('');
// Navigation tokens set by a search-result click. fieldFlash re-fires its
// consuming effect via object identity alone (each click sets a fresh
@@ -94,10 +106,10 @@ export function SettingsDialogShell({ open, onOpenChange }: SettingsDialogShellP
useEffect(() => {
if (open) {
- setActiveId('preferences');
+ setActiveId(initialSection ?? 'preferences');
setSearchQuery('');
}
- }, [open]);
+ }, [open, initialSection]);
// Imperative scroll-to-flash for a field the search navigated to. The target
// renders inside the lazily-loaded body and, for schema sections, only once
@@ -185,6 +197,7 @@ export function SettingsDialogShell({ open, onOpenChange }: SettingsDialogShellP
enabled: true,
items: [
{ id: 'preferences', label: t`Preferences` },
+ { id: 'configure-agents', label: t`Configure agents` },
{ id: 'hotkeys', label: t`Hotkeys` },
{ id: 'account', label: t`Account` },
// User-scope plugin management (toggle personal plugins like Themes).
diff --git a/packages/app/src/components/tab-strip-wheel.test.ts b/packages/app/src/components/tab-strip-wheel.test.ts
new file mode 100644
index 000000000..c7f947ee3
--- /dev/null
+++ b/packages/app/src/components/tab-strip-wheel.test.ts
@@ -0,0 +1,65 @@
+import type { WheelEvent } from 'react';
+import { describe, expect, test, vi } from 'vitest';
+import { scrollTabStripOnWheel } from './tab-strip-wheel';
+
+/** Minimal stand-in for the React WheelEvent fields the handler reads. */
+function wheelEvent(opts: {
+ deltaX: number;
+ deltaY: number;
+ scrollWidth: number;
+ clientWidth: number;
+ scrollLeft?: number;
+}) {
+ const preventDefault = vi.fn(() => {});
+ const currentTarget = {
+ scrollWidth: opts.scrollWidth,
+ clientWidth: opts.clientWidth,
+ scrollLeft: opts.scrollLeft ?? 0,
+ };
+ const event = {
+ deltaX: opts.deltaX,
+ deltaY: opts.deltaY,
+ currentTarget,
+ preventDefault,
+ } as unknown as WheelEvent<HTMLElement>;
+ return { event, currentTarget, preventDefault };
+}
+
+describe('scrollTabStripOnWheel', () => {
+ test('ignores a horizontal-dominant gesture (native scroll already handles it)', () => {
+ const { event, currentTarget, preventDefault } = wheelEvent({
+ deltaX: 30,
+ deltaY: 5,
+ scrollWidth: 400,
+ clientWidth: 200,
+ });
+ scrollTabStripOnWheel(event);
+ expect(preventDefault).not.toHaveBeenCalled();
+ expect(currentTarget.scrollLeft).toBe(0);
+ });
+
+ test('ignores a vertical gesture when the strip does not overflow', () => {
+ const { event, currentTarget, preventDefault } = wheelEvent({
+ deltaX: 0,
+ deltaY: 40,
+ scrollWidth: 200,
+ clientWidth: 200,
+ });
+ scrollTabStripOnWheel(event);
+ expect(preventDefault).not.toHaveBeenCalled();
+ expect(currentTarget.scrollLeft).toBe(0);
+ });
+
+ test('maps a vertical gesture to horizontal scroll when the strip overflows', () => {
+ const { event, currentTarget, preventDefault } = wheelEvent({
+ deltaX: 0,
+ deltaY: 40,
+ scrollWidth: 400,
+ clientWidth: 200,
+ scrollLeft: 10,
+ });
+ scrollTabStripOnWheel(event);
+ expect(preventDefault).toHaveBeenCalledTimes(1);
+ expect(currentTarget.scrollLeft).toBe(50);
+ });
+});
diff --git a/packages/app/src/components/tab-strip-wheel.ts b/packages/app/src/components/tab-strip-wheel.ts
new file mode 100644
index 000000000..1b871e8f4
--- /dev/null
+++ b/packages/app/src/components/tab-strip-wheel.ts
@@ -0,0 +1,16 @@
+import type { WheelEvent } from 'react';
+
+/**
+ * Remap a vertical mouse-wheel gesture to horizontal scroll on an overflow-x
+ * tab strip, so a plain (vertical) wheel scrolls the tabs sideways — matching
+ * the trackpad-horizontal / side-wheel behavior the browser already handles.
+ * No-ops when the gesture is already horizontal (let the browser scroll it) or
+ * the strip doesn't overflow. Shared by the editor tabs and the dock's
+ * terminal/agent tab strip so both behave identically.
+ */
+export function scrollTabStripOnWheel(event: WheelEvent<HTMLElement>): void {
+ if (Math.abs(event.deltaX) >= Math.abs(event.deltaY)) return;
+ if (event.currentTarget.scrollWidth <= event.currentTarget.clientWidth) return;
+ event.preventDefault();
+ event.currentTarget.scrollLeft += event.deltaY;
+}
diff --git a/packages/app/src/components/ui/textarea.tsx b/packages/app/src/components/ui/textarea.tsx
index ed1437d07..0913d81f2 100644
--- a/packages/app/src/components/ui/textarea.tsx
+++ b/packages/app/src/components/ui/textarea.tsx
@@ -7,7 +7,7 @@ function Textarea({ className, ...props }: React.ComponentProps<'textarea'>) {
<textarea
data-slot="textarea"
className={cn(
- 'flex field-sizing-content min-h-16 w-full rounded-lg border border-input bg-transparent px-2.5 py-2 text-base transition-colors outline-none placeholder:text-muted-foreground focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 disabled:cursor-not-allowed disabled:bg-input/50 disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/20 md:text-sm dark:bg-input/30 dark:disabled:bg-input/80 dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40',
+ 'flex field-sizing-content min-h-16 w-full rounded-lg border border-input bg-transparent px-2.5 py-2 text-base transition-colors outline-none placeholder:text-muted-foreground focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 disabled:cursor-not-allowed disabled:bg-input/50 disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/20 md:text-sm dark:bg-input/30 dark:disabled:bg-input/80 dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40 subtle-scrollbar',
className,
)}
{...props}
diff --git a/packages/app/src/editor/TiptapEditor.tsx b/packages/app/src/editor/TiptapEditor.tsx
index 47e244ef8..b099962c0 100644
--- a/packages/app/src/editor/TiptapEditor.tsx
+++ b/packages/app/src/editor/TiptapEditor.tsx
@@ -1,5 +1,6 @@
import type { HocuspocusProvider } from '@hocuspocus/provider';
import {
+ type AgentFlashEntry,
sharedExtensions as coreExtensions,
deriveIconColor,
evictStaleEntries,
@@ -26,6 +27,9 @@ import { getInteractionLayer } from './interaction-layer-host';
// measurements. WeakMap auto-GCs when the Editor is destroyed.
const editorCtorStartTimes = new WeakMap<object, number>();
+import type { Transaction as PMTransaction } from '@tiptap/pm/state';
+import type { EditorView as PMEditorView } from '@tiptap/pm/view';
+import { loadFollowFilePref } from '@/components/acp/follow-file';
import { OUTLINE_NAV_EVENT, type OutlineNavDetail } from '@/components/OutlinePanel';
import { anchorFromHash } from '@/lib/doc-hash';
import { mark } from '@/lib/perf';
@@ -53,6 +57,14 @@ import { uploadDecorationPlugin } from './image-upload/index.ts';
import { getMountId } from './mount-id-registry';
import { mountTiptapEditorPromise } from './mount-promise';
import { markUserTyping } from './observers';
+import {
+ AGENT_INSERT_FLASH_ACTIVATION_MS,
+ AGENT_INSERT_FLASH_MS,
+ agentInsertFlashKey,
+ blockRangeToPositions,
+ computeChangedRange,
+ createAgentInsertFlashPlugin,
+} from './plugins/agent-insert-flash';
import { publishSelectionContext, selectionSnapshotFromWysiwyg } from './selection-context';
import {
publishSelectionStats,
@@ -112,6 +124,26 @@ const INITIAL_FLASH_STATE: AgentFlashState = {
lastAgentId: null,
};
+/**
+ * The newest `agent-flash` entry with a timestamp after `since`, keyed by
+ * `agentId:timestamp` so the live flash and the activation replay can dedupe on
+ * the same write. Structural map param avoids a yjs type import.
+ */
+function freshestFlashEntry(
+ activityMap: { entries(): IterableIterator<[string, unknown]> },
+ since: number,
+): { key: string; entry: AgentFlashEntry } | null {
+ let best: { key: string; entry: AgentFlashEntry } | null = null;
+ for (const [id, value] of activityMap.entries()) {
+ const entry = value as AgentFlashEntry;
+ if (typeof entry?.timestamp !== 'number' || entry.timestamp <= since) continue;
+ if (best === null || entry.timestamp > best.entry.timestamp) {
+ best = { key: `${id}:${entry.timestamp}`, entry };
+ }
+ }
+ return best;
+}
+
const ANCHOR_SCROLL_MAX_ATTEMPTS = 100;
const ANCHOR_SCROLL_RETRY_MS = 100;
const ANCHOR_SCROLL_FOLLOW_UP_ATTEMPTS = 3;
@@ -1161,6 +1193,161 @@ const TiptapEditorChrome: FC<TiptapEditorChromeProps> = ({
};
}, [provider.document, flashStateRef, wrapperRef]);
+ // Position-accurate agent-insert flash + follow-the-write scroll. The block
+ // flash above is the ambient "an agent wrote here" signal; this decorates the
+ // ACTUAL changed range and, when following, brings it into view — the "watch
+ // the agent edit this document" moment.
+ //
+ // A single agent write is one atomic transaction, so there is one chance to
+ // catch it — and follow mode races navigation against that write. Two entry
+ // points cover both orderings:
+ // - LIVE: the write lands as a remote y-sync transaction while this doc is
+ // already the active, mounted editor. Diff before→after for the exact range.
+ // - ACTIVATION REPLAY: follow mode navigates here AFTER the write already
+ // applied (the editor mounts to already-final content, or was a hidden pool
+ // editor when the write landed), so there is no before→after transaction.
+ // The server stamped the changed block range on the `agent-flash` entry;
+ // map it to a PM range against the settled doc.
+ //
+ // Shared gates: an agent write is signalled by a fresh `agent-flash` entry —
+ // human co-editing drops none, so it never flashes. Only the active editor
+ // flashes (hidden pool editors still receive updates but must not decorate).
+ // Scroll additionally requires the follow pref, a visible tab, and an
+ // unfocused editor (never yank the viewport out from under a cursor). The two
+ // paths dedupe on the entry key so a write caught live isn't replayed on a
+ // later re-activation.
+ const lastAgentFlashKeyRef = useRef<string | null>(null);
+ useEffect(() => {
+ const plugin = createAgentInsertFlashPlugin();
+ const activityMap = provider.document.getMap('agent-flash');
+ let sweepTimeout: number | null = null;
+ let disposed = false;
+ // Defer registration out of React's synchronous commit phase. registerPlugin
+ // reconfigures the editor state, which re-mounts TipTap's React node views via
+ // ReactRenderer (which calls flushSync). When this passive effect runs during
+ // a React `<Activity>` reveal — reconnectPassiveEffects fires passive effects
+ // inside the commit — that flushSync lands "inside a lifecycle method" and
+ // React rejects it (console error + dropped flush). A microtask runs after the
+ // commit unwinds; the rAF-driven activation replay below fires a frame later,
+ // so it still observes the registered plugin.
+ queueMicrotask(() => {
+ if (disposed || editor.isDestroyed) return;
+ editor.registerPlugin(plugin);
+ });
+ const followUpTimers: number[] = [];
+ // `view` is a throwing proxy pre-mount; `editorView` is the non-throwing
+ // private ref (same cast as editor-cache.ts's getTiptapEditorView).
+ const liveView = (): PMEditorView | null =>
+ (editor as unknown as { editorView?: PMEditorView }).editorView ?? null;
+
+ // Flash the changed PM range and, when following, scroll it into view.
+ // Re-asserts the scroll a few times because an agent write settles over
+ // several frames — the scroll container keeps growing as appended blocks lay
+ // out (fonts, wraps, embeds), so a single scroll targets a pre-growth
+ // position and lands short. The midpoint centers the new section itself.
+ const flashAndScroll = (view: PMEditorView, from: number, to: number): void => {
+ view.dispatch(
+ view.state.tr.setMeta(agentInsertFlashKey, { add: { from, to }, now: Date.now() }),
+ );
+ if (sweepTimeout !== null) clearTimeout(sweepTimeout);
+ sweepTimeout = window.setTimeout(() => {
+ sweepTimeout = null;
+ const sweepView = liveView();
+ if (sweepView == null) return;
+ sweepView.dispatch(
+ sweepView.state.tr.setMeta(agentInsertFlashKey, { now: Date.now(), sweep: true }),
+ );
+ }, AGENT_INSERT_FLASH_MS + 50);
+
+ if (!loadFollowFilePref()) return;
+ if (document.visibilityState !== 'visible') return;
+ if (view.hasFocus()) return;
+ const scrollToChange = (): void => {
+ const sv = liveView();
+ if (sv == null || sv.hasFocus() || document.visibilityState !== 'visible') return;
+ try {
+ const docSize = sv.state.doc.content.size;
+ const pos = Math.max(0, Math.min(Math.floor((from + to) / 2), docSize - 1));
+ const domRef = sv.domAtPos(pos);
+ // domAtPos returns a text node (→ its block is the parent) or, at a
+ // block boundary, the container element with `offset` = the child
+ // index (→ that child is the block).
+ const node = domRef.node;
+ const raw =
+ node.nodeType === Node.TEXT_NODE
+ ? node.parentElement
+ : (node.childNodes[domRef.offset] ?? node);
+ const el = raw instanceof HTMLElement ? raw : (raw?.parentElement ?? null);
+ if (el == null) return;
+ const rect = el.getBoundingClientRect();
+ if (rect.top >= 0 && rect.bottom <= window.innerHeight) return;
+ el.scrollIntoView({ block: 'center', behavior: 'smooth' });
+ } catch {
+ // domAtPos on a just-replaced doc edge — skip, keep the flash.
+ }
+ };
+ requestAnimationFrame(scrollToChange);
+ followUpTimers.push(
+ window.setTimeout(scrollToChange, 250),
+ window.setTimeout(scrollToChange, 550),
+ );
+ };
+
+ const onTransaction = ({ transaction }: { transaction: PMTransaction }) => {
+ if (!transaction.docChanged) return;
+ const syncMeta = transaction.getMeta(ySyncPluginKey) as
+ | { isChangeOrigin?: boolean }
+ | undefined;
+ if (syncMeta?.isChangeOrigin !== true) return;
+ if (!hasNewEntries(activityMap, Date.now() - AGENT_INSERT_FLASH_MS)) return;
+ if (docName !== activeDocName) return;
+ const fresh = freshestFlashEntry(activityMap, Date.now() - AGENT_INSERT_FLASH_MS);
+ if (fresh !== null && fresh.key === lastAgentFlashKeyRef.current) return;
+ // Diff the doc before/after this transaction so a whole-body `replace`
+ // (every agent write) collapses to just the bytes that changed.
+ const range = computeChangedRange(transaction.before, transaction.doc);
+ if (range === null) return;
+ const view = liveView();
+ if (view == null) return;
+ if (fresh !== null) lastAgentFlashKeyRef.current = fresh.key;
+ flashAndScroll(view, range.from, range.to);
+ };
+ editor.on('transaction', onTransaction);
+
+ // Replay from the server-stamped block range when this doc is (or becomes)
+ // active after a write already applied. Runs a frame later so the PM doc +
+ // layout have settled; on `synced` too, for a fresh mount whose write
+ // predates the initial sync.
+ const replayFromEntry = (): void => {
+ if (disposed || docName !== activeDocName) return;
+ const view = liveView();
+ if (view == null) return;
+ const fresh = freshestFlashEntry(activityMap, Date.now() - AGENT_INSERT_FLASH_ACTIVATION_MS);
+ if (fresh === null || fresh.key === lastAgentFlashKeyRef.current) return;
+ const blocks = fresh.entry.changedBlocks;
+ if (blocks === undefined) return;
+ const range = blockRangeToPositions(view.state.doc, blocks.from, blocks.to);
+ if (range === null) return;
+ lastAgentFlashKeyRef.current = fresh.key;
+ flashAndScroll(view, range.from, range.to);
+ };
+ const activationRaf = requestAnimationFrame(replayFromEntry);
+ const onSynced = (): void => {
+ requestAnimationFrame(replayFromEntry);
+ };
+ provider.on('synced', onSynced);
+
+ return () => {
+ disposed = true;
+ editor.off('transaction', onTransaction);
+ provider.off('synced', onSynced);
+ cancelAnimationFrame(activationRaf);
+ if (sweepTimeout !== null) clearTimeout(sweepTimeout);
+ for (const timer of followUpTimers) clearTimeout(timer);
+ editor.unregisterPlugin(agentInsertFlashKey);
+ };
+ }, [editor, provider.document, docName, activeDocName, provider.on, provider.off]);
+
// Scroll to an anchor target after navigating from a wiki link, Mirror
// "Open source" chrome link, or other `#/<doc>#<slug>` deep-link.
// Fires on initial editor mount AND on every `hashchange` — the latter
diff --git a/packages/app/src/editor/plugins/agent-insert-flash.test.ts b/packages/app/src/editor/plugins/agent-insert-flash.test.ts
new file mode 100644
index 000000000..dc0590538
--- /dev/null
+++ b/packages/app/src/editor/plugins/agent-insert-flash.test.ts
@@ -0,0 +1,139 @@
+import { Schema } from '@tiptap/pm/model';
+import { EditorState } from '@tiptap/pm/state';
+import { describe, expect, test } from 'vitest';
+import {
+ AGENT_INSERT_FLASH_MS,
+ agentInsertFlashKey,
+ blockRangeToPositions,
+ computeChangedRange,
+ createAgentInsertFlashPlugin,
+} from './agent-insert-flash';
+
+const schema = new Schema({
+ nodes: {
+ doc: { content: 'paragraph+' },
+ paragraph: { content: 'text*', toDOM: () => ['p', 0] },
+ text: {},
+ },
+});
+
+const para = (text: string) => schema.node('paragraph', null, text ? [schema.text(text)] : []);
+const doc = (...texts: string[]) => schema.node('doc', null, texts.map(para));
+
+function makeState() {
+ return EditorState.create({
+ schema,
+ doc: doc('alpha', 'omega'),
+ plugins: [createAgentInsertFlashPlugin()],
+ });
+}
+
+describe('computeChangedRange', () => {
+ test('identical docs → null', () => {
+ expect(computeChangedRange(doc('alpha', 'omega'), doc('alpha', 'omega'))).toBeNull();
+ });
+
+ test('an appended paragraph is the only changed range (not the whole doc)', () => {
+ const before = doc('alpha', 'omega');
+ const after = doc('alpha', 'omega', 'appended');
+ const range = computeChangedRange(before, after);
+ // The change must start at the END of the shared prefix, not at 0 — this
+ // is the whole point (a full-body replace must not report the whole doc).
+ expect(range).not.toBeNull();
+ expect(range?.from).toBeGreaterThanOrEqual(before.content.size - 1);
+ expect(range?.to).toBeGreaterThan(range?.from ?? 0);
+ expect(range?.to).toBeLessThanOrEqual(after.content.size);
+ });
+
+ test('an edited middle paragraph is bounded to that paragraph', () => {
+ const before = doc('alpha', 'middle', 'omega');
+ const after = doc('alpha', 'MIDDLE-edited', 'omega');
+ const range = computeChangedRange(before, after);
+ expect(range).not.toBeNull();
+ // Prefix "alpha" (7) is shared; suffix "omega" is shared. The range sits
+ // strictly inside, not spanning the whole doc.
+ expect(range?.from).toBeGreaterThan(0);
+ expect(range?.to).toBeLessThan(after.content.size);
+ });
+
+ test('a prepended paragraph starts at the top', () => {
+ const range = computeChangedRange(doc('omega'), doc('alpha', 'omega'));
+ // Near the very top (position 1 is inside the first paragraph, where the
+ // text first diverges) — not deep in the document.
+ expect(range?.from).toBeLessThanOrEqual(1);
+ });
+
+ test('pure deletion yields no positive range', () => {
+ const range = computeChangedRange(doc('alpha', 'omega'), doc('alpha'));
+ // Everything after "alpha" was removed — nothing to highlight in the new doc.
+ expect(range === null || range.to <= range.from).toBe(true);
+ });
+});
+
+describe('blockRangeToPositions', () => {
+ // paragraphs: 'alpha'(nodeSize 7) 'omega'(7) 'appended'(10); content.size 24.
+ test('maps an appended block index to its tail PM range', () => {
+ const range = blockRangeToPositions(doc('alpha', 'omega', 'appended'), 2, 3);
+ expect(range).toEqual({ from: 14, to: 24 });
+ });
+
+ test('maps the first block from the top', () => {
+ expect(blockRangeToPositions(doc('alpha', 'omega'), 0, 1)).toEqual({ from: 0, to: 7 });
+ });
+
+ test('spans multiple blocks', () => {
+ expect(blockRangeToPositions(doc('alpha', 'omega', 'appended'), 0, 2)).toEqual({
+ from: 0,
+ to: 14,
+ });
+ });
+
+ test('empty range → null', () => {
+ expect(blockRangeToPositions(doc('alpha'), 1, 1)).toBeNull();
+ });
+
+ test('out-of-bounds `to` clamps to the tail; fully-past range → null', () => {
+ // The doc shrank since the server stamped the range — clamp, do not throw.
+ expect(blockRangeToPositions(doc('alpha', 'omega'), 1, 9)).toEqual({ from: 7, to: 14 });
+ expect(blockRangeToPositions(doc('alpha', 'omega'), 5, 9)).toBeNull();
+ });
+});
+
+describe('agent-insert-flash plugin', () => {
+ test('add meta decorates; sweep removes only expired decorations', () => {
+ let state = makeState();
+ const t0 = 1_000_000;
+
+ state = state.apply(
+ state.tr.setMeta(agentInsertFlashKey, { add: { from: 1, to: 6 }, now: t0 }),
+ );
+ expect(agentInsertFlashKey.getState(state)?.find()).toHaveLength(1);
+
+ const t1 = t0 + AGENT_INSERT_FLASH_MS / 2;
+ state = state.apply(
+ state.tr.setMeta(agentInsertFlashKey, { add: { from: 8, to: 13 }, now: t1 }),
+ );
+ expect(agentInsertFlashKey.getState(state)?.find()).toHaveLength(2);
+
+ const t2 = t0 + AGENT_INSERT_FLASH_MS + 1;
+ state = state.apply(state.tr.setMeta(agentInsertFlashKey, { now: t2, sweep: true }));
+ const remaining = agentInsertFlashKey.getState(state)?.find() ?? [];
+ expect(remaining).toHaveLength(1);
+ expect(remaining[0]?.from).toBe(8);
+
+ const t3 = t1 + AGENT_INSERT_FLASH_MS + 1;
+ state = state.apply(state.tr.setMeta(agentInsertFlashKey, { now: t3, sweep: true }));
+ expect(agentInsertFlashKey.getState(state)?.find()).toHaveLength(0);
+ });
+
+ test('decorations map through unrelated document changes', () => {
+ let state = makeState();
+ state = state.apply(
+ state.tr.setMeta(agentInsertFlashKey, { add: { from: 8, to: 13 }, now: 1 }),
+ );
+ state = state.apply(state.tr.insertText('shift', 2));
+ const decos = agentInsertFlashKey.getState(state)?.find() ?? [];
+ expect(decos).toHaveLength(1);
+ expect(decos[0]?.from).toBe(13);
+ });
+});
diff --git a/packages/app/src/editor/plugins/agent-insert-flash.ts b/packages/app/src/editor/plugins/agent-insert-flash.ts
new file mode 100644
index 000000000..3440231c5
--- /dev/null
+++ b/packages/app/src/editor/plugins/agent-insert-flash.ts
@@ -0,0 +1,142 @@
+/**
+ * Agent-insert flash — position-accurate highlight of the ranges an agent
+ * write just changed, the "the agent is editing this document" moment for
+ * follow mode.
+ *
+ * The ambient block flash (`data-agent-flash-state`, first/last-3-blocks
+ * CSS) stays as the coarse signal; this plugin decorates the ACTUAL changed
+ * ranges of the remote transaction with `.ok-agent-insert-flash`, whose CSS
+ * animation is a short highlight sweep. Decorations are timestamped and
+ * swept after `AGENT_INSERT_FLASH_MS`, so overlapping writes each get their
+ * own full animation without an early global clear.
+ *
+ * Pure ProseMirror — the TipTap wiring (which transactions count as agent
+ * writes, the follow-mode scroll) lives in `TiptapEditor.tsx`.
+ */
+
+import type { Node as PMNode } from '@tiptap/pm/model';
+import { Plugin, PluginKey } from '@tiptap/pm/state';
+import { Decoration, DecorationSet } from '@tiptap/pm/view';
+
+export const AGENT_INSERT_FLASH_MS = 1_400;
+
+export const agentInsertFlashKey = new PluginKey<DecorationSet>('okAgentInsertFlash');
+
+interface AgentInsertFlashMeta {
+ /** Range (final-doc coordinates) to decorate, stamped with `now`. */
+ add?: { from: number; to: number };
+ /** Wall-clock of the add / sweep — injectable for tests. */
+ now: number;
+ /** Drop decorations older than `AGENT_INSERT_FLASH_MS` as of `now`. */
+ sweep?: boolean;
+}
+
+interface FlashSpec {
+ addedAt: number;
+}
+
+/**
+ * The single region that actually changed between two document states, in
+ * new-document coordinates, or null when they are identical.
+ *
+ * Uses ProseMirror's structural `findDiffStart` / `findDiffEnd` rather than
+ * the transaction's step ranges. This is what makes the flash precise for
+ * agent writes: an agent `replace` rewrites the whole raw body, so the
+ * resulting transaction reports a single whole-document step (`0..end`) even
+ * when only a tail section was appended — the step range would flash and
+ * scroll the entire doc. The prefix/suffix diff collapses that to just the
+ * bytes that differ (the appended section, the edited paragraph), so follow
+ * mode scrolls to where the agent is actually writing.
+ */
+export function computeChangedRange(
+ before: PMNode,
+ after: PMNode,
+): { from: number; to: number } | null {
+ const start = before.content.findDiffStart(after.content);
+ if (start === null || start === undefined) return null;
+ const ends = before.content.findDiffEnd(after.content);
+ // `ends.b` is the last-differing boundary in the AFTER doc. Clamp so a
+ // suffix shorter than the prefix (heavy deletion) still yields from <= to.
+ const afterSize = after.content.size;
+ const from = Math.max(0, Math.min(start, afterSize));
+ const to = Math.max(from, Math.min(ends?.b ?? afterSize, afterSize));
+ if (to <= from) return null;
+ return { from, to };
+}
+
+/**
+ * Freshness window for the activation replay (follow mode). When an editor
+ * becomes the active doc — or first mounts and syncs — AFTER an agent write
+ * already landed, there is no before→after transaction to drive the live
+ * flash. If the accompanying `agent-flash` entry is younger than this, we
+ * replay the flash + scroll from the entry's `changedBlocks` range. Wider than
+ * `AGENT_INSERT_FLASH_MS` to absorb follow-navigation lag, but short enough
+ * that clicking into a doc the agent touched a while ago doesn't re-flash it.
+ */
+export const AGENT_INSERT_FLASH_ACTIVATION_MS = 6_000;
+
+/**
+ * Map a top-level block-index range `[fromBlock, toBlock)` to a ProseMirror
+ * position range in `doc`, or null when empty / out of bounds.
+ *
+ * The activation-replay counterpart to `computeChangedRange`: the write has
+ * already applied, so there is no transaction to diff — the server stamped the
+ * changed block indices instead. They address PM top-level nodes directly
+ * (y-prosemirror mirrors the XmlFragment's children onto the PM doc), so the
+ * PM range is the span from the boundary before the first changed block to the
+ * boundary after the last.
+ */
+export function blockRangeToPositions(
+ doc: PMNode,
+ fromBlock: number,
+ toBlock: number,
+): { from: number; to: number } | null {
+ const childCount = doc.childCount;
+ const first = Math.max(0, Math.min(fromBlock, childCount));
+ const last = Math.max(first, Math.min(toBlock, childCount));
+ if (last <= first) return null;
+ let pos = 0;
+ for (let i = 0; i < first; i++) pos += doc.child(i).nodeSize;
+ const from = pos;
+ for (let i = first; i < last; i++) pos += doc.child(i).nodeSize;
+ const to = pos;
+ const size = doc.content.size;
+ const clampedFrom = Math.max(0, Math.min(from, size));
+ const clampedTo = Math.max(clampedFrom, Math.min(to, size));
+ if (clampedTo <= clampedFrom) return null;
+ return { from: clampedFrom, to: clampedTo };
+}
+
+export function createAgentInsertFlashPlugin(): Plugin<DecorationSet> {
+ return new Plugin<DecorationSet>({
+ key: agentInsertFlashKey,
+ state: {
+ init: () => DecorationSet.empty,
+ apply(tr, decorations) {
+ let next = decorations.map(tr.mapping, tr.doc);
+ const meta = tr.getMeta(agentInsertFlashKey) as AgentInsertFlashMeta | undefined;
+ if (meta === undefined) return next;
+ if (meta.sweep === true) {
+ const expired = next
+ .find()
+ .filter(
+ (deco) => meta.now - ((deco.spec as FlashSpec).addedAt ?? 0) >= AGENT_INSERT_FLASH_MS,
+ );
+ if (expired.length > 0) next = next.remove(expired);
+ }
+ if (meta.add !== undefined && meta.add.to > meta.add.from) {
+ const spec: FlashSpec = { addedAt: meta.now };
+ next = next.add(tr.doc, [
+ Decoration.inline(meta.add.from, meta.add.to, { class: 'ok-agent-insert-flash' }, spec),
+ ]);
+ }
+ return next;
+ },
+ },
+ props: {
+ decorations(state) {
+ return agentInsertFlashKey.getState(state);
+ },
+ },
+ });
+}
diff --git a/packages/app/src/globals.css b/packages/app/src/globals.css
index 7e771fb6c..77012fa76 100644
--- a/packages/app/src/globals.css
+++ b/packages/app/src/globals.css
@@ -112,6 +112,14 @@
*/
@source "./**/*.{tsx,ts,jsx,js}";
+/*
+ * Streamdown (ACP thread markdown) ships its utility classes inside its
+ * prebuilt dist chunks, which no auto-detected source root covers — without
+ * this line its blocks render unstyled. Glob (not index.js) because the
+ * class strings live in the hashed chunk files, not the entry.
+ */
+@source "../../../node_modules/streamdown/dist/*.js";
+
/*
* index.html is the only place the `antialiased` body class is used, and it
* sits outside the src glob above. Under packages/app's own `bun run dev` /
@@ -212,6 +220,25 @@
}
}
+ /* Agent insert flash — position-accurate highlight on the exact ranges an
+ agent write changed (.ok-agent-insert-flash inline decorations from the
+ agent-insert-flash PM plugin). Background/box-shadow only — no layout,
+ so it stays cheap on large writes. */
+ @keyframes agent-insert-flash {
+ 0% {
+ background: rgba(217, 119, 87, 0.3);
+ box-shadow: 0 0 0 2px rgba(217, 119, 87, 0.12);
+ }
+ 55% {
+ background: rgba(217, 119, 87, 0.14);
+ box-shadow: 0 0 0 0 transparent;
+ }
+ 100% {
+ background: transparent;
+ box-shadow: 0 0 0 0 transparent;
+ }
+ }
+
/* Agent badge breathing — subtle pulse when agent is editing */
@keyframes agent-breathing {
0%,
@@ -240,6 +267,7 @@
}
--animate-agent-flash: agent-flash 2s var(--ease-out-strong) forwards;
+ --animate-agent-insert-flash: agent-insert-flash 1.4s var(--ease-out-strong) forwards;
--animate-agent-breathing: agent-breathing 2.4s ease-in-out infinite;
--animate-undo-ready: undo-ready 600ms var(--ease-out-strong) forwards;
@@ -365,6 +393,48 @@
}
}
+/* Text shimmer: a light band sweeps through the text via a clipped gradient,
+ used on the agent-thread "starting/installing/connecting" status line so the
+ wait reads as working. Text-only (relies on `background-clip: text`), so it
+ has no effect on non-text (SVG/icon) elements. Registered as a real Tailwind
+ utility (not a plain class) so state variants can also drive it. */
+@utility shimmer {
+ background: linear-gradient(
+ 90deg,
+ var(--muted-foreground) 25%,
+ var(--foreground) 50%,
+ var(--muted-foreground) 75%
+ );
+ background-size: 200% 100%;
+ -webkit-background-clip: text;
+ background-clip: text;
+ -webkit-text-fill-color: transparent;
+ color: transparent;
+ animation: shimmer 1.5s linear infinite;
+}
+
+@keyframes shimmer {
+ from {
+ background-position: 200% 0;
+ }
+ to {
+ background-position: -200% 0;
+ }
+}
+
+/* Pin the shimmer static for reduced-motion users. Stopping the animation
+ alone leaves `background-clip: text` + transparent fill, which freezes a
+ gradient band across the text; reset both so it renders as plain
+ muted-foreground. */
+@media (prefers-reduced-motion: reduce) {
+ .shimmer {
+ animation: none;
+ background: none;
+ -webkit-text-fill-color: var(--muted-foreground);
+ color: var(--muted-foreground);
+ }
+}
+
/* Reduced-motion override — keep the opacity crossfade as a comprehension
aid (the panel still appears/disappears) but pin the height so the
layout-triggering animation doesn't fire. Matches the rest of this
@@ -422,6 +492,23 @@
Staggered entry (30ms per block) via animation-delay for a cascading feel on multi-block writes. */
+/* Position-accurate agent-insert flash — inline decoration class applied by
+ the agent-insert-flash PM plugin to the exact ranges a remote agent write
+ changed. `box-decoration-break: clone` keeps wrapped lines individually
+ rounded; duration matches AGENT_INSERT_FLASH_MS in agent-insert-flash.ts. */
+.ok-agent-insert-flash {
+ animation: agent-insert-flash 1.4s var(--ease-out-strong) forwards;
+ border-radius: 3px;
+ box-decoration-break: clone;
+ -webkit-box-decoration-break: clone;
+}
+
+@media (prefers-reduced-motion: reduce) {
+ .ok-agent-insert-flash {
+ animation-duration: 1ms;
+ }
+}
+
[data-agent-flash-state="editing"][data-agent-flash-position="append"]
.ProseMirror
> *:nth-last-child(-n + 3),
diff --git a/packages/app/src/hooks/use-installed-clis.ts b/packages/app/src/hooks/use-installed-clis.ts
index 221656224..a24cc9644 100644
--- a/packages/app/src/hooks/use-installed-clis.ts
+++ b/packages/app/src/hooks/use-installed-clis.ts
@@ -10,7 +10,7 @@ import { useEffect, useState } from 'react';
* Starts empty (unknown, not "none installed") until the async probe resolves.
* A partial/older bridge, the web host with no `terminal` surface, or a probe
* failure leaves keys `undefined` (unknown). Consumers must NOT read unknown as
- * "absent": `resolveDefaultCli` treats it optimistically, and `visibleTerminalClis`
+ * "absent": `resolveDefaultCli` treats it optimistically, and `isTerminalCliEnabled`
* fails open (an unknown CLI still renders), so a probe miss never silently drops
* an installed CLI from the launch surfaces for the whole session.
*
diff --git a/packages/app/src/lib/acp/agent-visibility.test.ts b/packages/app/src/lib/acp/agent-visibility.test.ts
new file mode 100644
index 000000000..872ccec1b
--- /dev/null
+++ b/packages/app/src/lib/acp/agent-visibility.test.ts
@@ -0,0 +1,75 @@
+import { describe, expect, test } from 'vitest';
+
+import {
+ isDesktopTargetEnabled,
+ isInAppAgentEnabled,
+ isTerminalCliEnabled,
+} from './agent-visibility';
+import { desktopEnabledKey, inAppEnabledKey, terminalEnabledKey } from './enabled-agents';
+
+describe('agent-visibility — in-app', () => {
+ test('defaults to registered; override wins either way', () => {
+ // No override: enabled iff registered. `supported: true` throughout.
+ expect(isInAppAgentEnabled({}, 'registry', 'claude', true, true)).toBe(true);
+ expect(isInAppAgentEnabled({}, 'registry', 'claude', false, true)).toBe(false);
+ // Override false hides even a registered agent; override true shows an
+ // unregistered one.
+ const key = inAppEnabledKey('registry', 'claude');
+ expect(isInAppAgentEnabled({ [key]: false }, 'registry', 'claude', true, true)).toBe(false);
+ expect(isInAppAgentEnabled({ [key]: true }, 'registry', 'claude', false, true)).toBe(true);
+ });
+
+ test('supported: undefined fails open (catalog not yet hydrated)', () => {
+ expect(isInAppAgentEnabled({}, 'registry', 'claude', true, undefined)).toBe(true);
+ });
+
+ test('supported: false force-hides regardless of override or registration', () => {
+ const key = inAppEnabledKey('registry', 'cursor');
+ // Registered → still hidden when unsupported.
+ expect(isInAppAgentEnabled({}, 'registry', 'cursor', true, false)).toBe(false);
+ // Even an explicit enable override cannot turn on an unsupported agent, so
+ // the menus and the Settings toggle can never disagree.
+ expect(isInAppAgentEnabled({ [key]: true }, 'registry', 'cursor', true, false)).toBe(false);
+ });
+});
+
+describe('agent-visibility — terminal (fail-open default)', () => {
+ test('Claude is not special-cased: hidden when the probe reports it absent', () => {
+ // Unknown (undefined) → shown (fail-open); positively absent → hidden, same
+ // as every other CLI. Claude no longer overrides install detection.
+ expect(isTerminalCliEnabled({}, 'claude', {})).toBe(true);
+ expect(isTerminalCliEnabled({}, 'claude', { claude: true })).toBe(true);
+ expect(isTerminalCliEnabled({}, 'claude', { claude: false })).toBe(false);
+ });
+
+ test('other CLIs default enabled unless positively absent', () => {
+ // Unknown (undefined) → shown (fail-open); positively absent → hidden.
+ expect(isTerminalCliEnabled({}, 'codex', {})).toBe(true);
+ expect(isTerminalCliEnabled({}, 'codex', { codex: true })).toBe(true);
+ expect(isTerminalCliEnabled({}, 'codex', { codex: false })).toBe(false);
+ });
+
+ test('override wins over the fail-open default', () => {
+ const key = terminalEnabledKey('codex');
+ // Enable a positively-absent CLI; disable an otherwise-visible one.
+ expect(isTerminalCliEnabled({ [key]: true }, 'codex', { codex: false })).toBe(true);
+ expect(isTerminalCliEnabled({ [key]: false }, 'codex', { codex: true })).toBe(false);
+ // Even Claude can be turned off explicitly.
+ expect(isTerminalCliEnabled({ [terminalEnabledKey('claude')]: false }, 'claude', {})).toBe(
+ false,
+ );
+ });
+});
+
+describe('agent-visibility — desktop (off by default)', () => {
+ test('defaults to off regardless of install detection (opt-in)', () => {
+ expect(isDesktopTargetEnabled({}, 'claude-code')).toBe(false);
+ expect(isDesktopTargetEnabled({}, 'codex')).toBe(false);
+ });
+
+ test('override wins — an enabled target shows, disabled stays hidden', () => {
+ const key = desktopEnabledKey('cursor');
+ expect(isDesktopTargetEnabled({ [key]: true }, 'cursor')).toBe(true);
+ expect(isDesktopTargetEnabled({ [key]: false }, 'cursor')).toBe(false);
+ });
+});
diff --git a/packages/app/src/lib/acp/agent-visibility.ts b/packages/app/src/lib/acp/agent-visibility.ts
new file mode 100644
index 000000000..d134e3729
--- /dev/null
+++ b/packages/app/src/lib/acp/agent-visibility.ts
@@ -0,0 +1,70 @@
+/**
+ * Effective enabled-state per agent category — the single source of the
+ * per-category defaults, so the Settings toggle list and all three launcher
+ * dropdowns resolve visibility identically.
+ *
+ * Enablement = the user's explicit override (from `enabled-agents.ts`) when
+ * present, else the category default computed from the runtime signal the
+ * caller supplies:
+ * - In app → registered (enabling registers; nothing installs to detect)
+ * - Terminal → fail-open: shown unless positively absent on PATH
+ * (`installed[cli] === false`); an unresolved probe still shows
+ * - Desktop → off (opt-in; the user enables desktop hand-offs in Settings)
+ */
+
+import type { HandoffTarget, TerminalCli } from '@inkeep/open-knowledge-core';
+import {
+ desktopEnabledKey,
+ type EnabledOverrides,
+ inAppEnabledKey,
+ resolveEnabled,
+ terminalEnabledKey,
+} from './enabled-agents';
+
+/**
+ * In-app agent: default enabled when the user has registered it. An agent with
+ * no launchable build for this host (`supported === false`) is force-disabled —
+ * it can't be turned on in Settings and never appears in a launcher, so the
+ * Settings toggle and the menus can't disagree. `supported === undefined` means
+ * the catalog hasn't hydrated yet: fail open until we know (matches the
+ * detection-pending stance used elsewhere), converging once the catalog loads.
+ */
+export function isInAppAgentEnabled(
+ overrides: EnabledOverrides,
+ source: string,
+ id: string,
+ isRegistered: boolean,
+ supported: boolean | undefined,
+): boolean {
+ if (supported === false) return false;
+ return resolveEnabled(overrides[inAppEnabledKey(source, id)], isRegistered);
+}
+
+/**
+ * Terminal CLI: default fail-open — shown unless the PATH probe positively
+ * reports the CLI absent (`installed[cli] === false`). An unresolved probe
+ * (`undefined`, e.g. the cold-start window) still shows the row, so a probe miss
+ * never silently drops an installed CLI. Claude is not special-cased visible: a
+ * probed-absent Claude CLI hides like any other. The user can still re-enable it
+ * in Settings, and the install-nudge launch default in `resolveDefaultCli` is a
+ * separate last-resort path, not a visibility rule.
+ */
+export function isTerminalCliEnabled(
+ overrides: EnabledOverrides,
+ cli: TerminalCli,
+ installed: Partial<Record<TerminalCli, boolean>>,
+): boolean {
+ return resolveEnabled(overrides[terminalEnabledKey(cli)], installed[cli] !== false);
+}
+
+/**
+ * Desktop target: default OFF. Desktop hand-offs are opt-in — the user enables
+ * the apps they want in Settings → Configure agents. Install detection only
+ * drives the "Not installed" hint in Settings, not the default.
+ */
+export function isDesktopTargetEnabled(
+ overrides: EnabledOverrides,
+ targetId: HandoffTarget,
+): boolean {
+ return resolveEnabled(overrides[desktopEnabledKey(targetId)], false);
+}
diff --git a/packages/app/src/lib/acp/catalog.dom.test.tsx b/packages/app/src/lib/acp/catalog.dom.test.tsx
new file mode 100644
index 000000000..c2b519020
--- /dev/null
+++ b/packages/app/src/lib/acp/catalog.dom.test.tsx
@@ -0,0 +1,78 @@
+/**
+ * useHydrateRegisteredAgentMeta fills a seeded agent's placeholder name/icon
+ * from the registry catalog on mount. This is what runs at app startup (mounted
+ * in main.tsx) so the launcher menus show real brand icons without the user ever
+ * opening Configure agents.
+ */
+
+import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
+import { cleanup, render, waitFor } from '@testing-library/react';
+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
+import type { AgentCatalog } from './catalog';
+import { useHydrateRegisteredAgentMeta } from './catalog';
+import {
+ getDefaultRegisteredAgent,
+ registerAgent,
+ reloadRegisteredAgentsFromStorage,
+} from './registered-agents';
+
+const backing = new Map<string, string>();
+if (typeof globalThis.localStorage === 'undefined') {
+ (globalThis as { localStorage?: unknown }).localStorage = {
+ getItem: (key: string) => backing.get(key) ?? null,
+ setItem: (key: string, value: string) => void backing.set(key, value),
+ removeItem: (key: string) => void backing.delete(key),
+ clear: () => backing.clear(),
+ };
+}
+
+const catalog: AgentCatalog = {
+ agents: [
+ {
+ id: 'claude-acp',
+ name: 'Claude',
+ version: '1',
+ source: 'registry',
+ supported: true,
+ featured: true,
+ iconUrl: 'https://registry.example/claude.svg',
+ },
+ ],
+ stale: false,
+ maxThreads: 8,
+};
+
+function Harness() {
+ useHydrateRegisteredAgentMeta();
+ return null;
+}
+
+beforeEach(() => {
+ localStorage.clear();
+ reloadRegisteredAgentsFromStorage();
+ globalThis.fetch = vi.fn(async () => ({
+ ok: true,
+ json: async () => catalog,
+ })) as unknown as typeof fetch;
+});
+
+afterEach(() => cleanup());
+
+describe('useHydrateRegisteredAgentMeta', () => {
+ test('fills a seeded agent brand icon from the catalog on mount', async () => {
+ // A freshly registered agent ships id + name only, no icon.
+ registerAgent({ source: 'registry', id: 'claude-acp', name: 'Claude' });
+ expect(getDefaultRegisteredAgent()?.iconUrl).toBeUndefined();
+
+ const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });
+ render(
+ <QueryClientProvider client={client}>
+ <Harness />
+ </QueryClientProvider>,
+ );
+
+ await waitFor(() =>
+ expect(getDefaultRegisteredAgent()?.iconUrl).toBe('https://registry.example/claude.svg'),
+ );
+ });
+});
diff --git a/packages/app/src/lib/acp/catalog.test.ts b/packages/app/src/lib/acp/catalog.test.ts
new file mode 100644
index 000000000..ef874bf4c
--- /dev/null
+++ b/packages/app/src/lib/acp/catalog.test.ts
@@ -0,0 +1,31 @@
+import { describe, expect, test } from 'vitest';
+import { type CatalogAgent, detectedHarnessAgents } from './catalog';
+
+function agent(
+ id: string,
+ availability: 'present' | 'not-found' | 'unknown',
+ supported = true,
+): CatalogAgent {
+ return {
+ id,
+ name: id,
+ version: '1',
+ source: 'registry',
+ supported,
+ featured: true,
+ harness: { cli: id === 'cursor' ? 'cursor' : 'claude', availability },
+ };
+}
+
+describe('detectedHarnessAgents', () => {
+ test('returns supported, present harnesses in default priority order', () => {
+ expect(
+ detectedHarnessAgents([
+ agent('cursor', 'present'),
+ agent('claude-acp', 'present'),
+ agent('codex-acp', 'not-found'),
+ agent('opencode', 'present', false),
+ ]).map((entry) => entry.id),
+ ).toEqual(['claude-acp', 'cursor']);
+ });
+});
diff --git a/packages/app/src/lib/acp/catalog.ts b/packages/app/src/lib/acp/catalog.ts
new file mode 100644
index 000000000..75318b89a
--- /dev/null
+++ b/packages/app/src/lib/acp/catalog.ts
@@ -0,0 +1,96 @@
+/**
+ * Fetch the ACP agent catalog from the server (`GET /api/acp/catalog`) — the
+ * registry-driven list the launch UI renders. The server owns the CDN fetch +
+ * offline cache; the client just consumes the resolved rows.
+ */
+
+import { useQuery } from '@tanstack/react-query';
+import { useEffect } from 'react';
+import { hydrateRegisteredAgentMeta } from './registered-agents';
+
+export interface CatalogAgent {
+ id: string;
+ name: string;
+ version: string;
+ description?: string;
+ license?: string;
+ iconUrl?: string;
+ website?: string;
+ source: 'registry' | 'custom';
+ /** A launchable distribution exists for this host platform. */
+ supported: boolean;
+ featured: boolean;
+ harness?: {
+ cli: 'claude' | 'codex' | 'cursor' | 'opencode' | 'pi';
+ availability: 'present' | 'not-found' | 'unknown';
+ };
+}
+
+/** Registry agents whose corresponding first-party CLI is on the server host. */
+export function detectedHarnessAgents(agents: readonly CatalogAgent[]): CatalogAgent[] {
+ const priority = ['claude-acp', 'codex-acp', 'cursor', 'opencode'];
+ // `indexOf` returns -1 for an id not in the priority list; map that to the end
+ // so an unranked agent sorts AFTER the known first-party ones, not before them.
+ const rank = (id: string): number => {
+ const i = priority.indexOf(id);
+ return i === -1 ? priority.length : i;
+ };
+ return agents
+ .filter((agent) => agent.supported && agent.harness?.availability === 'present')
+ .sort((a, b) => rank(a.id) - rank(b.id));
+}
+
+export interface AgentCatalog {
+ agents: CatalogAgent[];
+ /** True when the server served its offline fallback cache. */
+ stale: boolean;
+ maxThreads: number;
+}
+
+export async function fetchAgentCatalog(signal?: AbortSignal): Promise<AgentCatalog> {
+ const res = await fetch('/api/acp/catalog', {
+ signal: signal ?? AbortSignal.timeout(20_000),
+ });
+ if (!res.ok) {
+ throw new Error(`agent catalog request failed: HTTP ${res.status}`);
+ }
+ const body = (await res.json()) as AgentCatalog;
+ return {
+ agents: Array.isArray(body.agents) ? body.agents : [],
+ stale: body.stale === true,
+ maxThreads: typeof body.maxThreads === 'number' ? body.maxThreads : 8,
+ };
+}
+
+/**
+ * Fill in registered agents' real display names + brand icons from the registry
+ * catalog. A freshly registered agent (from a launcher pick or a Configure
+ * agents toggle) ships ids + names only, so every launcher menu renders a
+ * neutral glyph until this runs.
+ *
+ * Mount once high in the app tree so hydration happens on cold start regardless
+ * of whether the user ever opens Configure agents. Shares the `['acp-catalog']`
+ * query cache with that settings tab (React Query dedups by key — no double
+ * fetch), and only patches metadata in place, never the launch default.
+ */
+export function useHydrateRegisteredAgentMeta(): void {
+ const { data } = useQuery({
+ queryKey: ['acp-catalog'],
+ queryFn: ({ signal }) => fetchAgentCatalog(signal),
+ staleTime: 5 * 60 * 1000,
+ });
+
+ const agents = data?.agents;
+ useEffect(() => {
+ if (!agents) return;
+ hydrateRegisteredAgentMeta(
+ agents.map((agent) => ({
+ source: agent.source,
+ id: agent.id,
+ name: agent.name,
+ supported: agent.supported,
+ ...(agent.iconUrl !== undefined ? { iconUrl: agent.iconUrl } : {}),
+ })),
+ );
+ }, [agents]);
+}
diff --git a/packages/app/src/lib/acp/desktop-migration.test.ts b/packages/app/src/lib/acp/desktop-migration.test.ts
new file mode 100644
index 000000000..2367fa055
--- /dev/null
+++ b/packages/app/src/lib/acp/desktop-migration.test.ts
@@ -0,0 +1,79 @@
+import type { InstallState } from '@inkeep/open-knowledge-core';
+import { beforeEach, describe, expect, test } from 'vitest';
+import { VISIBLE_TARGETS } from '@/lib/handoff/targets';
+import { desktopTargetsToMigrate, isExistingLauncherUser } from './desktop-migration';
+
+const backing = new Map<string, string>();
+if (typeof globalThis.localStorage === 'undefined') {
+ (globalThis as { localStorage?: unknown }).localStorage = {
+ getItem: (key: string) => backing.get(key) ?? null,
+ setItem: (key: string, value: string) => void backing.set(key, value),
+ removeItem: (key: string) => void backing.delete(key),
+ clear: () => backing.clear(),
+ };
+}
+
+const firstTargetId = VISIBLE_TARGETS[0].id;
+const secondTargetId = VISIBLE_TARGETS[1].id;
+
+function states(entries: Record<string, boolean | null>): Record<string, InstallState> {
+ return Object.fromEntries(
+ Object.entries(entries).map(([id, installed]) => [id, { installed } as InstallState]),
+ );
+}
+
+beforeEach(() => {
+ localStorage.clear();
+});
+
+describe('isExistingLauncherUser', () => {
+ test('false on a fresh install (no prior launcher keys)', () => {
+ expect(isExistingLauncherUser()).toBe(false);
+ });
+
+ test('true when a legacy preferred-agent pick exists', () => {
+ localStorage.setItem('ok-preferred-agent-v1', 'claude-code');
+ expect(isExistingLauncherUser()).toBe(true);
+ });
+
+ test('true when the unified sticky pick exists', () => {
+ localStorage.setItem('ok-ask-ai-agent-v2', 'codex');
+ expect(isExistingLauncherUser()).toBe(true);
+ });
+
+ test('the feature-added seed keys do NOT count as prior launcher use', () => {
+ // A brand-new user gets these written by the in-app seed; they must not
+ // trip the migration into treating a fresh install as existing.
+ localStorage.setItem('ok-acp-default-agents-seeded-v1', '1');
+ localStorage.setItem('ok-acp-registered-agents-v1', '{}');
+ expect(isExistingLauncherUser()).toBe(false);
+ });
+});
+
+describe('desktopTargetsToMigrate', () => {
+ test('null while the probe is unresolved (every entry undefined/null)', () => {
+ expect(desktopTargetsToMigrate({})).toBeNull();
+ expect(desktopTargetsToMigrate(states({ [firstTargetId]: null }))).toBeNull();
+ });
+
+ test('null while ANY target is still unresolved (waits for every probe)', () => {
+ // The migration is one-shot: committing on a partially-resolved probe would
+ // permanently skip whichever target had not landed yet.
+ const nearlyResolved = Object.fromEntries(VISIBLE_TARGETS.map((t) => [t.id, false]));
+ nearlyResolved[firstTargetId] = true;
+ delete nearlyResolved[secondTargetId]; // one probe still pending
+ expect(desktopTargetsToMigrate(states(nearlyResolved))).toBeNull();
+ });
+
+ test('returns only the installed targets once every probe resolves', () => {
+ const allResolved = Object.fromEntries(VISIBLE_TARGETS.map((t) => [t.id, false]));
+ allResolved[firstTargetId] = true;
+ const result = desktopTargetsToMigrate(states(allResolved));
+ expect(result).toEqual([firstTargetId]);
+ });
+
+ test('resolves to an empty list when nothing is installed', () => {
+ const allFalse = Object.fromEntries(VISIBLE_TARGETS.map((t) => [t.id, false]));
+ expect(desktopTargetsToMigrate(states(allFalse))).toEqual([]);
+ });
+});
diff --git a/packages/app/src/lib/acp/desktop-migration.ts b/packages/app/src/lib/acp/desktop-migration.ts
new file mode 100644
index 000000000..ec181b081
--- /dev/null
+++ b/packages/app/src/lib/acp/desktop-migration.ts
@@ -0,0 +1,99 @@
+/**
+ * One-time upgrade migration for Desktop-off-by-default.
+ *
+ * Desktop hand-offs are now opt-in (`isDesktopTargetEnabled` defaults off). Before
+ * this feature the launcher showed every INSTALLED desktop app automatically, so
+ * a user who was already launching Claude Desktop / Cursor / … would see those
+ * rows silently disappear on upgrade. This migration preserves their experience:
+ * on the first run of this version, for a user who had used the OK agent launcher
+ * before, it enables every desktop target the install probe reports installed —
+ * reproducing the pre-feature launcher. Fresh installs (no prior launcher state)
+ * are skipped, so off-by-default still holds for brand-new users.
+ *
+ * Additive only: it writes enable overrides for installed targets and never
+ * disables anything. Idempotent via a localStorage flag.
+ *
+ * Edge: a user who only ever launched a desktop app from the file-tree
+ * right-click submenu (never a composer, so no sticky/preferred pick was saved)
+ * reads as a fresh install and won't be migrated — they re-enable in Settings.
+ */
+
+import type { HandoffTarget, InstallState } from '@inkeep/open-knowledge-core';
+import { useEffect } from 'react';
+import { VISIBLE_TARGETS } from '@/lib/handoff/targets';
+import { desktopEnabledKey, setAgentEnabled } from './enabled-agents';
+
+const MIGRATION_FLAG_KEY = 'ok-acp-desktop-migration-v1';
+
+/**
+ * Launcher-pick keys that predate this feature. Their presence means this
+ * machine used the OK agent launcher before Desktop went opt-in, so its
+ * installed desktop apps should carry over. A fresh install has none of them.
+ */
+const PRIOR_LAUNCHER_KEYS: readonly string[] = [
+ 'ok-preferred-agent-v1', // create composer's last desktop pick
+ 'ok-ask-ai-agent-v2', // unified sticky pick
+ 'ok-ask-ai-default-agent-v1', // legacy bottom-composer default
+];
+
+function readKey(key: string): string | null {
+ try {
+ return localStorage.getItem(key);
+ } catch {
+ return null;
+ }
+}
+
+function markMigrated(): void {
+ try {
+ localStorage.setItem(MIGRATION_FLAG_KEY, '1');
+ } catch {
+ // Non-fatal — a probe-less session just retries next launch.
+ }
+}
+
+/** True when this machine used the OK agent launcher before this feature. */
+export function isExistingLauncherUser(): boolean {
+ return PRIOR_LAUNCHER_KEYS.some((k) => readKey(k) !== null);
+}
+
+/**
+ * The desktop targets to enable on migration: those the probe reports installed.
+ * Returns `null` until EVERY target has a definite true/false, so the caller
+ * waits rather than marking migrated prematurely. The migration is one-shot, so
+ * committing on a partially-resolved probe would permanently skip any target
+ * whose state hadn't landed yet.
+ */
+export function desktopTargetsToMigrate(
+ states: Record<string, InstallState | undefined>,
+): readonly HandoffTarget[] | null {
+ const resolved = VISIBLE_TARGETS.every((t) => states[t.id]?.installed != null);
+ if (!resolved) return null;
+ return VISIBLE_TARGETS.filter((t) => states[t.id]?.installed === true).map((t) => t.id);
+}
+
+/**
+ * Run the migration once. Mount on the desktop host with the live install
+ * `states` from `useInstalledAgents`. Self-gates on the localStorage flag and
+ * waits for the probe to resolve before acting; the effect re-runs as `states`
+ * settles.
+ */
+export function useMigrateInstalledDesktopAgentsOnce(
+ states: Record<string, InstallState | undefined>,
+): void {
+ useEffect(() => {
+ if (readKey(MIGRATION_FLAG_KEY) !== null) return;
+ // Fresh install → nothing to carry over; mark done so a brand-new user never
+ // gets desktop apps auto-enabled.
+ if (!isExistingLauncherUser()) {
+ markMigrated();
+ return;
+ }
+ const targets = desktopTargetsToMigrate(states);
+ if (targets === null) return; // probe not resolved yet — wait for the next update
+ for (const id of targets) {
+ setAgentEnabled(desktopEnabledKey(id), true);
+ }
+ markMigrated();
+ }, [states]);
+}
diff --git a/packages/app/src/lib/acp/enabled-agents.test.ts b/packages/app/src/lib/acp/enabled-agents.test.ts
new file mode 100644
index 000000000..3724eaefe
--- /dev/null
+++ b/packages/app/src/lib/acp/enabled-agents.test.ts
@@ -0,0 +1,87 @@
+import { beforeEach, describe, expect, test } from 'vitest';
+
+// Plain `bun test` has no localStorage — install a minimal stub BEFORE the
+// module under test first touches it (reads are lazy, so import order is safe).
+const backing = new Map<string, string>();
+if (typeof globalThis.localStorage === 'undefined') {
+ (globalThis as { localStorage?: unknown }).localStorage = {
+ getItem: (key: string) => backing.get(key) ?? null,
+ setItem: (key: string, value: string) => void backing.set(key, value),
+ removeItem: (key: string) => void backing.delete(key),
+ clear: () => backing.clear(),
+ };
+}
+
+import {
+ desktopEnabledKey,
+ inAppEnabledKey,
+ reloadEnabledAgentsFromStorage,
+ resolveEnabled,
+ setAgentEnabled,
+ terminalEnabledKey,
+} from './enabled-agents';
+
+const STORAGE_KEY = 'ok-acp-enabled-agents-v1';
+
+function overrides(): Record<string, boolean> {
+ return JSON.parse(localStorage.getItem(STORAGE_KEY) ?? '{}');
+}
+
+beforeEach(() => {
+ localStorage.clear();
+ reloadEnabledAgentsFromStorage();
+});
+
+describe('enabled-agents store', () => {
+ test('key builders are category-scoped and stable', () => {
+ expect(inAppEnabledKey('registry', 'claude-acp')).toBe('in-app:registry:claude-acp');
+ expect(terminalEnabledKey('codex')).toBe('terminal:codex');
+ expect(desktopEnabledKey('claude-code')).toBe('desktop:claude-code');
+ });
+
+ test('resolveEnabled: override wins over the category default', () => {
+ expect(resolveEnabled(undefined, true)).toBe(true);
+ expect(resolveEnabled(undefined, false)).toBe(false);
+ expect(resolveEnabled(true, false)).toBe(true);
+ expect(resolveEnabled(false, true)).toBe(false);
+ });
+
+ test('setAgentEnabled persists an explicit override', () => {
+ const key = desktopEnabledKey('cursor');
+ setAgentEnabled(key, false);
+ expect(overrides()).toEqual({ [key]: false });
+ setAgentEnabled(key, true);
+ expect(overrides()).toEqual({ [key]: true });
+ });
+
+ test('clearing an override (undefined) reverts to the category default', () => {
+ const key = terminalEnabledKey('claude');
+ setAgentEnabled(key, false);
+ expect(overrides()).toEqual({ [key]: false });
+ setAgentEnabled(key, undefined);
+ expect(overrides()).toEqual({});
+ // With no override, the caller's default governs.
+ expect(resolveEnabled(overrides()[key], true)).toBe(true);
+ });
+
+ test('a corrupt payload is discarded (treated as no overrides)', () => {
+ localStorage.setItem(STORAGE_KEY, '{ not json');
+ reloadEnabledAgentsFromStorage();
+ // Discarded in memory; the next write starts from empty (no merge with the
+ // corrupt bytes) and overwrites storage with clean state.
+ setAgentEnabled(desktopEnabledKey('codex'), true);
+ expect(overrides()).toEqual({ 'desktop:codex': true });
+ });
+
+ test('non-boolean values are dropped, valid ones kept', () => {
+ localStorage.setItem(
+ STORAGE_KEY,
+ JSON.stringify({ 'desktop:codex': true, 'desktop:cursor': 'yes', 'terminal:pi': 0 }),
+ );
+ reloadEnabledAgentsFromStorage();
+ // A real change flushes the sanitized in-memory map back to storage — the
+ // non-boolean 'desktop:cursor'/'terminal:pi' entries never make it back.
+ setAgentEnabled('terminal:pi', true);
+ expect(overrides()).toEqual({ 'desktop:codex': true, 'terminal:pi': true });
+ });
+});
diff --git a/packages/app/src/lib/acp/enabled-agents.ts b/packages/app/src/lib/acp/enabled-agents.ts
new file mode 100644
index 000000000..45f1bf418
--- /dev/null
+++ b/packages/app/src/lib/acp/enabled-agents.ts
@@ -0,0 +1,151 @@
+/**
+ * Per-agent enable/disable overrides — the user's source of truth for which
+ * agents appear in the launcher dropdowns (footer "Ask", empty-state "Create
+ * with", header "Open with AI"). Managed from the Settings → Configure agents
+ * tab; consumed by every picker surface.
+ *
+ * The store holds ONLY explicit user overrides. The effective enabled-state is
+ * `override ?? categoryDefault`, computed at each call site where the runtime
+ * signals live (install detection, PATH probe, registration) — so the store
+ * stays pure and free of the async catalog / probe dependencies. Category
+ * defaults:
+ * - Terminal / Desktop → detected (auto-enabled when installed)
+ * - In app → registered (enabling registers; nothing to detect)
+ *
+ * Persisted in localStorage like the sibling launcher stores (registered
+ * agents, sticky handoff target). Enablement is per-machine by design: it pairs
+ * with per-machine detection, so it does not sync across devices.
+ *
+ * Store shape follows `registered-agents.ts`: module-scope state, a listener
+ * set, and bound snapshot getters that stay referentially stable between
+ * changes — with React Compiler enabled, a `useSyncExternalStore` hook must
+ * return the subscription value from stable getters or it memoizes to the first
+ * snapshot.
+ */
+
+import { useSyncExternalStore } from 'react';
+
+/** Explicit user overrides, keyed by the category-scoped agent key. Absent key
+ * means "no override" → the caller falls back to the category default. */
+export type EnabledOverrides = Readonly<Record<string, boolean>>;
+
+const STORAGE_KEY = 'ok-acp-enabled-agents-v1';
+const EMPTY_STATE: EnabledOverrides = {};
+
+/** Stable override key for an in-app (registry/custom) agent. */
+export function inAppEnabledKey(source: string, id: string): string {
+ return `in-app:${source}:${id}`;
+}
+
+/** Stable override key for a terminal CLI (`claude`, `codex`, …). */
+export function terminalEnabledKey(cli: string): string {
+ return `terminal:${cli}`;
+}
+
+/** Stable override key for a desktop handoff target (`claude-code`, …). */
+export function desktopEnabledKey(targetId: string): string {
+ return `desktop:${targetId}`;
+}
+
+/**
+ * Effective enabled-state: the user's explicit override when present, else the
+ * caller-supplied category default. The single place override precedence is
+ * expressed, so every surface resolves enablement identically.
+ */
+export function resolveEnabled(override: boolean | undefined, fallback: boolean): boolean {
+ return override ?? fallback;
+}
+
+function readFromStorage(): EnabledOverrides {
+ let raw: string | null;
+ try {
+ raw = localStorage.getItem(STORAGE_KEY);
+ } catch (err) {
+ // localStorage unavailable — non-browser env, or a browser blocking it via
+ // a privacy setting / CSP / partitioned-storage. Behave as empty, but log
+ // for diagnostics (matches the corrupt-payload catch below).
+ console.warn('[enabled-agents] localStorage unavailable; treating overrides as empty', err);
+ return EMPTY_STATE;
+ }
+ if (raw === null) return EMPTY_STATE;
+ try {
+ const parsed = JSON.parse(raw) as unknown;
+ if (typeof parsed !== 'object' || parsed === null) return EMPTY_STATE;
+ // Keep only string→boolean entries; a corrupt/foreign value for a key is
+ // dropped rather than poisoning the whole map.
+ const out: Record<string, boolean> = {};
+ for (const [key, value] of Object.entries(parsed as Record<string, unknown>)) {
+ if (typeof value === 'boolean') out[key] = value;
+ }
+ return out;
+ } catch (err) {
+ console.warn('[enabled-agents] discarding corrupt localStorage payload', err);
+ return EMPTY_STATE;
+ }
+}
+
+function writeToStorage(state: EnabledOverrides): void {
+ try {
+ localStorage.setItem(STORAGE_KEY, JSON.stringify(state));
+ } catch (err) {
+ // Quota / privacy mode — the in-memory state still serves this session,
+ // but the change will NOT survive a reload; say so.
+ console.warn('[enabled-agents] failed to persist override', err);
+ }
+}
+
+let state: EnabledOverrides | null = null;
+const listeners = new Set<() => void>();
+
+function currentState(): EnabledOverrides {
+ if (state === null) state = readFromStorage();
+ return state;
+}
+
+function setState(next: EnabledOverrides): void {
+ state = next;
+ for (const listener of listeners) listener();
+}
+
+/** Re-read persisted state (cross-tab `storage` events; tests). */
+export function reloadEnabledAgentsFromStorage(): void {
+ setState(readFromStorage());
+}
+
+if (typeof window !== 'undefined' && typeof window.addEventListener === 'function') {
+ window.addEventListener('storage', (event) => {
+ if (event.key === STORAGE_KEY || event.key === null) reloadEnabledAgentsFromStorage();
+ });
+}
+
+function subscribe(listener: () => void): () => void {
+ listeners.add(listener);
+ return () => listeners.delete(listener);
+}
+
+const getOverrides = (): EnabledOverrides => currentState();
+
+/**
+ * Set (or clear) an explicit enable/disable override for one agent key.
+ * Passing `undefined` removes the override so the agent reverts to its category
+ * default.
+ */
+export function setAgentEnabled(key: string, enabled: boolean | undefined): void {
+ const currentOverrides = currentState();
+ if (enabled === undefined) {
+ if (!(key in currentOverrides)) return;
+ const { [key]: _removed, ...rest } = currentOverrides;
+ writeToStorage(rest);
+ setState(rest);
+ return;
+ }
+ if (currentOverrides[key] === enabled) return;
+ const next: EnabledOverrides = { ...currentOverrides, [key]: enabled };
+ writeToStorage(next);
+ setState(next);
+}
+
+/** Reactive override map. Resolve effective state via {@link resolveEnabled}. */
+export function useEnabledOverrides(): EnabledOverrides {
+ return useSyncExternalStore(subscribe, getOverrides, getOverrides);
+}
diff --git a/packages/app/src/lib/acp/inline-diff.test.ts b/packages/app/src/lib/acp/inline-diff.test.ts
new file mode 100644
index 000000000..fb8f38938
--- /dev/null
+++ b/packages/app/src/lib/acp/inline-diff.test.ts
@@ -0,0 +1,49 @@
+import { describe, expect, test } from 'vitest';
+import { computeDiffRows, type DiffRow } from './inline-diff';
+
+const rowTypes = (rows: DiffRow[]): string[] => rows.map((r) => r.type);
+
+describe('computeDiffRows', () => {
+ test('a null oldText renders as pure addition (file creation)', () => {
+ const rows = computeDiffRows(null, 'one\ntwo\n');
+ expect(rows).toEqual([
+ { type: 'add', text: 'one' },
+ { type: 'add', text: 'two' },
+ ]);
+ });
+
+ test('a one-line change in a large file is a one-line diff, not two full files', () => {
+ const lines = Array.from({ length: 40 }, (_, i) => `line ${i}`);
+ const before = lines.join('\n');
+ const after = lines.map((l) => (l === 'line 20' ? 'line twenty' : l)).join('\n');
+ const rows = computeDiffRows(before, after);
+ expect(rows.filter((r) => r.type === 'del')).toEqual([{ type: 'del', text: 'line 20' }]);
+ expect(rows.filter((r) => r.type === 'add')).toEqual([{ type: 'add', text: 'line twenty' }]);
+ // The untouched top and bottom collapse into gap rows.
+ const gaps = rows.filter((r): r is Extract<DiffRow, { type: 'gap' }> => r.type === 'gap');
+ expect(gaps.length).toBeGreaterThanOrEqual(2);
+ const shownLines = rows.filter((r) => r.type !== 'gap').length;
+ expect(shownLines).toBeLessThan(12);
+ const hidden = gaps.reduce((n, g) => n + g.count, 0);
+ expect(shownLines + hidden).toBeGreaterThanOrEqual(40);
+ });
+
+ test('short unchanged runs render inline without a gap', () => {
+ const rows = computeDiffRows('a\nb\nc\nd\n', 'a\nb\nc\nX\n');
+ expect(rowTypes(rows)).toEqual(['ctx', 'ctx', 'ctx', 'del', 'add']);
+ });
+
+ test('identical texts produce only context (or a single gap)', () => {
+ const text = 'same\nlines\n';
+ const rows = computeDiffRows(text, text);
+ expect(rows.every((r) => r.type === 'ctx' || r.type === 'gap')).toBe(true);
+ });
+
+ test('keeps a genuinely empty trailing line when there is no final newline', () => {
+ const rows = computeDiffRows(null, 'a\n\n');
+ expect(rows).toEqual([
+ { type: 'add', text: 'a' },
+ { type: 'add', text: '' },
+ ]);
+ });
+});
diff --git a/packages/app/src/lib/acp/inline-diff.ts b/packages/app/src/lib/acp/inline-diff.ts
new file mode 100644
index 000000000..a38087a43
--- /dev/null
+++ b/packages/app/src/lib/acp/inline-diff.ts
@@ -0,0 +1,56 @@
+/**
+ * Row model for the transcript's inline tool-call diff: a genuine line diff
+ * (jsdiff) instead of "all old lines red, all new lines green". Long
+ * unchanged runs collapse to a gap row so a one-line edit in a large file
+ * reads as a one-line edit.
+ */
+
+import { diffLines } from 'diff';
+
+export type DiffRow =
+ | { type: 'add' | 'del' | 'ctx'; text: string }
+ | { type: 'gap'; count: number };
+
+/** Unchanged runs longer than this collapse to leading/trailing context + a gap. */
+const CONTEXT_LINES = 3;
+const COLLAPSE_THRESHOLD = CONTEXT_LINES * 2 + 2;
+
+function toLines(value: string): string[] {
+ const lines = value.split('\n');
+ // A diff part's value ends with the trailing newline of its last line —
+ // drop the phantom empty line it splits into (but keep a genuinely empty
+ // final line when the part has no trailing newline at all).
+ if (lines[lines.length - 1] === '') lines.pop();
+ return lines;
+}
+
+export function computeDiffRows(oldText: string | null, newText: string): DiffRow[] {
+ if (oldText === null) {
+ return toLines(newText).map((text) => ({ type: 'add' as const, text }));
+ }
+ const rows: DiffRow[] = [];
+ const parts = diffLines(oldText, newText);
+ for (const [index, part] of parts.entries()) {
+ const lines = toLines(part.value);
+ if (part.added) {
+ for (const text of lines) rows.push({ type: 'add', text });
+ continue;
+ }
+ if (part.removed) {
+ for (const text of lines) rows.push({ type: 'del', text });
+ continue;
+ }
+ if (lines.length <= COLLAPSE_THRESHOLD) {
+ for (const text of lines) rows.push({ type: 'ctx', text });
+ continue;
+ }
+ // Head context only after a change; tail context only before one — the
+ // file's untouched top/bottom collapse entirely.
+ const head = index > 0 ? lines.slice(0, CONTEXT_LINES) : [];
+ const tail = index < parts.length - 1 ? lines.slice(-CONTEXT_LINES) : [];
+ for (const text of head) rows.push({ type: 'ctx', text });
+ rows.push({ type: 'gap', count: lines.length - head.length - tail.length });
+ for (const text of tail) rows.push({ type: 'ctx', text });
+ }
+ return rows;
+}
diff --git a/packages/app/src/lib/acp/launch-agent-thread.ts b/packages/app/src/lib/acp/launch-agent-thread.ts
new file mode 100644
index 000000000..91fc9f387
--- /dev/null
+++ b/packages/app/src/lib/acp/launch-agent-thread.ts
@@ -0,0 +1,56 @@
+/**
+ * Fire an agent-thread creation with double-click dedup + user-facing failure
+ * toast — the launch path shared by every "Start an agent" surface (the sessions
+ * dock's New button, the handoff-menu launch bus, the catalog dialog's own
+ * launches route through the client directly).
+ *
+ * Lifted out of the retired `AgentThreadRegion` so the sessions dock host and the
+ * launch bus can both invoke it without re-implementing the in-flight guard.
+ */
+
+import { t } from '@lingui/core/macro';
+import { toast } from 'sonner';
+import { getAgentThreadClient, ThreadChannelUnavailableError } from '@/lib/acp/thread-client';
+
+/**
+ * One launch per agent may be in flight at a time: creation can take seconds
+ * (npx install + handshake) and every extra click would spawn another agent that
+ * immediately runs the launch prompt on the customer's account, so impatient
+ * double-clicks drop rather than duplicate. Module-scope so it survives the
+ * host's re-renders and spans every launch surface in the window.
+ */
+const inflightLaunches = new Set<string>();
+
+/**
+ * Create a thread for a concrete agent. Agent-level failures stream into the dock
+ * as thread status events; the catch fires only when no thread was created at all,
+ * so a toast is the sole feedback channel there.
+ */
+export function launchAgentThread(
+ agent: { source: 'registry' | 'custom'; id: string },
+ prompt: string | null,
+ docName: string | null,
+ titleHint: string | null,
+): void {
+ const launchKey = `${agent.source}:${agent.id}`;
+ if (inflightLaunches.has(launchKey)) return;
+ inflightLaunches.add(launchKey);
+ void getAgentThreadClient()
+ .createThread({
+ agent,
+ prompt: prompt ?? undefined,
+ docName: docName ?? undefined,
+ titleHint: titleHint ?? undefined,
+ })
+ .catch((err) => {
+ console.error('[agent-threads] launch failed:', err);
+ toast.error(
+ err instanceof ThreadChannelUnavailableError
+ ? t`Couldn't connect to the agent service. Make sure the OpenKnowledge server is running and up to date (restart it if it was already running), then try again.`
+ : t`Couldn't start the agent thread — please try again.`,
+ );
+ })
+ .finally(() => {
+ inflightLaunches.delete(launchKey);
+ });
+}
diff --git a/packages/app/src/lib/acp/launcher-selection.test.ts b/packages/app/src/lib/acp/launcher-selection.test.ts
new file mode 100644
index 000000000..ddba5f660
--- /dev/null
+++ b/packages/app/src/lib/acp/launcher-selection.test.ts
@@ -0,0 +1,212 @@
+import type { TerminalCli } from '@inkeep/open-knowledge-core';
+import { describe, expect, test } from 'vitest';
+import { IN_APP_THREAD_ID, terminalCliId } from '../unified-agent-store';
+import {
+ desktopEnabledKey,
+ type EnabledOverrides,
+ inAppEnabledKey,
+ terminalEnabledKey,
+} from './enabled-agents';
+import {
+ enabledDesktopTargets,
+ enabledTerminalClis,
+ enabledThreadAgents,
+ type LauncherSelectionInputs,
+ resolveLauncherSelection,
+} from './launcher-selection';
+import type { RegisteredAgent } from './registered-agents';
+
+const claude: RegisteredAgent = { source: 'registry', id: 'claude-acp', name: 'Claude' };
+const codexAgent: RegisteredAgent = { source: 'registry', id: 'codex-acp', name: 'Codex' };
+
+const base: LauncherSelectionInputs = {
+ sticky: null,
+ effectiveThreadAgent: null,
+ enabledClis: [],
+ enabledDesktopTargets: [],
+ installedClis: {},
+ terminalAvailable: true,
+ threadsAvailable: true,
+ desktopSelectable: false,
+};
+
+function inputs(over: Partial<LauncherSelectionInputs>): LauncherSelectionInputs {
+ return { ...base, ...over };
+}
+
+describe('enabled-set helpers', () => {
+ test('enabledThreadAgents drops disabled + keeps registered-by-default', () => {
+ const key = inAppEnabledKey('registry', 'codex-acp');
+ const overrides: EnabledOverrides = { [key]: false };
+ expect(enabledThreadAgents([claude, codexAgent], overrides).map((a) => a.id)).toEqual([
+ 'claude-acp',
+ ]);
+ });
+
+ test('enabledTerminalClis: fail-open unless probed absent or toggled off', () => {
+ const overrides: EnabledOverrides = { [terminalEnabledKey('codex')]: false };
+ const clis = enabledTerminalClis(overrides, { cursor: false });
+ expect(clis).toContain('claude'); // unknown install → shown
+ expect(clis).not.toContain('codex'); // toggled off
+ expect(clis).not.toContain('cursor'); // probed absent
+ });
+
+ test('enabledDesktopTargets: off by default, on with an override', () => {
+ expect(enabledDesktopTargets({})).toEqual([]);
+ expect(enabledDesktopTargets({ [desktopEnabledKey('cursor')]: true })).toEqual(['cursor']);
+ });
+});
+
+describe('resolveLauncherSelection — defaults', () => {
+ test('leads with the effective in-app agent (thread-first)', () => {
+ expect(resolveLauncherSelection(inputs({ effectiveThreadAgent: claude }))).toEqual({
+ kind: 'thread',
+ agent: claude,
+ });
+ });
+
+ test('no in-app agent but an enabled CLI → that CLI', () => {
+ expect(
+ resolveLauncherSelection(inputs({ effectiveThreadAgent: null, enabledClis: ['codex'] })),
+ ).toEqual({ kind: 'cli', cli: 'codex' });
+ });
+
+ test('default CLI prefers an installed enabled CLI over an unknown-install one', () => {
+ const clis: TerminalCli[] = ['claude', 'codex'];
+ expect(
+ resolveLauncherSelection(
+ inputs({ effectiveThreadAgent: null, enabledClis: clis, installedClis: { codex: true } }),
+ ),
+ ).toEqual({ kind: 'cli', cli: 'codex' });
+ });
+
+ test('nothing enabled → none (composer) or bare terminal (dock)', () => {
+ expect(resolveLauncherSelection(inputs({}))).toEqual({ kind: 'none' });
+ expect(resolveLauncherSelection(inputs({ bareTerminalFallback: true }))).toEqual({
+ kind: 'terminal',
+ });
+ });
+
+ test('preferBareTerminal wins on a terminal surface', () => {
+ expect(
+ resolveLauncherSelection(inputs({ preferBareTerminal: true, effectiveThreadAgent: claude })),
+ ).toEqual({ kind: 'terminal' });
+ });
+});
+
+describe('resolveLauncherSelection — remembered pick honored only when still enabled', () => {
+ test('thread sticky → the effective agent', () => {
+ expect(
+ resolveLauncherSelection(
+ inputs({ sticky: IN_APP_THREAD_ID, effectiveThreadAgent: codexAgent }),
+ ),
+ ).toEqual({ kind: 'thread', agent: codexAgent });
+ });
+
+ test('CLI sticky that is still enabled → that CLI', () => {
+ expect(
+ resolveLauncherSelection(inputs({ sticky: terminalCliId('codex'), enabledClis: ['codex'] })),
+ ).toEqual({ kind: 'cli', cli: 'codex' });
+ });
+
+ test('BUG 2: a CLI sticky the user disabled is NOT kept — it degrades', () => {
+ // sticky = claude CLI, but claude is no longer enabled and no other CLI is
+ // either; an in-app agent is enabled → fall to it (never the disabled CLI).
+ const result = resolveLauncherSelection(
+ inputs({
+ sticky: terminalCliId('claude'),
+ enabledClis: [],
+ effectiveThreadAgent: claude,
+ }),
+ );
+ expect(result).toEqual({ kind: 'thread', agent: claude });
+ });
+
+ test('BUG 2 (dock): all CLIs disabled, no in-app agent → bare terminal, never Claude CLI', () => {
+ const result = resolveLauncherSelection(
+ inputs({
+ sticky: terminalCliId('claude'),
+ enabledClis: [],
+ effectiveThreadAgent: null,
+ bareTerminalFallback: true,
+ }),
+ );
+ expect(result).toEqual({ kind: 'terminal' });
+ });
+
+ test('desktop sticky honored only when enabled + desktopSelectable', () => {
+ expect(
+ resolveLauncherSelection(
+ inputs({ sticky: 'cursor', desktopSelectable: true, enabledDesktopTargets: ['cursor'] }),
+ ),
+ ).toEqual({ kind: 'desktop', target: 'cursor' });
+ // Not enabled → degrades (here: to none).
+ expect(
+ resolveLauncherSelection(
+ inputs({ sticky: 'cursor', desktopSelectable: true, enabledDesktopTargets: [] }),
+ ),
+ ).toEqual({ kind: 'none' });
+ });
+
+ test('enabled desktop app is the default when it is the only enabled family', () => {
+ // Turn on one Desktop agent with nothing picked and no in-app agent / CLI
+ // enabled: the composer must default to it, not dead-end on a disabled
+ // Create button with no picker to reach it.
+ expect(
+ resolveLauncherSelection(
+ inputs({ desktopSelectable: true, enabledDesktopTargets: ['cursor'] }),
+ ),
+ ).toEqual({ kind: 'desktop', target: 'cursor' });
+ });
+
+ test('desktop never outranks an enabled in-app agent or CLI as the default', () => {
+ // In-app agent wins.
+ expect(
+ resolveLauncherSelection(
+ inputs({
+ desktopSelectable: true,
+ enabledDesktopTargets: ['cursor'],
+ effectiveThreadAgent: claude,
+ }),
+ ),
+ ).toEqual({ kind: 'thread', agent: claude });
+ // No in-app agent, but an enabled CLI still wins over desktop.
+ expect(
+ resolveLauncherSelection(
+ inputs({
+ desktopSelectable: true,
+ enabledDesktopTargets: ['cursor'],
+ enabledClis: ['codex'],
+ }),
+ ),
+ ).toEqual({ kind: 'cli', cli: 'codex' });
+ });
+});
+
+describe('resolveLauncherSelection — surface capabilities', () => {
+ test('terminal window (no threads): a thread sticky degrades to a CLI', () => {
+ expect(
+ resolveLauncherSelection(
+ inputs({
+ sticky: IN_APP_THREAD_ID,
+ threadsAvailable: false,
+ effectiveThreadAgent: claude,
+ enabledClis: ['claude'],
+ }),
+ ),
+ ).toEqual({ kind: 'cli', cli: 'claude' });
+ });
+
+ test('web (no terminal): a CLI sticky degrades to the in-app agent', () => {
+ expect(
+ resolveLauncherSelection(
+ inputs({
+ sticky: terminalCliId('codex'),
+ terminalAvailable: false,
+ enabledClis: ['codex'],
+ effectiveThreadAgent: claude,
+ }),
+ ),
+ ).toEqual({ kind: 'thread', agent: claude });
+ });
+});
diff --git a/packages/app/src/lib/acp/launcher-selection.ts b/packages/app/src/lib/acp/launcher-selection.ts
new file mode 100644
index 000000000..ed054cd87
--- /dev/null
+++ b/packages/app/src/lib/acp/launcher-selection.ts
@@ -0,0 +1,147 @@
+/**
+ * The single source of truth for "what does an agent-launcher's primary button
+ * launch, and which rows are visible?" — shared by every primary-button surface
+ * (footer Ask composer, empty-state Create composer, sessions-dock New button).
+ *
+ * Before this, each surface re-derived selection its own way: one used the
+ * enabled-aware effective default, another read the raw default with a
+ * mount-time snapshot, a third forced a Claude CLI fallback that ignored the
+ * enable/disable toggles. That divergence is exactly what let disabling an agent
+ * fix one surface and leave another showing it. This module makes every category
+ * (in-app agent / terminal CLI / desktop app) respect the Configure-agents
+ * toggles UNIFORMLY, so a disabled thing is never the selection anywhere.
+ *
+ * Pure + host-agnostic: callers feed the reactive store + probe values, so React
+ * re-derives selection every render (no stale snapshots).
+ */
+
+import type { HandoffTarget, TerminalCli } from '@inkeep/open-knowledge-core';
+import { TERMINAL_CLI_IDS } from '@inkeep/open-knowledge-core';
+import { VISIBLE_TARGETS } from '@/lib/handoff/targets';
+import { parseStickyCliId, parseStickyThreadAgent } from '../unified-agent-store';
+import {
+ isDesktopTargetEnabled,
+ isInAppAgentEnabled,
+ isTerminalCliEnabled,
+} from './agent-visibility';
+import type { EnabledOverrides } from './enabled-agents';
+import type { RegisteredAgent } from './registered-agents';
+
+/** What a primary launcher button launches. `none` = nothing enabled to launch. */
+export type LauncherSelection =
+ | { readonly kind: 'thread'; readonly agent: RegisteredAgent }
+ | { readonly kind: 'cli'; readonly cli: TerminalCli }
+ | { readonly kind: 'desktop'; readonly target: HandoffTarget }
+ | { readonly kind: 'terminal' } // bare shell — sessions dock only
+ | { readonly kind: 'none' };
+
+/** Registered in-app agents the user has ENABLED (and that are supported here). */
+export function enabledThreadAgents(
+ agents: readonly RegisteredAgent[],
+ overrides: EnabledOverrides,
+): RegisteredAgent[] {
+ return agents.filter((a) => isInAppAgentEnabled(overrides, a.source, a.id, true, a.supported));
+}
+
+/**
+ * Terminal CLIs the user has ENABLED, in launch-priority order. `isTerminalCliEnabled`
+ * already folds in install detection (fail-open: shown unless probed absent).
+ */
+export function enabledTerminalClis(
+ overrides: EnabledOverrides,
+ installedClis: Partial<Record<TerminalCli, boolean>>,
+): TerminalCli[] {
+ return TERMINAL_CLI_IDS.filter((cli) => isTerminalCliEnabled(overrides, cli, installedClis));
+}
+
+/** Desktop targets the user has ENABLED (opt-in; independent of install state). */
+export function enabledDesktopTargets(overrides: EnabledOverrides): HandoffTarget[] {
+ return VISIBLE_TARGETS.filter((t) => isDesktopTargetEnabled(overrides, t.id)).map((t) => t.id);
+}
+
+export interface LauncherSelectionInputs {
+ /** Raw sticky/explicit pick (unified-agent-store id), or null. */
+ readonly sticky: string | null;
+ /** The in-app agent the primary leads with: `pickEffectiveDefaultAgent` over the
+ * ENABLED set (the registered default when still enabled, else the first
+ * enabled one). Null when no in-app agent is enabled. */
+ readonly effectiveThreadAgent: RegisteredAgent | null;
+ /** Enabled terminal CLIs, priority order ({@link enabledTerminalClis}). */
+ readonly enabledClis: readonly TerminalCli[];
+ /** Enabled desktop targets ({@link enabledDesktopTargets}). */
+ readonly enabledDesktopTargets: readonly HandoffTarget[];
+ /** Install map — the default CLI prefers an installed enabled CLI over an
+ * unknown-install one. */
+ readonly installedClis: Partial<Record<TerminalCli, boolean>>;
+ /** The surface can launch terminal CLIs / a bare shell (desktop bridge). */
+ readonly terminalAvailable: boolean;
+ /** The surface can launch in-app agent threads. */
+ readonly threadsAvailable: boolean;
+ /** The surface offers Desktop app rows as picks (composers do; the dock doesn't). */
+ readonly desktopSelectable: boolean;
+ /** Remembered bare-terminal pick (dock only). */
+ readonly preferBareTerminal?: boolean;
+ /** Final fallback is a bare terminal (dock) rather than `none` (composers). */
+ readonly bareTerminalFallback?: boolean;
+}
+
+/**
+ * Resolve the primary button's effective selection. A remembered pick is honored
+ * only when its family is available AND the thing is still ENABLED; a disabled
+ * (or vanished) pick degrades to the zero-config default. The default precedence
+ * is uniform: an enabled in-app agent, else an enabled CLI, else — on surfaces
+ * that offer Desktop rows — an enabled Desktop app, else a bare terminal (dock) /
+ * nothing (composers). Desktop only defaults when it is the sole enabled family;
+ * it never outranks an in-app agent or CLI.
+ */
+export function resolveLauncherSelection(inputs: LauncherSelectionInputs): LauncherSelection {
+ const {
+ sticky,
+ effectiveThreadAgent,
+ enabledClis,
+ enabledDesktopTargets: desktopTargets,
+ installedClis,
+ terminalAvailable,
+ threadsAvailable,
+ desktopSelectable,
+ preferBareTerminal,
+ bareTerminalFallback,
+ } = inputs;
+
+ if (preferBareTerminal && terminalAvailable) return { kind: 'terminal' };
+
+ // A remembered pick — honored only if still enabled + launchable here.
+ if (
+ threadsAvailable &&
+ parseStickyThreadAgent(sticky) !== null &&
+ effectiveThreadAgent !== null
+ ) {
+ return { kind: 'thread', agent: effectiveThreadAgent };
+ }
+ if (terminalAvailable) {
+ const cli = parseStickyCliId(sticky);
+ if (cli !== null && enabledClis.includes(cli)) return { kind: 'cli', cli };
+ }
+ if (desktopSelectable && sticky !== null && desktopTargets.includes(sticky as HandoffTarget)) {
+ return { kind: 'desktop', target: sticky as HandoffTarget };
+ }
+
+ // Zero-config default precedence (thread-first for consistency across surfaces).
+ if (threadsAvailable && effectiveThreadAgent !== null) {
+ return { kind: 'thread', agent: effectiveThreadAgent };
+ }
+ if (terminalAvailable && enabledClis.length > 0) {
+ const cli = enabledClis.find((c) => installedClis[c] === true) ?? enabledClis[0];
+ return { kind: 'cli', cli };
+ }
+ // An enabled Desktop app is a valid default only when nothing higher-priority
+ // is enabled — the user opted it in, so defaulting to it beats stranding the
+ // primary on a disabled Create button with no picker to reach it. It never
+ // outranks an in-app agent or CLI, and a fresh install (in-app seeded, Desktop
+ // off) never reaches here.
+ if (desktopSelectable && desktopTargets.length > 0) {
+ return { kind: 'desktop', target: desktopTargets[0] };
+ }
+ if (bareTerminalFallback && terminalAvailable) return { kind: 'terminal' };
+ return { kind: 'none' };
+}
diff --git a/packages/app/src/lib/acp/registered-agents.test.ts b/packages/app/src/lib/acp/registered-agents.test.ts
new file mode 100644
index 000000000..09df58298
--- /dev/null
+++ b/packages/app/src/lib/acp/registered-agents.test.ts
@@ -0,0 +1,233 @@
+import { beforeEach, describe, expect, test } from 'vitest';
+
+// Plain `bun test` has no localStorage — install a minimal stub BEFORE the
+// module under test first touches it (reads are lazy, so import order is
+// safe either way).
+const backing = new Map<string, string>();
+if (typeof globalThis.localStorage === 'undefined') {
+ (globalThis as { localStorage?: unknown }).localStorage = {
+ getItem: (key: string) => backing.get(key) ?? null,
+ setItem: (key: string, value: string) => void backing.set(key, value),
+ removeItem: (key: string) => void backing.delete(key),
+ clear: () => backing.clear(),
+ };
+}
+
+import {
+ getDefaultRegisteredAgent,
+ getRegisteredAgentOptions,
+ hydrateRegisteredAgentMeta,
+ mergeRegisteredAgentSuggestions,
+ pickEffectiveDefaultAgent,
+ type RegisteredAgent,
+ reassignDefaultIfDisabled,
+ registerAgent,
+ reloadRegisteredAgentsFromStorage,
+ setDetectedRegisteredAgentSuggestions,
+} from './registered-agents';
+
+const STORAGE_KEY = 'ok-acp-registered-agents-v1';
+
+function storedAgents(): RegisteredAgent[] {
+ return JSON.parse(localStorage.getItem(STORAGE_KEY) ?? '{}').agents ?? [];
+}
+
+const claude: RegisteredAgent = {
+ source: 'registry',
+ id: 'claude-acp',
+ name: 'Claude Agent',
+ iconUrl: 'https://example.com/claude.svg',
+};
+const codex: RegisteredAgent = { source: 'registry', id: 'codex-acp', name: 'Codex' };
+
+beforeEach(() => {
+ localStorage.clear();
+ setDetectedRegisteredAgentSuggestions([]);
+ reloadRegisteredAgentsFromStorage();
+});
+
+describe('registered-agents store', () => {
+ test('empty before any registration', () => {
+ expect(getDefaultRegisteredAgent()).toBeNull();
+ });
+
+ test('registerAgent sets the default and persists', () => {
+ registerAgent(claude);
+ expect(getDefaultRegisteredAgent()).toEqual(claude);
+ const persisted = JSON.parse(localStorage.getItem(STORAGE_KEY) ?? '{}');
+ expect(persisted.agents).toEqual([claude]);
+ expect(persisted.defaultKey).toBe('registry:claude-acp');
+ });
+
+ test('the most recently registered agent becomes the default; re-registering dedupes', () => {
+ registerAgent(claude);
+ registerAgent(codex);
+ expect(getDefaultRegisteredAgent()?.id).toBe('codex-acp');
+ registerAgent(claude);
+ expect(getDefaultRegisteredAgent()?.id).toBe('claude-acp');
+ const persisted = JSON.parse(localStorage.getItem(STORAGE_KEY) ?? '{}');
+ expect(persisted.agents).toHaveLength(2);
+ expect(persisted.agents.map((a: RegisteredAgent) => a.id)).toEqual(['claude-acp', 'codex-acp']);
+ });
+
+ test('survives reload from storage', () => {
+ registerAgent(claude);
+ reloadRegisteredAgentsFromStorage();
+ expect(getDefaultRegisteredAgent()).toEqual(claude);
+ });
+
+ test('makeDefault:false registers for visibility without changing the default', () => {
+ registerAgent(claude); // claude is the default
+ registerAgent(codex, { makeDefault: false }); // enable-in-Settings path
+ // Default unchanged, codex appended (not prepended), both present.
+ expect(getDefaultRegisteredAgent()?.id).toBe('claude-acp');
+ const persisted = JSON.parse(localStorage.getItem(STORAGE_KEY) ?? '{}');
+ expect(persisted.agents.map((a: RegisteredAgent) => a.id)).toEqual(['claude-acp', 'codex-acp']);
+ });
+
+ test('makeDefault:false updates an existing agent in place without reordering or re-defaulting', () => {
+ registerAgent(claude);
+ registerAgent(codex); // codex now default, order [codex, claude]
+ registerAgent({ ...claude, name: 'Claude Renamed' }, { makeDefault: false });
+ // Default stays codex; claude keeps its position; metadata refreshed.
+ expect(getDefaultRegisteredAgent()?.id).toBe('codex-acp');
+ const persisted = JSON.parse(localStorage.getItem(STORAGE_KEY) ?? '{}');
+ expect(persisted.agents.map((a: RegisteredAgent) => a.id)).toEqual(['codex-acp', 'claude-acp']);
+ expect(persisted.agents.find((a: RegisteredAgent) => a.id === 'claude-acp')?.name).toBe(
+ 'Claude Renamed',
+ );
+ });
+
+ test('corrupt storage behaves as empty rather than throwing', () => {
+ localStorage.setItem(STORAGE_KEY, '{not json');
+ reloadRegisteredAgentsFromStorage();
+ expect(getDefaultRegisteredAgent()).toBeNull();
+ });
+
+ test('a default pointing at a missing agent is dropped on read', () => {
+ localStorage.setItem(
+ STORAGE_KEY,
+ JSON.stringify({ agents: [claude], defaultKey: 'registry:vanished' }),
+ );
+ reloadRegisteredAgentsFromStorage();
+ expect(getDefaultRegisteredAgent()).toBeNull();
+ });
+
+ test('malformed entries are filtered on read', () => {
+ localStorage.setItem(
+ STORAGE_KEY,
+ JSON.stringify({
+ agents: [claude, { source: 'registry', id: '' }, { name: 'no id' }, 42],
+ defaultKey: 'registry:claude-acp',
+ }),
+ );
+ reloadRegisteredAgentsFromStorage();
+ expect(getDefaultRegisteredAgent()).toEqual(claude);
+ });
+
+ test('merges detected suggestions without replacing explicit registrations', () => {
+ expect(mergeRegisteredAgentSuggestions([claude], [codex, claude])).toEqual([claude, codex]);
+ expect(localStorage.getItem(STORAGE_KEY)).toBeNull();
+ });
+
+ test('detected suggestions appear everywhere without becoming the default or persisting', () => {
+ setDetectedRegisteredAgentSuggestions([codex]);
+
+ expect(getRegisteredAgentOptions()).toEqual([codex]);
+ expect(getDefaultRegisteredAgent()).toBeNull();
+ expect(localStorage.getItem(STORAGE_KEY)).toBeNull();
+
+ registerAgent(claude);
+ expect(getRegisteredAgentOptions()).toEqual([claude, codex]);
+ expect(getDefaultRegisteredAgent()).toEqual(claude);
+ });
+});
+
+describe('hydrateRegisteredAgentMeta', () => {
+ beforeEach(() => {
+ localStorage.clear();
+ reloadRegisteredAgentsFromStorage();
+ });
+
+ test('updates name/icon in place without changing the default or order', () => {
+ // Claude first + default; the rest appended in order.
+ registerAgent(claude, { makeDefault: true });
+ registerAgent(codex, { makeDefault: false });
+ registerAgent({ source: 'registry', id: 'cursor', name: 'Cursor' }, { makeDefault: false });
+ registerAgent({ source: 'registry', id: 'gemini', name: 'Gemini' }, { makeDefault: false });
+ hydrateRegisteredAgentMeta([
+ { source: 'registry', id: 'codex-acp', name: 'Codex', iconUrl: 'https://x/codex.svg' },
+ { source: 'registry', id: 'gemini', name: 'Gemini CLI' },
+ ]);
+ const agents = storedAgents();
+ expect(agents.map((a) => a.id)).toEqual(['claude-acp', 'codex-acp', 'cursor', 'gemini']);
+ expect(agents.find((a) => a.id === 'codex-acp')?.iconUrl).toBe('https://x/codex.svg');
+ expect(agents.find((a) => a.id === 'gemini')?.name).toBe('Gemini CLI');
+ // Default is unchanged by hydration.
+ expect(getDefaultRegisteredAgent()?.id).toBe('claude-acp');
+ });
+
+ test('ignores patches for agents that are not registered', () => {
+ registerAgent(claude);
+ hydrateRegisteredAgentMeta([{ source: 'registry', id: 'not-registered', name: 'Nope' }]);
+ expect(storedAgents().map((a) => a.id)).toEqual(['claude-acp']);
+ });
+
+ test('stores the supported flag so the launcher can hide unavailable agents', () => {
+ registerAgent(codex);
+ hydrateRegisteredAgentMeta([{ source: 'registry', id: 'codex-acp', supported: false }]);
+ expect(storedAgents().find((a) => a.id === 'codex-acp')?.supported).toBe(false);
+ });
+});
+
+describe('pickEffectiveDefaultAgent', () => {
+ test('keeps the default when it is still enabled', () => {
+ expect(pickEffectiveDefaultAgent([claude, codex], claude)).toBe(claude);
+ });
+
+ test('falls back to the first enabled agent when the default is disabled', () => {
+ // claude is the default but not in the enabled list → lead with codex.
+ expect(pickEffectiveDefaultAgent([codex], claude)).toBe(codex);
+ });
+
+ test('returns null when no agents are enabled', () => {
+ expect(pickEffectiveDefaultAgent([], claude)).toBeNull();
+ expect(pickEffectiveDefaultAgent([], null)).toBeNull();
+ });
+
+ test('leads with the first enabled agent when there is no default', () => {
+ expect(pickEffectiveDefaultAgent([codex, claude], null)).toBe(codex);
+ });
+});
+
+describe('reassignDefaultIfDisabled', () => {
+ beforeEach(() => {
+ localStorage.clear();
+ reloadRegisteredAgentsFromStorage();
+ });
+
+ test('moves the default to the next still-enabled agent when the default is disabled', () => {
+ registerAgent(codex); // order [codex]
+ registerAgent(claude); // order [claude, codex], claude is default
+ expect(getDefaultRegisteredAgent()?.id).toBe('claude-acp');
+ // Disable claude (the default); codex is still enabled.
+ reassignDefaultIfDisabled('registry:claude-acp', (a) => a.id === 'codex-acp');
+ expect(getDefaultRegisteredAgent()?.id).toBe('codex-acp');
+ // Order is preserved — only the default moved.
+ expect(storedAgents().map((a) => a.id)).toEqual(['claude-acp', 'codex-acp']);
+ });
+
+ test('clears the default when no other agent is still enabled', () => {
+ registerAgent(claude);
+ reassignDefaultIfDisabled('registry:claude-acp', () => false);
+ expect(getDefaultRegisteredAgent()).toBeNull();
+ });
+
+ test('no-op when the disabled agent was not the default', () => {
+ registerAgent(codex); // default
+ registerAgent(claude); // now default is claude
+ // Disable codex, which is NOT the default → default stays claude.
+ reassignDefaultIfDisabled('registry:codex-acp', () => true);
+ expect(getDefaultRegisteredAgent()?.id).toBe('claude-acp');
+ });
+});
diff --git a/packages/app/src/lib/acp/registered-agents.ts b/packages/app/src/lib/acp/registered-agents.ts
new file mode 100644
index 000000000..ebddfcd62
--- /dev/null
+++ b/packages/app/src/lib/acp/registered-agents.ts
@@ -0,0 +1,298 @@
+/**
+ * ACP agent options — the user's explicit shortlist plus live, machine-detected
+ * harness suggestions. Picking an agent registers it once; the default remains
+ * the most recently registered (last explicitly chosen) agent.
+ *
+ * Persisted in localStorage like the other launcher preferences (sticky
+ * handoff target, terminal CLI sentinel). Name + icon are cached alongside the
+ * id so menus can render rows without refetching the registry catalog.
+ *
+ * Store shape follows `thread-client.ts`: module-scope state, a listener set,
+ * and bound snapshot getters that stay referentially stable between changes —
+ * with React Compiler enabled, a `useSyncExternalStore` hook must return the
+ * subscription value from stable getters or it memoizes to the first snapshot.
+ */
+
+import { useSyncExternalStore } from 'react';
+
+export interface RegisteredAgent {
+ readonly source: 'registry' | 'custom';
+ readonly id: string;
+ readonly name: string;
+ readonly iconUrl?: string;
+ /**
+ * Whether the registry ships a build this agent can launch on this host.
+ * Hydrated from the catalog (undefined until then). `false` force-hides the
+ * agent from every launcher and its Settings toggle, so the two always agree.
+ */
+ readonly supported?: boolean;
+}
+
+interface RegisteredAgentsState {
+ readonly agents: readonly RegisteredAgent[];
+ readonly defaultKey: string | null;
+}
+
+const STORAGE_KEY = 'ok-acp-registered-agents-v1';
+const EMPTY_STATE: RegisteredAgentsState = { agents: [], defaultKey: null };
+
+function agentKey(agent: Pick<RegisteredAgent, 'source' | 'id'>): string {
+ return `${agent.source}:${agent.id}`;
+}
+
+function isRegisteredAgent(value: unknown): value is RegisteredAgent {
+ if (typeof value !== 'object' || value === null) return false;
+ const a = value as Record<string, unknown>;
+ return (
+ (a.source === 'registry' || a.source === 'custom') &&
+ typeof a.id === 'string' &&
+ a.id !== '' &&
+ typeof a.name === 'string' &&
+ a.name !== '' &&
+ (a.iconUrl === undefined || typeof a.iconUrl === 'string')
+ );
+}
+
+function readFromStorage(): RegisteredAgentsState {
+ let raw: string | null;
+ try {
+ raw = localStorage.getItem(STORAGE_KEY);
+ } catch {
+ // No localStorage (non-browser env) — behave as empty, silently.
+ return EMPTY_STATE;
+ }
+ if (raw === null) return EMPTY_STATE;
+ try {
+ const parsed = JSON.parse(raw) as { agents?: unknown; defaultKey?: unknown };
+ const agents = Array.isArray(parsed.agents) ? parsed.agents.filter(isRegisteredAgent) : [];
+ const defaultKey =
+ typeof parsed.defaultKey === 'string' && agents.some((a) => agentKey(a) === parsed.defaultKey)
+ ? parsed.defaultKey
+ : null;
+ return { agents, defaultKey };
+ } catch (err) {
+ // A present-but-corrupt payload is a real storage failure, distinct from
+ // "never registered" — leave a signal for the disappearing-registration
+ // bug report before discarding.
+ console.warn('[registered-agents] discarding corrupt localStorage payload', err);
+ return EMPTY_STATE;
+ }
+}
+
+function writeToStorage(state: RegisteredAgentsState): void {
+ try {
+ localStorage.setItem(STORAGE_KEY, JSON.stringify(state));
+ } catch (err) {
+ // Quota / privacy mode — the in-memory state still serves this session,
+ // but the registration will NOT survive a reload; say so.
+ console.warn('[registered-agents] failed to persist registration', err);
+ }
+}
+
+let state: RegisteredAgentsState | null = null;
+let detectedSuggestions: readonly RegisteredAgent[] = [];
+let presentedAgents: readonly RegisteredAgent[] | null = null;
+const listeners = new Set<() => void>();
+
+function currentState(): RegisteredAgentsState {
+ if (state === null) state = readFromStorage();
+ return state;
+}
+
+function setState(next: RegisteredAgentsState): void {
+ state = next;
+ presentedAgents = mergeRegisteredAgentSuggestions(next.agents, detectedSuggestions);
+ for (const listener of listeners) listener();
+}
+
+/** Re-read persisted state (cross-tab `storage` events; tests). */
+export function reloadRegisteredAgentsFromStorage(): void {
+ setState(readFromStorage());
+}
+
+if (typeof window !== 'undefined' && typeof window.addEventListener === 'function') {
+ window.addEventListener('storage', (event) => {
+ if (event.key === STORAGE_KEY || event.key === null) reloadRegisteredAgentsFromStorage();
+ });
+}
+
+function subscribe(listener: () => void): () => void {
+ listeners.add(listener);
+ return () => listeners.delete(listener);
+}
+
+const getAgents = (): readonly RegisteredAgent[] => {
+ if (presentedAgents === null) {
+ presentedAgents = mergeRegisteredAgentSuggestions(currentState().agents, detectedSuggestions);
+ }
+ return presentedAgents;
+};
+
+const getDefault = (): RegisteredAgent | null => {
+ const { agents, defaultKey } = currentState();
+ if (defaultKey === null) return null;
+ return agents.find((a) => agentKey(a) === defaultKey) ?? null;
+};
+
+/**
+ * Register (or refresh) an agent.
+ *
+ * `makeDefault` (the default) is the explicit-pick path: the agent jumps to the
+ * front and becomes the launch default — "the agent you chose last is your
+ * agent". Every launcher pick uses it.
+ *
+ * `makeDefault: false` is the visibility-only path used by the Settings toggle:
+ * it registers/refreshes the agent so it shows in the menus but leaves the
+ * launch default untouched (and doesn't reorder an agent already present).
+ * Enabling an agent in Settings must not silently repoint which agent the
+ * primary button launches — only an explicit launcher pick does that.
+ */
+export function registerAgent(
+ agent: RegisteredAgent,
+ options: { makeDefault?: boolean } = {},
+): void {
+ const { makeDefault = true } = options;
+ const key = agentKey(agent);
+ const current = currentState();
+ if (!makeDefault) {
+ const exists = current.agents.some((a) => agentKey(a) === key);
+ const agents = exists
+ ? current.agents.map((a) => (agentKey(a) === key ? agent : a))
+ : [...current.agents, agent];
+ const next: RegisteredAgentsState = { agents, defaultKey: current.defaultKey };
+ writeToStorage(next);
+ setState(next);
+ return;
+ }
+ const rest = current.agents.filter((a) => agentKey(a) !== key);
+ const next: RegisteredAgentsState = { agents: [agent, ...rest], defaultKey: key };
+ writeToStorage(next);
+ setState(next);
+}
+
+/**
+ * Add live, machine-detected suggestions after the explicit shortlist without
+ * persisting them. An explicit registration with the same id always wins.
+ */
+export function mergeRegisteredAgentSuggestions(
+ registered: readonly RegisteredAgent[],
+ suggestions: readonly RegisteredAgent[],
+): readonly RegisteredAgent[] {
+ const explicitKeys = new Set(registered.map(agentKey));
+ return [...registered, ...suggestions.filter((agent) => !explicitKeys.has(agentKey(agent)))];
+}
+
+/**
+ * Replace live server-host suggestions without persisting them or changing the
+ * explicit default. The app-level catalog detector owns this projection.
+ */
+export function setDetectedRegisteredAgentSuggestions(
+ suggestions: readonly RegisteredAgent[],
+): void {
+ detectedSuggestions = [...suggestions];
+ presentedAgents = mergeRegisteredAgentSuggestions(currentState().agents, detectedSuggestions);
+ for (const listener of listeners) listener();
+}
+
+/** Current explicit registrations plus live detected suggestions. */
+export function getRegisteredAgentOptions(): readonly RegisteredAgent[] {
+ return getAgents();
+}
+
+/** The default agent for pickerless launches; null before first registration. */
+export function getDefaultRegisteredAgent(): RegisteredAgent | null {
+ return getDefault();
+}
+
+/**
+ * When the user disables the agent that is currently the launch default, move
+ * the default off it — to the first still-enabled registered agent, or clear it
+ * when none remain. Keeps the composer from showing a just-disabled agent as the
+ * selected one. No-op when the disabled agent wasn't the default. Order is
+ * preserved (only `defaultKey` moves).
+ *
+ * `disabledKey` is `<source>:<id>`; `stillEnabled` reports whether a given agent
+ * is still enabled AFTER the disable (the disabled agent is excluded by key, so
+ * the predicate can read a pre-disable overrides snapshot safely).
+ */
+export function reassignDefaultIfDisabled(
+ disabledKey: string,
+ stillEnabled: (agent: RegisteredAgent) => boolean,
+): void {
+ const current = currentState();
+ if (current.defaultKey !== disabledKey) return;
+ const next = current.agents.find((a) => agentKey(a) !== disabledKey && stillEnabled(a)) ?? null;
+ const nextState: RegisteredAgentsState = {
+ agents: current.agents,
+ defaultKey: next ? agentKey(next) : null,
+ };
+ writeToStorage(nextState);
+ setState(nextState);
+}
+
+/**
+ * The registered agent a primary launcher should lead with: the current default
+ * when it is still in `enabled`, else the first enabled one (null if none). Lets
+ * every launcher surface avoid leading with an agent the user disabled.
+ */
+export function pickEffectiveDefaultAgent(
+ enabled: readonly RegisteredAgent[],
+ defaultAgent: RegisteredAgent | null,
+): RegisteredAgent | null {
+ if (
+ defaultAgent !== null &&
+ enabled.some((a) => a.source === defaultAgent.source && a.id === defaultAgent.id)
+ ) {
+ return defaultAgent;
+ }
+ return enabled[0] ?? null;
+}
+
+/**
+ * Update the cached name/icon/supported flag of already-registered agents in
+ * place, WITHOUT changing the default or list order. Used to hydrate the seeded
+ * defaults' placeholder metadata once the registry catalog resolves (the seed
+ * ships names only; the catalog carries display names, icon URLs, and whether a
+ * launchable build exists for this host).
+ */
+export function hydrateRegisteredAgentMeta(
+ patches: ReadonlyArray<Pick<RegisteredAgent, 'source' | 'id'> & Partial<RegisteredAgent>>,
+): void {
+ const byKey = new Map(patches.map((p) => [agentKey(p), p]));
+ const current = currentState();
+ let changed = false;
+ const agents = current.agents.map((agent) => {
+ const patch = byKey.get(agentKey(agent));
+ if (patch === undefined) return agent;
+ const nextName = patch.name ?? agent.name;
+ const nextIconUrl = patch.iconUrl ?? agent.iconUrl;
+ const nextSupported = patch.supported ?? agent.supported;
+ if (
+ nextName === agent.name &&
+ nextIconUrl === agent.iconUrl &&
+ nextSupported === agent.supported
+ )
+ return agent;
+ changed = true;
+ return {
+ ...agent,
+ name: nextName,
+ ...(nextIconUrl !== undefined ? { iconUrl: nextIconUrl } : {}),
+ ...(nextSupported !== undefined ? { supported: nextSupported } : {}),
+ };
+ });
+ if (!changed) return;
+ const next: RegisteredAgentsState = { agents, defaultKey: current.defaultKey };
+ writeToStorage(next);
+ setState(next);
+}
+
+/** Reactive explicit registrations followed by live detected suggestions. */
+export function useRegisteredAgents(): readonly RegisteredAgent[] {
+ return useSyncExternalStore(subscribe, getAgents, getAgents);
+}
+
+/** Reactive default agent; null before the first catalog pick. */
+export function useDefaultRegisteredAgent(): RegisteredAgent | null {
+ return useSyncExternalStore(subscribe, getDefault, getDefault);
+}
diff --git a/packages/app/src/lib/acp/terminal-text.test.ts b/packages/app/src/lib/acp/terminal-text.test.ts
new file mode 100644
index 000000000..b42f552d5
--- /dev/null
+++ b/packages/app/src/lib/acp/terminal-text.test.ts
@@ -0,0 +1,41 @@
+import { describe, expect, test } from 'vitest';
+import { renderTerminalText, stripAnsi } from './terminal-text';
+
+describe('stripAnsi', () => {
+ test('removes SGR color sequences', () => {
+ expect(stripAnsi('\x1b[32mPASS\x1b[0m suite')).toBe('PASS suite');
+ });
+
+ test('removes cursor movement and erase sequences', () => {
+ expect(stripAnsi('progress\x1b[2K\x1b[1G100%')).toBe('progress100%');
+ });
+
+ test('removes OSC sequences (BEL- and ST-terminated)', () => {
+ expect(stripAnsi('\x1b]0;window title\x07visible')).toBe('visible');
+ expect(stripAnsi('\x1b]8;;https://example.com\x1b\\link\x1b]8;;\x1b\\')).toBe('link');
+ });
+
+ test('leaves plain text untouched', () => {
+ expect(stripAnsi('just text — no escapes')).toBe('just text — no escapes');
+ });
+});
+
+describe('renderTerminalText', () => {
+ test('a carriage return restarts its line (progress bars show final frame)', () => {
+ expect(renderTerminalText('downloading 10%\rdownloading 50%\rdownloading 100%\ndone')).toBe(
+ 'downloading 100%\ndone',
+ );
+ });
+
+ test('strips ANSI and resolves \\r together', () => {
+ expect(renderTerminalText('\x1b[33m10%\x1b[0m\r\x1b[32m100%\x1b[0m')).toBe('100%');
+ });
+
+ test('CRLF line endings keep their line content', () => {
+ expect(renderTerminalText('hello\r\ndone\r\n')).toBe('hello\ndone\n');
+ });
+
+ test('a redraw with a trailing \\r still shows the final frame', () => {
+ expect(renderTerminalText('10%\r100%\r\nnext')).toBe('100%\nnext');
+ });
+});
diff --git a/packages/app/src/lib/acp/terminal-text.ts b/packages/app/src/lib/acp/terminal-text.ts
new file mode 100644
index 000000000..1c0e616c0
--- /dev/null
+++ b/packages/app/src/lib/acp/terminal-text.ts
@@ -0,0 +1,30 @@
+/**
+ * Normalize raw terminal output for the transcript's terminal card: strip
+ * ANSI escape sequences (colors, cursor movement) and resolve carriage
+ * returns the way a terminal would — a `\r` restarts its line, so progress
+ * bars render as their final state instead of hundreds of stacked frames.
+ */
+
+// CSI (colors/cursor), OSC (titles/hyperlinks, BEL- or ST-terminated), and
+// single-character escapes. Sufficient for display cleanup; not a parser.
+// biome-ignore lint/suspicious/noControlCharactersInRegex: ESC/BEL bytes are exactly what this strips
+const ANSI_PATTERN = /\x1b\[[0-9;?]*[ -/]*[@-~]|\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)|\x1b[@-Z\\-_]/g;
+
+export function stripAnsi(text: string): string {
+ return text.replace(ANSI_PATTERN, '');
+}
+
+export function renderTerminalText(text: string): string {
+ const stripped = stripAnsi(text);
+ return stripped
+ .split('\n')
+ .map((line) => {
+ // A trailing `\r` is just CRLF line-ending residue — dropping the text
+ // before it would blank every line of ordinary Windows output. Only a
+ // `\r` FOLLOWED by more characters is a redraw to collapse.
+ const trimmed = line.replace(/\r+$/, '');
+ const idx = trimmed.lastIndexOf('\r');
+ return idx === -1 ? trimmed : trimmed.slice(idx + 1);
+ })
+ .join('\n');
+}
diff --git a/packages/app/src/lib/acp/thread-client.test.ts b/packages/app/src/lib/acp/thread-client.test.ts
new file mode 100644
index 000000000..24a731915
--- /dev/null
+++ b/packages/app/src/lib/acp/thread-client.test.ts
@@ -0,0 +1,163 @@
+import { readFileSync } from 'node:fs';
+import type {
+ ThreadEvent,
+ ThreadInfo,
+ ThreadServerFrame,
+} from '@inkeep/open-knowledge-core/acp/thread-protocol';
+import { describe, expect, test } from 'vitest';
+import { AgentThreadClient, ThreadChannelUnavailableError } from './thread-client';
+
+/**
+ * Regression coverage for the agent-thread store hooks.
+ *
+ * These hooks feed `useSyncExternalStore`, and the app builds with React
+ * Compiler enabled. A hook that CALLS `useSyncExternalStore(...)` for its
+ * subscription but then returns a *separate* `client.getX()` (discarding the
+ * subscription result) has no reactive input the compiler can see, so the
+ * compiler memoizes the hook's return value to the first — empty — snapshot and
+ * the UI never updates. That exact shape once shipped and made the agent-thread
+ * dock never display created threads.
+ *
+ * The compiler runs at BUILD time, not under `bun test`, so a render test can't
+ * catch it — a broken hook still "works" in the test env. Hence the two guards
+ * below: a runtime check that the store getter is a stable snapshot (the
+ * property the fix relies on) and a source check that each hook returns the
+ * `useSyncExternalStore` value directly.
+ */
+
+describe('AgentThreadClient store snapshots', () => {
+ test('getThreads returns a referentially stable snapshot until the store changes', () => {
+ const client = new AgentThreadClient();
+ const first = client.getThreads();
+ // A fresh `[...].map()` on every call would loop useSyncExternalStore and, with
+ // React Compiler on, let the hook memoize the first snapshot forever. The
+ // getter must return the same reference while the store version is unchanged.
+ expect(client.getThreads()).toBe(first);
+ expect(client.getThreads()).toBe(first);
+ });
+
+ test('getConnectionStatus is idle before any URL is set', () => {
+ expect(new AgentThreadClient().getConnectionStatus()).toBe('idle');
+ });
+});
+
+describe('batched event delivery', () => {
+ const info: ThreadInfo = {
+ threadId: 't1',
+ agent: { id: 'a', name: 'A', source: 'custom' },
+ title: 'A',
+ status: 'ready',
+ createdAt: 1,
+ lastActivityAt: 1,
+ modes: null,
+ configOptions: null,
+ lastSeq: -1,
+ };
+ const ev = (i: number): ThreadEvent => ({ kind: 'user_message', content: `m${i}`, ts: i });
+
+ function makeClient(): { client: AgentThreadClient; frame: (f: ThreadServerFrame) => void } {
+ const client = new AgentThreadClient();
+ const internals = client as unknown as { handleFrame: (f: ThreadServerFrame) => void };
+ internals.handleFrame.call(client, { op: 'subscribed', threadId: 't1', fromSeq: 0, info });
+ return { client, frame: (f) => internals.handleFrame.call(client, f) };
+ }
+
+ test('an events frame appends the batch with a single store notification', () => {
+ const { client, frame } = makeClient();
+ let notifications = 0;
+ client.subscribe(() => {
+ notifications += 1;
+ });
+ frame({ op: 'events', threadId: 't1', fromSeq: 0, events: [ev(0), ev(1), ev(2)] });
+ expect(notifications).toBe(1);
+ expect(client.getThread('t1')?.events).toHaveLength(3);
+ expect(client.getThread('t1')?.lastSeq).toBe(2);
+ });
+
+ test('replay overlap dedups by seq: only genuinely new events append', () => {
+ const { client, frame } = makeClient();
+ frame({ op: 'events', threadId: 't1', fromSeq: 0, events: [ev(0), ev(1), ev(2)] });
+ // Overlapping window (a flush racing a replay) — only seq 3 is new.
+ frame({ op: 'events', threadId: 't1', fromSeq: 1, events: [ev(1), ev(2), ev(3)] });
+ expect(client.getThread('t1')?.events).toHaveLength(4);
+ expect(client.getThread('t1')?.lastSeq).toBe(3);
+ // A fully-stale frame is a no-op — no bump, no growth.
+ let notifications = 0;
+ client.subscribe(() => {
+ notifications += 1;
+ });
+ frame({ op: 'events', threadId: 't1', fromSeq: 0, events: [ev(0)] });
+ expect(notifications).toBe(0);
+ expect(client.getThread('t1')?.events).toHaveLength(4);
+ });
+
+ test('single event frames still work (terminal close notice path)', () => {
+ const { client, frame } = makeClient();
+ frame({ op: 'event', threadId: 't1', seq: 0, event: ev(0) });
+ expect(client.getThread('t1')?.events).toHaveLength(1);
+ expect(client.getThread('t1')?.lastSeq).toBe(0);
+ });
+});
+
+describe('createThread channel wait', () => {
+ test('rejects with ThreadChannelUnavailableError when no URL is ever bound', async () => {
+ const client = new AgentThreadClient();
+ // Private-field poke: shrink the wait so the test doesn't sit out the
+ // full production timeout. The wait path itself is what's under test.
+ const waitFor = (
+ client as unknown as { waitForOpen: (ms: number) => Promise<void> }
+ ).waitForOpen.bind(client);
+ await expect(waitFor(30)).rejects.toBeInstanceOf(ThreadChannelUnavailableError);
+ });
+
+ test('waitForOpen resolves when the channel opens during the wait', async () => {
+ const client = new AgentThreadClient();
+ const internals = client as unknown as {
+ waitForOpen: (ms: number) => Promise<void>;
+ ws: { readyState: number } | null;
+ bump: () => void;
+ };
+ const pending = internals.waitForOpen.call(client, 1_000);
+ // Simulate the socket transitioning to OPEN, then any store bump (the
+ // real client bumps via setStatus('open')).
+ internals.ws = { readyState: WebSocket.OPEN };
+ internals.bump.call(client);
+ await expect(pending).resolves.toBeUndefined();
+ });
+});
+
+describe('store hooks return the useSyncExternalStore subscription value (React Compiler safety)', () => {
+ const source = readFileSync(new URL('./thread-client.ts', import.meta.url), 'utf8');
+
+ function hookBody(name: string): string {
+ const start = source.indexOf(`export function ${name}(`);
+ expect(start).toBeGreaterThanOrEqual(0);
+ const open = source.indexOf('{', start);
+ let depth = 0;
+ for (let i = open; i < source.length; i++) {
+ if (source[i] === '{') depth += 1;
+ else if (source[i] === '}') {
+ depth -= 1;
+ if (depth === 0) return source.slice(open, i + 1);
+ }
+ }
+ throw new Error(`unterminated body for ${name}`);
+ }
+
+ for (const hook of [
+ 'useAgentThreads',
+ 'useAgentThread',
+ 'useAgentThreadConnection',
+ 'useOpenAgentThreadTabs',
+ 'useArchivedAgentThreads',
+ ]) {
+ test(`${hook} returns useSyncExternalStore(...) rather than discarding it`, () => {
+ const body = hookBody(hook);
+ // Must return the subscription result…
+ expect(body).toContain('return useSyncExternalStore(');
+ // …and must NOT call it as a bare statement and then return a separate
+ // store read (the shape the React Compiler memoizes into staleness).
+ expect(body).not.toMatch(/useSyncExternalStore\([^;]*\);\s*return\s+client\.get/);
+ });
+ }
+});
diff --git a/packages/app/src/lib/acp/thread-client.ts b/packages/app/src/lib/acp/thread-client.ts
new file mode 100644
index 000000000..218ae0019
--- /dev/null
+++ b/packages/app/src/lib/acp/thread-client.ts
@@ -0,0 +1,661 @@
+/**
+ * Client for the `/collab/thread` WebSocket — the app-side half of the ACP
+ * thread transport.
+ *
+ * One module-scope client per window holds a single WS, a map of thread
+ * states (info + copy-on-write event log), and a listener set for
+ * `useSyncExternalStore` consumers. Recovery contract: on (re)connect it
+ * sends `list`, then `subscribe { sinceSeq: lastSeq + 1 }` for every thread —
+ * the server replays the missed tail from its retained log, so a reload or a
+ * dropped socket loses nothing that the server still holds.
+ *
+ * The URL comes from the same `/api/config` resolution the CRDT provider
+ * uses (`useCollabUrl`), swapped onto the `/collab/thread` path — bind it via
+ * `AgentThreadClientBinder` (mounted once in EditorPane).
+ */
+
+import type {
+ ThreadClientFrame,
+ ThreadEvent,
+ ThreadInfo,
+ ThreadServerFrame,
+} from '@inkeep/open-knowledge-core/acp/thread-protocol';
+import { t } from '@lingui/core/macro';
+import { useSyncExternalStore } from 'react';
+import { toast } from 'sonner';
+import { type ThreadRenderModel, ThreadRenderModelBuilder } from './thread-event-model';
+
+export interface ThreadState {
+ readonly info: ThreadInfo;
+ /** Copy-on-write: a new array reference per appended event. */
+ readonly events: readonly ThreadEvent[];
+ readonly lastSeq: number;
+}
+
+export type ThreadConnectionStatus = 'idle' | 'connecting' | 'open' | 'closed';
+
+interface PendingCreate {
+ resolve: (info: ThreadInfo) => void;
+ reject: (err: Error) => void;
+ timer: ReturnType<typeof setTimeout>;
+}
+
+const RECONNECT_MIN_MS = 500;
+const RECONNECT_MAX_MS = 15_000;
+const CREATE_TIMEOUT_MS = 30_000;
+/** Resume resolves only after the full agent respawn + session handshake (npx cold boots take a while). */
+const RESUME_TIMEOUT_MS = 90_000;
+const CHANNEL_WAIT_MS = 8_000;
+
+/** A `resume` op the server rejected; `code` distinguishes "this agent can't
+ * resume old sessions" (offer a fresh thread) from transient failures. */
+export class ThreadResumeError extends Error {
+ readonly code: string;
+ constructor(code: string, message: string) {
+ super(message);
+ this.name = 'ThreadResumeError';
+ this.code = code;
+ }
+}
+
+/**
+ * The thread channel could not be opened (no URL bound yet, the server is
+ * down, or it predates the `/collab/thread` endpoint). Callers map this to a
+ * localized, actionable message — the raw `message` is diagnostic only.
+ */
+export class ThreadChannelUnavailableError extends Error {
+ constructor() {
+ super('agent-thread channel is not connected');
+ this.name = 'ThreadChannelUnavailableError';
+ }
+}
+
+export class AgentThreadClient {
+ private url: string | null = null;
+ private ws: WebSocket | null = null;
+ private reconnectDelay = RECONNECT_MIN_MS;
+ private reconnectTimer: ReturnType<typeof setTimeout> | null = null;
+ private threads = new Map<string, ThreadState>();
+ private listeners = new Set<() => void>();
+ private pendingCreates = new Map<string, PendingCreate>();
+ private pendingResumes = new Map<string, PendingCreate>();
+ /** Archived threads the user explicitly opened as tabs this session. */
+ private openedArchived = new Set<string>();
+ private reqCounter = 0;
+ private status: ThreadConnectionStatus = 'idle';
+ /** Bumped on every store change; the useSyncExternalStore snapshot. */
+ private version = 0;
+
+ /** Set (or clear) the WS URL. Reconnects when it changes. */
+ setUrl(url: string | null): void {
+ if (url === this.url) return;
+ this.url = url;
+ this.teardownSocket();
+ if (url !== null) this.connect();
+ else this.setStatus('idle');
+ }
+
+ subscribe = (listener: () => void): (() => void) => {
+ this.listeners.add(listener);
+ return () => this.listeners.delete(listener);
+ };
+
+ // Version-keyed snapshot cache. `useSyncExternalStore` requires getSnapshot to
+ // return a value that is referentially stable between store bumps. Returning a
+ // fresh array on every call would loop the store; worse, with React Compiler
+ // enabled, a hook that CALLS `client.getThreads()` outside the
+ // `useSyncExternalStore` return (discarding its result) has no tracked reactive
+ // input, so the compiler memoizes the hook's result to the first (empty)
+ // snapshot and the UI never updates. So the getters are bound fields returning
+ // references that change only when `version` advances, and the hooks return the
+ // store value directly (see the hooks at the bottom of this file).
+ private threadsSnapshot: ThreadInfo[] = [];
+ private threadsSnapshotVersion = -1;
+ getThreads = (): ThreadInfo[] => {
+ if (this.threadsSnapshotVersion !== this.version) {
+ this.threadsSnapshot = [...this.threads.values()]
+ .map((t) => t.info)
+ .sort((a, b) => a.createdAt - b.createdAt);
+ this.threadsSnapshotVersion = this.version;
+ }
+ return this.threadsSnapshot;
+ };
+
+ // Same version-keyed stability contract as getThreads (see above).
+ private openTabsSnapshot: ThreadInfo[] = [];
+ private openTabsSnapshotVersion = -1;
+ /** Dock tabs: every live thread, plus archived ones explicitly opened. */
+ getOpenTabs = (): ThreadInfo[] => {
+ if (this.openTabsSnapshotVersion !== this.version) {
+ this.openTabsSnapshot = [...this.threads.values()]
+ .map((t) => t.info)
+ .filter((info) => info.archived !== true || this.openedArchived.has(info.threadId))
+ .sort((a, b) => a.createdAt - b.createdAt);
+ this.openTabsSnapshotVersion = this.version;
+ }
+ return this.openTabsSnapshot;
+ };
+
+ private archivedSnapshot: ThreadInfo[] = [];
+ private archivedSnapshotVersion = -1;
+ /** History-menu list: archived threads, most recent activity first. */
+ getArchivedThreads = (): ThreadInfo[] => {
+ if (this.archivedSnapshotVersion !== this.version) {
+ this.archivedSnapshot = [...this.threads.values()]
+ .map((t) => t.info)
+ .filter((info) => info.archived === true)
+ .sort((a, b) => b.lastActivityAt - a.lastActivityAt);
+ this.archivedSnapshotVersion = this.version;
+ }
+ return this.archivedSnapshot;
+ };
+
+ // The stored `ThreadState` is replaced (new object) on every mutation and left
+ // untouched otherwise, so it is a valid stable snapshot as-is.
+ getThread = (threadId: string): ThreadState | null => this.threads.get(threadId) ?? null;
+
+ /**
+ * Render model per thread, folded incrementally as events arrive. Lazy: a
+ * thread nobody renders (dock hidden, background tab) never pays the fold.
+ * The builder caches its snapshot, so repeated calls without new events
+ * return the same reference — the `useSyncExternalStore` contract.
+ */
+ private readonly modelBuilders = new Map<string, ThreadRenderModelBuilder>();
+ getThreadModel = (threadId: string): ThreadRenderModel | null => {
+ const state = this.threads.get(threadId);
+ if (state === undefined) return null;
+ let builder = this.modelBuilders.get(threadId);
+ if (builder === undefined) {
+ builder = new ThreadRenderModelBuilder();
+ this.modelBuilders.set(threadId, builder);
+ }
+ return builder.sync(state.events);
+ };
+
+ getConnectionStatus = (): ThreadConnectionStatus => this.status;
+
+ async createThread(params: {
+ agent: { source: 'registry' | 'custom'; id: string };
+ prompt?: string;
+ docName?: string;
+ titleHint?: string;
+ }): Promise<ThreadInfo> {
+ // A click can land while the socket is still connecting, mid-reconnect
+ // backoff, or before the region has bound the URL. Fast-track a connect
+ // attempt and wait briefly for the channel instead of failing instantly.
+ this.connectNow();
+ await this.waitForOpen(CHANNEL_WAIT_MS);
+ this.reqCounter += 1;
+ const reqId = `create-${this.reqCounter}`;
+ const promise = new Promise<ThreadInfo>((resolve, reject) => {
+ const timer = setTimeout(() => {
+ this.pendingCreates.delete(reqId);
+ reject(new Error('thread creation timed out'));
+ }, CREATE_TIMEOUT_MS);
+ this.pendingCreates.set(reqId, { resolve, reject, timer });
+ });
+ this.send({ op: 'create', reqId, ...params });
+ return promise;
+ }
+
+ prompt(threadId: string, content: string): void {
+ this.reqCounter += 1;
+ this.send({ op: 'prompt', threadId, reqId: `prompt-${this.reqCounter}`, content });
+ }
+
+ respondPermission(
+ threadId: string,
+ requestId: string,
+ outcome: { kind: 'selected'; optionId: string } | { kind: 'cancelled' },
+ ): void {
+ this.send({ op: 'permission_response', threadId, requestId, outcome });
+ }
+
+ respondRuntimeConsent(
+ threadId: string,
+ requestId: string,
+ outcome: { kind: 'granted'; remember?: boolean } | { kind: 'declined'; remember?: boolean },
+ ): void {
+ this.send({ op: 'runtime_consent_response', threadId, requestId, outcome });
+ }
+
+ cancel(threadId: string): void {
+ this.send({ op: 'cancel', threadId });
+ }
+
+ setMode(threadId: string, modeId: string): void {
+ this.send({ op: 'set_mode', threadId, modeId });
+ }
+
+ /**
+ * Manually retitle a thread (tab rename). Blank titles are a no-op; the
+ * server clamps and confirms via an `info` frame, so no optimistic update.
+ */
+ renameThread(threadId: string, title: string): void {
+ const trimmed = title.trim();
+ if (trimmed === '') return;
+ this.send({ op: 'rename', threadId, title: trimmed });
+ }
+
+ setConfigOption(threadId: string, configId: string, value: string | boolean): void {
+ this.send({ op: 'set_config_option', threadId, configId, value });
+ }
+
+ closeThread(threadId: string): void {
+ const state = this.threads.get(threadId);
+ if (state?.info.archived === true) {
+ // Archived tabs close locally — the server-side record (and its
+ // transcript) stays. Drop the replayed events so a later reopen
+ // replays fresh from disk instead of accreting.
+ this.send({ op: 'unsubscribe', threadId });
+ this.openedArchived.delete(threadId);
+ this.modelBuilders.delete(threadId);
+ this.threads.set(threadId, { info: state.info, events: [], lastSeq: -1 });
+ this.bump();
+ return;
+ }
+ this.send({ op: 'close', threadId });
+ // Drop local state immediately — the tab is gone; the server confirms via
+ // the refreshed `threads` frame (which re-adds it as archived history).
+ this.openedArchived.delete(threadId);
+ this.modelBuilders.delete(threadId);
+ if (this.threads.delete(threadId)) this.bump();
+ }
+
+ /** Open an archived thread as a tab, replaying its transcript from disk. */
+ openArchivedThread(threadId: string): void {
+ const state = this.threads.get(threadId);
+ if (state === undefined || state.info.archived !== true) return;
+ if (this.openedArchived.has(threadId)) return;
+ this.openedArchived.add(threadId);
+ this.send({ op: 'subscribe', threadId, sinceSeq: state.lastSeq + 1 });
+ this.bump();
+ }
+
+ /** Permanently delete an archived thread's transcript. */
+ deleteThread(threadId: string): void {
+ this.send({ op: 'delete', threadId });
+ this.openedArchived.delete(threadId);
+ this.modelBuilders.delete(threadId);
+ if (this.threads.delete(threadId)) this.bump();
+ }
+
+ /**
+ * Resume an archived thread (respawn agent + reconnect its session),
+ * optionally sending `prompt` as the first turn. Resolves once the thread
+ * is live again; rejects with {@link ThreadResumeError} on failure —
+ * `code === 'resume-unsupported'` means the agent can't continue old
+ * sessions and the UI should offer a fresh thread.
+ */
+ async resumeThread(threadId: string, prompt?: string): Promise<ThreadInfo> {
+ this.connectNow();
+ await this.waitForOpen(CHANNEL_WAIT_MS);
+ this.reqCounter += 1;
+ const reqId = `resume-${this.reqCounter}`;
+ const promise = new Promise<ThreadInfo>((resolve, reject) => {
+ const timer = setTimeout(() => {
+ this.pendingResumes.delete(reqId);
+ reject(new ThreadResumeError('timeout', 'resume timed out'));
+ }, RESUME_TIMEOUT_MS);
+ this.pendingResumes.set(reqId, { resolve, reject, timer });
+ });
+ this.send({ op: 'resume', threadId, reqId, prompt });
+ return promise;
+ }
+
+ // ── internals ─────────────────────────────────────────────────────────
+
+ /**
+ * Connect immediately if a URL is bound and no socket exists — cancels a
+ * pending reconnect backoff (up to 15s) so a user-initiated action doesn't
+ * sit out the timer. No-op while a socket is connecting or open.
+ */
+ private connectNow(): void {
+ if (this.url === null || this.ws !== null) return;
+ if (this.reconnectTimer !== null) {
+ clearTimeout(this.reconnectTimer);
+ this.reconnectTimer = null;
+ }
+ this.reconnectDelay = RECONNECT_MIN_MS;
+ this.connect();
+ }
+
+ /** Resolve once the socket is OPEN; reject after `timeoutMs`. */
+ private waitForOpen(timeoutMs: number): Promise<void> {
+ if (this.ws !== null && this.ws.readyState === WebSocket.OPEN) return Promise.resolve();
+ return new Promise((resolve, reject) => {
+ const settle = (ok: boolean) => {
+ clearTimeout(timer);
+ unsubscribe();
+ if (ok) resolve();
+ else reject(new ThreadChannelUnavailableError());
+ };
+ const unsubscribe = this.subscribe(() => {
+ if (this.ws !== null && this.ws.readyState === WebSocket.OPEN) settle(true);
+ });
+ const timer = setTimeout(() => settle(false), timeoutMs);
+ });
+ }
+
+ private connect(): void {
+ if (this.url === null) return;
+ this.setStatus('connecting');
+ let ws: WebSocket;
+ try {
+ ws = new WebSocket(this.url);
+ } catch {
+ this.scheduleReconnect();
+ return;
+ }
+ this.ws = ws;
+ ws.onopen = () => {
+ if (this.ws !== ws) return;
+ this.reconnectDelay = RECONNECT_MIN_MS;
+ this.setStatus('open');
+ this.send({ op: 'list' });
+ // Re-attach to every LIVE thread (and any archived tab the user has
+ // open), replaying whatever we missed. Unopened archived threads must
+ // not re-subscribe — that would replay the whole retained archive on
+ // every reconnect.
+ for (const [threadId, state] of this.threads) {
+ if (state.info.archived === true && !this.openedArchived.has(threadId)) continue;
+ this.send({ op: 'subscribe', threadId, sinceSeq: state.lastSeq + 1 });
+ }
+ };
+ ws.onmessage = (event) => {
+ if (this.ws !== ws) return;
+ if (typeof event.data !== 'string') return;
+ let frame: ThreadServerFrame;
+ try {
+ frame = JSON.parse(event.data) as ThreadServerFrame;
+ } catch {
+ return;
+ }
+ this.handleFrame(frame);
+ };
+ ws.onclose = () => {
+ if (this.ws !== ws) return;
+ this.ws = null;
+ this.setStatus('closed');
+ this.scheduleReconnect();
+ };
+ ws.onerror = () => {
+ // onclose follows; nothing to do here.
+ };
+ }
+
+ private teardownSocket(): void {
+ if (this.reconnectTimer !== null) {
+ clearTimeout(this.reconnectTimer);
+ this.reconnectTimer = null;
+ }
+ // Reject in-flight creates and resumes immediately — the socket they
+ // were issued on is gone, so letting them ride out their create/resume
+ // timeouts would leak the timers and hand callers a late, misleading
+ // timeout error.
+ for (const pending of this.pendingCreates.values()) {
+ clearTimeout(pending.timer);
+ pending.reject(new ThreadChannelUnavailableError());
+ }
+ this.pendingCreates.clear();
+ for (const pending of this.pendingResumes.values()) {
+ clearTimeout(pending.timer);
+ pending.reject(new ThreadChannelUnavailableError());
+ }
+ this.pendingResumes.clear();
+ const ws = this.ws;
+ this.ws = null;
+ if (ws !== null) {
+ try {
+ ws.close();
+ } catch {
+ // Already closed.
+ }
+ }
+ }
+
+ private scheduleReconnect(): void {
+ if (this.url === null || this.reconnectTimer !== null) return;
+ const delay = this.reconnectDelay;
+ this.reconnectDelay = Math.min(this.reconnectDelay * 2, RECONNECT_MAX_MS);
+ this.reconnectTimer = setTimeout(() => {
+ this.reconnectTimer = null;
+ this.connect();
+ }, delay);
+ }
+
+ private send(frame: ThreadClientFrame): void {
+ const ws = this.ws;
+ if (ws === null || ws.readyState !== WebSocket.OPEN) return;
+ try {
+ ws.send(JSON.stringify(frame));
+ } catch {
+ // The close handler owns recovery.
+ }
+ }
+
+ private handleFrame(frame: ThreadServerFrame): void {
+ switch (frame.op) {
+ case 'created': {
+ const pending = this.pendingCreates.get(frame.reqId);
+ if (pending !== undefined) {
+ this.pendingCreates.delete(frame.reqId);
+ clearTimeout(pending.timer);
+ pending.resolve(frame.info);
+ }
+ this.upsertInfo(frame.info);
+ return;
+ }
+ case 'threads': {
+ const seen = new Set<string>();
+ for (const info of frame.threads) {
+ seen.add(info.threadId);
+ const known = this.threads.has(info.threadId);
+ this.upsertInfo(info);
+ // A LIVE thread we did not know about (fresh reload) — attach to
+ // it. Archived threads are history: subscribing here would replay
+ // every retained transcript on every reload, so they attach only
+ // when explicitly opened.
+ if (!known && info.archived !== true) {
+ this.send({ op: 'subscribe', threadId: info.threadId, sinceSeq: 0 });
+ }
+ }
+ let dropped = false;
+ // Snapshot the keys before deleting during iteration.
+ for (const threadId of Array.from(this.threads.keys())) {
+ if (!seen.has(threadId)) {
+ this.threads.delete(threadId);
+ this.modelBuilders.delete(threadId);
+ this.openedArchived.delete(threadId);
+ dropped = true;
+ }
+ }
+ if (dropped) this.bump();
+ return;
+ }
+ case 'resumed': {
+ const pending = this.pendingResumes.get(frame.reqId);
+ if (pending !== undefined) {
+ this.pendingResumes.delete(frame.reqId);
+ clearTimeout(pending.timer);
+ pending.resolve(frame.info);
+ }
+ this.upsertInfo(frame.info);
+ return;
+ }
+ case 'subscribed': {
+ this.upsertInfo(frame.info);
+ return;
+ }
+ case 'info': {
+ this.upsertInfo(frame.info);
+ return;
+ }
+ case 'event': {
+ this.appendEvents(frame.threadId, frame.seq, [frame.event]);
+ return;
+ }
+ case 'events': {
+ this.appendEvents(frame.threadId, frame.fromSeq, frame.events);
+ return;
+ }
+ case 'error': {
+ if (frame.reqId !== undefined) {
+ const pending = this.pendingCreates.get(frame.reqId);
+ if (pending !== undefined) {
+ this.pendingCreates.delete(frame.reqId);
+ clearTimeout(pending.timer);
+ pending.reject(new Error(frame.message));
+ return;
+ }
+ const pendingResume = this.pendingResumes.get(frame.reqId);
+ if (pendingResume !== undefined) {
+ this.pendingResumes.delete(frame.reqId);
+ clearTimeout(pendingResume.timer);
+ pendingResume.reject(new ThreadResumeError(frame.code, frame.message));
+ return;
+ }
+ if (frame.reqId.startsWith('prompt-')) {
+ // A rejected prompt (e.g. a turn was already running) never
+ // reaches the transcript — the composer already cleared, so
+ // without feedback the user's message just vanishes.
+ toast.error(t`Message not sent: ${frame.message}`);
+ return;
+ }
+ }
+ // Thread-scoped errors surface through status events; log the rest.
+ console.warn('[agent-threads] server error frame:', frame.code, frame.message);
+ return;
+ }
+ default:
+ return;
+ }
+ }
+
+ /**
+ * Append consecutive events starting at `fromSeq`, skipping any the store
+ * already has (replay/flush overlap) — one array copy and one listener
+ * notification per batch, however many events arrived.
+ */
+ private appendEvents(threadId: string, fromSeq: number, events: readonly ThreadEvent[]): void {
+ const state = this.threads.get(threadId);
+ if (state === undefined || events.length === 0) return;
+ const skip = Math.max(state.lastSeq + 1 - fromSeq, 0);
+ if (skip >= events.length) return;
+ const fresh = skip === 0 ? events : events.slice(skip);
+ let info = state.info;
+ for (const event of fresh) {
+ info = applyEventToInfo(info, event);
+ }
+ this.threads.set(threadId, {
+ info,
+ events: [...state.events, ...fresh],
+ lastSeq: fromSeq + events.length - 1,
+ });
+ this.bump();
+ }
+
+ private upsertInfo(info: ThreadInfo): void {
+ const existing = this.threads.get(info.threadId);
+ if (existing === undefined) {
+ this.threads.set(info.threadId, { info, events: [], lastSeq: -1 });
+ } else if (info.archived === true && existing.info.archived !== true) {
+ // Live → archived (server-side close/reap). The tab derivation drops it
+ // and the retained events would only go stale — free them so a later
+ // history open replays fresh from disk.
+ this.openedArchived.delete(info.threadId);
+ this.modelBuilders.delete(info.threadId);
+ this.threads.set(info.threadId, { info, events: [], lastSeq: -1 });
+ } else {
+ this.threads.set(info.threadId, { ...existing, info });
+ }
+ this.bump();
+ }
+
+ private setStatus(status: ThreadConnectionStatus): void {
+ if (this.status === status) return;
+ this.status = status;
+ this.bump();
+ }
+
+ private bump(): void {
+ this.version += 1;
+ for (const listener of this.listeners) listener();
+ }
+}
+
+/** Keep tab labels/status live without waiting for the next `info` frame. */
+function applyEventToInfo(info: ThreadInfo, event: ThreadEvent): ThreadInfo {
+ switch (event.kind) {
+ case 'status':
+ return { ...info, status: event.status, lastActivityAt: event.ts };
+ case 'title_changed':
+ return { ...info, title: event.title, lastActivityAt: event.ts };
+ default:
+ return { ...info, lastActivityAt: event.ts };
+ }
+}
+
+const client = new AgentThreadClient();
+
+export function getAgentThreadClient(): AgentThreadClient {
+ return client;
+}
+
+/** Reactive list of thread infos (creation order). */
+export function useAgentThreads(): ThreadInfo[] {
+ return useSyncExternalStore(client.subscribe, client.getThreads, client.getThreads);
+}
+
+/** Reactive dock-tab list: live threads + explicitly opened archived ones. */
+export function useOpenAgentThreadTabs(): ThreadInfo[] {
+ return useSyncExternalStore(client.subscribe, client.getOpenTabs, client.getOpenTabs);
+}
+
+/** Reactive archived-thread list (history menu), latest activity first. */
+export function useArchivedAgentThreads(): ThreadInfo[] {
+ return useSyncExternalStore(
+ client.subscribe,
+ client.getArchivedThreads,
+ client.getArchivedThreads,
+ );
+}
+
+/** Reactive state (info + events) for one thread; null when unknown. */
+export function useAgentThread(threadId: string): ThreadState | null {
+ const getSnapshot = () => client.getThread(threadId);
+ return useSyncExternalStore(client.subscribe, getSnapshot, getSnapshot);
+}
+
+/**
+ * Reactive render model for one thread; null when unknown. Incrementally
+ * folded in the store — consuming this instead of re-folding
+ * `state.events` in render is what keeps long streaming transcripts O(new
+ * events) per update.
+ */
+export function useAgentThreadModel(threadId: string): ThreadRenderModel | null {
+ const getSnapshot = () => client.getThreadModel(threadId);
+ return useSyncExternalStore(client.subscribe, getSnapshot, getSnapshot);
+}
+
+/** Reactive connection status for the thread channel. */
+export function useAgentThreadConnection(): ThreadConnectionStatus {
+ return useSyncExternalStore(
+ client.subscribe,
+ client.getConnectionStatus,
+ client.getConnectionStatus,
+ );
+}
+
+/** Derive the thread WS URL from the resolved collab URL. */
+export function threadUrlFromCollabUrl(collabUrl: string | null): string | null {
+ if (collabUrl === null) return null;
+ try {
+ const url = new URL(collabUrl);
+ url.pathname = '/collab/thread';
+ url.search = '';
+ return url.toString();
+ } catch {
+ return null;
+ }
+}
diff --git a/packages/app/src/lib/acp/thread-event-model.incremental.test.ts b/packages/app/src/lib/acp/thread-event-model.incremental.test.ts
new file mode 100644
index 000000000..53c9f72c1
--- /dev/null
+++ b/packages/app/src/lib/acp/thread-event-model.incremental.test.ts
@@ -0,0 +1,187 @@
+/**
+ * Property: incrementally sync()ing an event log in arbitrary batch splits
+ * yields exactly the same model as one-shot folding the whole log. This is
+ * the correctness contract that lets the store fold O(new events) per update
+ * instead of re-folding the transcript on every streamed chunk.
+ */
+
+import type { SessionUpdate, ThreadEvent } from '@inkeep/open-knowledge-core/acp/thread-protocol';
+import { describe, expect, test } from 'vitest';
+import { buildThreadRenderModel, ThreadRenderModelBuilder } from './thread-event-model';
+
+/** Deterministic LCG so failures reproduce. */
+function makeRng(seed: number): () => number {
+ let s = seed >>> 0;
+ return () => {
+ s = (s * 1664525 + 1013904223) >>> 0;
+ return s / 0x100000000;
+ };
+}
+
+function generateEvents(rng: () => number, count: number): ThreadEvent[] {
+ const events: ThreadEvent[] = [];
+ const toolCallIds: string[] = [];
+ const permissionIds: string[] = [];
+ let ts = 1;
+ const su = (update: SessionUpdate): ThreadEvent => ({
+ kind: 'session_update',
+ update,
+ ts: ts++,
+ });
+ for (let i = 0; i < count; i++) {
+ const roll = rng();
+ if (roll < 0.35) {
+ // Streamed message chunk — the hot path. Vary role and messageId
+ // presence to exercise tail-coalescing vs fresh-block starts.
+ const role = rng() < 0.7 ? 'agent' : rng() < 0.5 ? 'thought' : 'user';
+ const update = {
+ sessionUpdate: `${role}_message_chunk`,
+ content: { type: 'text', text: `chunk${i} ` },
+ ...(rng() < 0.3 ? { messageId: `m${Math.floor(rng() * 3)}` } : {}),
+ } as unknown as SessionUpdate;
+ events.push(su(update));
+ } else if (roll < 0.5) {
+ const id = `tool-${toolCallIds.length}`;
+ toolCallIds.push(id);
+ events.push(
+ su({
+ sessionUpdate: 'tool_call',
+ toolCallId: id,
+ title: `Tool ${id}`,
+ kind: 'edit',
+ status: 'pending',
+ content: [{ type: 'content', content: { type: 'text', text: `start ${id}` } }],
+ locations: [{ path: `docs/${id}.md` }],
+ } as unknown as SessionUpdate),
+ );
+ } else if (roll < 0.65 && toolCallIds.length > 0) {
+ const id = toolCallIds[Math.floor(rng() * toolCallIds.length)];
+ events.push(
+ su({
+ sessionUpdate: 'tool_call_update',
+ toolCallId: id,
+ status: rng() < 0.5 ? 'in_progress' : 'completed',
+ ...(rng() < 0.4
+ ? {
+ content: [{ type: 'diff', path: `docs/${id}.md`, oldText: 'a', newText: `b${i}` }],
+ }
+ : {}),
+ ...(rng() < 0.3 ? { rawInput: { arguments: { doc: `d${i}` } } } : {}),
+ } as unknown as SessionUpdate),
+ );
+ } else if (roll < 0.72) {
+ const id = `perm-${permissionIds.length}`;
+ permissionIds.push(id);
+ events.push({
+ kind: 'permission_request',
+ requestId: id,
+ toolCall: { toolCallId: `tool-x${i}`, title: `Allow ${i}?`, kind: 'edit' },
+ options: [{ optionId: 'allow', name: 'Allow', kind: 'allow_once' }],
+ ts: ts++,
+ } as unknown as ThreadEvent);
+ } else if (roll < 0.78 && permissionIds.length > 0) {
+ const id = permissionIds[Math.floor(rng() * permissionIds.length)];
+ events.push({
+ kind: 'permission_resolved',
+ requestId: id,
+ optionId: rng() < 0.5 ? 'allow' : null,
+ auto: rng() < 0.5,
+ ts: ts++,
+ });
+ } else if (roll < 0.85) {
+ events.push({ kind: 'user_message', content: `ask ${i}`, ts: ts++ });
+ events.push({ kind: 'turn_started', ts: ts++ });
+ } else if (roll < 0.9) {
+ events.push({ kind: 'turn_ended', stopReason: 'end_turn', ts: ts++ } as ThreadEvent);
+ } else if (roll < 0.95) {
+ events.push(
+ su({
+ sessionUpdate: 'plan',
+ entries: [
+ { content: `step ${i}`, status: 'pending' },
+ { content: `step ${i + 1}`, status: 'completed' },
+ ],
+ } as unknown as SessionUpdate),
+ );
+ } else {
+ events.push({
+ kind: 'status',
+ status: rng() < 0.5 ? 'error' : 'running',
+ detail: `detail ${i}`,
+ ts: ts++,
+ });
+ }
+ }
+ return events;
+}
+
+describe('incremental fold equivalence', () => {
+ test('arbitrary batch splits produce the one-shot fold result', () => {
+ for (let seed = 1; seed <= 20; seed++) {
+ const rng = makeRng(seed * 7919);
+ const events = generateEvents(rng, 120);
+ const expected = buildThreadRenderModel(events);
+
+ const builder = new ThreadRenderModelBuilder();
+ let applied = 0;
+ let model = builder.sync([]);
+ while (applied < events.length) {
+ const step = 1 + Math.floor(rng() * 7);
+ applied = Math.min(applied + step, events.length);
+ model = builder.sync(events.slice(0, applied));
+ }
+ expect(model).toEqual(expected);
+ }
+ });
+
+ test('snapshot is referentially stable when no new events arrive', () => {
+ const events = generateEvents(makeRng(42), 50);
+ const builder = new ThreadRenderModelBuilder();
+ const first = builder.sync(events);
+ expect(builder.sync(events)).toBe(first);
+ expect(builder.sync(events)).toBe(first);
+ });
+
+ test('untouched rows keep object identity across snapshots (copy-on-write)', () => {
+ const builder = new ThreadRenderModelBuilder();
+ const base: ThreadEvent[] = [
+ { kind: 'user_message', content: 'hi', ts: 1 },
+ {
+ kind: 'session_update',
+ update: {
+ sessionUpdate: 'tool_call',
+ toolCallId: 't1',
+ title: 'Read',
+ kind: 'read',
+ status: 'pending',
+ } as unknown as SessionUpdate,
+ ts: 2,
+ },
+ ];
+ const before = builder.sync(base);
+ const after = builder.sync([
+ ...base,
+ {
+ kind: 'session_update',
+ update: {
+ sessionUpdate: 'agent_message_chunk',
+ content: { type: 'text', text: 'done' },
+ } as unknown as SessionUpdate,
+ ts: 3,
+ },
+ ]);
+ // New snapshot object, but the two untouched rows are the same objects.
+ expect(after).not.toBe(before);
+ expect(after.items[0]).toBe(before.items[0]);
+ expect(after.items[1]).toBe(before.items[1]);
+ expect(after.items).toHaveLength(3);
+ });
+
+ test('a shorter log than previously seen resets the builder', () => {
+ const events = generateEvents(makeRng(7), 40);
+ const builder = new ThreadRenderModelBuilder();
+ builder.sync(events);
+ const shorter = events.slice(0, 5);
+ expect(builder.sync(shorter)).toEqual(buildThreadRenderModel(shorter));
+ });
+});
diff --git a/packages/app/src/lib/acp/thread-event-model.test.ts b/packages/app/src/lib/acp/thread-event-model.test.ts
new file mode 100644
index 000000000..cd02f7a55
--- /dev/null
+++ b/packages/app/src/lib/acp/thread-event-model.test.ts
@@ -0,0 +1,432 @@
+import type { ThreadEvent } from '@inkeep/open-knowledge-core/acp/thread-protocol';
+import { describe, expect, test } from 'vitest';
+import {
+ buildThreadRenderModel,
+ type RenderedItem,
+ resolvePermissionOutcome,
+} from './thread-event-model';
+
+function ev(event: ThreadEvent): ThreadEvent {
+ return event;
+}
+
+describe('buildThreadRenderModel', () => {
+ test('coalesces streamed agent chunks by messageId into one message', () => {
+ const events: ThreadEvent[] = [
+ ev({ kind: 'user_message', content: 'hi', ts: 1 }),
+ ev({ kind: 'turn_started', ts: 2 }),
+ ev({
+ kind: 'session_update',
+ ts: 3,
+ update: {
+ sessionUpdate: 'agent_message_chunk',
+ messageId: 'm1',
+ content: { type: 'text', text: 'Hello' },
+ } as never,
+ }),
+ ev({
+ kind: 'session_update',
+ ts: 4,
+ update: {
+ sessionUpdate: 'agent_message_chunk',
+ messageId: 'm1',
+ content: { type: 'text', text: ' world' },
+ } as never,
+ }),
+ ];
+ const model = buildThreadRenderModel(events);
+ const messages = model.items.filter((i) => i.kind === 'message');
+ expect(messages).toHaveLength(2); // user + one coalesced agent message
+ expect(messages[1]).toMatchObject({ role: 'agent', text: 'Hello world' });
+ expect(model.turnActive).toBe(true);
+ });
+
+ test('a tool call between chunks starts a new message block (chronological transcript)', () => {
+ const chunk = (ts: number, text: string): ThreadEvent =>
+ ev({
+ kind: 'session_update',
+ ts,
+ update: {
+ sessionUpdate: 'agent_message_chunk',
+ content: { type: 'text', text },
+ } as never,
+ });
+ const events: ThreadEvent[] = [
+ ev({ kind: 'user_message', content: 'go', ts: 1 }),
+ chunk(2, 'Creating the file'),
+ chunk(3, ' now.'),
+ ev({
+ kind: 'session_update',
+ ts: 4,
+ update: {
+ sessionUpdate: 'tool_call',
+ toolCallId: 'c1',
+ title: 'Write hello.md',
+ kind: 'edit',
+ status: 'completed',
+ } as never,
+ }),
+ chunk(5, 'Done. Editing next'),
+ chunk(6, ' file.'),
+ ev({
+ kind: 'session_update',
+ ts: 7,
+ update: {
+ sessionUpdate: 'tool_call',
+ toolCallId: 'c2',
+ title: 'Edit other.md',
+ kind: 'edit',
+ status: 'completed',
+ } as never,
+ }),
+ chunk(8, 'All finished.'),
+ ];
+ const model = buildThreadRenderModel(events);
+ // Chronological: user, text, tool, text, tool, text — chunks coalesce only
+ // while their message is still the tail, never across a tool call.
+ expect(model.items.map((i) => (i.kind === 'message' ? `${i.kind}:${i.text}` : i.kind))).toEqual(
+ [
+ 'message:go',
+ 'message:Creating the file now.',
+ 'tool_call',
+ 'message:Done. Editing next file.',
+ 'tool_call',
+ 'message:All finished.',
+ ],
+ );
+ });
+
+ test('tracks a tool call through status transitions and captures its diff', () => {
+ const events: ThreadEvent[] = [
+ ev({
+ kind: 'session_update',
+ ts: 1,
+ update: {
+ sessionUpdate: 'tool_call',
+ toolCallId: 'c1',
+ title: 'Edit config',
+ kind: 'edit',
+ status: 'pending',
+ } as never,
+ }),
+ ev({
+ kind: 'session_update',
+ ts: 2,
+ update: {
+ sessionUpdate: 'tool_call_update',
+ toolCallId: 'c1',
+ status: 'completed',
+ content: [{ type: 'diff', path: 'a.md', oldText: 'x', newText: 'y' }],
+ } as never,
+ }),
+ ];
+ const model = buildThreadRenderModel(events);
+ const call = model.items.find((i) => i.kind === 'tool_call');
+ expect(call).toMatchObject({ toolCallId: 'c1', status: 'completed', toolKind: 'edit' });
+ if (call?.kind !== 'tool_call') throw new Error('unreachable');
+ expect(call.diffs).toEqual([{ path: 'a.md', oldText: 'x', newText: 'y' }]);
+ });
+
+ test('marks a permission as resolved when the resolution event follows', () => {
+ const events: ThreadEvent[] = [
+ ev({
+ kind: 'permission_request',
+ requestId: 'p1',
+ toolCall: { toolCallId: 'c1', title: 'Write file', kind: 'edit' } as never,
+ options: [{ optionId: 'allow', name: 'Allow', kind: 'allow_once' }],
+ ts: 1,
+ }),
+ ev({ kind: 'permission_resolved', requestId: 'p1', optionId: 'allow', auto: false, ts: 2 }),
+ ];
+ const model = buildThreadRenderModel(events);
+ const perm = model.items.find((i) => i.kind === 'permission');
+ if (perm?.kind !== 'permission') throw new Error('unreachable');
+ expect(perm.resolved).toEqual({ optionId: 'allow', auto: false });
+ });
+
+ test('keeps the latest plan as a checklist', () => {
+ const events: ThreadEvent[] = [
+ ev({
+ kind: 'session_update',
+ ts: 1,
+ update: {
+ sessionUpdate: 'plan',
+ entries: [
+ { content: 'Step 1', status: 'completed' },
+ { content: 'Step 2', status: 'pending' },
+ ],
+ } as never,
+ }),
+ ];
+ const model = buildThreadRenderModel(events);
+ expect(model.plan).toHaveLength(2);
+ expect(model.plan[0]).toMatchObject({ content: 'Step 1', status: 'completed' });
+ });
+
+ test('surfaces error and auth notices from status events', () => {
+ const events: ThreadEvent[] = [
+ ev({ kind: 'status', status: 'error', detail: 'boom', ts: 1 }),
+ ev({ kind: 'status', status: 'auth_required', detail: 'sign in', ts: 2 }),
+ ];
+ const model = buildThreadRenderModel(events);
+ const notices = model.items.filter((i) => i.kind === 'notice');
+ expect(notices).toEqual([
+ { kind: 'notice', text: 'boom', tone: 'error' },
+ { kind: 'notice', text: 'sign in', tone: 'info' },
+ ]);
+ });
+
+ test('a terminal exit ends a dangling turn (crash-mid-stream transcript)', () => {
+ // The agent process exited after the turn opened but before the prompt
+ // settled, so the persisted log has `turn_started` and no `turn_ended`.
+ // On replay the turn must read as ended, not a perpetual "working" spinner.
+ const events: ThreadEvent[] = [
+ ev({ kind: 'user_message', content: 'ping', ts: 1 }),
+ ev({ kind: 'turn_started', ts: 2 }),
+ ev({ kind: 'status', status: 'running', ts: 3 }),
+ ev({ kind: 'status', status: 'exited', detail: 'agent exited (SIGTERM)', ts: 4 }),
+ ];
+ expect(buildThreadRenderModel(events).turnActive).toBe(false);
+ });
+
+ test('a resume after an exit re-arms the turn', () => {
+ const events: ThreadEvent[] = [
+ ev({ kind: 'turn_started', ts: 1 }),
+ ev({ kind: 'status', status: 'exited', ts: 2 }),
+ // Resume respawns the agent and opens a fresh turn.
+ ev({ kind: 'turn_started', ts: 3 }),
+ ev({ kind: 'status', status: 'running', ts: 4 }),
+ ];
+ expect(buildThreadRenderModel(events).turnActive).toBe(true);
+ });
+
+ const consentRequest = (): ThreadEvent =>
+ ev({
+ kind: 'runtime_consent_request',
+ requestId: 'r1',
+ runtime: 'node',
+ displayName: 'Node.js',
+ provides: 'npx',
+ version: 'v24.18.0',
+ approxSizeMB: 45,
+ sourceHost: 'nodejs.org',
+ agentName: 'Gemini CLI',
+ ts: 1,
+ });
+
+ test('renders a pending runtime-consent card from the request event', () => {
+ const model = buildThreadRenderModel([consentRequest()]);
+ const card = model.items.find((i) => i.kind === 'runtime_consent');
+ if (card?.kind !== 'runtime_consent') throw new Error('unreachable');
+ expect(card).toMatchObject({
+ runtime: 'node',
+ provides: 'npx',
+ agentName: 'Gemini CLI',
+ resolved: null,
+ install: null,
+ progress: null,
+ });
+ });
+
+ test('grant → progress → spawning drives the card through running to done', () => {
+ const model = buildThreadRenderModel([
+ consentRequest(),
+ ev({ kind: 'runtime_consent_resolved', requestId: 'r1', decision: 'granted', ts: 2 }),
+ ev({
+ kind: 'runtime_install_progress',
+ runtime: 'node',
+ phase: 'downloading',
+ receivedBytes: 20,
+ totalBytes: 40,
+ ts: 3,
+ }),
+ ev({ kind: 'status', status: 'spawning', ts: 4 }),
+ ]);
+ const card = model.items.find((i) => i.kind === 'runtime_consent');
+ if (card?.kind !== 'runtime_consent') throw new Error('unreachable');
+ // Progress captured, and the follow-on spawning status marks it done.
+ expect(card.resolved).toBe('granted');
+ expect(card.install).toBe('done');
+ expect(card.progress).toEqual({ receivedBytes: 20, totalBytes: 40 });
+ });
+
+ test('a decline resolves the card without an install lifecycle', () => {
+ const model = buildThreadRenderModel([
+ consentRequest(),
+ ev({ kind: 'runtime_consent_resolved', requestId: 'r1', decision: 'declined', ts: 2 }),
+ ]);
+ const card = model.items.find((i) => i.kind === 'runtime_consent');
+ if (card?.kind !== 'runtime_consent') throw new Error('unreachable');
+ expect(card.resolved).toBe('declined');
+ expect(card.install).toBeNull();
+ });
+
+ test('a failed launch after a grant marks the install failed', () => {
+ const model = buildThreadRenderModel([
+ consentRequest(),
+ ev({ kind: 'runtime_consent_resolved', requestId: 'r1', decision: 'granted', ts: 2 }),
+ ev({ kind: 'status', status: 'error', detail: 'checksum mismatch', ts: 3 }),
+ ]);
+ const card = model.items.find((i) => i.kind === 'runtime_consent');
+ if (card?.kind !== 'runtime_consent') throw new Error('unreachable');
+ expect(card.install).toBe('failed');
+ // The error detail still surfaces as its own notice.
+ expect(model.items.some((i) => i.kind === 'notice' && i.text === 'checksum mismatch')).toBe(
+ true,
+ );
+ });
+});
+
+describe('terminal folding', () => {
+ const created = (id: string, ts = 1): ThreadEvent =>
+ ev({ kind: 'terminal_created', terminalId: id, command: 'npm', args: ['test'], ts });
+
+ test('folds created → output chunks → exit into one terminal record', () => {
+ const model = buildThreadRenderModel([
+ created('t1'),
+ ev({ kind: 'terminal_output', terminalId: 't1', chunk: 'compiling…\n', ts: 2 }),
+ ev({ kind: 'terminal_output', terminalId: 't1', chunk: 'ok 12 tests\n', ts: 3 }),
+ ev({ kind: 'terminal_exit', terminalId: 't1', exitCode: 0, signal: null, ts: 4 }),
+ ]);
+ expect(model.terminals.t1).toMatchObject({
+ command: 'npm',
+ args: ['test'],
+ output: 'compiling…\nok 12 tests\n',
+ truncated: false,
+ exit: { exitCode: 0, signal: null },
+ });
+ });
+
+ test('a running terminal has a null exit; output for unknown ids is dropped', () => {
+ const model = buildThreadRenderModel([
+ created('t1'),
+ ev({ kind: 'terminal_output', terminalId: 't1', chunk: 'partial', ts: 2 }),
+ ev({ kind: 'terminal_output', terminalId: 'ghost', chunk: 'nope', ts: 3 }),
+ ]);
+ expect(model.terminals.t1?.exit).toBeNull();
+ expect(model.terminals.t1?.output).toBe('partial');
+ expect(model.terminals.ghost).toBeUndefined();
+ });
+
+ test('caps rendered output, keeping the tail', () => {
+ const events: ThreadEvent[] = [created('t1')];
+ for (let i = 0; i < 80; i++) {
+ events.push({
+ kind: 'terminal_output',
+ terminalId: 't1',
+ chunk: 'x'.repeat(1000),
+ ts: 2 + i,
+ });
+ }
+ events.push({ kind: 'terminal_output', terminalId: 't1', chunk: 'TAIL', ts: 99 });
+ const model = buildThreadRenderModel(events);
+ const terminal = model.terminals.t1;
+ if (terminal === undefined) throw new Error('unreachable');
+ expect(terminal.output.length).toBeLessThanOrEqual(64_000);
+ expect(terminal.truncated).toBe(true);
+ expect(terminal.output.endsWith('TAIL')).toBe(true);
+ });
+
+ test('signal exits carry the signal through', () => {
+ const model = buildThreadRenderModel([
+ created('t1'),
+ ev({ kind: 'terminal_exit', terminalId: 't1', exitCode: null, signal: 'SIGTERM', ts: 2 }),
+ ]);
+ expect(model.terminals.t1?.exit).toEqual({ exitCode: null, signal: 'SIGTERM' });
+ });
+});
+
+describe('token usage', () => {
+ test('folds a spec usage_update (top-level used/size)', () => {
+ const model = buildThreadRenderModel([
+ ev({
+ kind: 'session_update',
+ ts: 1,
+ update: { sessionUpdate: 'usage_update', used: 12_345, size: 200_000 } as never,
+ }),
+ ]);
+ expect(model.tokenUsage).toEqual({ used: 12_345, size: 200_000 });
+ });
+
+ test('still accepts the nested `usage` key shape from pre-spec adapters', () => {
+ const model = buildThreadRenderModel([
+ ev({
+ kind: 'session_update',
+ ts: 1,
+ update: { sessionUpdate: 'something_else', usage: { used: 7, size: 100 } } as never,
+ }),
+ ]);
+ expect(model.tokenUsage).toEqual({ used: 7, size: 100 });
+ });
+
+ test('latest usage wins', () => {
+ const usage = (used: number, ts: number): ThreadEvent =>
+ ev({
+ kind: 'session_update',
+ ts,
+ update: { sessionUpdate: 'usage_update', used, size: 200_000 } as never,
+ });
+ const model = buildThreadRenderModel([usage(10, 1), usage(50, 2)]);
+ expect(model.tokenUsage?.used).toBe(50);
+ });
+});
+
+describe('resolvePermissionOutcome', () => {
+ const permission = (
+ resolved: { optionId: string | null; auto: boolean } | null,
+ ): Extract<RenderedItem, { kind: 'permission' }> => ({
+ kind: 'permission',
+ requestId: 'r1',
+ title: 'Run npm test?',
+ toolKind: 'execute',
+ options: [
+ { optionId: 'yes', name: 'Yes, run it', kind: 'allow_once' },
+ { optionId: 'no', name: 'No, reject', kind: 'reject_once' },
+ ],
+ resolved,
+ });
+
+ test('pending request has no outcome yet', () => {
+ expect(resolvePermissionOutcome(permission(null))).toBeNull();
+ });
+
+ test('an allow option approves (auto and manual)', () => {
+ expect(resolvePermissionOutcome(permission({ optionId: 'yes', auto: false }))).toEqual({
+ kind: 'approved',
+ auto: false,
+ optionName: 'Yes, run it',
+ });
+ expect(resolvePermissionOutcome(permission({ optionId: 'yes', auto: true }))).toMatchObject({
+ kind: 'approved',
+ auto: true,
+ });
+ });
+
+ test("choosing the agent's own reject option is a denial, not an approval", () => {
+ expect(resolvePermissionOutcome(permission({ optionId: 'no', auto: false }))).toEqual({
+ kind: 'denied',
+ auto: false,
+ optionName: 'No, reject',
+ });
+ });
+
+ test('an explicit user deny (no optionId, not auto) is a denial', () => {
+ expect(resolvePermissionOutcome(permission({ optionId: null, auto: false }))).toEqual({
+ kind: 'denied',
+ auto: false,
+ optionName: null,
+ });
+ });
+
+ test('an automatic no-answer resolution (timeout, turn cancel) is dismissed', () => {
+ expect(resolvePermissionOutcome(permission({ optionId: null, auto: true }))).toEqual({
+ kind: 'dismissed',
+ });
+ });
+
+ test('an optionId matching none of the offered options is dismissed, never approved', () => {
+ expect(resolvePermissionOutcome(permission({ optionId: 'ghost', auto: false }))).toEqual({
+ kind: 'dismissed',
+ });
+ });
+});
diff --git a/packages/app/src/lib/acp/thread-event-model.ts b/packages/app/src/lib/acp/thread-event-model.ts
new file mode 100644
index 000000000..7fc1902ab
--- /dev/null
+++ b/packages/app/src/lib/acp/thread-event-model.ts
@@ -0,0 +1,546 @@
+/**
+ * Fold a thread's flat `ThreadEvent[]` into the render model the thread view
+ * draws: an ordered list of turns and system notices, with streamed message
+ * chunks coalesced by `messageId`, tool calls tracked by `toolCallId` through
+ * their status transitions, and the latest plan kept as a live checklist.
+ *
+ * The fold is INCREMENTAL: `ThreadRenderModelBuilder.sync(events)` applies
+ * only the events it hasn't seen, so a streaming turn costs O(new events) per
+ * update instead of re-folding the whole log — the full re-fold made long
+ * transcripts progressively more sluggish (each chunk re-paid every string
+ * concat since turn start). Item updates are copy-on-write: an untouched
+ * transcript row keeps its object identity across snapshots; only rows that
+ * actually changed get new ones.
+ *
+ * Kept pure (no React) so it is unit-testable and the components stay thin
+ * renderers over this model.
+ */
+
+import type {
+ PermissionOption,
+ SessionUpdate,
+ ThreadEvent,
+} from '@inkeep/open-knowledge-core/acp/thread-protocol';
+
+interface RenderedMessage {
+ kind: 'message';
+ role: 'user' | 'agent' | 'thought';
+ text: string;
+ messageId: string;
+}
+
+export interface RenderedToolCall {
+ kind: 'tool_call';
+ toolCallId: string;
+ title: string;
+ toolKind: string;
+ status: 'pending' | 'in_progress' | 'completed' | 'failed';
+ /** Diffs the agent attached to this call (path + before/after). */
+ diffs: Array<{ path: string; oldText: string | null; newText: string }>;
+ /** Terminal ids embedded in the call (live output rendered elsewhere). */
+ terminalIds: string[];
+ /** Plain text/content result blocks. */
+ content: string[];
+ /** File locations the agent touched (follow-the-agent). */
+ locations: Array<{ path: string; line?: number }>;
+ /** The adapter-reported raw tool input (MCP calls carry docName args here). */
+ rawInput: unknown;
+}
+
+interface RenderedPermission {
+ kind: 'permission';
+ requestId: string;
+ title: string;
+ toolKind: string;
+ options: PermissionOption[];
+ resolved: { optionId: string | null; auto: boolean } | null;
+}
+
+interface RenderedNotice {
+ kind: 'notice';
+ text: string;
+ tone: 'info' | 'error';
+}
+
+/**
+ * Live state of one ACP terminal (a command OK ran for the agent), folded
+ * from `terminal_*` events. Rendered inside the tool call that embeds the
+ * terminal id — terminals are not transcript items of their own.
+ */
+export interface RenderedTerminal {
+ terminalId: string;
+ command: string;
+ args: string[];
+ output: string;
+ /** The transcript copy dropped output (display bound), not the command's. */
+ truncated: boolean;
+ /** null while the command is still running. */
+ exit: { exitCode: number | null; signal: string | null } | null;
+}
+
+/** Keep at most this much of a terminal's output in the render model (tail wins). */
+const TERMINAL_RENDER_CHAR_CAP = 64_000;
+
+interface RenderedRuntimeConsent {
+ kind: 'runtime_consent';
+ requestId: string;
+ runtime: 'node' | 'uv';
+ /** "Node.js" / "uv". */
+ displayName: string;
+ /** The interpreter it unlocks — "npx" / "uvx". */
+ provides: string;
+ version: string;
+ approxSizeMB: number;
+ sourceHost: string;
+ agentName: string;
+ /** null while awaiting the user's answer. */
+ resolved: 'granted' | 'declined' | 'timeout' | null;
+ /**
+ * Install lifecycle after a grant, driven by the follow-on thread status:
+ * `running` while downloading, `done` once the launch proceeds (spawning),
+ * `failed` if the launch errored out. Keeps a completed card from showing a
+ * stuck spinner on replay.
+ */
+ install: 'running' | 'done' | 'failed' | null;
+ /** Latest download progress once granted (bytes), else null. */
+ progress: { receivedBytes: number; totalBytes: number | null } | null;
+}
+
+export type RenderedItem =
+ | RenderedMessage
+ | RenderedToolCall
+ | RenderedPermission
+ | RenderedNotice
+ | RenderedRuntimeConsent;
+
+interface PlanEntry {
+ content: string;
+ priority?: string;
+ status?: string;
+}
+
+export interface ThreadRenderModel {
+ items: RenderedItem[];
+ plan: PlanEntry[];
+ /** True while the current prompt turn is streaming. */
+ turnActive: boolean;
+ /** Context-window fill from the agent's `usage_update` (tokens). */
+ tokenUsage: { used?: number; size?: number } | null;
+ /** Terminals by id, for tool calls that embed them (`terminalIds`). */
+ terminals: Record<string, RenderedTerminal>;
+}
+
+function textFromContent(content: unknown): string | null {
+ if (typeof content !== 'object' || content === null) return null;
+ const c = content as { type?: string; text?: string };
+ return c.type === 'text' && typeof c.text === 'string' ? c.text : null;
+}
+
+export class ThreadRenderModelBuilder {
+ private items: RenderedItem[] = [];
+ private plan: PlanEntry[] = [];
+ private turnActive = false;
+ private tokenUsage: ThreadRenderModel['tokenUsage'] = null;
+ private terminals: Record<string, RenderedTerminal> = {};
+ /** Item index by toolCallId / permission requestId / `role:messageId`. */
+ private toolCallIndex = new Map<string, number>();
+ private permissionIndex = new Map<string, number>();
+ private messageIndex = new Map<string, number>();
+ private runtimeConsentIndex = new Map<string, number>();
+ /** Item index of the most recent consent card — progress events target it. */
+ private lastConsentIndex: number | null = null;
+ private appliedCount = 0;
+ private dirty = false;
+ private snapshot: ThreadRenderModel = {
+ items: [],
+ plan: [],
+ turnActive: false,
+ tokenUsage: null,
+ terminals: {},
+ };
+
+ /**
+ * Apply any events beyond what was applied already and return the current
+ * model. The snapshot is referentially stable while no new events arrive —
+ * safe as a `useSyncExternalStore` getter. A shorter array than previously
+ * seen means the log was rebuilt (thread dropped and re-added); the
+ * builder starts over.
+ */
+ sync(events: readonly ThreadEvent[]): ThreadRenderModel {
+ if (events.length < this.appliedCount) this.reset();
+ for (let i = this.appliedCount; i < events.length; i++) {
+ this.applyEvent(events[i]);
+ }
+ this.appliedCount = events.length;
+ if (this.dirty) {
+ this.snapshot = {
+ items: [...this.items],
+ plan: this.plan,
+ turnActive: this.turnActive,
+ tokenUsage: this.tokenUsage,
+ terminals: { ...this.terminals },
+ };
+ this.dirty = false;
+ }
+ return this.snapshot;
+ }
+
+ private reset(): void {
+ this.items = [];
+ this.plan = [];
+ this.turnActive = false;
+ this.tokenUsage = null;
+ this.terminals = {};
+ this.toolCallIndex = new Map();
+ this.permissionIndex = new Map();
+ this.messageIndex = new Map();
+ this.runtimeConsentIndex = new Map();
+ this.lastConsentIndex = null;
+ this.appliedCount = 0;
+ this.dirty = true;
+ }
+
+ private applyEvent(event: ThreadEvent): void {
+ this.dirty = true;
+ switch (event.kind) {
+ case 'user_message': {
+ this.items.push({
+ kind: 'message',
+ role: 'user',
+ text: event.content,
+ messageId: `user-${this.items.length}`,
+ });
+ // A user turn resets streaming message coalescing.
+ this.messageIndex.clear();
+ break;
+ }
+ case 'turn_started':
+ this.turnActive = true;
+ break;
+ case 'turn_ended':
+ this.turnActive = false;
+ this.messageIndex.clear();
+ break;
+ case 'status':
+ // A terminal exit ends any dangling turn. A persisted transcript can
+ // end with `turn_started` and no `turn_ended` — the agent process
+ // exited before the prompt settled — which would otherwise replay as a
+ // perpetual "working" spinner. A later `turn_started` (resume) re-arms.
+ if (event.status === 'exited') this.turnActive = false;
+ // A granted runtime install resolves when the launch moves on: the
+ // agent spawns (done) or the thread errors (failed).
+ if (this.lastConsentIndex !== null) {
+ const c = this.items[this.lastConsentIndex];
+ if (c?.kind === 'runtime_consent' && c.install === 'running') {
+ if (
+ event.status === 'spawning' ||
+ event.status === 'ready' ||
+ event.status === 'running'
+ ) {
+ this.items[this.lastConsentIndex] = { ...c, install: 'done' };
+ } else if (event.status === 'error' || event.status === 'exited') {
+ this.items[this.lastConsentIndex] = { ...c, install: 'failed' };
+ }
+ }
+ }
+ if (event.status === 'error' && event.detail) {
+ this.items.push({ kind: 'notice', text: event.detail, tone: 'error' });
+ } else if (event.status === 'auth_required' && event.detail) {
+ this.items.push({ kind: 'notice', text: event.detail, tone: 'info' });
+ }
+ break;
+ case 'permission_request':
+ this.permissionIndex.set(event.requestId, this.items.length);
+ this.items.push({
+ kind: 'permission',
+ requestId: event.requestId,
+ title: event.toolCall.title ?? 'Permission required',
+ toolKind: event.toolCall.kind ?? 'other',
+ options: event.options,
+ resolved: null,
+ });
+ break;
+ case 'permission_resolved': {
+ const index = this.permissionIndex.get(event.requestId);
+ if (index === undefined) break;
+ const target = this.items[index];
+ if (target.kind !== 'permission') break;
+ this.items[index] = {
+ ...target,
+ resolved: { optionId: event.optionId, auto: event.auto },
+ };
+ break;
+ }
+ case 'runtime_consent_request':
+ this.runtimeConsentIndex.set(event.requestId, this.items.length);
+ this.lastConsentIndex = this.items.length;
+ this.items.push({
+ kind: 'runtime_consent',
+ requestId: event.requestId,
+ runtime: event.runtime,
+ displayName: event.displayName,
+ provides: event.provides,
+ version: event.version,
+ approxSizeMB: event.approxSizeMB,
+ sourceHost: event.sourceHost,
+ agentName: event.agentName,
+ resolved: null,
+ install: null,
+ progress: null,
+ });
+ break;
+ case 'runtime_consent_resolved': {
+ const index = this.runtimeConsentIndex.get(event.requestId);
+ if (index === undefined) break;
+ const target = this.items[index];
+ if (target.kind !== 'runtime_consent') break;
+ this.items[index] = {
+ ...target,
+ resolved: event.decision,
+ install: event.decision === 'granted' ? 'running' : null,
+ };
+ break;
+ }
+ case 'runtime_install_progress': {
+ if (this.lastConsentIndex === null) break;
+ const target = this.items[this.lastConsentIndex];
+ if (target === undefined || target.kind !== 'runtime_consent') break;
+ this.items[this.lastConsentIndex] = {
+ ...target,
+ progress: {
+ receivedBytes: event.receivedBytes ?? 0,
+ totalBytes: event.totalBytes ?? null,
+ },
+ };
+ break;
+ }
+ case 'terminal_created':
+ this.terminals[event.terminalId] = {
+ terminalId: event.terminalId,
+ command: event.command,
+ args: event.args,
+ output: '',
+ truncated: false,
+ exit: null,
+ };
+ break;
+ case 'terminal_output': {
+ const terminal = this.terminals[event.terminalId];
+ if (terminal === undefined) break;
+ let output = terminal.output + event.chunk;
+ let truncated = terminal.truncated;
+ if (output.length > TERMINAL_RENDER_CHAR_CAP) {
+ output = output.slice(-TERMINAL_RENDER_CHAR_CAP);
+ truncated = true;
+ }
+ this.terminals[event.terminalId] = { ...terminal, output, truncated };
+ break;
+ }
+ case 'terminal_exit': {
+ const terminal = this.terminals[event.terminalId];
+ if (terminal === undefined) break;
+ this.terminals[event.terminalId] = {
+ ...terminal,
+ exit: { exitCode: event.exitCode, signal: event.signal },
+ };
+ break;
+ }
+ case 'session_update':
+ this.applyUpdate(event.update);
+ break;
+ default:
+ break;
+ }
+ }
+
+ private pushMessageChunk(role: RenderedMessage['role'], messageId: string, text: string): void {
+ const key = `${role}:${messageId}`;
+ const index = this.messageIndex.get(key);
+ // Coalesce streamed chunks only while the message is still the transcript
+ // tail. Most adapters send no messageId (everything keys to 'default'),
+ // so without the tail check every later chunk glues onto the FIRST
+ // bubble and tool calls pile up beneath it — instead of the
+ // chronological output → tool call → output the transcript should read
+ // as. Anything in between (tool call, permission, notice, user turn)
+ // starts a fresh block.
+ if (index !== undefined && index === this.items.length - 1) {
+ const existing = this.items[index] as RenderedMessage;
+ this.items[index] = { ...existing, text: existing.text + text };
+ return;
+ }
+ this.messageIndex.set(key, this.items.length);
+ this.items.push({ kind: 'message', role, text, messageId });
+ }
+
+ private applyUpdate(update: SessionUpdate): void {
+ switch (update.sessionUpdate) {
+ case 'agent_message_chunk': {
+ const text = textFromContent(update.content);
+ if (text !== null) this.pushMessageChunk('agent', messageId(update), text);
+ break;
+ }
+ case 'agent_thought_chunk': {
+ const text = textFromContent(update.content);
+ if (text !== null) this.pushMessageChunk('thought', messageId(update), text);
+ break;
+ }
+ case 'user_message_chunk': {
+ const text = textFromContent(update.content);
+ if (text !== null) this.pushMessageChunk('user', messageId(update), text);
+ break;
+ }
+ case 'tool_call': {
+ const call: RenderedToolCall = {
+ kind: 'tool_call',
+ toolCallId: update.toolCallId,
+ title: update.title ?? 'Tool call',
+ toolKind: update.kind ?? 'other',
+ status: (update.status as RenderedToolCall['status']) ?? 'pending',
+ diffs: [],
+ terminalIds: [],
+ content: [],
+ locations: normalizeLocations(update.locations),
+ rawInput: (update as { rawInput?: unknown }).rawInput,
+ };
+ mergeToolContent(call, update.content);
+ this.toolCallIndex.set(update.toolCallId, this.items.length);
+ this.items.push(call);
+ break;
+ }
+ case 'tool_call_update': {
+ const index = this.toolCallIndex.get(update.toolCallId);
+ if (index === undefined) break;
+ const existing = this.items[index];
+ if (existing.kind !== 'tool_call') break;
+ // Copy-on-write, arrays included — the previous snapshot keeps the
+ // untouched row while mergeToolContent appends to the copy.
+ const call: RenderedToolCall = {
+ ...existing,
+ diffs: [...existing.diffs],
+ terminalIds: [...existing.terminalIds],
+ content: [...existing.content],
+ };
+ if (update.status) call.status = update.status as RenderedToolCall['status'];
+ if (update.title) call.title = update.title;
+ if (update.locations) call.locations = normalizeLocations(update.locations);
+ const rawInput = (update as { rawInput?: unknown }).rawInput;
+ if (rawInput !== undefined) call.rawInput = rawInput;
+ mergeToolContent(call, update.content);
+ this.items[index] = call;
+ break;
+ }
+ case 'plan': {
+ const entries = (update as { entries?: unknown }).entries;
+ if (Array.isArray(entries)) {
+ this.plan = entries
+ .map((e) => e as Record<string, unknown>)
+ .filter((e) => typeof e.content === 'string')
+ .map((e) => ({
+ content: e.content as string,
+ priority: typeof e.priority === 'string' ? e.priority : undefined,
+ status: typeof e.status === 'string' ? e.status : undefined,
+ }));
+ }
+ break;
+ }
+ case 'usage_update': {
+ // Spec shape: context-window fill at the update's top level.
+ const u = update as { used?: unknown; size?: unknown };
+ this.tokenUsage = {
+ used: typeof u.used === 'number' ? u.used : undefined,
+ size: typeof u.size === 'number' ? u.size : undefined,
+ };
+ break;
+ }
+ default: {
+ // Pre-spec adapters ride usage on a nested `usage` key instead.
+ const usage = (update as { usage?: { used?: number; size?: number } }).usage;
+ if (usage !== undefined) this.tokenUsage = { used: usage.used, size: usage.size };
+ break;
+ }
+ }
+ }
+}
+
+/** One-shot fold — the non-incremental entry point for tests and tooling. */
+export function buildThreadRenderModel(events: readonly ThreadEvent[]): ThreadRenderModel {
+ return new ThreadRenderModelBuilder().sync(events);
+}
+
+/**
+ * How a permission request ended, classified by the CHOSEN option's kind —
+ * not by mere presence of an optionId. Picking the agent's own "No, reject"
+ * option is a denial and must never summarize as "Approved".
+ *
+ * `dismissed` is the no-classifiable-answer terminal state (timeout, turn
+ * cancel, agent exit, or an optionId matching none of the offered options):
+ * nobody approved or denied, the request just stopped mattering.
+ */
+export type PermissionOutcome =
+ | { kind: 'approved'; auto: boolean; optionName: string | null }
+ | { kind: 'denied'; auto: boolean; optionName: string | null }
+ | { kind: 'dismissed' }
+ | null;
+
+export function resolvePermissionOutcome(
+ item: Extract<RenderedItem, { kind: 'permission' }>,
+): PermissionOutcome {
+ const resolved = item.resolved;
+ if (resolved === null) return null;
+ if (resolved.optionId === null) {
+ // No option chosen: an explicit user deny (our Deny button sends the
+ // ACP `cancelled` outcome) vs. an automatic expiry.
+ return resolved.auto
+ ? { kind: 'dismissed' }
+ : { kind: 'denied', auto: false, optionName: null };
+ }
+ const chosen = item.options.find((option) => option.optionId === resolved.optionId);
+ if (chosen === undefined) {
+ // An optionId that matches nothing in the request can't be classified —
+ // claiming "approved" for it could mislabel a refusal.
+ return { kind: 'dismissed' };
+ }
+ return {
+ kind: chosen.kind.startsWith('reject') ? 'denied' : 'approved',
+ auto: resolved.auto,
+ optionName: chosen.name,
+ };
+}
+
+function messageId(update: SessionUpdate): string {
+ const id = (update as { messageId?: unknown }).messageId;
+ return typeof id === 'string' ? id : 'default';
+}
+
+function normalizeLocations(locations: unknown): Array<{ path: string; line?: number }> {
+ if (!Array.isArray(locations)) return [];
+ return locations
+ .map((l) => l as { path?: unknown; line?: unknown })
+ .filter((l) => typeof l.path === 'string')
+ .map((l) => ({
+ path: l.path as string,
+ line: typeof l.line === 'number' ? l.line : undefined,
+ }));
+}
+
+function mergeToolContent(call: RenderedToolCall, content: unknown): void {
+ if (!Array.isArray(content)) return;
+ for (const block of content) {
+ const b = block as Record<string, unknown>;
+ if (b.type === 'diff' && typeof b.path === 'string' && typeof b.newText === 'string') {
+ call.diffs.push({
+ path: b.path,
+ oldText: typeof b.oldText === 'string' ? b.oldText : null,
+ newText: b.newText,
+ });
+ } else if (b.type === 'terminal' && typeof b.terminalId === 'string') {
+ if (!call.terminalIds.includes(b.terminalId)) call.terminalIds.push(b.terminalId);
+ } else if (b.type === 'content') {
+ const text = textFromContent(b.content);
+ if (text !== null) call.content.push(text);
+ } else {
+ const text = textFromContent(b);
+ if (text !== null) call.content.push(text);
+ }
+ }
+}
diff --git a/packages/app/src/lib/desktop-bridge-types.ts b/packages/app/src/lib/desktop-bridge-types.ts
index fa82419cc..d5363b7a4 100644
--- a/packages/app/src/lib/desktop-bridge-types.ts
+++ b/packages/app/src/lib/desktop-bridge-types.ts
@@ -1439,8 +1439,10 @@ export interface OkDesktopBridge {
* survives a renderer reload. Fire-and-forget.
*/
setOrder(orderedPtyIds: readonly string[]): void;
- /** Per-window dock visibility. Canonical JSDoc in `bridge-contract.ts`; mirrored verbatim (drift-tested). */
- getDockState(): Promise<{ visible: boolean }>;
+ /** Per-window sessions-dock state (visibility + unified tab order + active key). Canonical JSDoc in `bridge-contract.ts`; mirrored verbatim (drift-tested). */
+ getDockState(): Promise<{ visible: boolean; order?: string[]; activeKey?: string | null }>;
+ /** Persist the unified sessions-dock order + active key per window. Canonical JSDoc in `bridge-contract.ts`; mirrored verbatim (drift-tested). */
+ setDockState(state: { order: string[]; activeKey: string | null }): void;
onData(cb: (msg: OkPtyData) => void): OkUnsubscribe;
onExit(cb: (msg: OkPtyExit) => void): OkUnsubscribe;
claudePreflight(): Promise<ClaudeReadiness>;
diff --git a/packages/app/src/lib/dock-session-persistence.ts b/packages/app/src/lib/dock-session-persistence.ts
new file mode 100644
index 000000000..f71bb5740
--- /dev/null
+++ b/packages/app/src/lib/dock-session-persistence.ts
@@ -0,0 +1,100 @@
+/**
+ * Reload-durable dock order for the unified sessions dock: the interleaved list
+ * of session keys (terminal ptyIds + thread threadIds, in tab order) plus the
+ * active key. This is the ONE net-new persistence the unified dock needs — the
+ * cross-kind order and active tab a renderer reload must restore. Everything else
+ * already survives: terminal PTYs + their labels/ordinals in main, thread liveness
+ * on the server, dock visibility in main, dock position in localStorage.
+ *
+ * Two backends behind one interface:
+ * - desktop: per-window main-process dock state (survives a renderer reload, is
+ * per-window so multi-window order never bleeds) via the terminal bridge;
+ * - web: best-effort localStorage (per-origin; multi-tab bleed is unsolved for
+ * both docks today and out of scope), since there is no main process.
+ *
+ * Keys are reload-STABLE identities, not the host's ephemeral client ids: a
+ * terminal's ptyId (what `list()`/`adopt()` speak) and a thread's threadId (what
+ * the server replays). The host maps its descriptors to these keys.
+ */
+
+import type { OkDesktopBridge } from '@/lib/desktop-bridge-types';
+
+export interface DockSessionOrder {
+ /** Session keys (ptyIds + threadIds) in tab order. */
+ readonly order: readonly string[];
+ /** The active session's key, or null when nothing is active. */
+ readonly activeKey: string | null;
+}
+
+/** localStorage key for the web backend — a UI-pref store like the other dock
+ * prefs (position, height, width), never a `config.yml` field. */
+const WEB_STORAGE_KEY = 'ok-dock-session-order-v1';
+
+/**
+ * Synchronous localStorage read of the web dock order (the mount seed reads it
+ * before the async {@link readDockSessionOrder} would resolve). Returns `null`
+ * when nothing is stored or storage is unavailable.
+ */
+export function readWebDockSessionOrder(): DockSessionOrder | null {
+ if (typeof window === 'undefined') return null;
+ try {
+ const raw = window.localStorage.getItem(WEB_STORAGE_KEY);
+ if (raw === null) return null;
+ const parsed = JSON.parse(raw) as { order?: unknown; activeKey?: unknown };
+ const order = Array.isArray(parsed.order)
+ ? parsed.order.filter((k): k is string => typeof k === 'string')
+ : [];
+ const activeKey = typeof parsed.activeKey === 'string' ? parsed.activeKey : null;
+ return { order, activeKey };
+ } catch {
+ return null;
+ }
+}
+
+/** Persist the web dock order to localStorage (best-effort). */
+function writeWeb(state: DockSessionOrder): void {
+ if (typeof window === 'undefined') return;
+ try {
+ window.localStorage.setItem(WEB_STORAGE_KEY, JSON.stringify(state));
+ } catch {
+ // Quota / privacy mode — best-effort, the in-memory order still serves the session.
+ }
+}
+
+/**
+ * Read the persisted dock order for this window/origin, or `null` when none is
+ * retained (fresh launch, or a read failure — the caller cold-starts). Desktop
+ * reads main's per-window dock state; web reads localStorage synchronously
+ * (wrapped in a promise for one call shape).
+ */
+export function readDockSessionOrder(
+ bridge: OkDesktopBridge | null | undefined,
+): Promise<DockSessionOrder | null> {
+ if (typeof bridge?.terminal?.getDockState === 'function') {
+ return bridge.terminal
+ .getDockState()
+ .then((state) => {
+ const order = Array.isArray(state.order)
+ ? state.order.filter((k): k is string => typeof k === 'string')
+ : [];
+ const activeKey = typeof state.activeKey === 'string' ? state.activeKey : null;
+ // No retained order at all (fresh launch) reads as null so the caller
+ // cold-starts rather than seeding an empty arrangement.
+ return order.length === 0 && activeKey === null ? null : { order, activeKey };
+ })
+ .catch(() => null);
+ }
+ return Promise.resolve(readWebDockSessionOrder());
+}
+
+/** Persist the dock order for this window/origin. Fire-and-forget on both backends. */
+export function writeDockSessionOrder(
+ bridge: OkDesktopBridge | null | undefined,
+ state: DockSessionOrder,
+): void {
+ if (typeof bridge?.terminal?.setDockState === 'function') {
+ bridge.terminal.setDockState({ order: [...state.order], activeKey: state.activeKey });
+ return;
+ }
+ writeWeb(state);
+}
diff --git a/packages/app/src/lib/new-session-choice.ts b/packages/app/src/lib/new-session-choice.ts
new file mode 100644
index 000000000..87f70dae5
--- /dev/null
+++ b/packages/app/src/lib/new-session-choice.ts
@@ -0,0 +1,19 @@
+/**
+ * The shape of the sessions dock's "New" split-button primary pick, sticky across
+ * the three session families (a bare terminal, a CLI chat, an in-app agent thread).
+ *
+ * The pick itself is now computed by the shared `resolveLauncherSelection`
+ * (`lib/acp/launcher-selection.ts`) — the single, enablement-aware selection rule
+ * every launcher surface uses. This module keeps only the button's contract type.
+ */
+
+import type { TerminalCli } from '@inkeep/open-knowledge-core';
+import type { RegisteredAgent } from '@/lib/acp/registered-agents';
+
+/** The primary pick a New-session click launches. */
+export type NewSessionChoice =
+ | { readonly kind: 'terminal' }
+ | { readonly kind: 'cli'; readonly cli: TerminalCli }
+ // `agent === null` means "start an agent, but no concrete one is remembered"
+ // — the primary click opens Settings rather than launching blindly.
+ | { readonly kind: 'agent'; readonly agent: RegisteredAgent | null };
diff --git a/packages/app/src/lib/unified-agent-store.test.ts b/packages/app/src/lib/unified-agent-store.test.ts
index a149a21e0..dd262c5d6 100644
--- a/packages/app/src/lib/unified-agent-store.test.ts
+++ b/packages/app/src/lib/unified-agent-store.test.ts
@@ -5,19 +5,22 @@
* prior pick (from either old surface) survives the consolidation.
*/
-import { describe, expect, test } from 'bun:test';
import {
type HandoffTarget,
type InstallState,
TERMINAL_CLI_IDS,
} from '@inkeep/open-knowledge-core';
+import { describe, expect, test } from 'vitest';
import {
+ IN_APP_THREAD_ID,
loadStickyAgent,
parseStickyCliId,
+ parseStickyThreadAgent,
resolveStickyAgent,
saveStickyAgent,
TERMINAL_CLI_ID,
terminalCliId,
+ threadAgentId,
UNIFIED_AGENT_KEY,
} from './unified-agent-store';
@@ -160,3 +163,43 @@ describe('terminalCliId / parseStickyCliId', () => {
expect(resolved?.id).toBe('codex');
});
});
+
+describe('threadAgentId / parseStickyThreadAgent', () => {
+ test('round-trips a concrete registered agent through the sentinel', () => {
+ const id = threadAgentId({ source: 'registry', id: 'acme-agent' });
+ expect(id).toBe('in-app-thread:registry:acme-agent');
+ expect(parseStickyThreadAgent(id)).toEqual({
+ kind: 'concrete',
+ source: 'registry',
+ id: 'acme-agent',
+ });
+ });
+
+ test('the bare legacy sentinel parses as the default in-app agent', () => {
+ expect(parseStickyThreadAgent(IN_APP_THREAD_ID)).toEqual({ kind: 'default' });
+ });
+
+ test('a custom-source agent id round-trips', () => {
+ expect(parseStickyThreadAgent(threadAgentId({ source: 'custom', id: 'my-agent' }))).toEqual({
+ kind: 'concrete',
+ source: 'custom',
+ id: 'my-agent',
+ });
+ });
+
+ test('a non-thread id (CLI sentinel / app target / junk / null) parses to null', () => {
+ expect(parseStickyThreadAgent(terminalCliId('codex'))).toBeNull();
+ expect(parseStickyThreadAgent('claude-code')).toBeNull();
+ expect(parseStickyThreadAgent('in-app-thread:bogus:x')).toBeNull(); // unknown source
+ expect(parseStickyThreadAgent('in-app-thread:registry:')).toBeNull(); // empty id
+ expect(parseStickyThreadAgent(null)).toBeNull();
+ });
+
+ test('a concrete thread-agent sticky id is invisible to the CLI + app-target readers', () => {
+ const id = threadAgentId({ source: 'registry', id: 'acme-agent' });
+ // The unified store is shared with the Ask-AI composers; a concrete agent
+ // pick must degrade to "not mine" for the CLI + app-target resolvers.
+ expect(parseStickyCliId(id)).toBeNull();
+ expect(resolveStickyAgent(states({ codex: true }), id)?.id).toBe('codex');
+ });
+});
diff --git a/packages/app/src/lib/unified-agent-store.ts b/packages/app/src/lib/unified-agent-store.ts
index 75de091ff..272093675 100644
--- a/packages/app/src/lib/unified-agent-store.ts
+++ b/packages/app/src/lib/unified-agent-store.ts
@@ -56,6 +56,67 @@ export function terminalCliId(cli: TerminalCli): string {
return `${TERMINAL_CLI_ID}:${cli}`;
}
+/**
+ * Picker sentinel for the in-app agent-thread mode ("Start an agent").
+ * Distinct from every `HandoffTarget` id and the CLI sentinels; persisted
+ * like a sticky agent choice. `parseStickyCliId` returns null for it and
+ * `resolveStickyAgent` (app targets only) never returns it, so callers gate
+ * thread mode explicitly (`id === IN_APP_THREAD_ID`) — the same shape the
+ * CLI sentinel uses. On terminal-only surfaces it degrades via
+ * `resolveDefaultCli` to the default CLI, harmlessly.
+ *
+ * Two forms coexist (additive parse, no key bump — see {@link parseStickyThreadAgent}):
+ * - the bare `in-app-thread` sentinel — "in-app thread, whatever the default
+ * registered agent is" (what the Ask-AI composers persist);
+ * - the concrete `in-app-thread:<source>:<id>` form the unified sessions dock's
+ * New split-button persists so its primary repeats the exact agent last
+ * launched, alongside the CLI sentinel and the bare-terminal flag. A concrete
+ * value still degrades to "the default agent" for any reader that only knows
+ * the bare sentinel, so it is safe for the shared Ask-AI surfaces too.
+ */
+export const IN_APP_THREAD_ID = 'in-app-thread';
+
+/**
+ * Per-agent picker sentinel — `in-app-thread:<source>:<id>` (e.g.
+ * `in-app-thread:registry:acme-agent`). The concrete twin of {@link IN_APP_THREAD_ID},
+ * persisted so the sessions dock's New button primary relaunches the exact agent
+ * the user last chose. `parseStickyThreadAgent` reads it back; every other reader
+ * (`parseStickyCliId`, `resolveStickyAgent`) treats it as "not mine" and degrades
+ * harmlessly, so it never leaks a concrete agent into the CLI / app-target paths.
+ */
+export function threadAgentId(agent: { source: 'registry' | 'custom'; id: string }): string {
+ return `${IN_APP_THREAD_ID}:${agent.source}:${agent.id}`;
+}
+
+/** A persisted sticky pick that names the in-app agent-thread launcher. */
+export type StickyThreadAgent =
+ | { readonly kind: 'concrete'; readonly source: 'registry' | 'custom'; readonly id: string }
+ | { readonly kind: 'default' };
+
+/**
+ * Parse a persisted sticky id into the in-app-thread launcher it names, or `null`
+ * when it does not name one:
+ * - `in-app-thread` → `{ kind: 'default' }` (use the default registered agent);
+ * - `in-app-thread:<source>:<id>` → `{ kind: 'concrete', source, id }`;
+ * - anything else (a CLI sentinel, a `HandoffTarget`, junk, or null) → `null`.
+ *
+ * Additive over the bare sentinel: a value written before the concrete form
+ * existed still parses as `{ kind: 'default' }`, so no storage migration is needed.
+ */
+export function parseStickyThreadAgent(id: string | null): StickyThreadAgent | null {
+ if (id === null) return null;
+ if (id === IN_APP_THREAD_ID) return { kind: 'default' };
+ const prefix = `${IN_APP_THREAD_ID}:`;
+ if (!id.startsWith(prefix)) return null;
+ const rest = id.slice(prefix.length);
+ const sep = rest.indexOf(':');
+ if (sep <= 0) return null;
+ const source = rest.slice(0, sep);
+ const agentId = rest.slice(sep + 1);
+ if ((source !== 'registry' && source !== 'custom') || agentId === '') return null;
+ return { kind: 'concrete', source, id: agentId };
+}
+
/**
* Parse a persisted sticky id back into a `TerminalCli`, or `null` when it does
* not name a CLI launcher. The bare legacy `terminal-cli` sentinel maps to
diff --git a/packages/app/src/lib/use-settings-route.test.ts b/packages/app/src/lib/use-settings-route.test.ts
index bf8b82906..4830bac5e 100644
--- a/packages/app/src/lib/use-settings-route.test.ts
+++ b/packages/app/src/lib/use-settings-route.test.ts
@@ -3,8 +3,13 @@
* of `useSettingsRoute` itself lives in `use-settings-route.dom.test.tsx`.
*/
-import { describe, expect, test } from 'bun:test';
-import { isSettingsHashOpen, isSettingsShortcut, SETTINGS_OPEN_HASH } from './use-settings-route';
+import { describe, expect, test } from 'vitest';
+import {
+ isSettingsHashOpen,
+ isSettingsShortcut,
+ SETTINGS_OPEN_HASH,
+ settingsHashSection,
+} from './use-settings-route';
describe('isSettingsHashOpen', () => {
test('empty hash → false', () => {
@@ -24,19 +29,24 @@ describe('isSettingsHashOpen', () => {
expect(isSettingsHashOpen('settings')).toBe(true);
});
- test('legacy sub-routes are no longer recognized', () => {
- // Pre-redesign hashes (`#settings/project`, `#settings/user`) carried
- // the scope toggle state. Sub-routes were dropped when the toggle
- // went away. Anyone still navigating to a sub-route gets `false`
- // here — entry points (HelpPopover, CommandPalette, Cmd-,, Electron
- // menu) all use `SETTINGS_OPEN_HASH` so they're unaffected.
- expect(isSettingsHashOpen('#settings/project')).toBe(false);
- expect(isSettingsHashOpen('#settings/user')).toBe(false);
+ test('section deep-links open (unknown sections fall back to the default)', () => {
+ // `#settings/<section>` opens Settings to that sidebar section — the
+ // launcher dropdowns' "Settings" row uses `#settings/configure-agents`.
+ // An unrecognized section (e.g. the pre-redesign `project`/`user` scope
+ // hashes) still opens; the shell falls back to Preferences for an id that
+ // matches no sidebar item.
+ expect(isSettingsHashOpen('#settings/configure-agents')).toBe(true);
+ expect(isSettingsHashOpen('#settings/project')).toBe(true);
+ expect(isSettingsHashOpen('#settings/user')).toBe(true);
+ expect(settingsHashSection('#settings/configure-agents')).toBe('configure-agents');
});
test('typo / unrecognized hash → false', () => {
expect(isSettingsHashOpen('#settings-typo')).toBe(false);
+ // A bare `#settings/` (empty section) does not count as open.
expect(isSettingsHashOpen('#settings/')).toBe(false);
+ expect(settingsHashSection('#settings/')).toBeNull();
+ expect(settingsHashSection('#settings')).toBeNull();
});
});
diff --git a/packages/app/src/lib/use-settings-route.ts b/packages/app/src/lib/use-settings-route.ts
index 9c69c5e2e..1537bd1d9 100644
--- a/packages/app/src/lib/use-settings-route.ts
+++ b/packages/app/src/lib/use-settings-route.ts
@@ -1,10 +1,16 @@
/**
* Hash-based routing for the Settings dialog.
*
- * One recognized hash form: `#settings` → dialog open.
+ * Two recognized hash forms: `#settings` → dialog open on its default section;
+ * `#settings/<section-id>` → dialog open with that sidebar section active (an
+ * entry-point deep link, e.g. the launcher dropdowns' "Settings" row opening
+ * `#settings/configure-agents`). The `<section-id>` matches a sidebar item id
+ * in `SettingsDialogShell`; an unknown id falls back to the default section.
+ *
* The earlier per-scope sub-routes (`#settings/project`, `#settings/user`)
* went away when the scope toggle was removed; sidebar group membership
- * communicates scope now, so there's nothing to encode in the hash.
+ * communicates scope now. The section sub-route below encodes the target
+ * sidebar item, not a scope.
*
* Closing the dialog navigates back via `history.back()` so the prior
* doc hash is restored when settings was opened from a doc view. If the
@@ -33,9 +39,30 @@ import {
*/
export const SETTINGS_OPEN_HASH = '#settings';
+/** Hash that opens Settings directly to a sidebar section (deep link). */
+function settingsSectionHash(sectionId: string): string {
+ return `#settings/${sectionId}`;
+}
+
+/** Sidebar item id for the User → Configure agents section. */
+const CONFIGURE_AGENTS_SECTION = 'configure-agents';
+
+/**
+ * Open Settings straight to Configure agents — the "Settings" row every agent
+ * launcher dropdown funnels through so the deep-link literal is single-sourced
+ * (mirrors `SETTINGS_OPEN_HASH` usage in `SettingsButton`).
+ */
+export function openAgentSettings(): void {
+ if (typeof window === 'undefined') return;
+ const target = settingsSectionHash(CONFIGURE_AGENTS_SECTION);
+ if (window.location.hash !== target) window.location.hash = target;
+}
+
interface SettingsRouteState {
- /** True when the dialog is open (hash is `#settings`). */
+ /** True when the dialog is open (hash is `#settings` or `#settings/<id>`). */
open: boolean;
+ /** Target sidebar section id from `#settings/<id>`, or null for the default. */
+ section: string | null;
/** Close the dialog via `history.back()`. No-op when already closed. */
close: () => void;
}
@@ -57,7 +84,18 @@ export function isSettingsShortcut(e: ShortcutEventLike): boolean {
export function isSettingsHashOpen(hash: string): boolean {
const cleaned = hash.replace(/^#/, '');
- return cleaned === 'settings';
+ if (cleaned === 'settings') return true;
+ // `#settings/<section>` opens to that section; require a non-empty section so
+ // a bare `#settings/` does not count as open.
+ return cleaned.startsWith('settings/') && cleaned.length > 'settings/'.length;
+}
+
+/** The sidebar section id encoded in `#settings/<id>`, or null for `#settings`. */
+export function settingsHashSection(hash: string): string | null {
+ const cleaned = hash.replace(/^#/, '');
+ if (!cleaned.startsWith('settings/')) return null;
+ const section = cleaned.slice('settings/'.length);
+ return section.length > 0 ? section : null;
}
function readCurrentHash(): string {
@@ -67,6 +105,9 @@ function readCurrentHash(): string {
export function useSettingsRoute(): SettingsRouteState {
const [open, setOpen] = useState<boolean>(() => isSettingsHashOpen(readCurrentHash()));
+ const [section, setSection] = useState<string | null>(() =>
+ settingsHashSection(readCurrentHash()),
+ );
useEffect(() => {
const onHashChange = () => {
@@ -83,7 +124,9 @@ export function useSettingsRoute(): SettingsRouteState {
// genuinely needs to fetch); the dialog shell paints synchronously
// in either case because it lives in the main bundle.
startTransition(() => {
- setOpen(isSettingsHashOpen(readCurrentHash()));
+ const hash = readCurrentHash();
+ setOpen(isSettingsHashOpen(hash));
+ setSection(settingsHashSection(hash));
});
};
window.addEventListener('hashchange', onHashChange);
@@ -96,5 +139,5 @@ export function useSettingsRoute(): SettingsRouteState {
window.history.back();
};
- return { open, close };
+ return { open, section, close };
}
diff --git a/packages/app/src/locales/en/messages.json b/packages/app/src/locales/en/messages.json
index e84ee4948..03fe1521d 100644
--- a/packages/app/src/locales/en/messages.json
+++ b/packages/app/src/locales/en/messages.json
@@ -10,6 +10,7 @@
],
"-3ois8": ["Hard break"],
"-5jISU": [["0", "plural", { "one": ["#", " template"], "other": ["#", " templates"] }]],
+ "-7s4fw": ["Search agents"],
"-8PP0T": ["Match case"],
"-FeyRg": ["Keep original file"],
"-K0AvT": ["Disconnect"],
@@ -58,7 +59,7 @@
"0LBDjY": ["\"", ["0"], "\" uninstalled — back to a draft"],
"0NA4b3": ["Keep my version"],
"0NkNB5": [["0"], "mo ago"],
- "0SBTff": ["Show terminal"],
+ "0QVrvp": ["Maximum agents already running"],
"0TnCvC": ["Rename ", ["0"]],
"0YEbfk": ["Connect to AI tools"],
"0YUS3Q": ["Subfolder under current folder"],
@@ -90,7 +91,9 @@
"10g8I_": ["Turn off Only markdown files"],
"12F9WL": ["(no id)"],
"151wvk": ["Show sidebar"],
+ "161NCV": ["Stopping"],
"16D5Zj": ["Are you sure you want to delete ", ["itemName"], "? This action cannot be undone."],
+ "16eIWu": ["Force stop"],
"170Js2": ["Hide panel"],
"1AumWo": ["Push failed — check the server logs for details."],
"1CalO6": ["Style"],
@@ -99,7 +102,6 @@
"1FLarN": ["Describe what you want to create to continue"],
"1GhYxC": ["of ", ["totalPages"]],
"1HBhDS": ["Checking out files"],
- "1MGRQl": ["Terminal sessions"],
"1OKzC_": ["Your report couldn't be sent. Try again or email it instead."],
"1QfxQT": ["Dismiss"],
"1RluQD": ["Show replace"],
@@ -110,6 +112,7 @@
],
"1YJ4Yg": ["Update available", ["0"]],
"1ZpfyB": ["Open with AI ", ["displayName"], ", ", ["hint"]],
+ "1a6ICf": ["Following the agent's edits"],
"1bDVu5": ["Workspace Command Palette"],
"1d1F11": ["Select all files and folders"],
"1di5fu": ["Document not found"],
@@ -123,6 +126,7 @@
"2277Tu": ["Collapse graph"],
"237hSL": ["Ended"],
"25Pw6a": ["Cloning"],
+ "27TLNq": ["Enable ", ["displayName"], " CLI"],
"27XW26": ["Clone happens in the Project Navigator. Reclick the share link there."],
"28B21t": ["Agent Skills"],
"29VNqC": ["Unknown error"],
@@ -155,7 +159,9 @@
["FULLSCREEN_HUB_LIMIT"],
" results."
],
+ "2ojpo0": ["Dock sessions on the right"],
"2q_Q7x": ["Visibility"],
+ "2rLM8r": ["Couldn't start the agent thread — please try again."],
"2ryd91": ["Failed to rename property"],
"2tgFCe": ["Starting clone"],
"2vIPtm": ["Open link in new tab"],
@@ -177,7 +183,6 @@
"3HNlwb": ["Hello, world!"],
"3Ib6FN": ["Move down"],
"3Ijjy1": ["Couldn't load this skill's files."],
- "3IseAk": ["Install an AI agent to create with AI"],
"3J7d2N": ["Big section heading."],
"3JYy1p": ["Branch ", ["0"], " no longer exists. Cloned to default branch."],
"3MnvrL": ["Showing top ", ["0"], " matches — keep typing to narrow"],
@@ -203,6 +208,7 @@
"3m2GBo": ["Searching docs"],
"3mFsc3": ["Restore with remote changes"],
"3o3tur": ["Starter content"],
+ "3oEK1e": ["Resuming the conversation"],
"3oh0nQ": ["Nested .okignore error in ", ["path"]],
"3pU8e-": ["Pin tab"],
"3wiBAs": ["Where should it live?"],
@@ -238,6 +244,7 @@
"Detected from the editors this project is set up for. Adjust to control where every skill installs."
],
"4buZWd": ["Inherited from ", ["path"]],
+ "4cEClj": ["Sessions"],
"4c_a6S": ["Nothing set yet."],
"4g19V6": ["Failed to update property"],
"4h3e0H": ["Couldn't update skills sharing — ", ["detail"], "."],
@@ -282,6 +289,7 @@
"5OTgC7": ["Open and focus the bottom Ask AI prompt composer."],
"5OqaJi": ["Enter a project name"],
"5PHgV2": ["You can also create one from a terminal with <0>ok bug-report</0>."],
+ "5PrrYw": ["Start ", ["agentName"]],
"5QGTaA": ["Could not copy relative path"],
"5SwVv1": ["Not installed"],
"5Tk8Fb": ["Loading files"],
@@ -299,6 +307,7 @@
["userToken"],
"</1> to fill in today's date or the author's name automatically."
],
+ "5jEnaB": ["Not available on this platform"],
"5kWklo": ["(some may already be hidden by other rules)"],
"5lWFkC": ["Sign in"],
"5mksg0": ["Failed to disable semantic search — ", ["detail"]],
@@ -318,6 +327,7 @@
}
]
],
+ "5vYdh9": ["New thread with ", ["0"]],
"5wV2qQ": ["and more"],
"5y_9lO": ["Waiting for authorization"],
"6-wLTJ": [["behind"], " behind origin"],
@@ -396,8 +406,11 @@
"7d1a0d": ["Public"],
"7hctf2": ["Describe the project you want to create"],
"7jIIFX": ["You're all set up!"],
+ "7kb4LU": ["Approved"],
+ "7l15X4": ["failed"],
"7qRHf0": ["Install for Claude Chat & Cowork"],
"7uBlRT": ["Copy the focused file-tree item so Paste can duplicate it."],
+ "7vQdBK": ["Loading the conversation"],
"80c4-P": ["Code copied to clipboard"],
"81H_23": ["Add properties"],
"881Uwh": ["Delete selected table"],
@@ -438,6 +451,7 @@
"8lwQlE": [["0"], " added, ", ["1"], " removed"],
"8m8diM": ["No location selected. Use Browse to choose a folder."],
"8nWu1k": ["Empty diagram"],
+ "8t9CRE": ["Starting ", ["agentName"], "…"],
"8tjQCz": ["Explore"],
"8uAWix": [
"This template lives in a parent folder — deleting it affects every folder beneath it that doesn't define its own version."
@@ -496,10 +510,12 @@
],
"AB4qw9": ["New terminal"],
"AE7BY3": ["The terminal session ended."],
+ "AIVHDc": ["Choose what a new session starts"],
"AIn2Yv": [["displayName"], " CLI, ", ["hint"]],
"AItsE5": ["Open it there"],
"AKxFtn": [["openedWorktreeCount", "plural", { "one": ["worktree"], "other": ["worktrees"] }]],
"ALhMYW": ["Terminal"],
+ "APNlbk": ["exit ", ["0"]],
"AQ-Lfg": ["Couldn't load templates"],
"AQGtjK": [
"Commands run with the full access of your macOS user account on this machine. Turn this off to disable the shell."
@@ -565,6 +581,7 @@
"Bh9671": [
"This project is local-only, so .ok/skills is hidden from git and these skills can't be committed or shared. Share just the skills folder — the rest of your OK config stays on this computer."
],
+ "BjitBo": ["Download ", ["0"]],
"Bn9-El": ["default"],
"Bv5a9_": ["Selection statistics"],
"Bx4EXG": ["Actions for ", ["label"]],
@@ -575,12 +592,14 @@
"C62P6b": ["Editor selection"],
"C7XjNB": ["Global Skill"],
"C9TBvF": ["No Outgoing"],
+ "CBsdhe": ["The agent isn't stopping. Force stop closes this thread and quits the agent."],
"CCTop_": ["Recent"],
"CFnavk": ["This project isn't a git repository, so worktrees aren't available."],
"CKyk7Q": ["Go back"],
"COr1Y7": [
"Pick <0>openknowledge.skill</0> from your <1>Downloads</1> folder. It enables automatically."
],
+ "CPmYSG": ["Checking for agents"],
"CSL0l1": ["Couldn't clear the key — please try again."],
"CTJLpz": ["\"", ["trimmed"], "\" already exists here"],
"CU3AiE": ["Switching branches"],
@@ -599,6 +618,7 @@
"Ck9XRt": ["Couldn't save the key — please try again."],
"CmeH9S": ["Add property to ", ["keyName"]],
"CoHvYd": ["Moved ", ["0"], " to position ", ["1"], " of ", ["2"]],
+ "CooKEf": ["Dock sessions at the bottom"],
"CvsD6Y": ["via ", ["viaTags"]],
"D-Oh1s": ["How to set up ", ["0"], " (opens in browser)"],
"D12vtS": ["(detached)"],
@@ -618,6 +638,7 @@
"DFfRbX": ["Sync status: ", ["syncStateLabel"], " — git identity unset"],
"DId6MT": ["Project-level pages with no outgoing graph edges."],
"DJd000": ["Activate the previous editor tab."],
+ "DMeaxi": ["Downloading ", ["0"], " ", ["1"], "…"],
"DPfwMq": ["Done"],
"DTI-fp": [
"This ",
@@ -679,6 +700,7 @@
"EL_YRd": ["Mirror of <0>api-spec</0>"],
"ENpRJV": ["External link previews"],
"EOjU5V": ["Inline Math Properties"],
+ "EPwuTC": [["usedLabel"], " / ", ["sizeLabel"], " tokens used"],
"ETyvvg": ["No language match."],
"EVnzPs": ["Edit with AI"],
"EWPtMO": ["Code"],
@@ -693,6 +715,7 @@
"Ea1prf": ["Choose which editors every skill in this project installs into."],
"EarrCe": ["Search emoji"],
"Eax_et": ["Accent"],
+ "EbMUlU": ["Agent mode"],
"EbZT7P": ["Toggle the left file sidebar."],
"EbjWsS": ["Current commit"],
"EcM3k7": ["Failed to clean up pending ", ["kind"]],
@@ -706,6 +729,15 @@
"Eji13z": ["Toggle highlight formatting."],
"EkH9pt": ["Update"],
"El7NbA": ["Heading 2"],
+ "ElatXA": [
+ "Context window: ",
+ ["percent"],
+ "% used, ",
+ ["usedLabel"],
+ " of ",
+ ["sizeLabel"],
+ " tokens"
+ ],
"Emz5BG": [
"Embeddings are computed only when a search runs and are cached locally under <0>.ok/local</0>."
],
@@ -754,6 +786,7 @@
"FgRAvd": ["Logs & system info"],
"FjkaiT": ["Zoom out"],
"FnMkli": ["Sync disabled — you don't have permission to push"],
+ "FqGWeR": ["Couldn't reach the agent registry."],
"FqTpiN": ["Bird wiki"],
"Fqr8BP": ["Multi-page PDF viewer with toolbar controls (thumbnails, page nav, zoom)."],
"Fsx78O": ["Add the <0>ok</0> command to your terminal"],
@@ -773,6 +806,7 @@
"G1XxbZ": ["Checkbox"],
"G4-bgo": ["Ask AI (from selection)"],
"G7-rf8": ["Pattern syntax error: ", ["message"]],
+ "G7bn_N": ["Start an agent"],
"G7cMuO": ["HTML preview"],
"G8t9NN": ["Add a property"],
"GA-UkN": [["keyName"], " type: ", ["typeLabel"], ". Click to change."],
@@ -877,6 +911,7 @@
"If0crP": ["Open with AI ", ["targetDisplayName"], ", ", ["hint"]],
"IgTwLt": ["Open this document in the editor and collapse the graph."],
"Ik-gP0": ["Heading H", ["level"], ": ", ["text"]],
+ "IlH15B": ["Start a session with the + button, or launch an agent from a page."],
"Iq8zdU": ["Close terminal"],
"IrB5AK": [
"Server-side cleanup failed for ",
@@ -911,8 +946,10 @@
"JfPuv7": [["shareBranch"], " isn't a valid branch name."],
"Jhj_lh": ["Modify the link target, anchor, and display label."],
"JkCD2u": ["Sync paused — you don't have permission to push to this repo"],
+ "JlFcis": ["Send"],
"JmfgFc": ["(a worktree of ", ["0"], ")"],
"Jqqevv": ["System error"],
+ "JsY1p5": ["Denied"],
"JtD-Br": ["Page link"],
"Jw6EC4": ["Branch switch failed — try opening the ", ["targetNoun"], " manually."],
"K-a33w": ["Start writing to create this page"],
@@ -943,6 +980,7 @@
"KPW5WC": ["moved template"],
"KQGZuq": ["Reused if it already exists, created if not."],
"KRJ6xh": ["No tags yet. Continue typing to create one."],
+ "KUjOb9": ["running"],
"KWL_Ih": ["Blog post"],
"KX1MZR": ["Your repositories"],
"KYSocE": ["Research the extinction of flightless birds"],
@@ -969,7 +1007,9 @@
"KtACeE": ["Default: <0>", ["0"], "</0>"],
"KujtjC": ["Find"],
"L-rMC9": ["Reset to default"],
+ "L1BQTH": [["0"], " isn't installed yet — opening its download page."],
"L1ZE3M": ["Document statistics"],
+ "L1qaHQ": ["Approved — ", ["0"]],
"L1rRuU": ["Embeddings API endpoint"],
"L3CEC1": ["this item"],
"L4Cdd9": ["or create a new file <0/>"],
@@ -992,6 +1032,7 @@
],
"LKOLNn": ["No AI agents installed"],
"LNum6A": [["minutes"], " min ago"],
+ "LPAv9E": [["days"], "d ago"],
"LRgZAt": [["owner"], "/", ["name"], " already exists"],
"LXdWeS": ["Medium section heading."],
"LXfNU-": ["Navigation and suggestions"],
@@ -1047,6 +1088,7 @@
],
"MHrjPM": ["Title"],
"MJqRO6": ["Your report is being sent."],
+ "MJuO1q": ["Context window:"],
"MKOVhz": ["Enable git auto-sync"],
"MQIM_Y": ["Couldn't copy. Select the URL above to copy it manually."],
"MRZxAn": ["Edited"],
@@ -1081,6 +1123,7 @@
["0"],
" — your previous version is in history if you need to restore it."
],
+ "MysZUL": ["Connecting to ", ["agentName"], "…"],
"N1KkEO": ["Jump to last tab"],
"N1YYa7": ["Loading image"],
"N1mdmS": ["This file can't be opened in the text editor."],
@@ -1110,6 +1153,7 @@
"N_7kkF": [
"Read through this codebase and draft a technical spec for the most complex module: an overview, the architecture, key files, and open questions, all linked from a specs index page."
],
+ "Nay2Yr": ["No agents match your search."],
"NcurBF": ["Pan down"],
"NgZwB0": [["enabledCount"], "/", ["0"], " on"],
"NjrIak": ["File: <0>", ["fixedName"], ".md</0>"],
@@ -1142,6 +1186,7 @@
"OFBmkg": [
"Search files, commands, projects, and AI handoff actions. With text selected in the visual editor, this chord adds a link instead."
],
+ "OJOA7Z": ["⋯ ", ["0"], " unchanged lines"],
"OJTOUj": ["Requires ", ["brand"], "."],
"OJeiSH": ["Failed to add property"],
"OLBz-_": ["Mermaid diagram failed to render."],
@@ -1157,6 +1202,9 @@
"OYnx7O": ["Path cannot start with \"/\""],
"OZJeTZ": ["Skill"],
"Oawo4U": ["The report service couldn't be reached."],
+ "OcBurH": [
+ "Choose which agents appear in the agent selector. Turn one off to hide it everywhere."
+ ],
"OdmsFg": ["Failed to delete item"],
"OeAl1e": ["e.g. assets/uploads"],
"OfhWJH": ["Reset"],
@@ -1222,6 +1270,7 @@
"Q6hhn8": ["Preferences"],
"Q7W-mC": ["Same folder as current file"],
"Q7cNKe": ["Skills are now shared. Commit .ok/skills to share them with your team."],
+ "Q7xfEj": ["done"],
"Q8A-U_": ["Connected to"],
"QAi7Q9": [
"Branch <0>",
@@ -1229,11 +1278,12 @@
"</0> already has a worktree — it'll open in its own window."
],
"QDZbvN": [["diffDays"], "d ago"],
- "QJaG-9": ["Choose CLI for new chat"],
- "QNxpRm": ["Dock terminal to the right"],
+ "QM3SBZ": ["Plan (", ["done"], "/", ["0"], ")"],
"QOINDn": ["empty"],
+ "QQbwzK": ["No agents available."],
"QQghPu": ["Install in Claude Desktop"],
"QR5SP1": ["created template"],
+ "QTsvh1": ["This agent needs you to sign in first — see the notice below."],
"QYfQdv": [["displayName"], " CLI"],
"QcpeeE": ["Navigate to ", ["docName"]],
"QfFBdJ": ["The template's filename (without `.md`)."],
@@ -1279,6 +1329,7 @@
"RO-yts": ["Failed to disable link previews — ", ["detail"]],
"RSqaSd": ["Project root"],
"RVZJWQ": ["Search projects..."],
+ "RXEbZy": ["In app"],
"RXNu_r": ["Shared via git with everyone working on this project."],
"RY6Bq1": ["Open shared ", ["targetNoun"]],
"RaPMZv": ["Keyboard shortcuts available in the editor and workspace."],
@@ -1305,6 +1356,8 @@
],
"S33tz3": ["Not connected"],
"S34Vju": ["Have something else in mind?"],
+ "S48xcO": ["pending"],
+ "S60KvX": ["Delete this conversation?"],
"S6l5dv": ["Could not start creating a new item"],
"S9Vnum": ["Remove ", ["patternText"]],
"S9t1PI": ["Fixing ", ["0"], "/", ["1"]],
@@ -1312,6 +1365,7 @@
"SCzAbA": [["phase"], " — ", ["pct"], "%"],
"SFN6dN": ["Heading 3"],
"SOPwPh": ["Restore to this edit"],
+ "SQWJ-i": ["Restore sessions"],
"STTOnz": [["keyName"], " type: complex value (nested; read-only)"],
"SUOoXn": ["Failed to open project."],
"SVLPt5": [["formatted"], " GitHub stars"],
@@ -1348,6 +1402,7 @@
"T_wG4n": ["We couldn't check your GitHub connection."],
"Ta25TG": ["No history yet"],
"TbjyhA": ["Docs"],
+ "TdfEV7": ["Archived"],
"Te6sK2": [
"Heads up: editing any rule or option here creates a <0>.markdownlint.json</0> file in your project to save your changes."
],
@@ -1357,6 +1412,7 @@
"TvY_XA": ["Documentation"],
"TwYboS": ["Navigate CodeMirror source search results or dismiss the search panel."],
"Tz0i8g": ["Settings"],
+ "Tz4dq-": ["This request is no longer active."],
"Tz9pJB": ["Clone stream ended unexpectedly — check if the clone completed"],
"U2Kx6T": ["Close all unpinned"],
"U2pMtf": ["tag-name"],
@@ -1436,7 +1492,6 @@
"VU3Nrn": ["Missing"],
"VUijjF": ["Embed an image with optional alt text."],
"VYd_YA": ["Open an existing project folder from disk."],
- "VZGGPK": ["Collapse terminal"],
"VZGh8G": ["Fold, unfold, fold all, or unfold all source ranges."],
"VZSBXL": ["Semantic ranking activates the first time an agent runs a search."],
"V_6bJ4": ["Terminal settings not loaded yet — try again in a moment."],
@@ -1492,6 +1547,7 @@
"Wcv-Zi": ["Make this knowledge base available as a Claude Skill."],
"We7h2I": ["📝 or assets/icon.png"],
"Weq9zb": ["General"],
+ "Wfy3rU": ["Agent settings"],
"Wgmlsw": ["Fetching"],
"Wh0im4": ["editing [[", ["realCurrentDoc"], "]]"],
"WhOsNE": ["Strikethrough"],
@@ -1514,10 +1570,14 @@
"XDzAnp": ["Opens in a new tab"],
"XH30C4": ["document"],
"XJOV1Y": ["Activity"],
+ "XNBGZw": ["Message not sent: ", ["0"]],
"XPJ0sN": [["settingsDescriptorLabel"], " properties"],
"XPqe3B": ["Create new tag #", ["tagValue"]],
+ "XQkJlB": ["No open conversations. Reopen a past one, or start a session with the + button."],
"XRuL0i": ["Create page"],
+ "XT-L4j": ["Turn on an agent to create with AI"],
"XU0OXn": ["Enable auto-sync"],
+ "XU5AOg": ["Input"],
"XV5sC0": ["Open worktree"],
"XW18jo": ["Page headings response did not match success schema"],
"XYlJJT": ["Setting up"],
@@ -1530,6 +1590,7 @@
"Xk0-VC": [
"Previews of links to other documents in this project are always on and read from the local index — nothing leaves your computer for those."
],
+ "XklovM": ["Working…"],
"Xl-UUg": ["guides/install or https://example.com"],
"XmJfZT": ["name"],
"XnlF3W": ["Add the next matching source selection."],
@@ -1554,8 +1615,10 @@
["pickedRelative"],
"</1> because it contains a <2>.git</2> folder (one .ok/ per git repo). <3>Content directory</3> defaults to <4>.</4> (the whole repo); type a sub-folder to narrow it."
],
+ "Y2tU6I": ["Delete ", ["0"]],
"Y6SK9K": ["Show source"],
"Y8ViJx": ["A newer version may have been deployed since this tab opened."],
+ "YBt9YP": ["Beta"],
"YC6_wP": ["Edit ", ["keyName"]],
"YEIS9T": ["Edits apply live. Light or dark is chosen from the background."],
"YEP3X2": ["Delete a table when the active table cell selection covers the full table."],
@@ -1570,6 +1633,8 @@
"YSFv5w": ["No git repository — config sharing does not apply here."],
"YTLmTM": ["Remove the parent <0>.git</0> folder"],
"YW7Q86": ["Search settings not yet loaded — try again in a moment"],
+ "Y_GpJd": ["The ", ["0"], " download request timed out."],
+ "Y_ZQ6l": ["Installing ", ["agentName"], "…"],
"Y_kL7X": ["Customize how the editor looks and behaves."],
"YaeyFh": ["Pulls may overwrite uncommitted edits in your local files."],
"Yea-K5": ["Restore to this point"],
@@ -1659,6 +1724,7 @@
"_NX6gG": ["Managing project AI tools is unavailable in this build."],
"_PACVa": ["Release notes"],
"_PBJRl": ["Add at least one letter or number."],
+ "_Pmhxt": ["… earlier output trimmed"],
"_QwkMu": ["No matching paths"],
"_RcqUM": [
"You picked your home directory. OpenKnowledge will index everything in your home tree — large and may surface personal files."
@@ -1677,6 +1743,7 @@
"_azghp": ["Previous change"],
"_bth6g": ["Claude Code is installed, but OpenKnowledge tools aren't connected to it yet."],
"_eguJc": ["Uploading"],
+ "_gO_m8": ["Waiting for your approval"],
"_gkGSK": ["deleted template"],
"_hPpdX": ["Skill renamed"],
"_pY_Vq": ["The repository was moved, renamed, or deleted."],
@@ -1707,6 +1774,9 @@
"aWlJai": ["Starting sign-in flow"],
"a_u4ck": ["Loading tags"],
"aaE55D": ["Clear ", ["keyName"]],
+ "aaI6cN": [
+ "Couldn't connect to the agent service. Make sure the OpenKnowledge server is running and up to date (restart it if it was already running), then try again."
+ ],
"aalx4E": ["Editing broken MDX source: ", ["reason"]],
"abiHje": ["Delete selected items"],
"adsMWO": ["Resolving deltas"],
@@ -1757,6 +1827,7 @@
"c8jBgX": ["Checking for updates on GitHub"],
"cEoyWz": ["Add item to ", ["keyName"]],
"cF9DyA": ["Reconnecting after server restart"],
+ "cFCKYZ": ["Deny"],
"cGV6Mh": [
"Show a preview card when you hover an external link in the editor. This setting applies only to this computer."
],
@@ -1828,6 +1899,7 @@
"dURmlQ": ["\"frontmatter\" is a reserved property name"],
"dVaXnv": ["Content rules not yet loaded — try again in a moment"],
"dXWMFn": ["Removes this skill from your editors."],
+ "dYCvMf": ["Couldn't resume this conversation: ", ["0"]],
"dbapvC": ["Follow us on social media"],
"dbhUX1": ["Hide this file"],
"dbtjJh": ["(opens in new tab)"],
@@ -1849,6 +1921,7 @@
"e8L17t": ["A non-empty folder already exists at this path. Pick a different folder."],
"e8zRrb": ["Show Files"],
"e8zYa8": ["Could not open ", ["shareBranch"], " in a worktree. Try again."],
+ "e9sHSO": ["Pick up where you left off"],
"eBIT9h": ["Paste failed.", ["restoreSuffix"]],
"eFJkVt": ["Clone failed: ", ["cloneError"]],
"eG8Jsg": ["Toggle source tab focus mode"],
@@ -1873,6 +1946,10 @@
"euc6Ns": ["Duplicate"],
"evs0iw": ["Tags matching \"", ["tagListQuery"], "\""],
"f1XQyZ": ["Move block"],
+ "f3Nvg7": [
+ ["0"],
+ " can't continue this conversation — the transcript is kept, but the agent session is gone."
+ ],
"f65AOQ": ["Start from"],
"f8jU-L": [["0"], "/", ["1"], " — ", ["2"]],
"f9lQNJ": ["Adds a managed block to"],
@@ -1909,6 +1986,7 @@
"g3UF2V": ["Accept"],
"g4WlQK": ["Project AI tool management is only available in the OpenKnowledge desktop app."],
"g4XBm0": ["Small section heading."],
+ "g4e0hS": ["Ask ", ["agentName"]],
"g58Kwy": [
"<",
["descriptorLabel"],
@@ -1950,6 +2028,7 @@
"goO4Ll": ["Editor status bar"],
"gp3I7-": ["Before syncing, set your identity for git commits:"],
"gtEbeW": ["Highlight"],
+ "gtGQ9S": ["Start ", ["agentName"], ", ", ["hint"]],
"gvApb7": [
"Turn the things you read into clear, trusted articles. Save a source, figure out what it means, then keep the final version so you can rely on it later."
],
@@ -1973,7 +2052,6 @@
"hDoLrm": ["Remove ", ["projectName"], " from recent projects"],
"hGmuTc": ["Docs tagged #", ["tagDocsName"]],
"hHMv6l": ["Delete block"],
- "hIQkLb": ["New chat"],
"hItdtk": ["Browse folder"],
"hLod4_": ["Convert to template"],
"hLy8b1": ["Updated to Version ", ["version"]],
@@ -2069,6 +2147,7 @@
"jEdF24": ["Missing page: ", ["linkTitle"], ". Click to create."],
"jKd3AP": ["Could not enable the terminal: ", ["0"]],
"jPUPvG": ["Couldn't resolve the conflict for ", ["filePath"], "."],
+ "jRAGrQ": ["Configure agents"],
"jRHdCz": ["Failed to load PDF"],
"jSO1X5": ["Inherited templates can't be renamed here — rename it in the folder that owns it."],
"jSY41h": ["\"", ["docName"], "\" took too long. Check your connection."],
@@ -2078,6 +2157,7 @@
"j_Z6g7": ["Shared default"],
"jbSG8V": ["Show Files (", ["sidebarShortcutLabel"], ")"],
"jdGUeI": ["Couldn't create template: ", ["error"]],
+ "jeJexw": ["Couldn't finish installing ", ["0"], " — see below."],
"jerqF0": ["Loading branch state"],
"jhtG3I": [" Your selection has been restored."],
"jjtmV_": ["First file name"],
@@ -2097,6 +2177,7 @@
["trimmedSlug"],
"</0> already exists here. Saving creates a local copy that overrides it for this folder."
],
+ "k0dL2I": ["Reconnecting to the agent service…"],
"k0vc0N": ["New terminal tab"],
"k2fEi7": [
"User plugins are personal to this device — turn them on or off here. The choice lives in your user config and is never committed to the project. Each enabled plugin gets its own page under Plugins in the settings sidebar."
@@ -2158,6 +2239,7 @@
"l1aQKz": ["Visual editor table"],
"l1l8sj": [["0"], "d ago"],
"l3s5ri": ["Import"],
+ "l3zD7w": ["Starting the agent…"],
"l46MqT": ["Next tab"],
"l6OXqI": ["No installed agents found"],
"l6kpzR": [
@@ -2167,6 +2249,19 @@
["branch"],
"</0>, and that change hasn't synced yet."
],
+ "l7Qq48": [
+ "This agent runs through ",
+ ["0"],
+ ", which isn't installed. Open Knowledge can download a private copy of ",
+ ["1"],
+ " ",
+ ["2"],
+ " (about ",
+ ["3"],
+ " MB from ",
+ ["4"],
+ ") that won't touch the rest of your system."
+ ],
"l8G3S9": ["Auto-sync is off — you don't have permission to push to this repo"],
"lAiyU_": ["Only the current document uses <0>#", ["tag"], "</0>."],
"lCC_D5": ["Subscribing..."],
@@ -2175,6 +2270,7 @@
"lHwYMr": ["Server error: ", ["status"], " ", ["statusText"]],
"lI0Td2": ["Use letters, digits, <0>_</0> and <1>-</1> only."],
"lIn9L9": ["Disable sync"],
+ "lKQnp-": ["Installed ", ["0"], " ", ["1"]],
"lPzyrU": ["All hunks resolved"],
"lVWEIL": ["Indexed ", ["embedded"], " of ", ["total"], " pages."],
"lWNpNB": ["Add cursors or select matching occurrences through CodeMirror."],
@@ -2212,6 +2308,7 @@
"mPy9lS": [
"Organize my existing specs into a linked index grouped by area, and flag any that have drifted out of sync with the current code."
],
+ "mToVM9": ["Message ", ["agentName"]],
"mU3j1b": ["Remove item ", ["0"]],
"mVFyH-": [["accessibleLabel"], " (conflict)"],
"mWVJRX": ["Collapsible section with a clickable summary."],
@@ -2299,11 +2396,13 @@
"nh3wwx": ["Embeddings provider key"],
"njBeMm": ["Both"],
"njU86j": ["Property \"", ["trimmed"], "\" already exists"],
+ "nmwqWS": ["Not answered"],
"noH1JX": [
"Couldn't reach collab server — ",
["errorDetail"],
". Try <0>ok status</0> or check <1>.ok/local/last-spawn-error.log</1>."
],
+ "np9pbC": ["Show ", ["inAppHiddenCount"], " more"],
"npcziF": ["Install on"],
"nqV0Kk": ["This folder hasn't synced to GitHub yet. The link will work after the next sync."],
"nrGWJ7": [
@@ -2357,6 +2456,7 @@
],
"ogAuyr": ["Back to document view"],
"ohUJJM": ["Plugins"],
+ "oi4zaa": ["Remember this for future agents"],
"omXJcU": ["Close others"],
"onTlRk": ["Couldn't update skills sharing"],
"optX0N": [["0"], "h ago"],
@@ -2365,6 +2465,7 @@
"ot5BRK": ["Duplicate selected file or folder"],
"otE4aj": ["Show external URL nodes"],
"ou1hFW": ["Toggle an ordered list."],
+ "ouTaKR": ["Denied — ", ["0"]],
"outYNy": ["Duplicate name \"", ["keyName"], "\""],
"ovIGrT": [
"Local collaboration data for \"",
@@ -2372,6 +2473,7 @@
"\" could not be cleared. Reload to retry."
],
"p0Iq25": ["Insert link"],
+ "p8TjFD": ["Collapse session dock"],
"p9sdCy": ["New ignore pattern"],
"pAgkuZ": ["Reopening \"", ["docName"], "\" with a fresh local collaboration cache."],
"pBROkv": ["Thanks for subscribing. Watch your inbox for product updates."],
@@ -2380,6 +2482,7 @@
"pHYP6v": ["Open <0>Customize</0> in the sidebar <1/> <2>Skills</2>."],
"pQf2Ux": [".ok/skills is back to local-only."],
"pTPqMK": ["Toggle a fenced code block."],
+ "pUKV4K": ["Auto-denied"],
"pWT04I": ["Checking..."],
"pWbsW6": ["Loading docs"],
"pZAs1T": ["Failed to load outgoing links"],
@@ -2440,6 +2543,7 @@
"qvWGzP": ["Collapse all"],
"qyLmWw": ["Source editor search panel"],
"r-OJYm": ["Enter a valid branch name (no spaces, no leading dot, no \"..\")."],
+ "r2eKE3": ["Sign in to ", ["agentName"], " first"],
"r2huLx": ["Undo, redo, or undo selection changes through CodeMirror history."],
"r4R7AZ": ["Network error during cleanup"],
"r51jLC": ["File saved & Claude Desktop App opened"],
@@ -2472,7 +2576,6 @@
"rZVMkf": ["Visual editor replace input focused"],
"rageVb": ["Custom HTML with a live preview pane (sandboxed iframe)."],
"rdU729": ["Layout"],
- "rf6x3F": ["Dock terminal to the bottom"],
"rfFpcF": ["Remove ", ["chip"]],
"rgPqOw": ["Convert the current block to a paragraph."],
"riqekz": ["Suggestion menu navigation"],
@@ -2517,6 +2620,7 @@
"saIASg": ["Second item"],
"saYiIO": ["Path cannot contain null bytes"],
"seeS6l": ["Setup OpenKnowledge in this folder?"],
+ "sgmRY8": ["Skipped downloading ", ["0"], "."],
"shNd9t": ["Slash command menu"],
"si3L24": [
"Open an additional terminal tab. With text selected, stage it in the new tab's AI input."
@@ -2536,6 +2640,7 @@
"sxTdZI": ["Loading paths…"],
"sxjyRq": ["Worktrees"],
"sxkWRg": ["Advanced"],
+ "syi2ye": [["percent"], "% used (", ["left"], "% left)"],
"t-JXbf": ["Notion-style inline row for a downloadable file. Drag-drop also works."],
"t18QYR": ["Unpin ", ["accessibleLabel"]],
"t2TkQ3": ["Sync paused — resolve conflicts to resume."],
@@ -2546,6 +2651,7 @@
"</0> will be created from the current commit, in its own worktree under <1>.ok/worktrees/</1>."
],
"t6w1cq": ["Open a blank editor tab."],
+ "t9Qn8y": ["No agents enabled"],
"tAPZEx": ["Below"],
"tHKQ6j": ["Renaming"],
"tP5DDk": ["Apply link"],
@@ -2566,6 +2672,7 @@
"u3BOHd": [["fileCount", "plural", { "one": ["#", " file"], "other": ["#", " files"] }]],
"u3YnKw": ["Could not construct share URL."],
"u3wRF-": ["Published"],
+ "u5Utjn": [["0"], " needs ", ["1"]],
"u6Hp4N": ["Markdown"],
"u7H-Wn": ["Show panel (", ["panelShortcutLabel"], ")"],
"u7U_Ij": ["Link the selected text, or edit the link under the caret."],
@@ -2596,6 +2703,7 @@
"u_lS4C": ["Clone complete — opening project"],
"uaUc6t": ["Restart server"],
"ubMwcO": ["The terminal session ended (signal ", ["0"], ")."],
+ "ucXZ0k": ["Loading agents…"],
"ugoTXs": ["folder"],
"uhJEA2": [
[
@@ -2630,6 +2738,7 @@
"vGeNNQ": ["Copy a prompt and paste it into your agent to set up your project."],
"vIxrEk": ["Fit width"],
"vLyv1R": ["Hide"],
+ "vPKX2i": ["In app (beta)"],
"vQIVHc": ["Folder properties"],
"vWc9a0": ["Type to edit; <0>⌘ Enter</0> saves, <1>Esc</1> cancels."],
"vZVeFG": ["Upload failed — please try again"],
@@ -2639,6 +2748,7 @@
"vfWA_g": ["You picked ~/Desktop. OpenKnowledge will index everything on your desktop."],
"vhAnzJ": ["Turn on semantic search?"],
"viwC-K": ["Failed to remove project."],
+ "vja0Dg": ["Open session dock"],
"vppAju": ["Where newly added attachments are placed."],
"vv7kpg": ["Cancelled"],
"vvWZnu": ["Diff unavailable"],
@@ -2648,6 +2758,7 @@
"Could not read branch state for this project. Close this dialog and open the share link again."
],
"w6sBjd": ["Terminal settings not yet loaded — try again in a moment"],
+ "w6sT-y": ["Follow the agent's edits"],
"w7SsvI": ["That folder isn't an OpenKnowledge project yet. Initialize it and open?"],
"w7nm4K": ["Indented blockquote for citations."],
"wDgmsr": ["\"", ["0"], "\" install refreshed (", ["1"], ")"],
@@ -2722,6 +2833,7 @@
"xnP32l": ["No description yet — add one so agents know when to use this skill."],
"xrVr_k": ["Couldn't create skill: ", ["0"]],
"xsZhu-": ["Page number"],
+ "xzAmL_": ["Auto-approved"],
"xzktOa": ["Edit wiki link"],
"y1t8bQ": ["Settings sections"],
"y3aU20": ["Save changes"],
@@ -2768,6 +2880,7 @@
["typeLabel"],
" (inherited from folder properties; not editable here)"
],
+ "ygCKqB": ["Stop"],
"yhdqox": [
"Installed — ok is available in external terminals. Unchecking removes it; OpenKnowledge's built-in terminal and AI tools keep working."
],
diff --git a/packages/app/src/locales/en/messages.po b/packages/app/src/locales/en/messages.po
index d7bfd8d51..fd15a1907 100644
--- a/packages/app/src/locales/en/messages.po
+++ b/packages/app/src/locales/en/messages.po
@@ -25,6 +25,10 @@ msgstr " Your selection could not be restored."
msgid " Your selection has been restored."
msgstr " Your selection has been restored."
+#: src/components/acp/ThreadView.tsx
+msgid "… earlier output trimmed"
+msgstr "… earlier output trimmed"
+
#: src/components/FileSidebar.tsx
msgid ".ok folders"
msgstr ".ok folders"
@@ -200,11 +204,27 @@ msgstr "{0, plural, one {No problems across # document.} other {No problems acro
msgid "{0} added, {1} removed"
msgstr "{0} added, {1} removed"
+#. placeholder {0}: info.agent.name
+#: src/components/acp/ThreadView.tsx
+msgid "{0} can't continue this conversation — the transcript is kept, but the agent session is gone."
+msgstr "{0} can't continue this conversation — the transcript is kept, but the agent session is gone."
+
#. placeholder {0}: labels[key]
#: src/components/settings/CustomThemeEditor.tsx
msgid "{0} hex value"
msgstr "{0} hex value"
+#. placeholder {0}: resolvedTarget.displayName
+#: src/components/BottomComposer.tsx
+msgid "{0} isn't installed yet — opening its download page."
+msgstr "{0} isn't installed yet — opening its download page."
+
+#. placeholder {0}: item.agentName
+#. placeholder {1}: item.displayName
+#: src/components/acp/ThreadView.tsx
+msgid "{0} needs {1}"
+msgstr "{0} needs {1}"
+
#. placeholder {0}: templates.length
#: src/components/empty-state/CreateView.tsx
msgid "{0} templates available"
@@ -329,6 +349,10 @@ msgstr "{count, plural, one {matches # file} other {matches # files}}"
msgid "{days, plural, one {# day ago} other {# days ago}}"
msgstr "{days, plural, one {# day ago} other {# days ago}}"
+#: src/components/acp/ThreadHistoryMenu.tsx
+msgid "{days}d ago"
+msgstr "{days}d ago"
+
#: src/components/FileTree.tsx
msgid "{deleteCount, plural, one {Delete} other {Delete # items}}"
msgstr "{deleteCount, plural, one {Delete} other {Delete # items}}"
@@ -362,6 +386,7 @@ msgstr "{displayName} ({bin}) isn't installed or on your PATH."
#: src/components/handoff/OpenInAgentContextSubmenu.tsx
#: src/components/handoff/OpenInAgentEmptySpaceSubmenu.tsx
#: src/components/handoff/OpenInAgentMenu.tsx
+#: src/components/settings/ConfigureAgentsSection.tsx
msgid "{displayName} CLI"
msgstr "{displayName} CLI"
@@ -401,6 +426,7 @@ msgstr "{folderCount, plural, one {folder} other {folders}}"
msgid "{formatted} GitHub stars"
msgstr "{formatted} GitHub stars"
+#: src/components/acp/ThreadHistoryMenu.tsx
#: src/components/ActivityModeContent.tsx
#: src/components/ActivityPanelFileRow.tsx
#: src/components/SyncStatusBadge.tsx
@@ -458,6 +484,7 @@ msgstr "{mins, plural, one {# min ago} other {# min ago}}"
msgid "{minutes} min ago"
msgstr "{minutes} min ago"
+#: src/components/acp/ThreadHistoryMenu.tsx
#: src/components/ActivityModeContent.tsx
#: src/components/ActivityPanelBurstRow.tsx
#: src/components/ActivityPanelFileRow.tsx
@@ -492,6 +519,10 @@ msgstr "{packName} skill installed."
msgid "{packName} was already set up. Nothing to do."
msgstr "{packName} was already set up. Nothing to do."
+#: src/components/acp/ThreadView.tsx
+msgid "{percent}% used ({left}% left)"
+msgstr "{percent}% used ({left}% left)"
+
#: src/lib/share/clone-controller.ts
msgid "{phase} — {pct}%"
msgstr "{phase} — {pct}%"
@@ -550,6 +581,10 @@ msgstr "{truncatedShownCount, plural, one {Showing the first item in one folder
msgid "{uploadedCount, plural, one {Uploaded one file} other {Uploaded {uploadedCount} files}}"
msgstr "{uploadedCount, plural, one {Uploaded one file} other {Uploaded {uploadedCount} files}}"
+#: src/components/acp/ThreadView.tsx
+msgid "{usedLabel} / {sizeLabel} tokens used"
+msgstr "{usedLabel} / {sizeLabel} tokens used"
+
#: src/presence/PresenceBar.tsx
msgid "{userName} · {tabCount, plural, one {# tab} other {# tabs}}"
msgstr "{userName} · {tabCount, plural, one {# tab} other {# tabs}}"
@@ -623,6 +658,11 @@ msgstr "<0>Mirror source removed.</0> The doc <1>{src}</1> is no longer availabl
msgid "<0>ok</0> won't run in external terminals until you add it later from the File menu. OpenKnowledge's built-in terminal and AI tools keep working."
msgstr "<0>ok</0> won't run in external terminals until you add it later from the File menu. OpenKnowledge's built-in terminal and AI tools keep working."
+#. placeholder {0}: row.count
+#: src/components/acp/ThreadView.tsx
+msgid "⋯ {0} unchanged lines"
+msgstr "⋯ {0} unchanged lines"
+
#: src/components/PageHeaderWidgets.tsx
msgid "📝 or assets/icon.png"
msgstr "📝 or assets/icon.png"
@@ -924,6 +964,7 @@ msgstr "Advanced"
msgid "Advanced settings"
msgstr "Advanced settings"
+#: src/components/TerminalSessionsHost.tsx
#: src/presence/PresenceBar.tsx
msgid "Agent"
msgstr "Agent"
@@ -936,6 +977,14 @@ msgstr "Agent activity"
msgid "Agent configuration file"
msgstr "Agent configuration file"
+#: src/components/acp/ThreadView.tsx
+msgid "Agent mode"
+msgstr "Agent mode"
+
+#: src/components/acp/ThreadView.tsx
+msgid "Agent settings"
+msgstr "Agent settings"
+
#. Group label above the skill rows in Settings → AI tools & CLI
#. Section label above the skill checkboxes in the first-launch dialog
#: src/components/McpConsentDialogBody.tsx
@@ -1046,6 +1095,19 @@ msgstr "Apply link"
msgid "Applying your change"
msgstr "Applying your change"
+#: src/components/acp/ThreadView.tsx
+msgid "Approved"
+msgstr "Approved"
+
+#. placeholder {0}: outcome.optionName
+#: src/components/acp/ThreadView.tsx
+msgid "Approved — {0}"
+msgstr "Approved — {0}"
+
+#: src/components/acp/ThreadView.tsx
+msgid "Archived"
+msgstr "Archived"
+
#: src/components/FileTree.tsx
msgid "Are you sure you want to convert this file into a template? The original file will be deleted. This action cannot be undone."
msgstr "Are you sure you want to convert this file into a template? The original file will be deleted. This action cannot be undone."
@@ -1076,6 +1138,10 @@ msgstr "Ask {0}"
msgid "Ask {0} CLI"
msgstr "Ask {0} CLI"
+#: src/components/acp/ThreadView.tsx
+msgid "Ask {agentName}"
+msgstr "Ask {agentName}"
+
#: src/components/BottomComposer.tsx
#: src/components/EditorFooter.tsx
#: src/components/OnboardingCard.tsx
@@ -1134,6 +1200,14 @@ msgstr "Auto"
msgid "Auto-approve settings not yet loaded — try again in a moment"
msgstr "Auto-approve settings not yet loaded — try again in a moment"
+#: src/components/acp/ThreadView.tsx
+msgid "Auto-approved"
+msgstr "Auto-approved"
+
+#: src/components/acp/ThreadView.tsx
+msgid "Auto-denied"
+msgstr "Auto-denied"
+
#: src/components/FolderTimelineCard.tsx
#: src/components/TimelinePanel.tsx
msgid "Auto-save"
@@ -1221,6 +1295,10 @@ msgstr "Before syncing, set your identity for git commits:"
msgid "Below"
msgstr "Below"
+#: src/components/acp/AgentBetaBadge.tsx
+msgid "Beta"
+msgstr "Beta"
+
#: src/components/BetaBadge.tsx
msgid "BETA"
msgstr "BETA"
@@ -1384,6 +1462,7 @@ msgstr "Can't safely edit this project config"
msgid "Can't safely edit this tool's config"
msgstr "Can't safely edit this tool's config"
+#: src/components/acp/ThreadHistoryMenu.tsx
#: src/components/ActivityPanelBurstRow.tsx
#: src/components/AuthModal.tsx
#: src/components/CloneDialog.tsx
@@ -1445,9 +1524,10 @@ msgid "Checkbox"
msgstr "Checkbox"
#: src/components/BottomComposer.tsx
+msgid "Checking for agents"
+msgstr "Checking for agents"
+
#: src/components/handoff/EditWithAiPopover.tsx
-#: src/components/handoff/OpenInAgentContextSubmenu.tsx
-#: src/components/handoff/OpenInAgentMenu.tsx
msgid "Checking for installed agents"
msgstr "Checking for installed agents"
@@ -1486,13 +1566,17 @@ msgid "Choose agent"
msgstr "Choose agent"
#: src/components/TerminalNewChatButton.tsx
-msgid "Choose CLI for new chat"
-msgstr "Choose CLI for new chat"
+msgid "Choose what a new session starts"
+msgstr "Choose what a new session starts"
#: src/components/settings/SharingSection.tsx
msgid "Choose whether this project's OpenKnowledge setup, including its AI-tool connections, is saved with the project so teammates get it too, or kept only on your computer."
msgstr "Choose whether this project's OpenKnowledge setup, including its AI-tool connections, is saved with the project so teammates get it too, or kept only on your computer."
+#: src/components/settings/ConfigureAgentsSection.tsx
+msgid "Choose which agents appear in the agent selector. Turn one off to hide it everywhere."
+msgstr "Choose which agents appear in the agent selector. Turn one off to hide it everywhere."
+
#: src/components/settings/SkillTargetsPicker.tsx
msgid "Choose which editors every skill in this project installs into."
msgstr "Choose which editors every skill in this project installs into."
@@ -1715,8 +1799,8 @@ msgid "Collapse graph"
msgstr "Collapse graph"
#: src/components/TerminalTabStrip.tsx
-msgid "Collapse terminal"
-msgstr "Collapse terminal"
+msgid "Collapse session dock"
+msgstr "Collapse session dock"
#: src/editor/slash-command/component-items.tsx
msgid "Collapsible section with a clickable summary."
@@ -1812,6 +1896,17 @@ msgstr "Config sharing unchanged — see details below."
msgid "Configuration warnings"
msgstr "Configuration warnings"
+#: src/components/empty-state/CreatePromptComposer.tsx
+#: src/components/handoff/AgentSplitButton.tsx
+#: src/components/handoff/OpenInAgentContextSubmenu.tsx
+#: src/components/handoff/OpenInAgentEmptySpaceSubmenu.tsx
+#: src/components/handoff/OpenInAgentMenu.tsx
+#: src/components/settings/ConfigureAgentsSection.tsx
+#: src/components/settings/SettingsDialogShell.tsx
+#: src/components/TerminalNewChatButton.tsx
+msgid "Configure agents"
+msgstr "Configure agents"
+
#: src/components/settings/SettingsDialogShell.tsx
msgid "Configure user, project, and integration settings."
msgstr "Configure user, project, and integration settings."
@@ -1896,6 +1991,10 @@ msgstr "Connecting"
msgid "Connecting — waiting for collab server"
msgstr "Connecting — waiting for collab server"
+#: src/components/acp/ThreadView.tsx
+msgid "Connecting to {agentName}…"
+msgstr "Connecting to {agentName}…"
+
#: src/components/DocumentErrorBoundary.tsx
msgid "Connection dropped"
msgstr "Connection dropped"
@@ -1929,6 +2028,14 @@ msgstr "Content root"
msgid "Content rules not yet loaded — try again in a moment"
msgstr "Content rules not yet loaded — try again in a moment"
+#: src/components/acp/ThreadView.tsx
+msgid "Context window:"
+msgstr "Context window:"
+
+#: src/components/acp/ThreadView.tsx
+msgid "Context window: {percent}% used, {usedLabel} of {sizeLabel} tokens"
+msgstr "Context window: {percent}% used, {usedLabel} of {sizeLabel} tokens"
+
#: src/components/FileTree.tsx
msgid "Convert"
msgstr "Convert"
@@ -2189,6 +2296,10 @@ msgstr "Couldn't clear the key — please try again."
msgid "Couldn't connect OpenKnowledge tools to Claude Code. Please try again."
msgstr "Couldn't connect OpenKnowledge tools to Claude Code. Please try again."
+#: src/lib/acp/launch-agent-thread.ts
+msgid "Couldn't connect to the agent service. Make sure the OpenKnowledge server is running and up to date (restart it if it was already running), then try again."
+msgstr "Couldn't connect to the agent service. Make sure the OpenKnowledge server is running and up to date (restart it if it was already running), then try again."
+
#: src/components/PublishToGitHubDialog.tsx
msgid "Couldn't construct the share URL. Try Done and re-share."
msgstr "Couldn't construct the share URL. Try Done and re-share."
@@ -2240,6 +2351,11 @@ msgstr "Couldn't disconnect — please try again."
msgid "Couldn't duplicate \"{0}\": {1}"
msgstr "Couldn't duplicate \"{0}\": {1}"
+#. placeholder {0}: item.displayName
+#: src/components/acp/ThreadView.tsx
+msgid "Couldn't finish installing {0} — see below."
+msgstr "Couldn't finish installing {0} — see below."
+
#. placeholder {0}: result.error
#: src/components/skill-actions.tsx
msgid "Couldn't install skill: {0}"
@@ -2310,6 +2426,10 @@ msgstr "Couldn't reach collab server — {errorDetail}. Try <0>ok status</0> or
msgid "Couldn't reach GitHub. Try again?"
msgstr "Couldn't reach GitHub. Try again?"
+#: src/components/settings/ConfigureAgentsSection.tsx
+msgid "Couldn't reach the agent registry."
+msgstr "Couldn't reach the agent registry."
+
#: src/components/CommandPalette.tsx
msgid "Couldn't reach the embeddings provider — press ↵ to retry"
msgstr "Couldn't reach the embeddings provider — press ↵ to retry"
@@ -2358,6 +2478,11 @@ msgstr "Couldn't restart the server automatically. Try running `ok stop all` in
msgid "Couldn't restart the server. Try `ok start` in this folder."
msgstr "Couldn't restart the server. Try `ok start` in this folder."
+#. placeholder {0}: resumeError.message
+#: src/components/acp/ThreadView.tsx
+msgid "Couldn't resume this conversation: {0}"
+msgstr "Couldn't resume this conversation: {0}"
+
#: src/components/TemplateForm.tsx
msgid "Couldn't save template: {error}"
msgstr "Couldn't save template: {error}"
@@ -2394,6 +2519,10 @@ msgstr "Couldn't share skills — {detail}."
msgid "Couldn't share skills: internal error. Please restart the app."
msgstr "Couldn't share skills: internal error. Please restart the app."
+#: src/lib/acp/launch-agent-thread.ts
+msgid "Couldn't start the agent thread — please try again."
+msgstr "Couldn't start the agent thread — please try again."
+
#. placeholder {0}: result.error
#: src/components/skill-actions.tsx
msgid "Couldn't uninstall skill: {0}"
@@ -2619,6 +2748,7 @@ msgstr "Default properties"
msgid "Default: <0>{0}</0>"
msgstr "Default: <0>{0}</0>"
+#: src/components/acp/ThreadHistoryMenu.tsx
#: src/components/DeleteConfirmationDialog.tsx
#: src/components/skill-actions.tsx
#: src/components/TemplateRow.tsx
@@ -2626,6 +2756,11 @@ msgstr "Default: <0>{0}</0>"
msgid "Delete"
msgstr "Delete"
+#. placeholder {0}: thread.title
+#: src/components/acp/ThreadHistoryMenu.tsx
+msgid "Delete {0}"
+msgstr "Delete {0}"
+
#: src/editor/extensions/JsxComponentView.tsx
msgid "Delete {deleteDescriptorLabel}"
msgstr "Delete {deleteDescriptorLabel}"
@@ -2674,6 +2809,10 @@ msgstr "Delete selected items"
msgid "Delete selected table"
msgstr "Delete selected table"
+#: src/components/acp/ThreadHistoryMenu.tsx
+msgid "Delete this conversation?"
+msgstr "Delete this conversation?"
+
#: src/components/FolderTimelineCard.tsx
msgid "deleted template"
msgstr "deleted template"
@@ -2683,6 +2822,19 @@ msgstr "deleted template"
msgid "Deleting"
msgstr "Deleting"
+#: src/components/acp/ThreadView.tsx
+msgid "Denied"
+msgstr "Denied"
+
+#. placeholder {0}: outcome.optionName
+#: src/components/acp/ThreadView.tsx
+msgid "Denied — {0}"
+msgstr "Denied — {0}"
+
+#: src/components/acp/ThreadView.tsx
+msgid "Deny"
+msgstr "Deny"
+
#: src/components/empty-state/CreatePromptComposer.tsx
msgid "Describe the project you want to create"
msgstr "Describe the project you want to create"
@@ -2717,6 +2869,7 @@ msgstr "Description (optional)"
#: src/components/handoff/OpenInAgentContextSubmenu.tsx
#: src/components/handoff/OpenInAgentEmptySpaceSubmenu.tsx
#: src/components/handoff/OpenInAgentMenu.tsx
+#: src/components/settings/ConfigureAgentsSection.tsx
msgid "Desktop"
msgstr "Desktop"
@@ -2844,12 +2997,12 @@ msgid "Doc mention suggestions"
msgstr "Doc mention suggestions"
#: src/components/TerminalTabStrip.tsx
-msgid "Dock terminal to the bottom"
-msgstr "Dock terminal to the bottom"
+msgid "Dock sessions at the bottom"
+msgstr "Dock sessions at the bottom"
#: src/components/TerminalTabStrip.tsx
-msgid "Dock terminal to the right"
-msgstr "Dock terminal to the right"
+msgid "Dock sessions on the right"
+msgstr "Dock sessions on the right"
#: src/components/HelpPopover.tsx
msgid "Docs"
@@ -2906,6 +3059,10 @@ msgstr "Documents tagged <0>#{tagName}</0>"
msgid "Don't see <0>Skills</0>? Enable <1>Settings <2/> Capabilities <3/> Code execution and file creation</1> first."
msgstr "Don't see <0>Skills</0>? Enable <1>Settings <2/> Capabilities <3/> Code execution and file creation</1> first."
+#: src/components/acp/ThreadView.tsx
+msgid "done"
+msgstr "done"
+
#: src/components/InstallInClaudeDesktopDialog.tsx
#: src/components/PublishToGitHubDialog.tsx
#: src/components/ReportBugDialogBody.tsx
@@ -2915,6 +3072,11 @@ msgstr "Don't see <0>Skills</0>? Enable <1>Settings <2/> Capabilities <3/> Code
msgid "Done"
msgstr "Done"
+#. placeholder {0}: item.displayName
+#: src/components/acp/ThreadView.tsx
+msgid "Download {0}"
+msgstr "Download {0}"
+
#: src/editor/bubble-menu/FileBubbleButtons.tsx
msgid "Download file"
msgstr "Download file"
@@ -2923,6 +3085,12 @@ msgstr "Download file"
msgid "Download started"
msgstr "Download started"
+#. placeholder {0}: item.displayName
+#. placeholder {1}: item.version
+#: src/components/acp/ThreadView.tsx
+msgid "Downloading {0} {1}…"
+msgstr "Downloading {0} {1}…"
+
#: src/components/ShareReceiveDialog.tsx
msgid "Downloads a fresh copy from GitHub."
msgstr "Downloads a fresh copy from GitHub."
@@ -3146,13 +3314,19 @@ msgstr "Empty diagram"
msgid "Empty starting content"
msgstr "Empty starting content"
+#. placeholder {0}: agent.name
#. placeholder {0}: plugin.label
#. placeholder {0}: rule.name
+#: src/components/settings/ConfigureAgentsSection.tsx
#: src/components/settings/LintingSection.tsx
#: src/components/settings/markdownlint-rule-browser.tsx
msgid "Enable {0}"
msgstr "Enable {0}"
+#: src/components/settings/ConfigureAgentsSection.tsx
+msgid "Enable {displayName} CLI"
+msgstr "Enable {displayName} CLI"
+
#: src/components/AutoSyncOnboardingDialog.tsx
#: src/components/EnableSyncConfirmDialog.tsx
#: src/components/share-receive-miss-content.tsx
@@ -3245,6 +3419,11 @@ msgstr "Exception: skills are shared"
msgid "Existing branch <0>{trimmed}</0> will be checked out into its own window, under <1>.ok/worktrees/</1>."
msgstr "Existing branch <0>{trimmed}</0> will be checked out into its own window, under <1>.ok/worktrees/</1>."
+#. placeholder {0}: exit.exitCode ?? 0
+#: src/components/acp/ThreadView.tsx
+msgid "exit {0}"
+msgstr "exit {0}"
+
#: src/components/DiffView.tsx
msgid "Exit merge"
msgstr "Exit merge"
@@ -3296,6 +3475,10 @@ msgstr "External link previews show a card with the site name, page title, and d
msgid "External wiki link"
msgstr "External wiki link"
+#: src/components/acp/ThreadView.tsx
+msgid "failed"
+msgstr "failed"
+
#: src/components/ArrayOfObjectsWidget.tsx
msgid "Failed to add item"
msgstr "Failed to add item"
@@ -3765,6 +3948,10 @@ msgstr "Folder target: {linkTitle}. Click to open the overview."
msgid "Folders"
msgstr "Folders"
+#: src/components/acp/ThreadView.tsx
+msgid "Follow the agent's edits"
+msgstr "Follow the agent's edits"
+
#: src/components/SubscribeCard.tsx
msgid "Follow us on"
msgstr "Follow us on"
@@ -3777,10 +3964,18 @@ msgstr "Follow us on social media"
msgid "Follow us on X"
msgstr "Follow us on X"
+#: src/components/acp/ThreadView.tsx
+msgid "Following the agent's edits"
+msgstr "Following the agent's edits"
+
#: src/editor/slash-command/items.tsx
msgid "Footnote"
msgstr "Footnote"
+#: src/components/acp/ThreadView.tsx
+msgid "Force stop"
+msgstr "Force stop"
+
#: src/components/LinksPanel.tsx
msgid "Forward-links response did not match expected shape."
msgstr "Forward-links response did not match expected shape."
@@ -4172,6 +4367,24 @@ msgstr "Import as template"
msgid "In a subfolder"
msgstr "In a subfolder"
+#: src/components/empty-state/CreatePromptComposer.tsx
+#: src/components/handoff/AgentSplitButton.tsx
+#: src/components/handoff/OpenInAgentContextSubmenu.tsx
+#: src/components/handoff/OpenInAgentEmptySpaceSubmenu.tsx
+#: src/components/handoff/OpenInAgentMenu.tsx
+#: src/components/settings/ConfigureAgentsSection.tsx
+#: src/components/TerminalNewChatButton.tsx
+msgid "In app"
+msgstr "In app"
+
+#: src/components/empty-state/CreatePromptComposer.tsx
+#: src/components/handoff/AgentSplitButton.tsx
+#: src/components/handoff/OpenInAgentContextSubmenu.tsx
+#: src/components/handoff/OpenInAgentEmptySpaceSubmenu.tsx
+#: src/components/TerminalNewChatButton.tsx
+msgid "In app (beta)"
+msgstr "In app (beta)"
+
#: src/components/InstallInClaudeDesktopDialog.tsx
msgid "In the Claude Desktop App"
msgstr "In the Claude Desktop App"
@@ -4273,6 +4486,10 @@ msgstr "Inline Math"
msgid "Inline Math Properties"
msgstr "Inline Math Properties"
+#: src/components/acp/ThreadView.tsx
+msgid "Input"
+msgstr "Input"
+
#: src/editor/slash-command/items.tsx
msgid "Insert a footnote reference + matching definition stub."
msgstr "Insert a footnote reference + matching definition stub."
@@ -4300,10 +4517,6 @@ msgstr "Install"
msgid "Install {brand} →"
msgstr "Install {brand} →"
-#: src/components/empty-state/CreatePromptComposer.tsx
-msgid "Install an AI agent to create with AI"
-msgstr "Install an AI agent to create with AI"
-
#. Dialog title — installing the OpenKnowledge skill into the Claude Desktop App
#: src/components/InstallInClaudeDesktopDialog.tsx
msgid "Install for Claude Chat & Cowork"
@@ -4351,6 +4564,12 @@ msgstr "Installed — ok is available in external terminals. Unchecking removes
msgid "Installed \"{0}\" into {1}"
msgstr "Installed \"{0}\" into {1}"
+#. placeholder {0}: item.displayName
+#. placeholder {1}: item.version
+#: src/components/acp/ThreadView.tsx
+msgid "Installed {0} {1}"
+msgstr "Installed {0} {1}"
+
#: src/components/SkillRow.tsx
msgid "Installed into"
msgstr "Installed into"
@@ -4359,6 +4578,10 @@ msgstr "Installed into"
msgid "Installing"
msgstr "Installing"
+#: src/components/acp/ThreadView.tsx
+msgid "Installing {agentName}…"
+msgstr "Installing {agentName}…"
+
#: src/components/handoff/EditWithAiPopover.tsx
#: src/components/handoff/OpenInAgentMenu.tsx
msgid "Instruction for the AI"
@@ -4402,6 +4625,7 @@ msgstr "Jump to page {pageNumber}"
msgid "Jump to tab 1-8"
msgstr "Jump to tab 1-8"
+#: src/components/acp/ThreadHistoryMenu.tsx
#: src/components/FolderOverview.tsx
#: src/components/FolderTimelineCard.tsx
#: src/components/SyncStatusBadge.tsx
@@ -4566,6 +4790,10 @@ msgstr "Loading {fileName}"
msgid "Loading agent activity"
msgstr "Loading agent activity"
+#: src/components/settings/ConfigureAgentsSection.tsx
+msgid "Loading agents…"
+msgstr "Loading agents…"
+
#: src/components/ShareBranchSwitchDialog.tsx
msgid "Loading branch state"
msgstr "Loading branch state"
@@ -4651,6 +4879,10 @@ msgstr "Loading tags"
msgid "Loading templates"
msgstr "Loading templates"
+#: src/components/acp/ThreadView.tsx
+msgid "Loading the conversation"
+msgstr "Loading the conversation"
+
#: src/components/TimelinePanel.tsx
msgid "Loading timeline history"
msgstr "Loading timeline history"
@@ -4757,6 +4989,10 @@ msgstr "markdownlint rules"
msgid "Match case"
msgstr "Match case"
+#: src/components/TerminalNewChatButton.tsx
+msgid "Maximum agents already running"
+msgstr "Maximum agents already running"
+
#. Group label above the per-editor MCP list in Settings → AI tools & CLI — each row wires OpenKnowledge's MCP server into that tool
#. Group label above the per-editor project MCP list in Settings → This project → AI tools
#. Section label above the editor checkbox list in the first-launch dialog — each row wires OpenKnowledge's MCP server into that tool
@@ -4782,6 +5018,15 @@ msgstr "Mermaid diagram controls"
msgid "Mermaid diagram failed to render."
msgstr "Mermaid diagram failed to render."
+#: src/components/acp/ThreadView.tsx
+msgid "Message {agentName}"
+msgstr "Message {agentName}"
+
+#. placeholder {0}: frame.message
+#: src/lib/acp/thread-client.ts
+msgid "Message not sent: {0}"
+msgstr "Message not sent: {0}"
+
#: src/editor/components/Mirror.tsx
msgid "Mirror loading <0>{mirrorRef}</0>"
msgstr "Mirror loading <0>{mirrorRef}</0>"
@@ -5003,7 +5248,8 @@ msgstr "never"
msgid "New"
msgstr "New"
-#. placeholder {0}: TERMINAL_CLIS[selected].displayName
+#. placeholder {0}: TERMINAL_CLIS[selected.cli].displayName
+#. placeholder {0}: selected.agent.name
#: src/components/TerminalNewChatButton.tsx
msgid "New {0} chat"
msgstr "New {0} chat"
@@ -5016,10 +5262,6 @@ msgstr "New branch <0>{trimmed}</0> will be created from <1>{currentBaseLabel}</
msgid "New branch <0>{trimmed}</0> will be created from the current commit, in its own worktree under <1>.ok/worktrees/</1>."
msgstr "New branch <0>{trimmed}</0> will be created from the current commit, in its own worktree under <1>.ok/worktrees/</1>."
-#: src/components/TerminalNewChatButton.tsx
-msgid "New chat"
-msgstr "New chat"
-
#: src/components/command-palette-commands.ts
#: src/components/FileSidebar.tsx
#: src/components/FileTree.tsx
@@ -5092,6 +5334,11 @@ msgstr "New Terminal"
msgid "New terminal tab"
msgstr "New terminal tab"
+#. placeholder {0}: info.agent.name
+#: src/components/acp/ThreadView.tsx
+msgid "New thread with {0}"
+msgstr "New thread with {0}"
+
#: src/components/command-palette-commands.ts
#: src/components/NewWorktreeDialog.tsx
#: src/components/ProjectSwitcher.tsx
@@ -5118,6 +5365,18 @@ msgstr "Next tab"
msgid "No <0>.markdownlint.*</0> file yet — every rule runs on the same defaults as the VS Code markdownlint extension: all on, except line length."
msgstr "No <0>.markdownlint.*</0> file yet — every rule runs on the same defaults as the VS Code markdownlint extension: all on, except line length."
+#: src/components/settings/ConfigureAgentsSection.tsx
+msgid "No agents available."
+msgstr "No agents available."
+
+#: src/components/BottomComposer.tsx
+msgid "No agents enabled"
+msgstr "No agents enabled"
+
+#: src/components/settings/ConfigureAgentsSection.tsx
+msgid "No agents match your search."
+msgstr "No agents match your search."
+
#: src/components/FileSidebar.tsx
msgid "No AI agents installed"
msgstr "No AI agents installed"
@@ -5215,10 +5474,7 @@ msgstr "No hub pages yet. Hubs appear once pages accumulate inbound graph links.
msgid "No Incoming"
msgstr "No Incoming"
-#: src/components/BottomComposer.tsx
#: src/components/handoff/EditWithAiPopover.tsx
-#: src/components/handoff/OpenInAgentContextSubmenu.tsx
-#: src/components/handoff/OpenInAgentMenu.tsx
msgid "No installed agents found"
msgstr "No installed agents found"
@@ -5266,6 +5522,10 @@ msgstr "No matching repositories."
msgid "No matching worktrees or branches."
msgstr "No matching worktrees or branches."
+#: src/components/acp/ThreadHistoryMenu.tsx
+msgid "No open conversations. Reopen a past one, or start a session with the + button."
+msgstr "No open conversations. Reopen a past one, or start a session with the + button."
+
#: src/components/GraphPanel.tsx
msgid "No Outgoing"
msgstr "No Outgoing"
@@ -5386,6 +5646,14 @@ msgstr "No workspace"
msgid "None"
msgstr "None"
+#: src/components/acp/ThreadView.tsx
+msgid "Not answered"
+msgstr "Not answered"
+
+#: src/components/settings/ConfigureAgentsSection.tsx
+msgid "Not available on this platform"
+msgstr "Not available on this platform"
+
#: src/components/settings/AccountSection.tsx
msgid "Not connected"
msgstr "Not connected"
@@ -5400,9 +5668,11 @@ msgstr "Not in sidebar"
#: src/components/CommandPalette.tsx
#: src/components/handoff/OpenInAgentMenuItem.tsx
+#: src/components/settings/ConfigureAgentsSection.tsx
msgid "Not installed"
msgstr "Not installed"
+#: src/components/acp/ThreadView.tsx
#: src/components/ReportBugDialogBody.tsx
#: src/components/SkillsSidebarSection.tsx
#: src/lib/install-server-drift-listener.ts
@@ -5705,6 +5975,10 @@ msgstr "Open project menu"
msgid "Open recent project"
msgstr "Open recent project"
+#: src/components/TerminalRevealTab.tsx
+msgid "Open session dock"
+msgstr "Open session dock"
+
#: src/components/ShareBranchSwitchDialog.tsx
#: src/components/ShareReceiveDialog.tsx
msgid "Open shared {targetNoun}"
@@ -6034,6 +6308,10 @@ msgstr "Pattern syntax error: {message}"
msgid "Pattern warnings: {summary}"
msgstr "Pattern warnings: {summary}"
+#: src/components/acp/ThreadView.tsx
+msgid "pending"
+msgstr "pending"
+
#: src/components/CreateProjectDialog.tsx
msgid "Permanently deletes <0>{targetGitPath}</0> and all its git history. Working files stay in place. If the parent git repo is intentional (e.g. you cloned it), cancel and pick a location outside it."
msgstr "Permanently deletes <0>{targetGitPath}</0> and all its git history. Working files stay in place. If the parent git repo is intentional (e.g. you cloned it), cancel and pick a location outside it."
@@ -6074,6 +6352,10 @@ msgstr "Pick a starter pack to scaffold your project with ready-made folders and
msgid "Pick the folder where you've cloned it."
msgstr "Pick the folder where you've cloned it."
+#: src/components/acp/ThreadView.tsx
+msgid "Pick up where you left off"
+msgstr "Pick up where you left off"
+
#: src/components/EditorTabs.tsx
msgid "Pin tab"
msgstr "Pin tab"
@@ -6082,6 +6364,11 @@ msgstr "Pin tab"
msgid "Plain"
msgstr "Plain"
+#. placeholder {0}: plan.length
+#: src/components/acp/ThreadView.tsx
+msgid "Plan ({done}/{0})"
+msgstr "Plan ({done}/{0})"
+
#: src/components/SubscribeForm.tsx
msgid "Please enter a valid email address."
msgstr "Please enter a valid email address."
@@ -6363,6 +6650,10 @@ msgstr "Reconnected"
msgid "Reconnecting after server restart"
msgstr "Reconnecting after server restart"
+#: src/components/TerminalSessionsHost.tsx
+msgid "Reconnecting to the agent service…"
+msgstr "Reconnecting to the agent service…"
+
#: src/components/FileTree.tsx
msgid "Reconnecting…"
msgstr "Reconnecting…"
@@ -6412,6 +6703,10 @@ msgstr "Release notes"
msgid "Reload"
msgstr "Reload"
+#: src/components/acp/ThreadView.tsx
+msgid "Remember this for future agents"
+msgstr "Remember this for future agents"
+
#: src/components/NewWorktreeDialog.tsx
msgid "remote"
msgstr "remote"
@@ -6727,6 +7022,10 @@ msgstr "Restore failed"
msgid "Restore failed — document unchanged"
msgstr "Restore failed — document unchanged"
+#: src/components/acp/ThreadHistoryMenu.tsx
+msgid "Restore sessions"
+msgstr "Restore sessions"
+
#: src/components/ActivityPanelBurstRow.tsx
msgid "Restore to edit {burstNumber} of {docName}"
msgstr "Restore to edit {burstNumber} of {docName}"
@@ -6762,9 +7061,14 @@ msgstr "Restored to the version from {0}"
msgid "Results capped — this workspace has more files than search can index. A missing file may be a cap artifact, not a typo."
msgstr "Results capped — this workspace has more files than search can index. A missing file may be a cap artifact, not a typo."
+#: src/components/acp/ThreadView.tsx
+msgid "Resuming the conversation"
+msgstr "Resuming the conversation"
+
#: src/components/ActivityModeContent.tsx
#: src/components/ConnectingBanner.tsx
#: src/components/PublishToGitHubDialog.tsx
+#: src/components/settings/ConfigureAgentsSection.tsx
#: src/components/SyncStatusBadge.tsx
#: src/components/TrashFailureModal.tsx
msgid "Retry"
@@ -6842,6 +7146,10 @@ msgstr "Run a real terminal docked inside OpenKnowledge, starting in this projec
msgid "Run this in your terminal"
msgstr "Run this in your terminal"
+#: src/components/acp/ThreadView.tsx
+msgid "running"
+msgstr "running"
+
#: src/components/ProblemsPanel.tsx
msgid "Running project audit"
msgstr "Running project audit"
@@ -6924,6 +7232,10 @@ msgstr "Search \"{semanticSubmitQuery}\" by meaning"
msgid "Search ({searchShortcut})"
msgstr "Search ({searchShortcut})"
+#: src/components/settings/ConfigureAgentsSection.tsx
+msgid "Search agents"
+msgstr "Search agents"
+
#: src/components/NewWorktreeDialog.tsx
msgid "Search branches"
msgstr "Search branches"
@@ -7097,6 +7409,10 @@ msgstr "Semantic search adds meaning-based ranking to the search tool so concept
msgid "Semantic search is on, but no API key is set — search falls back to keyword matching. Add one in <0>Settings → Account</0> (it's stored once for your whole machine)."
msgstr "Semantic search is on, but no API key is set — search falls back to keyword matching. Add one in <0>Settings → Account</0> (it's stored once for your whole machine)."
+#: src/components/acp/ThreadView.tsx
+msgid "Send"
+msgstr "Send"
+
#: src/components/ReportBugDialogBody.tsx
msgid "Send report"
msgstr "Send report"
@@ -7150,6 +7466,10 @@ msgstr "Session ended"
msgid "Session ended — undo unavailable"
msgstr "Session ended — undo unavailable"
+#: src/components/TerminalTabStrip.tsx
+msgid "Sessions"
+msgstr "Sessions"
+
#: src/components/AuthModal.tsx
msgid "Set git identity"
msgstr "Set git identity"
@@ -7178,6 +7498,7 @@ msgstr "Set where pasted and dropped files are stored for this project."
msgid "Setting up"
msgstr "Setting up"
+#: src/components/acp/ThreadView.tsx
#: src/components/command-palette-commands.ts
#: src/components/settings/SettingsDialogShell.tsx
#: src/components/SettingsButton.tsx
@@ -7285,6 +7606,10 @@ msgstr "Show {0} more"
msgid "Show {hidden} more"
msgstr "Show {hidden} more"
+#: src/components/settings/ConfigureAgentsSection.tsx
+msgid "Show {inAppHiddenCount} more"
+msgstr "Show {inAppHiddenCount} more"
+
#: src/components/settings/LinkPreviewsSection.tsx
msgid "Show a preview card when you hover an external link in the editor. This setting applies only to this computer."
msgstr "Show a preview card when you hover an external link in the editor. This setting applies only to this computer."
@@ -7332,6 +7657,7 @@ msgid "Show HTML preview"
msgstr "Show HTML preview"
#: src/components/PackCardGrid.tsx
+#: src/components/settings/ConfigureAgentsSection.tsx
msgid "Show less"
msgstr "Show less"
@@ -7386,10 +7712,6 @@ msgstr "Show skills section"
msgid "Show source"
msgstr "Show source"
-#: src/components/TerminalRevealTab.tsx
-msgid "Show terminal"
-msgstr "Show terminal"
-
#: src/components/command-palette-commands.ts
msgid "Show Terminal"
msgstr "Show Terminal"
@@ -7425,6 +7747,10 @@ msgstr "Shows above the code body. Round-trips as `title=\"...\"` in markdown."
msgid "Sign in"
msgstr "Sign in"
+#: src/components/acp/ThreadView.tsx
+msgid "Sign in to {agentName} first"
+msgstr "Sign in to {agentName} first"
+
#: src/components/AuthModal.tsx
msgid "Sign-in stream ended without confirmation — please try again"
msgstr "Sign-in stream ended without confirmation — please try again"
@@ -7480,6 +7806,11 @@ msgstr "Skills teach agents repeatable tasks. Author them here; install a skill
msgid "Skip"
msgstr "Skip"
+#. placeholder {0}: item.displayName
+#: src/components/acp/ThreadView.tsx
+msgid "Skipped downloading {0}."
+msgstr "Skipped downloading {0}."
+
#: src/lib/keyboard-shortcuts.ts
msgid "Slash command menu"
msgstr "Slash command menu"
@@ -7567,10 +7898,32 @@ msgstr "Split list item"
msgid "Star us on GitHub"
msgstr "Star us on GitHub"
+#: src/components/BottomComposer.tsx
+#: src/components/empty-state/CreatePromptComposer.tsx
+#: src/components/handoff/OpenInAgentContextSubmenu.tsx
+#: src/components/handoff/OpenInAgentEmptySpaceSubmenu.tsx
+#: src/components/handoff/OpenInAgentMenu.tsx
+msgid "Start {agentName}"
+msgstr "Start {agentName}"
+
+#: src/components/handoff/OpenInAgentContextSubmenu.tsx
+#: src/components/handoff/OpenInAgentEmptySpaceSubmenu.tsx
+msgid "Start {agentName}, {hint}"
+msgstr "Start {agentName}, {hint}"
+
#: src/components/NavigatorApp.tsx
msgid "Start a new OpenKnowledge project."
msgstr "Start a new OpenKnowledge project."
+#: src/components/TerminalSessionsHost.tsx
+msgid "Start a session with the + button, or launch an agent from a page."
+msgstr "Start a session with the + button, or launch an agent from a page."
+
+#: src/components/BottomComposer.tsx
+#: src/components/TerminalNewChatButton.tsx
+msgid "Start an agent"
+msgstr "Start an agent"
+
#: src/components/NewItemDialog.tsx
msgid "Start from"
msgstr "Start from"
@@ -7595,6 +7948,10 @@ msgstr "Starter content"
msgid "starter pack"
msgstr "starter pack"
+#: src/components/acp/ThreadView.tsx
+msgid "Starting {agentName}…"
+msgstr "Starting {agentName}…"
+
#: src/components/CloneDialog.tsx
msgid "Starting clone"
msgstr "Starting clone"
@@ -7603,6 +7960,10 @@ msgstr "Starting clone"
msgid "Starting sign-in flow"
msgstr "Starting sign-in flow"
+#: src/components/acp/ThreadView.tsx
+msgid "Starting the agent…"
+msgstr "Starting the agent…"
+
#: src/components/TemplateForm.tsx
msgid "status"
msgstr "status"
@@ -7621,6 +7982,14 @@ msgstr "Stays on this computer."
msgid "Still loading"
msgstr "Still loading"
+#: src/components/acp/ThreadView.tsx
+msgid "Stop"
+msgstr "Stop"
+
+#: src/components/acp/ThreadView.tsx
+msgid "Stopping"
+msgstr "Stopping"
+
#: src/components/settings/ProjectTemplatesSection.tsx
msgid "Stored at <0>.ok/templates/</0> in this project. Available in every folder (folder-scoped templates can override by filename)."
msgstr "Stored at <0>.ok/templates/</0> in this project. Available in every folder (folder-scoped templates can override by filename)."
@@ -7911,6 +8280,7 @@ msgstr "Templates available"
#: src/components/handoff/OpenInAgentMenu.tsx
#: src/components/McpConsentDialogBody.tsx
#: src/components/settings/AiToolsSection.tsx
+#: src/components/settings/ConfigureAgentsSection.tsx
#: src/components/settings/SettingsDialogShell.tsx
#: src/components/settings/TerminalSection.tsx
#: src/components/TerminalNewChatButton.tsx
@@ -7935,10 +8305,6 @@ msgstr "Terminal disabled"
msgid "Terminal failed to load"
msgstr "Terminal failed to load"
-#: src/components/TerminalTabStrip.tsx
-msgid "Terminal sessions"
-msgstr "Terminal sessions"
-
#: src/components/TerminalGate.tsx
msgid "Terminal settings not loaded yet — try again in a moment."
msgstr "Terminal settings not loaded yet — try again in a moment."
@@ -7969,6 +8335,11 @@ msgstr "That branch is already open in another worktree."
msgid "That folder isn't an OpenKnowledge project yet. Initialize it and open?"
msgstr "That folder isn't an OpenKnowledge project yet. Initialize it and open?"
+#. placeholder {0}: item.displayName
+#: src/components/acp/ThreadView.tsx
+msgid "The {0} download request timed out."
+msgstr "The {0} download request timed out."
+
#: src/components/ShareBranchSwitchDialog.tsx
msgid "The {targetNoun} could not be opened — try navigating to it manually."
msgstr "The {targetNoun} could not be opened — try navigating to it manually."
@@ -7977,6 +8348,10 @@ msgstr "The {targetNoun} could not be opened — try navigating to it manually."
msgid "The <0>type</0> every document created from this template gets (e.g. <1>research-note</1>). Keeps new docs Open Knowledge Format–conformant."
msgstr "The <0>type</0> every document created from this template gets (e.g. <1>research-note</1>). Keeps new docs Open Knowledge Format–conformant."
+#: src/components/acp/ThreadView.tsx
+msgid "The agent isn't stopping. Force stop closes this thread and quits the agent."
+msgstr "The agent isn't stopping. Force stop closes this thread and quits the agent."
+
#: src/components/CreatedItemsList.tsx
msgid "The agent's persona, values, and voice."
msgstr "The agent's persona, values, and voice."
@@ -8138,6 +8513,19 @@ msgstr "This {targetNoun} was shared from branch <0>{shareBranch}</0>. It doesn'
msgid "This {targetNoun} was shared from branch <0>{shareBranch}</0>. You're currently on <1>{currentLabel}</1>."
msgstr "This {targetNoun} was shared from branch <0>{shareBranch}</0>. You're currently on <1>{currentLabel}</1>."
+#: src/components/acp/ThreadView.tsx
+msgid "This agent needs you to sign in first — see the notice below."
+msgstr "This agent needs you to sign in first — see the notice below."
+
+#. placeholder {0}: item.provides
+#. placeholder {1}: item.displayName
+#. placeholder {2}: item.version
+#. placeholder {3}: item.approxSizeMB
+#. placeholder {4}: item.sourceHost
+#: src/components/acp/ThreadView.tsx
+msgid "This agent runs through {0}, which isn't installed. Open Knowledge can download a private copy of {1} {2} (about {3} MB from {4}) that won't touch the rest of your system."
+msgstr "This agent runs through {0}, which isn't installed. Open Knowledge can download a private copy of {1} {2} (about {3} MB from {4}) that won't touch the rest of your system."
+
#: src/components/ShareReceiveDialog.tsx
msgid "This branch is checked out in:"
msgstr "This branch is checked out in:"
@@ -8280,6 +8668,10 @@ msgstr "This replaces the current skill content with the bundled version {0} (yo
msgid "This replaces the current skill content with the bundled version {0}. Any local edits will be replaced — your current version is saved to history first, so you can restore it."
msgstr "This replaces the current skill content with the bundled version {0}. Any local edits will be replaced — your current version is saved to history first, so you can restore it."
+#: src/components/acp/ThreadView.tsx
+msgid "This request is no longer active."
+msgstr "This request is no longer active."
+
#: src/components/settings/SearchSection.tsx
msgid "This sends content off your machine"
msgstr "This sends content off your machine"
@@ -8424,6 +8816,10 @@ msgstr "Turn off Only markdown files"
msgid "Turn on"
msgstr "Turn on"
+#: src/components/empty-state/CreatePromptComposer.tsx
+msgid "Turn on an agent to create with AI"
+msgstr "Turn on an agent to create with AI"
+
#: src/components/settings/LinkPreviewsSection.tsx
msgid "Turn on external link previews?"
msgstr "Turn on external link previews?"
@@ -8778,6 +9174,10 @@ msgstr "Visual editor table selection"
msgid "Waiting for authorization"
msgstr "Waiting for authorization"
+#: src/components/acp/ThreadView.tsx
+msgid "Waiting for your approval"
+msgstr "Waiting for your approval"
+
#: src/components/settings/AccountSection.tsx
msgid "We couldn't check your GitHub connection."
msgstr "We couldn't check your GitHub connection."
@@ -8931,6 +9331,10 @@ msgstr "Word wrap"
msgid "Working"
msgstr "Working"
+#: src/components/acp/ThreadView.tsx
+msgid "Working…"
+msgstr "Working…"
+
#: src/lib/keyboard-shortcuts.ts
msgid "Workspace"
msgstr "Workspace"
diff --git a/packages/app/src/locales/pseudo/messages.json b/packages/app/src/locales/pseudo/messages.json
index 51616af66..dae1369b8 100644
--- a/packages/app/src/locales/pseudo/messages.json
+++ b/packages/app/src/locales/pseudo/messages.json
@@ -10,6 +10,7 @@
],
"-3ois8": ["Ĥàŕď ƀŕēàķ"],
"-5jISU": [["0", "plural", { "one": ["#", " ţēḿƥĺàţē"], "other": ["#", " ţēḿƥĺàţēś"] }]],
+ "-7s4fw": ["Śēàŕćĥ àĝēńţś"],
"-8PP0T": ["Ḿàţćĥ ćàśē"],
"-FeyRg": ["Ķēēƥ ōŕĩĝĩńàĺ ƒĩĺē"],
"-K0AvT": ["Ďĩśćōńńēćţ"],
@@ -58,7 +59,7 @@
"0LBDjY": ["\"", ["0"], "\" ũńĩńśţàĺĺēď — ƀàćķ ţō à ďŕàƒţ"],
"0NA4b3": ["Ķēēƥ ḿŷ vēŕśĩōń"],
"0NkNB5": [["0"], "ḿō àĝō"],
- "0SBTff": ["Śĥōŵ ţēŕḿĩńàĺ"],
+ "0QVrvp": ["Ḿàxĩḿũḿ àĝēńţś àĺŕēàďŷ ŕũńńĩńĝ"],
"0TnCvC": ["Ŕēńàḿē ", ["0"]],
"0YEbfk": ["Ćōńńēćţ ţō ÀĨ ţōōĺś"],
"0YUS3Q": ["Śũƀƒōĺďēŕ ũńďēŕ ćũŕŕēńţ ƒōĺďēŕ"],
@@ -90,7 +91,9 @@
"10g8I_": ["Ţũŕń ōƒƒ Ōńĺŷ ḿàŕķďōŵń ƒĩĺēś"],
"12F9WL": ["(ńō ĩď)"],
"151wvk": ["Śĥōŵ śĩďēƀàŕ"],
+ "161NCV": ["Śţōƥƥĩńĝ"],
"16D5Zj": ["Àŕē ŷōũ śũŕē ŷōũ ŵàńţ ţō ďēĺēţē ", ["itemName"], "? Ţĥĩś àćţĩōń ćàńńōţ ƀē ũńďōńē."],
+ "16eIWu": ["Ƒōŕćē śţōƥ"],
"170Js2": ["Ĥĩďē ƥàńēĺ"],
"1AumWo": ["Ƥũśĥ ƒàĩĺēď — ćĥēćķ ţĥē śēŕvēŕ ĺōĝś ƒōŕ ďēţàĩĺś."],
"1CalO6": ["Śţŷĺē"],
@@ -99,7 +102,6 @@
"1FLarN": ["Ďēśćŕĩƀē ŵĥàţ ŷōũ ŵàńţ ţō ćŕēàţē ţō ćōńţĩńũē"],
"1GhYxC": ["ōƒ ", ["totalPages"]],
"1HBhDS": ["Ćĥēćķĩńĝ ōũţ ƒĩĺēś"],
- "1MGRQl": ["Ţēŕḿĩńàĺ śēśśĩōńś"],
"1OKzC_": ["Ŷōũŕ ŕēƥōŕţ ćōũĺďń'ţ ƀē śēńţ. Ţŕŷ àĝàĩń ōŕ ēḿàĩĺ ĩţ ĩńśţēàď."],
"1QfxQT": ["Ďĩśḿĩśś"],
"1RluQD": ["Śĥōŵ ŕēƥĺàćē"],
@@ -110,6 +112,7 @@
],
"1YJ4Yg": ["Ũƥďàţē àvàĩĺàƀĺē", ["0"]],
"1ZpfyB": ["Ōƥēń ŵĩţĥ ÀĨ ", ["displayName"], ", ", ["hint"]],
+ "1a6ICf": ["Ƒōĺĺōŵĩńĝ ţĥē àĝēńţ'ś ēďĩţś"],
"1bDVu5": ["Ŵōŕķśƥàćē Ćōḿḿàńď Ƥàĺēţţē"],
"1d1F11": ["Śēĺēćţ àĺĺ ƒĩĺēś àńď ƒōĺďēŕś"],
"1di5fu": ["Ďōćũḿēńţ ńōţ ƒōũńď"],
@@ -123,6 +126,7 @@
"2277Tu": ["Ćōĺĺàƥśē ĝŕàƥĥ"],
"237hSL": ["Ēńďēď"],
"25Pw6a": ["Ćĺōńĩńĝ"],
+ "27TLNq": ["Ēńàƀĺē ", ["displayName"], " ĆĹĨ"],
"27XW26": ["Ćĺōńē ĥàƥƥēńś ĩń ţĥē ƤŕōĴēćţ Ńàvĩĝàţōŕ. Ŕēćĺĩćķ ţĥē śĥàŕē ĺĩńķ ţĥēŕē."],
"28B21t": ["Àĝēńţ Śķĩĺĺś"],
"29VNqC": ["Ũńķńōŵń ēŕŕōŕ"],
@@ -155,7 +159,9 @@
["FULLSCREEN_HUB_LIMIT"],
" ŕēśũĺţś."
],
+ "2ojpo0": ["Ďōćķ śēśśĩōńś ōń ţĥē ŕĩĝĥţ"],
"2q_Q7x": ["Vĩśĩƀĩĺĩţŷ"],
+ "2rLM8r": ["Ćōũĺďń'ţ śţàŕţ ţĥē àĝēńţ ţĥŕēàď — ƥĺēàśē ţŕŷ àĝàĩń."],
"2ryd91": ["Ƒàĩĺēď ţō ŕēńàḿē ƥŕōƥēŕţŷ"],
"2tgFCe": ["Śţàŕţĩńĝ ćĺōńē"],
"2vIPtm": ["Ōƥēń ĺĩńķ ĩń ńēŵ ţàƀ"],
@@ -177,7 +183,6 @@
"3HNlwb": ["Ĥēĺĺō, ŵōŕĺď!"],
"3Ib6FN": ["Ḿōvē ďōŵń"],
"3Ijjy1": ["Ćōũĺďń'ţ ĺōàď ţĥĩś śķĩĺĺ'ś ƒĩĺēś."],
- "3IseAk": ["Ĩńśţàĺĺ àń ÀĨ àĝēńţ ţō ćŕēàţē ŵĩţĥ ÀĨ"],
"3J7d2N": ["ßĩĝ śēćţĩōń ĥēàďĩńĝ."],
"3JYy1p": ["ßŕàńćĥ ", ["0"], " ńō ĺōńĝēŕ ēxĩśţś. Ćĺōńēď ţō ďēƒàũĺţ ƀŕàńćĥ."],
"3MnvrL": ["Śĥōŵĩńĝ ţōƥ ", ["0"], " ḿàţćĥēś — ķēēƥ ţŷƥĩńĝ ţō ńàŕŕōŵ"],
@@ -203,6 +208,7 @@
"3m2GBo": ["Śēàŕćĥĩńĝ ďōćś"],
"3mFsc3": ["Ŕēśţōŕē ŵĩţĥ ŕēḿōţē ćĥàńĝēś"],
"3o3tur": ["Śţàŕţēŕ ćōńţēńţ"],
+ "3oEK1e": ["Ŕēśũḿĩńĝ ţĥē ćōńvēŕśàţĩōń"],
"3oh0nQ": ["Ńēśţēď .ōķĩĝńōŕē ēŕŕōŕ ĩń ", ["path"]],
"3pU8e-": ["Ƥĩń ţàƀ"],
"3wiBAs": ["Ŵĥēŕē śĥōũĺď ĩţ ĺĩvē?"],
@@ -238,6 +244,7 @@
"Ďēţēćţēď ƒŕōḿ ţĥē ēďĩţōŕś ţĥĩś ƥŕōĴēćţ ĩś śēţ ũƥ ƒōŕ. ÀďĴũśţ ţō ćōńţŕōĺ ŵĥēŕē ēvēŕŷ śķĩĺĺ ĩńśţàĺĺś."
],
"4buZWd": ["Ĩńĥēŕĩţēď ƒŕōḿ ", ["path"]],
+ "4cEClj": ["Śēśśĩōńś"],
"4c_a6S": ["Ńōţĥĩńĝ śēţ ŷēţ."],
"4g19V6": ["Ƒàĩĺēď ţō ũƥďàţē ƥŕōƥēŕţŷ"],
"4h3e0H": ["Ćōũĺďń'ţ ũƥďàţē śķĩĺĺś śĥàŕĩńĝ — ", ["detail"], "."],
@@ -282,6 +289,7 @@
"5OTgC7": ["Ōƥēń àńď ƒōćũś ţĥē ƀōţţōḿ Àśķ ÀĨ ƥŕōḿƥţ ćōḿƥōśēŕ."],
"5OqaJi": ["Ēńţēŕ à ƥŕōĴēćţ ńàḿē"],
"5PHgV2": ["Ŷōũ ćàń àĺśō ćŕēàţē ōńē ƒŕōḿ à ţēŕḿĩńàĺ ŵĩţĥ <0>ōķ ƀũĝ-ŕēƥōŕţ</0>."],
+ "5PrrYw": ["Śţàŕţ ", ["agentName"]],
"5QGTaA": ["Ćōũĺď ńōţ ćōƥŷ ŕēĺàţĩvē ƥàţĥ"],
"5SwVv1": ["Ńōţ ĩńśţàĺĺēď"],
"5Tk8Fb": ["Ĺōàďĩńĝ ƒĩĺēś"],
@@ -299,6 +307,7 @@
["userToken"],
"</1> ţō ƒĩĺĺ ĩń ţōďàŷ'ś ďàţē ōŕ ţĥē àũţĥōŕ'ś ńàḿē àũţōḿàţĩćàĺĺŷ."
],
+ "5jEnaB": ["Ńōţ àvàĩĺàƀĺē ōń ţĥĩś ƥĺàţƒōŕḿ"],
"5kWklo": ["(śōḿē ḿàŷ àĺŕēàďŷ ƀē ĥĩďďēń ƀŷ ōţĥēŕ ŕũĺēś)"],
"5lWFkC": ["Śĩĝń ĩń"],
"5mksg0": ["Ƒàĩĺēď ţō ďĩśàƀĺē śēḿàńţĩć śēàŕćĥ — ", ["detail"]],
@@ -318,6 +327,7 @@
}
]
],
+ "5vYdh9": ["Ńēŵ ţĥŕēàď ŵĩţĥ ", ["0"]],
"5wV2qQ": ["àńď ḿōŕē"],
"5y_9lO": ["Ŵàĩţĩńĝ ƒōŕ àũţĥōŕĩźàţĩōń"],
"6-wLTJ": [["behind"], " ƀēĥĩńď ōŕĩĝĩń"],
@@ -396,8 +406,11 @@
"7d1a0d": ["Ƥũƀĺĩć"],
"7hctf2": ["Ďēśćŕĩƀē ţĥē ƥŕōĴēćţ ŷōũ ŵàńţ ţō ćŕēàţē"],
"7jIIFX": ["Ŷōũ'ŕē àĺĺ śēţ ũƥ!"],
+ "7kb4LU": ["Àƥƥŕōvēď"],
+ "7l15X4": ["ƒàĩĺēď"],
"7qRHf0": ["Ĩńśţàĺĺ ƒōŕ Ćĺàũďē Ćĥàţ & Ćōŵōŕķ"],
"7uBlRT": ["Ćōƥŷ ţĥē ƒōćũśēď ƒĩĺē-ţŕēē ĩţēḿ śō Ƥàśţē ćàń ďũƥĺĩćàţē ĩţ."],
+ "7vQdBK": ["Ĺōàďĩńĝ ţĥē ćōńvēŕśàţĩōń"],
"80c4-P": ["Ćōďē ćōƥĩēď ţō ćĺĩƥƀōàŕď"],
"81H_23": ["Àďď ƥŕōƥēŕţĩēś"],
"881Uwh": ["Ďēĺēţē śēĺēćţēď ţàƀĺē"],
@@ -438,6 +451,7 @@
"8lwQlE": [["0"], " àďďēď, ", ["1"], " ŕēḿōvēď"],
"8m8diM": ["Ńō ĺōćàţĩōń śēĺēćţēď. Ũśē ßŕōŵśē ţō ćĥōōśē à ƒōĺďēŕ."],
"8nWu1k": ["Ēḿƥţŷ ďĩàĝŕàḿ"],
+ "8t9CRE": ["Śţàŕţĩńĝ ", ["agentName"], "…"],
"8tjQCz": ["Ēxƥĺōŕē"],
"8uAWix": [
"Ţĥĩś ţēḿƥĺàţē ĺĩvēś ĩń à ƥàŕēńţ ƒōĺďēŕ — ďēĺēţĩńĝ ĩţ àƒƒēćţś ēvēŕŷ ƒōĺďēŕ ƀēńēàţĥ ĩţ ţĥàţ ďōēśń'ţ ďēƒĩńē ĩţś ōŵń vēŕśĩōń."
@@ -496,10 +510,12 @@
],
"AB4qw9": ["Ńēŵ ţēŕḿĩńàĺ"],
"AE7BY3": ["Ţĥē ţēŕḿĩńàĺ śēśśĩōń ēńďēď."],
+ "AIVHDc": ["Ćĥōōśē ŵĥàţ à ńēŵ śēśśĩōń śţàŕţś"],
"AIn2Yv": [["displayName"], " ĆĹĨ, ", ["hint"]],
"AItsE5": ["Ōƥēń ĩţ ţĥēŕē"],
"AKxFtn": [["openedWorktreeCount", "plural", { "one": ["ŵōŕķţŕēē"], "other": ["ŵōŕķţŕēēś"] }]],
"ALhMYW": ["Ţēŕḿĩńàĺ"],
+ "APNlbk": ["ēxĩţ ", ["0"]],
"AQ-Lfg": ["Ćōũĺďń'ţ ĺōàď ţēḿƥĺàţēś"],
"AQGtjK": [
"Ćōḿḿàńďś ŕũń ŵĩţĥ ţĥē ƒũĺĺ àććēśś ōƒ ŷōũŕ ḿàćŌŚ ũśēŕ àććōũńţ ōń ţĥĩś ḿàćĥĩńē. Ţũŕń ţĥĩś ōƒƒ ţō ďĩśàƀĺē ţĥē śĥēĺĺ."
@@ -565,6 +581,7 @@
"Bh9671": [
"Ţĥĩś ƥŕōĴēćţ ĩś ĺōćàĺ-ōńĺŷ, śō .ōķ/śķĩĺĺś ĩś ĥĩďďēń ƒŕōḿ ĝĩţ àńď ţĥēśē śķĩĺĺś ćàń'ţ ƀē ćōḿḿĩţţēď ōŕ śĥàŕēď. Śĥàŕē Ĵũśţ ţĥē śķĩĺĺś ƒōĺďēŕ — ţĥē ŕēśţ ōƒ ŷōũŕ ŌĶ ćōńƒĩĝ śţàŷś ōń ţĥĩś ćōḿƥũţēŕ."
],
+ "BjitBo": ["Ďōŵńĺōàď ", ["0"]],
"Bn9-El": ["ďēƒàũĺţ"],
"Bv5a9_": ["Śēĺēćţĩōń śţàţĩśţĩćś"],
"Bx4EXG": ["Àćţĩōńś ƒōŕ ", ["label"]],
@@ -575,12 +592,14 @@
"C62P6b": ["Ēďĩţōŕ śēĺēćţĩōń"],
"C7XjNB": ["Ĝĺōƀàĺ Śķĩĺĺ"],
"C9TBvF": ["Ńō Ōũţĝōĩńĝ"],
+ "CBsdhe": ["Ţĥē àĝēńţ ĩśń'ţ śţōƥƥĩńĝ. Ƒōŕćē śţōƥ ćĺōśēś ţĥĩś ţĥŕēàď àńď ǫũĩţś ţĥē àĝēńţ."],
"CCTop_": ["Ŕēćēńţ"],
"CFnavk": ["Ţĥĩś ƥŕōĴēćţ ĩśń'ţ à ĝĩţ ŕēƥōśĩţōŕŷ, śō ŵōŕķţŕēēś àŕēń'ţ àvàĩĺàƀĺē."],
"CKyk7Q": ["Ĝō ƀàćķ"],
"COr1Y7": [
"Ƥĩćķ <0>ōƥēńķńōŵĺēďĝē.śķĩĺĺ</0> ƒŕōḿ ŷōũŕ <1>Ďōŵńĺōàďś</1> ƒōĺďēŕ. Ĩţ ēńàƀĺēś àũţōḿàţĩćàĺĺŷ."
],
+ "CPmYSG": ["Ćĥēćķĩńĝ ƒōŕ àĝēńţś"],
"CSL0l1": ["Ćōũĺďń'ţ ćĺēàŕ ţĥē ķēŷ — ƥĺēàśē ţŕŷ àĝàĩń."],
"CTJLpz": ["\"", ["trimmed"], "\" àĺŕēàďŷ ēxĩśţś ĥēŕē"],
"CU3AiE": ["Śŵĩţćĥĩńĝ ƀŕàńćĥēś"],
@@ -599,6 +618,7 @@
"Ck9XRt": ["Ćōũĺďń'ţ śàvē ţĥē ķēŷ — ƥĺēàśē ţŕŷ àĝàĩń."],
"CmeH9S": ["Àďď ƥŕōƥēŕţŷ ţō ", ["keyName"]],
"CoHvYd": ["Ḿōvēď ", ["0"], " ţō ƥōśĩţĩōń ", ["1"], " ōƒ ", ["2"]],
+ "CooKEf": ["Ďōćķ śēśśĩōńś àţ ţĥē ƀōţţōḿ"],
"CvsD6Y": ["vĩà ", ["viaTags"]],
"D-Oh1s": ["Ĥōŵ ţō śēţ ũƥ ", ["0"], " (ōƥēńś ĩń ƀŕōŵśēŕ)"],
"D12vtS": ["(ďēţàćĥēď)"],
@@ -618,6 +638,7 @@
"DFfRbX": ["Śŷńć śţàţũś: ", ["syncStateLabel"], " — ĝĩţ ĩďēńţĩţŷ ũńśēţ"],
"DId6MT": ["ƤŕōĴēćţ-ĺēvēĺ ƥàĝēś ŵĩţĥ ńō ōũţĝōĩńĝ ĝŕàƥĥ ēďĝēś."],
"DJd000": ["Àćţĩvàţē ţĥē ƥŕēvĩōũś ēďĩţōŕ ţàƀ."],
+ "DMeaxi": ["Ďōŵńĺōàďĩńĝ ", ["0"], " ", ["1"], "…"],
"DPfwMq": ["Ďōńē"],
"DTI-fp": [
"Ţĥĩś ",
@@ -679,6 +700,7 @@
"EL_YRd": ["Ḿĩŕŕōŕ ōƒ <0>àƥĩ-śƥēć</0>"],
"ENpRJV": ["Ēxţēŕńàĺ ĺĩńķ ƥŕēvĩēŵś"],
"EOjU5V": ["Ĩńĺĩńē Ḿàţĥ Ƥŕōƥēŕţĩēś"],
+ "EPwuTC": [["usedLabel"], " / ", ["sizeLabel"], " ţōķēńś ũśēď"],
"ETyvvg": ["Ńō ĺàńĝũàĝē ḿàţćĥ."],
"EVnzPs": ["Ēďĩţ ŵĩţĥ ÀĨ"],
"EWPtMO": ["Ćōďē"],
@@ -693,6 +715,7 @@
"Ea1prf": ["Ćĥōōśē ŵĥĩćĥ ēďĩţōŕś ēvēŕŷ śķĩĺĺ ĩń ţĥĩś ƥŕōĴēćţ ĩńśţàĺĺś ĩńţō."],
"EarrCe": ["Śēàŕćĥ ēḿōĴĩ"],
"Eax_et": ["Àććēńţ"],
+ "EbMUlU": ["Àĝēńţ ḿōďē"],
"EbZT7P": ["Ţōĝĝĺē ţĥē ĺēƒţ ƒĩĺē śĩďēƀàŕ."],
"EbjWsS": ["Ćũŕŕēńţ ćōḿḿĩţ"],
"EcM3k7": ["Ƒàĩĺēď ţō ćĺēàń ũƥ ƥēńďĩńĝ ", ["kind"]],
@@ -706,6 +729,15 @@
"Eji13z": ["Ţōĝĝĺē ĥĩĝĥĺĩĝĥţ ƒōŕḿàţţĩńĝ."],
"EkH9pt": ["Ũƥďàţē"],
"El7NbA": ["Ĥēàďĩńĝ 2"],
+ "ElatXA": [
+ "Ćōńţēxţ ŵĩńďōŵ: ",
+ ["percent"],
+ "% ũśēď, ",
+ ["usedLabel"],
+ " ōƒ ",
+ ["sizeLabel"],
+ " ţōķēńś"
+ ],
"Emz5BG": [
"Ēḿƀēďďĩńĝś àŕē ćōḿƥũţēď ōńĺŷ ŵĥēń à śēàŕćĥ ŕũńś àńď àŕē ćàćĥēď ĺōćàĺĺŷ ũńďēŕ <0>.ōķ/ĺōćàĺ</0>."
],
@@ -754,6 +786,7 @@
"FgRAvd": ["Ĺōĝś & śŷśţēḿ ĩńƒō"],
"FjkaiT": ["Źōōḿ ōũţ"],
"FnMkli": ["Śŷńć ďĩśàƀĺēď — ŷōũ ďōń'ţ ĥàvē ƥēŕḿĩśśĩōń ţō ƥũśĥ"],
+ "FqGWeR": ["Ćōũĺďń'ţ ŕēàćĥ ţĥē àĝēńţ ŕēĝĩśţŕŷ."],
"FqTpiN": ["ßĩŕď ŵĩķĩ"],
"Fqr8BP": ["Ḿũĺţĩ-ƥàĝē ƤĎƑ vĩēŵēŕ ŵĩţĥ ţōōĺƀàŕ ćōńţŕōĺś (ţĥũḿƀńàĩĺś, ƥàĝē ńàv, źōōḿ)."],
"Fsx78O": ["Àďď ţĥē <0>ōķ</0> ćōḿḿàńď ţō ŷōũŕ ţēŕḿĩńàĺ"],
@@ -773,6 +806,7 @@
"G1XxbZ": ["Ćĥēćķƀōx"],
"G4-bgo": ["Àśķ ÀĨ (ƒŕōḿ śēĺēćţĩōń)"],
"G7-rf8": ["Ƥàţţēŕń śŷńţàx ēŕŕōŕ: ", ["message"]],
+ "G7bn_N": ["Śţàŕţ àń àĝēńţ"],
"G7cMuO": ["ĤŢḾĹ ƥŕēvĩēŵ"],
"G8t9NN": ["Àďď à ƥŕōƥēŕţŷ"],
"GA-UkN": [["keyName"], " ţŷƥē: ", ["typeLabel"], ". Ćĺĩćķ ţō ćĥàńĝē."],
@@ -877,6 +911,7 @@
"If0crP": ["Ōƥēń ŵĩţĥ ÀĨ ", ["targetDisplayName"], ", ", ["hint"]],
"IgTwLt": ["Ōƥēń ţĥĩś ďōćũḿēńţ ĩń ţĥē ēďĩţōŕ àńď ćōĺĺàƥśē ţĥē ĝŕàƥĥ."],
"Ik-gP0": ["Ĥēàďĩńĝ Ĥ", ["level"], ": ", ["text"]],
+ "IlH15B": ["Śţàŕţ à śēśśĩōń ŵĩţĥ ţĥē + ƀũţţōń, ōŕ ĺàũńćĥ àń àĝēńţ ƒŕōḿ à ƥàĝē."],
"Iq8zdU": ["Ćĺōśē ţēŕḿĩńàĺ"],
"IrB5AK": [
"Śēŕvēŕ-śĩďē ćĺēàńũƥ ƒàĩĺēď ƒōŕ ",
@@ -911,8 +946,10 @@
"JfPuv7": [["shareBranch"], " ĩśń'ţ à vàĺĩď ƀŕàńćĥ ńàḿē."],
"Jhj_lh": ["Ḿōďĩƒŷ ţĥē ĺĩńķ ţàŕĝēţ, àńćĥōŕ, àńď ďĩśƥĺàŷ ĺàƀēĺ."],
"JkCD2u": ["Śŷńć ƥàũśēď — ŷōũ ďōń'ţ ĥàvē ƥēŕḿĩśśĩōń ţō ƥũśĥ ţō ţĥĩś ŕēƥō"],
+ "JlFcis": ["Śēńď"],
"JmfgFc": ["(à ŵōŕķţŕēē ōƒ ", ["0"], ")"],
"Jqqevv": ["Śŷśţēḿ ēŕŕōŕ"],
+ "JsY1p5": ["Ďēńĩēď"],
"JtD-Br": ["Ƥàĝē ĺĩńķ"],
"Jw6EC4": ["ßŕàńćĥ śŵĩţćĥ ƒàĩĺēď — ţŕŷ ōƥēńĩńĝ ţĥē ", ["targetNoun"], " ḿàńũàĺĺŷ."],
"K-a33w": ["Śţàŕţ ŵŕĩţĩńĝ ţō ćŕēàţē ţĥĩś ƥàĝē"],
@@ -943,6 +980,7 @@
"KPW5WC": ["ḿōvēď ţēḿƥĺàţē"],
"KQGZuq": ["Ŕēũśēď ĩƒ ĩţ àĺŕēàďŷ ēxĩśţś, ćŕēàţēď ĩƒ ńōţ."],
"KRJ6xh": ["Ńō ţàĝś ŷēţ. Ćōńţĩńũē ţŷƥĩńĝ ţō ćŕēàţē ōńē."],
+ "KUjOb9": ["ŕũńńĩńĝ"],
"KWL_Ih": ["ßĺōĝ ƥōśţ"],
"KX1MZR": ["Ŷōũŕ ŕēƥōśĩţōŕĩēś"],
"KYSocE": ["Ŕēśēàŕćĥ ţĥē ēxţĩńćţĩōń ōƒ ƒĺĩĝĥţĺēśś ƀĩŕďś"],
@@ -969,7 +1007,9 @@
"KtACeE": ["Ďēƒàũĺţ: <0>", ["0"], "</0>"],
"KujtjC": ["Ƒĩńď"],
"L-rMC9": ["Ŕēśēţ ţō ďēƒàũĺţ"],
+ "L1BQTH": [["0"], " ĩśń'ţ ĩńśţàĺĺēď ŷēţ — ōƥēńĩńĝ ĩţś ďōŵńĺōàď ƥàĝē."],
"L1ZE3M": ["Ďōćũḿēńţ śţàţĩśţĩćś"],
+ "L1qaHQ": ["Àƥƥŕōvēď — ", ["0"]],
"L1rRuU": ["Ēḿƀēďďĩńĝś ÀƤĨ ēńďƥōĩńţ"],
"L3CEC1": ["ţĥĩś ĩţēḿ"],
"L4Cdd9": ["ōŕ ćŕēàţē à ńēŵ ƒĩĺē <0/>"],
@@ -992,6 +1032,7 @@
],
"LKOLNn": ["Ńō ÀĨ àĝēńţś ĩńśţàĺĺēď"],
"LNum6A": [["minutes"], " ḿĩń àĝō"],
+ "LPAv9E": [["days"], "ď àĝō"],
"LRgZAt": [["owner"], "/", ["name"], " àĺŕēàďŷ ēxĩśţś"],
"LXdWeS": ["Ḿēďĩũḿ śēćţĩōń ĥēàďĩńĝ."],
"LXfNU-": ["Ńàvĩĝàţĩōń àńď śũĝĝēśţĩōńś"],
@@ -1047,6 +1088,7 @@
],
"MHrjPM": ["Ţĩţĺē"],
"MJqRO6": ["Ŷōũŕ ŕēƥōŕţ ĩś ƀēĩńĝ śēńţ."],
+ "MJuO1q": ["Ćōńţēxţ ŵĩńďōŵ:"],
"MKOVhz": ["Ēńàƀĺē ĝĩţ àũţō-śŷńć"],
"MQIM_Y": ["Ćōũĺďń'ţ ćōƥŷ. Śēĺēćţ ţĥē ŨŔĹ àƀōvē ţō ćōƥŷ ĩţ ḿàńũàĺĺŷ."],
"MRZxAn": ["Ēďĩţēď"],
@@ -1081,6 +1123,7 @@
["0"],
" — ŷōũŕ ƥŕēvĩōũś vēŕśĩōń ĩś ĩń ĥĩśţōŕŷ ĩƒ ŷōũ ńēēď ţō ŕēśţōŕē ĩţ."
],
+ "MysZUL": ["Ćōńńēćţĩńĝ ţō ", ["agentName"], "…"],
"N1KkEO": ["ĵũḿƥ ţō ĺàśţ ţàƀ"],
"N1YYa7": ["Ĺōàďĩńĝ ĩḿàĝē"],
"N1mdmS": ["Ţĥĩś ƒĩĺē ćàń'ţ ƀē ōƥēńēď ĩń ţĥē ţēxţ ēďĩţōŕ."],
@@ -1110,6 +1153,7 @@
"N_7kkF": [
"Ŕēàď ţĥŕōũĝĥ ţĥĩś ćōďēƀàśē àńď ďŕàƒţ à ţēćĥńĩćàĺ śƥēć ƒōŕ ţĥē ḿōśţ ćōḿƥĺēx ḿōďũĺē: àń ōvēŕvĩēŵ, ţĥē àŕćĥĩţēćţũŕē, ķēŷ ƒĩĺēś, àńď ōƥēń ǫũēśţĩōńś, àĺĺ ĺĩńķēď ƒŕōḿ à śƥēćś ĩńďēx ƥàĝē."
],
+ "Nay2Yr": ["Ńō àĝēńţś ḿàţćĥ ŷōũŕ śēàŕćĥ."],
"NcurBF": ["Ƥàń ďōŵń"],
"NgZwB0": [["enabledCount"], "/", ["0"], " ōń"],
"NjrIak": ["Ƒĩĺē: <0>", ["fixedName"], ".ḿď</0>"],
@@ -1142,6 +1186,7 @@
"OFBmkg": [
"Śēàŕćĥ ƒĩĺēś, ćōḿḿàńďś, ƥŕōĴēćţś, àńď ÀĨ ĥàńďōƒƒ àćţĩōńś. Ŵĩţĥ ţēxţ śēĺēćţēď ĩń ţĥē vĩśũàĺ ēďĩţōŕ, ţĥĩś ćĥōŕď àďďś à ĺĩńķ ĩńśţēàď."
],
+ "OJOA7Z": ["⋯ ", ["0"], " ũńćĥàńĝēď ĺĩńēś"],
"OJTOUj": ["Ŕēǫũĩŕēś ", ["brand"], "."],
"OJeiSH": ["Ƒàĩĺēď ţō àďď ƥŕōƥēŕţŷ"],
"OLBz-_": ["Ḿēŕḿàĩď ďĩàĝŕàḿ ƒàĩĺēď ţō ŕēńďēŕ."],
@@ -1157,6 +1202,9 @@
"OYnx7O": ["Ƥàţĥ ćàńńōţ śţàŕţ ŵĩţĥ \"/\""],
"OZJeTZ": ["Śķĩĺĺ"],
"Oawo4U": ["Ţĥē ŕēƥōŕţ śēŕvĩćē ćōũĺďń'ţ ƀē ŕēàćĥēď."],
+ "OcBurH": [
+ "Ćĥōōśē ŵĥĩćĥ àĝēńţś àƥƥēàŕ ĩń ţĥē àĝēńţ śēĺēćţōŕ. Ţũŕń ōńē ōƒƒ ţō ĥĩďē ĩţ ēvēŕŷŵĥēŕē."
+ ],
"OdmsFg": ["Ƒàĩĺēď ţō ďēĺēţē ĩţēḿ"],
"OeAl1e": ["ē.ĝ. àśśēţś/ũƥĺōàďś"],
"OfhWJH": ["Ŕēśēţ"],
@@ -1222,6 +1270,7 @@
"Q6hhn8": ["Ƥŕēƒēŕēńćēś"],
"Q7W-mC": ["Śàḿē ƒōĺďēŕ àś ćũŕŕēńţ ƒĩĺē"],
"Q7cNKe": ["Śķĩĺĺś àŕē ńōŵ śĥàŕēď. Ćōḿḿĩţ .ōķ/śķĩĺĺś ţō śĥàŕē ţĥēḿ ŵĩţĥ ŷōũŕ ţēàḿ."],
+ "Q7xfEj": ["ďōńē"],
"Q8A-U_": ["Ćōńńēćţēď ţō"],
"QAi7Q9": [
"ßŕàńćĥ <0>",
@@ -1229,11 +1278,12 @@
"</0> àĺŕēàďŷ ĥàś à ŵōŕķţŕēē — ĩţ'ĺĺ ōƥēń ĩń ĩţś ōŵń ŵĩńďōŵ."
],
"QDZbvN": [["diffDays"], "ď àĝō"],
- "QJaG-9": ["Ćĥōōśē ĆĹĨ ƒōŕ ńēŵ ćĥàţ"],
- "QNxpRm": ["Ďōćķ ţēŕḿĩńàĺ ţō ţĥē ŕĩĝĥţ"],
+ "QM3SBZ": ["Ƥĺàń (", ["done"], "/", ["0"], ")"],
"QOINDn": ["ēḿƥţŷ"],
+ "QQbwzK": ["Ńō àĝēńţś àvàĩĺàƀĺē."],
"QQghPu": ["Ĩńśţàĺĺ ĩń Ćĺàũďē Ďēśķţōƥ"],
"QR5SP1": ["ćŕēàţēď ţēḿƥĺàţē"],
+ "QTsvh1": ["Ţĥĩś àĝēńţ ńēēďś ŷōũ ţō śĩĝń ĩń ƒĩŕśţ — śēē ţĥē ńōţĩćē ƀēĺōŵ."],
"QYfQdv": [["displayName"], " ĆĹĨ"],
"QcpeeE": ["Ńàvĩĝàţē ţō ", ["docName"]],
"QfFBdJ": ["Ţĥē ţēḿƥĺàţē'ś ƒĩĺēńàḿē (ŵĩţĥōũţ `.ḿď`)."],
@@ -1279,6 +1329,7 @@
"RO-yts": ["Ƒàĩĺēď ţō ďĩśàƀĺē ĺĩńķ ƥŕēvĩēŵś — ", ["detail"]],
"RSqaSd": ["ƤŕōĴēćţ ŕōōţ"],
"RVZJWQ": ["Śēàŕćĥ ƥŕōĴēćţś..."],
+ "RXEbZy": ["Ĩń àƥƥ"],
"RXNu_r": ["Śĥàŕēď vĩà ĝĩţ ŵĩţĥ ēvēŕŷōńē ŵōŕķĩńĝ ōń ţĥĩś ƥŕōĴēćţ."],
"RY6Bq1": ["Ōƥēń śĥàŕēď ", ["targetNoun"]],
"RaPMZv": ["Ķēŷƀōàŕď śĥōŕţćũţś àvàĩĺàƀĺē ĩń ţĥē ēďĩţōŕ àńď ŵōŕķśƥàćē."],
@@ -1305,6 +1356,8 @@
],
"S33tz3": ["Ńōţ ćōńńēćţēď"],
"S34Vju": ["Ĥàvē śōḿēţĥĩńĝ ēĺśē ĩń ḿĩńď?"],
+ "S48xcO": ["ƥēńďĩńĝ"],
+ "S60KvX": ["Ďēĺēţē ţĥĩś ćōńvēŕśàţĩōń?"],
"S6l5dv": ["Ćōũĺď ńōţ śţàŕţ ćŕēàţĩńĝ à ńēŵ ĩţēḿ"],
"S9Vnum": ["Ŕēḿōvē ", ["patternText"]],
"S9t1PI": ["Ƒĩxĩńĝ ", ["0"], "/", ["1"]],
@@ -1312,6 +1365,7 @@
"SCzAbA": [["phase"], " — ", ["pct"], "%"],
"SFN6dN": ["Ĥēàďĩńĝ 3"],
"SOPwPh": ["Ŕēśţōŕē ţō ţĥĩś ēďĩţ"],
+ "SQWJ-i": ["Ŕēśţōŕē śēśśĩōńś"],
"STTOnz": [["keyName"], " ţŷƥē: ćōḿƥĺēx vàĺũē (ńēśţēď; ŕēàď-ōńĺŷ)"],
"SUOoXn": ["Ƒàĩĺēď ţō ōƥēń ƥŕōĴēćţ."],
"SVLPt5": [["formatted"], " ĜĩţĤũƀ śţàŕś"],
@@ -1348,6 +1402,7 @@
"T_wG4n": ["Ŵē ćōũĺďń'ţ ćĥēćķ ŷōũŕ ĜĩţĤũƀ ćōńńēćţĩōń."],
"Ta25TG": ["Ńō ĥĩśţōŕŷ ŷēţ"],
"TbjyhA": ["Ďōćś"],
+ "TdfEV7": ["Àŕćĥĩvēď"],
"Te6sK2": [
"Ĥēàďś ũƥ: ēďĩţĩńĝ àńŷ ŕũĺē ōŕ ōƥţĩōń ĥēŕē ćŕēàţēś à <0>.ḿàŕķďōŵńĺĩńţ.Ĵśōń</0> ƒĩĺē ĩń ŷōũŕ ƥŕōĴēćţ ţō śàvē ŷōũŕ ćĥàńĝēś."
],
@@ -1357,6 +1412,7 @@
"TvY_XA": ["Ďōćũḿēńţàţĩōń"],
"TwYboS": ["Ńàvĩĝàţē ĆōďēḾĩŕŕōŕ śōũŕćē śēàŕćĥ ŕēśũĺţś ōŕ ďĩśḿĩśś ţĥē śēàŕćĥ ƥàńēĺ."],
"Tz0i8g": ["Śēţţĩńĝś"],
+ "Tz4dq-": ["Ţĥĩś ŕēǫũēśţ ĩś ńō ĺōńĝēŕ àćţĩvē."],
"Tz9pJB": ["Ćĺōńē śţŕēàḿ ēńďēď ũńēxƥēćţēďĺŷ — ćĥēćķ ĩƒ ţĥē ćĺōńē ćōḿƥĺēţēď"],
"U2Kx6T": ["Ćĺōśē àĺĺ ũńƥĩńńēď"],
"U2pMtf": ["ţàĝ-ńàḿē"],
@@ -1436,7 +1492,6 @@
"VU3Nrn": ["Ḿĩśśĩńĝ"],
"VUijjF": ["Ēḿƀēď àń ĩḿàĝē ŵĩţĥ ōƥţĩōńàĺ àĺţ ţēxţ."],
"VYd_YA": ["Ōƥēń àń ēxĩśţĩńĝ ƥŕōĴēćţ ƒōĺďēŕ ƒŕōḿ ďĩśķ."],
- "VZGGPK": ["Ćōĺĺàƥśē ţēŕḿĩńàĺ"],
"VZGh8G": ["Ƒōĺď, ũńƒōĺď, ƒōĺď àĺĺ, ōŕ ũńƒōĺď àĺĺ śōũŕćē ŕàńĝēś."],
"VZSBXL": ["Śēḿàńţĩć ŕàńķĩńĝ àćţĩvàţēś ţĥē ƒĩŕśţ ţĩḿē àń àĝēńţ ŕũńś à śēàŕćĥ."],
"V_6bJ4": ["Ţēŕḿĩńàĺ śēţţĩńĝś ńōţ ĺōàďēď ŷēţ — ţŕŷ àĝàĩń ĩń à ḿōḿēńţ."],
@@ -1492,6 +1547,7 @@
"Wcv-Zi": ["Ḿàķē ţĥĩś ķńōŵĺēďĝē ƀàśē àvàĩĺàƀĺē àś à Ćĺàũďē Śķĩĺĺ."],
"We7h2I": ["📝 ōŕ àśśēţś/ĩćōń.ƥńĝ"],
"Weq9zb": ["Ĝēńēŕàĺ"],
+ "Wfy3rU": ["Àĝēńţ śēţţĩńĝś"],
"Wgmlsw": ["Ƒēţćĥĩńĝ"],
"Wh0im4": ["ēďĩţĩńĝ [[", ["realCurrentDoc"], "]]"],
"WhOsNE": ["Śţŕĩķēţĥŕōũĝĥ"],
@@ -1514,10 +1570,14 @@
"XDzAnp": ["Ōƥēńś ĩń à ńēŵ ţàƀ"],
"XH30C4": ["ďōćũḿēńţ"],
"XJOV1Y": ["Àćţĩvĩţŷ"],
+ "XNBGZw": ["Ḿēśśàĝē ńōţ śēńţ: ", ["0"]],
"XPJ0sN": [["settingsDescriptorLabel"], " ƥŕōƥēŕţĩēś"],
"XPqe3B": ["Ćŕēàţē ńēŵ ţàĝ #", ["tagValue"]],
+ "XQkJlB": ["Ńō ōƥēń ćōńvēŕśàţĩōńś. Ŕēōƥēń à ƥàśţ ōńē, ōŕ śţàŕţ à śēśśĩōń ŵĩţĥ ţĥē + ƀũţţōń."],
"XRuL0i": ["Ćŕēàţē ƥàĝē"],
+ "XT-L4j": ["Ţũŕń ōń àń àĝēńţ ţō ćŕēàţē ŵĩţĥ ÀĨ"],
"XU0OXn": ["Ēńàƀĺē àũţō-śŷńć"],
+ "XU5AOg": ["Ĩńƥũţ"],
"XV5sC0": ["Ōƥēń ŵōŕķţŕēē"],
"XW18jo": ["Ƥàĝē ĥēàďĩńĝś ŕēśƥōńśē ďĩď ńōţ ḿàţćĥ śũććēśś śćĥēḿà"],
"XYlJJT": ["Śēţţĩńĝ ũƥ"],
@@ -1530,6 +1590,7 @@
"Xk0-VC": [
"Ƥŕēvĩēŵś ōƒ ĺĩńķś ţō ōţĥēŕ ďōćũḿēńţś ĩń ţĥĩś ƥŕōĴēćţ àŕē àĺŵàŷś ōń àńď ŕēàď ƒŕōḿ ţĥē ĺōćàĺ ĩńďēx — ńōţĥĩńĝ ĺēàvēś ŷōũŕ ćōḿƥũţēŕ ƒōŕ ţĥōśē."
],
+ "XklovM": ["Ŵōŕķĩńĝ…"],
"Xl-UUg": ["ĝũĩďēś/ĩńśţàĺĺ ōŕ ĥţţƥś://ēxàḿƥĺē.ćōḿ"],
"XmJfZT": ["ńàḿē"],
"XnlF3W": ["Àďď ţĥē ńēxţ ḿàţćĥĩńĝ śōũŕćē śēĺēćţĩōń."],
@@ -1554,8 +1615,10 @@
["pickedRelative"],
"</1> ƀēćàũśē ĩţ ćōńţàĩńś à <2>.ĝĩţ</2> ƒōĺďēŕ (ōńē .ōķ/ ƥēŕ ĝĩţ ŕēƥō). <3>Ćōńţēńţ ďĩŕēćţōŕŷ</3> ďēƒàũĺţś ţō <4>.</4> (ţĥē ŵĥōĺē ŕēƥō); ţŷƥē à śũƀ-ƒōĺďēŕ ţō ńàŕŕōŵ ĩţ."
],
+ "Y2tU6I": ["Ďēĺēţē ", ["0"]],
"Y6SK9K": ["Śĥōŵ śōũŕćē"],
"Y8ViJx": ["À ńēŵēŕ vēŕśĩōń ḿàŷ ĥàvē ƀēēń ďēƥĺōŷēď śĩńćē ţĥĩś ţàƀ ōƥēńēď."],
+ "YBt9YP": ["ßēţà"],
"YC6_wP": ["Ēďĩţ ", ["keyName"]],
"YEIS9T": ["Ēďĩţś àƥƥĺŷ ĺĩvē. Ĺĩĝĥţ ōŕ ďàŕķ ĩś ćĥōśēń ƒŕōḿ ţĥē ƀàćķĝŕōũńď."],
"YEP3X2": ["Ďēĺēţē à ţàƀĺē ŵĥēń ţĥē àćţĩvē ţàƀĺē ćēĺĺ śēĺēćţĩōń ćōvēŕś ţĥē ƒũĺĺ ţàƀĺē."],
@@ -1570,6 +1633,8 @@
"YSFv5w": ["Ńō ĝĩţ ŕēƥōśĩţōŕŷ — ćōńƒĩĝ śĥàŕĩńĝ ďōēś ńōţ àƥƥĺŷ ĥēŕē."],
"YTLmTM": ["Ŕēḿōvē ţĥē ƥàŕēńţ <0>.ĝĩţ</0> ƒōĺďēŕ"],
"YW7Q86": ["Śēàŕćĥ śēţţĩńĝś ńōţ ŷēţ ĺōàďēď — ţŕŷ àĝàĩń ĩń à ḿōḿēńţ"],
+ "Y_GpJd": ["Ţĥē ", ["0"], " ďōŵńĺōàď ŕēǫũēśţ ţĩḿēď ōũţ."],
+ "Y_ZQ6l": ["Ĩńśţàĺĺĩńĝ ", ["agentName"], "…"],
"Y_kL7X": ["Ćũśţōḿĩźē ĥōŵ ţĥē ēďĩţōŕ ĺōōķś àńď ƀēĥàvēś."],
"YaeyFh": ["Ƥũĺĺś ḿàŷ ōvēŕŵŕĩţē ũńćōḿḿĩţţēď ēďĩţś ĩń ŷōũŕ ĺōćàĺ ƒĩĺēś."],
"Yea-K5": ["Ŕēśţōŕē ţō ţĥĩś ƥōĩńţ"],
@@ -1659,6 +1724,7 @@
"_NX6gG": ["Ḿàńàĝĩńĝ ƥŕōĴēćţ ÀĨ ţōōĺś ĩś ũńàvàĩĺàƀĺē ĩń ţĥĩś ƀũĩĺď."],
"_PACVa": ["Ŕēĺēàśē ńōţēś"],
"_PBJRl": ["Àďď àţ ĺēàśţ ōńē ĺēţţēŕ ōŕ ńũḿƀēŕ."],
+ "_Pmhxt": ["… ēàŕĺĩēŕ ōũţƥũţ ţŕĩḿḿēď"],
"_QwkMu": ["Ńō ḿàţćĥĩńĝ ƥàţĥś"],
"_RcqUM": [
"Ŷōũ ƥĩćķēď ŷōũŕ ĥōḿē ďĩŕēćţōŕŷ. ŌƥēńĶńōŵĺēďĝē ŵĩĺĺ ĩńďēx ēvēŕŷţĥĩńĝ ĩń ŷōũŕ ĥōḿē ţŕēē — ĺàŕĝē àńď ḿàŷ śũŕƒàćē ƥēŕśōńàĺ ƒĩĺēś."
@@ -1677,6 +1743,7 @@
"_azghp": ["Ƥŕēvĩōũś ćĥàńĝē"],
"_bth6g": ["Ćĺàũďē Ćōďē ĩś ĩńśţàĺĺēď, ƀũţ ŌƥēńĶńōŵĺēďĝē ţōōĺś àŕēń'ţ ćōńńēćţēď ţō ĩţ ŷēţ."],
"_eguJc": ["Ũƥĺōàďĩńĝ"],
+ "_gO_m8": ["Ŵàĩţĩńĝ ƒōŕ ŷōũŕ àƥƥŕōvàĺ"],
"_gkGSK": ["ďēĺēţēď ţēḿƥĺàţē"],
"_hPpdX": ["Śķĩĺĺ ŕēńàḿēď"],
"_pY_Vq": ["Ţĥē ŕēƥōśĩţōŕŷ ŵàś ḿōvēď, ŕēńàḿēď, ōŕ ďēĺēţēď."],
@@ -1707,6 +1774,9 @@
"aWlJai": ["Śţàŕţĩńĝ śĩĝń-ĩń ƒĺōŵ"],
"a_u4ck": ["Ĺōàďĩńĝ ţàĝś"],
"aaE55D": ["Ćĺēàŕ ", ["keyName"]],
+ "aaI6cN": [
+ "Ćōũĺďń'ţ ćōńńēćţ ţō ţĥē àĝēńţ śēŕvĩćē. Ḿàķē śũŕē ţĥē ŌƥēńĶńōŵĺēďĝē śēŕvēŕ ĩś ŕũńńĩńĝ àńď ũƥ ţō ďàţē (ŕēśţàŕţ ĩţ ĩƒ ĩţ ŵàś àĺŕēàďŷ ŕũńńĩńĝ), ţĥēń ţŕŷ àĝàĩń."
+ ],
"aalx4E": ["Ēďĩţĩńĝ ƀŕōķēń ḾĎX śōũŕćē: ", ["reason"]],
"abiHje": ["Ďēĺēţē śēĺēćţēď ĩţēḿś"],
"adsMWO": ["Ŕēśōĺvĩńĝ ďēĺţàś"],
@@ -1757,6 +1827,7 @@
"c8jBgX": ["Ćĥēćķĩńĝ ƒōŕ ũƥďàţēś ōń ĜĩţĤũƀ"],
"cEoyWz": ["Àďď ĩţēḿ ţō ", ["keyName"]],
"cF9DyA": ["Ŕēćōńńēćţĩńĝ àƒţēŕ śēŕvēŕ ŕēśţàŕţ"],
+ "cFCKYZ": ["Ďēńŷ"],
"cGV6Mh": [
"Śĥōŵ à ƥŕēvĩēŵ ćàŕď ŵĥēń ŷōũ ĥōvēŕ àń ēxţēŕńàĺ ĺĩńķ ĩń ţĥē ēďĩţōŕ. Ţĥĩś śēţţĩńĝ àƥƥĺĩēś ōńĺŷ ţō ţĥĩś ćōḿƥũţēŕ."
],
@@ -1828,6 +1899,7 @@
"dURmlQ": ["\"ƒŕōńţḿàţţēŕ\" ĩś à ŕēśēŕvēď ƥŕōƥēŕţŷ ńàḿē"],
"dVaXnv": ["Ćōńţēńţ ŕũĺēś ńōţ ŷēţ ĺōàďēď — ţŕŷ àĝàĩń ĩń à ḿōḿēńţ"],
"dXWMFn": ["Ŕēḿōvēś ţĥĩś śķĩĺĺ ƒŕōḿ ŷōũŕ ēďĩţōŕś."],
+ "dYCvMf": ["Ćōũĺďń'ţ ŕēśũḿē ţĥĩś ćōńvēŕśàţĩōń: ", ["0"]],
"dbapvC": ["Ƒōĺĺōŵ ũś ōń śōćĩàĺ ḿēďĩà"],
"dbhUX1": ["Ĥĩďē ţĥĩś ƒĩĺē"],
"dbtjJh": ["(ōƥēńś ĩń ńēŵ ţàƀ)"],
@@ -1849,6 +1921,7 @@
"e8L17t": ["À ńōń-ēḿƥţŷ ƒōĺďēŕ àĺŕēàďŷ ēxĩśţś àţ ţĥĩś ƥàţĥ. Ƥĩćķ à ďĩƒƒēŕēńţ ƒōĺďēŕ."],
"e8zRrb": ["Śĥōŵ Ƒĩĺēś"],
"e8zYa8": ["Ćōũĺď ńōţ ōƥēń ", ["shareBranch"], " ĩń à ŵōŕķţŕēē. Ţŕŷ àĝàĩń."],
+ "e9sHSO": ["Ƥĩćķ ũƥ ŵĥēŕē ŷōũ ĺēƒţ ōƒƒ"],
"eBIT9h": ["Ƥàśţē ƒàĩĺēď.", ["restoreSuffix"]],
"eFJkVt": ["Ćĺōńē ƒàĩĺēď: ", ["cloneError"]],
"eG8Jsg": ["Ţōĝĝĺē śōũŕćē ţàƀ ƒōćũś ḿōďē"],
@@ -1873,6 +1946,10 @@
"euc6Ns": ["Ďũƥĺĩćàţē"],
"evs0iw": ["Ţàĝś ḿàţćĥĩńĝ \"", ["tagListQuery"], "\""],
"f1XQyZ": ["Ḿōvē ƀĺōćķ"],
+ "f3Nvg7": [
+ ["0"],
+ " ćàń'ţ ćōńţĩńũē ţĥĩś ćōńvēŕśàţĩōń — ţĥē ţŕàńśćŕĩƥţ ĩś ķēƥţ, ƀũţ ţĥē àĝēńţ śēśśĩōń ĩś ĝōńē."
+ ],
"f65AOQ": ["Śţàŕţ ƒŕōḿ"],
"f8jU-L": [["0"], "/", ["1"], " — ", ["2"]],
"f9lQNJ": ["Àďďś à ḿàńàĝēď ƀĺōćķ ţō"],
@@ -1909,6 +1986,7 @@
"g3UF2V": ["Àććēƥţ"],
"g4WlQK": ["ƤŕōĴēćţ ÀĨ ţōōĺ ḿàńàĝēḿēńţ ĩś ōńĺŷ àvàĩĺàƀĺē ĩń ţĥē ŌƥēńĶńōŵĺēďĝē ďēśķţōƥ àƥƥ."],
"g4XBm0": ["Śḿàĺĺ śēćţĩōń ĥēàďĩńĝ."],
+ "g4e0hS": ["Àśķ ", ["agentName"]],
"g58Kwy": [
"<",
["descriptorLabel"],
@@ -1950,6 +2028,7 @@
"goO4Ll": ["Ēďĩţōŕ śţàţũś ƀàŕ"],
"gp3I7-": ["ßēƒōŕē śŷńćĩńĝ, śēţ ŷōũŕ ĩďēńţĩţŷ ƒōŕ ĝĩţ ćōḿḿĩţś:"],
"gtEbeW": ["Ĥĩĝĥĺĩĝĥţ"],
+ "gtGQ9S": ["Śţàŕţ ", ["agentName"], ", ", ["hint"]],
"gvApb7": [
"Ţũŕń ţĥē ţĥĩńĝś ŷōũ ŕēàď ĩńţō ćĺēàŕ, ţŕũśţēď àŕţĩćĺēś. Śàvē à śōũŕćē, ƒĩĝũŕē ōũţ ŵĥàţ ĩţ ḿēàńś, ţĥēń ķēēƥ ţĥē ƒĩńàĺ vēŕśĩōń śō ŷōũ ćàń ŕēĺŷ ōń ĩţ ĺàţēŕ."
],
@@ -1973,7 +2052,6 @@
"hDoLrm": ["Ŕēḿōvē ", ["projectName"], " ƒŕōḿ ŕēćēńţ ƥŕōĴēćţś"],
"hGmuTc": ["Ďōćś ţàĝĝēď #", ["tagDocsName"]],
"hHMv6l": ["Ďēĺēţē ƀĺōćķ"],
- "hIQkLb": ["Ńēŵ ćĥàţ"],
"hItdtk": ["ßŕōŵśē ƒōĺďēŕ"],
"hLod4_": ["Ćōńvēŕţ ţō ţēḿƥĺàţē"],
"hLy8b1": ["Ũƥďàţēď ţō Vēŕśĩōń ", ["version"]],
@@ -2069,6 +2147,7 @@
"jEdF24": ["Ḿĩśśĩńĝ ƥàĝē: ", ["linkTitle"], ". Ćĺĩćķ ţō ćŕēàţē."],
"jKd3AP": ["Ćōũĺď ńōţ ēńàƀĺē ţĥē ţēŕḿĩńàĺ: ", ["0"]],
"jPUPvG": ["Ćōũĺďń'ţ ŕēśōĺvē ţĥē ćōńƒĺĩćţ ƒōŕ ", ["filePath"], "."],
+ "jRAGrQ": ["Ćōńƒĩĝũŕē àĝēńţś"],
"jRHdCz": ["Ƒàĩĺēď ţō ĺōàď ƤĎƑ"],
"jSO1X5": ["Ĩńĥēŕĩţēď ţēḿƥĺàţēś ćàń'ţ ƀē ŕēńàḿēď ĥēŕē — ŕēńàḿē ĩţ ĩń ţĥē ƒōĺďēŕ ţĥàţ ōŵńś ĩţ."],
"jSY41h": ["\"", ["docName"], "\" ţōōķ ţōō ĺōńĝ. Ćĥēćķ ŷōũŕ ćōńńēćţĩōń."],
@@ -2078,6 +2157,7 @@
"j_Z6g7": ["Śĥàŕēď ďēƒàũĺţ"],
"jbSG8V": ["Śĥōŵ Ƒĩĺēś (", ["sidebarShortcutLabel"], ")"],
"jdGUeI": ["Ćōũĺďń'ţ ćŕēàţē ţēḿƥĺàţē: ", ["error"]],
+ "jeJexw": ["Ćōũĺďń'ţ ƒĩńĩśĥ ĩńśţàĺĺĩńĝ ", ["0"], " — śēē ƀēĺōŵ."],
"jerqF0": ["Ĺōàďĩńĝ ƀŕàńćĥ śţàţē"],
"jhtG3I": [" Ŷōũŕ śēĺēćţĩōń ĥàś ƀēēń ŕēśţōŕēď."],
"jjtmV_": ["Ƒĩŕśţ ƒĩĺē ńàḿē"],
@@ -2097,6 +2177,7 @@
["trimmedSlug"],
"</0> àĺŕēàďŷ ēxĩśţś ĥēŕē. Śàvĩńĝ ćŕēàţēś à ĺōćàĺ ćōƥŷ ţĥàţ ōvēŕŕĩďēś ĩţ ƒōŕ ţĥĩś ƒōĺďēŕ."
],
+ "k0dL2I": ["Ŕēćōńńēćţĩńĝ ţō ţĥē àĝēńţ śēŕvĩćē…"],
"k0vc0N": ["Ńēŵ ţēŕḿĩńàĺ ţàƀ"],
"k2fEi7": [
"Ũśēŕ ƥĺũĝĩńś àŕē ƥēŕśōńàĺ ţō ţĥĩś ďēvĩćē — ţũŕń ţĥēḿ ōń ōŕ ōƒƒ ĥēŕē. Ţĥē ćĥōĩćē ĺĩvēś ĩń ŷōũŕ ũśēŕ ćōńƒĩĝ àńď ĩś ńēvēŕ ćōḿḿĩţţēď ţō ţĥē ƥŕōĴēćţ. Ēàćĥ ēńàƀĺēď ƥĺũĝĩń ĝēţś ĩţś ōŵń ƥàĝē ũńďēŕ Ƥĺũĝĩńś ĩń ţĥē śēţţĩńĝś śĩďēƀàŕ."
@@ -2158,6 +2239,7 @@
"l1aQKz": ["Vĩśũàĺ ēďĩţōŕ ţàƀĺē"],
"l1l8sj": [["0"], "ď àĝō"],
"l3s5ri": ["Ĩḿƥōŕţ"],
+ "l3zD7w": ["Śţàŕţĩńĝ ţĥē àĝēńţ…"],
"l46MqT": ["Ńēxţ ţàƀ"],
"l6OXqI": ["Ńō ĩńśţàĺĺēď àĝēńţś ƒōũńď"],
"l6kpzR": [
@@ -2167,6 +2249,19 @@
["branch"],
"</0>, àńď ţĥàţ ćĥàńĝē ĥàśń'ţ śŷńćēď ŷēţ."
],
+ "l7Qq48": [
+ "Ţĥĩś àĝēńţ ŕũńś ţĥŕōũĝĥ ",
+ ["0"],
+ ", ŵĥĩćĥ ĩśń'ţ ĩńśţàĺĺēď. Ōƥēń Ķńōŵĺēďĝē ćàń ďōŵńĺōàď à ƥŕĩvàţē ćōƥŷ ōƒ ",
+ ["1"],
+ " ",
+ ["2"],
+ " (àƀōũţ ",
+ ["3"],
+ " Ḿß ƒŕōḿ ",
+ ["4"],
+ ") ţĥàţ ŵōń'ţ ţōũćĥ ţĥē ŕēśţ ōƒ ŷōũŕ śŷśţēḿ."
+ ],
"l8G3S9": ["Àũţō-śŷńć ĩś ōƒƒ — ŷōũ ďōń'ţ ĥàvē ƥēŕḿĩśśĩōń ţō ƥũśĥ ţō ţĥĩś ŕēƥō"],
"lAiyU_": ["Ōńĺŷ ţĥē ćũŕŕēńţ ďōćũḿēńţ ũśēś <0>#", ["tag"], "</0>."],
"lCC_D5": ["Śũƀśćŕĩƀĩńĝ..."],
@@ -2175,6 +2270,7 @@
"lHwYMr": ["Śēŕvēŕ ēŕŕōŕ: ", ["status"], " ", ["statusText"]],
"lI0Td2": ["Ũśē ĺēţţēŕś, ďĩĝĩţś, <0>_</0> àńď <1>-</1> ōńĺŷ."],
"lIn9L9": ["Ďĩśàƀĺē śŷńć"],
+ "lKQnp-": ["Ĩńśţàĺĺēď ", ["0"], " ", ["1"]],
"lPzyrU": ["Àĺĺ ĥũńķś ŕēśōĺvēď"],
"lVWEIL": ["Ĩńďēxēď ", ["embedded"], " ōƒ ", ["total"], " ƥàĝēś."],
"lWNpNB": ["Àďď ćũŕśōŕś ōŕ śēĺēćţ ḿàţćĥĩńĝ ōććũŕŕēńćēś ţĥŕōũĝĥ ĆōďēḾĩŕŕōŕ."],
@@ -2212,6 +2308,7 @@
"mPy9lS": [
"Ōŕĝàńĩźē ḿŷ ēxĩśţĩńĝ śƥēćś ĩńţō à ĺĩńķēď ĩńďēx ĝŕōũƥēď ƀŷ àŕēà, àńď ƒĺàĝ àńŷ ţĥàţ ĥàvē ďŕĩƒţēď ōũţ ōƒ śŷńć ŵĩţĥ ţĥē ćũŕŕēńţ ćōďē."
],
+ "mToVM9": ["Ḿēśśàĝē ", ["agentName"]],
"mU3j1b": ["Ŕēḿōvē ĩţēḿ ", ["0"]],
"mVFyH-": [["accessibleLabel"], " (ćōńƒĺĩćţ)"],
"mWVJRX": ["Ćōĺĺàƥśĩƀĺē śēćţĩōń ŵĩţĥ à ćĺĩćķàƀĺē śũḿḿàŕŷ."],
@@ -2299,11 +2396,13 @@
"nh3wwx": ["Ēḿƀēďďĩńĝś ƥŕōvĩďēŕ ķēŷ"],
"njBeMm": ["ßōţĥ"],
"njU86j": ["Ƥŕōƥēŕţŷ \"", ["trimmed"], "\" àĺŕēàďŷ ēxĩśţś"],
+ "nmwqWS": ["Ńōţ àńśŵēŕēď"],
"noH1JX": [
"Ćōũĺďń'ţ ŕēàćĥ ćōĺĺàƀ śēŕvēŕ — ",
["errorDetail"],
". Ţŕŷ <0>ōķ śţàţũś</0> ōŕ ćĥēćķ <1>.ōķ/ĺōćàĺ/ĺàśţ-śƥàŵń-ēŕŕōŕ.ĺōĝ</1>."
],
+ "np9pbC": ["Śĥōŵ ", ["inAppHiddenCount"], " ḿōŕē"],
"npcziF": ["Ĩńśţàĺĺ ōń"],
"nqV0Kk": ["Ţĥĩś ƒōĺďēŕ ĥàśń'ţ śŷńćēď ţō ĜĩţĤũƀ ŷēţ. Ţĥē ĺĩńķ ŵĩĺĺ ŵōŕķ àƒţēŕ ţĥē ńēxţ śŷńć."],
"nrGWJ7": [
@@ -2357,6 +2456,7 @@
],
"ogAuyr": ["ßàćķ ţō ďōćũḿēńţ vĩēŵ"],
"ohUJJM": ["Ƥĺũĝĩńś"],
+ "oi4zaa": ["Ŕēḿēḿƀēŕ ţĥĩś ƒōŕ ƒũţũŕē àĝēńţś"],
"omXJcU": ["Ćĺōśē ōţĥēŕś"],
"onTlRk": ["Ćōũĺďń'ţ ũƥďàţē śķĩĺĺś śĥàŕĩńĝ"],
"optX0N": [["0"], "ĥ àĝō"],
@@ -2365,6 +2465,7 @@
"ot5BRK": ["Ďũƥĺĩćàţē śēĺēćţēď ƒĩĺē ōŕ ƒōĺďēŕ"],
"otE4aj": ["Śĥōŵ ēxţēŕńàĺ ŨŔĹ ńōďēś"],
"ou1hFW": ["Ţōĝĝĺē àń ōŕďēŕēď ĺĩśţ."],
+ "ouTaKR": ["Ďēńĩēď — ", ["0"]],
"outYNy": ["Ďũƥĺĩćàţē ńàḿē \"", ["keyName"], "\""],
"ovIGrT": [
"Ĺōćàĺ ćōĺĺàƀōŕàţĩōń ďàţà ƒōŕ \"",
@@ -2372,6 +2473,7 @@
"\" ćōũĺď ńōţ ƀē ćĺēàŕēď. Ŕēĺōàď ţō ŕēţŕŷ."
],
"p0Iq25": ["Ĩńśēŕţ ĺĩńķ"],
+ "p8TjFD": ["Ćōĺĺàƥśē śēśśĩōń ďōćķ"],
"p9sdCy": ["Ńēŵ ĩĝńōŕē ƥàţţēŕń"],
"pAgkuZ": ["Ŕēōƥēńĩńĝ \"", ["docName"], "\" ŵĩţĥ à ƒŕēśĥ ĺōćàĺ ćōĺĺàƀōŕàţĩōń ćàćĥē."],
"pBROkv": ["Ţĥàńķś ƒōŕ śũƀśćŕĩƀĩńĝ. Ŵàţćĥ ŷōũŕ ĩńƀōx ƒōŕ ƥŕōďũćţ ũƥďàţēś."],
@@ -2380,6 +2482,7 @@
"pHYP6v": ["Ōƥēń <0>Ćũśţōḿĩźē</0> ĩń ţĥē śĩďēƀàŕ <1/> <2>Śķĩĺĺś</2>."],
"pQf2Ux": [".ōķ/śķĩĺĺś ĩś ƀàćķ ţō ĺōćàĺ-ōńĺŷ."],
"pTPqMK": ["Ţōĝĝĺē à ƒēńćēď ćōďē ƀĺōćķ."],
+ "pUKV4K": ["Àũţō-ďēńĩēď"],
"pWT04I": ["Ćĥēćķĩńĝ..."],
"pWbsW6": ["Ĺōàďĩńĝ ďōćś"],
"pZAs1T": ["Ƒàĩĺēď ţō ĺōàď ōũţĝōĩńĝ ĺĩńķś"],
@@ -2440,6 +2543,7 @@
"qvWGzP": ["Ćōĺĺàƥśē àĺĺ"],
"qyLmWw": ["Śōũŕćē ēďĩţōŕ śēàŕćĥ ƥàńēĺ"],
"r-OJYm": ["Ēńţēŕ à vàĺĩď ƀŕàńćĥ ńàḿē (ńō śƥàćēś, ńō ĺēàďĩńĝ ďōţ, ńō \"..\")."],
+ "r2eKE3": ["Śĩĝń ĩń ţō ", ["agentName"], " ƒĩŕśţ"],
"r2huLx": ["Ũńďō, ŕēďō, ōŕ ũńďō śēĺēćţĩōń ćĥàńĝēś ţĥŕōũĝĥ ĆōďēḾĩŕŕōŕ ĥĩśţōŕŷ."],
"r4R7AZ": ["Ńēţŵōŕķ ēŕŕōŕ ďũŕĩńĝ ćĺēàńũƥ"],
"r51jLC": ["Ƒĩĺē śàvēď & Ćĺàũďē Ďēśķţōƥ Àƥƥ ōƥēńēď"],
@@ -2472,7 +2576,6 @@
"rZVMkf": ["Vĩśũàĺ ēďĩţōŕ ŕēƥĺàćē ĩńƥũţ ƒōćũśēď"],
"rageVb": ["Ćũśţōḿ ĤŢḾĹ ŵĩţĥ à ĺĩvē ƥŕēvĩēŵ ƥàńē (śàńďƀōxēď ĩƒŕàḿē)."],
"rdU729": ["Ĺàŷōũţ"],
- "rf6x3F": ["Ďōćķ ţēŕḿĩńàĺ ţō ţĥē ƀōţţōḿ"],
"rfFpcF": ["Ŕēḿōvē ", ["chip"]],
"rgPqOw": ["Ćōńvēŕţ ţĥē ćũŕŕēńţ ƀĺōćķ ţō à ƥàŕàĝŕàƥĥ."],
"riqekz": ["Śũĝĝēśţĩōń ḿēńũ ńàvĩĝàţĩōń"],
@@ -2517,6 +2620,7 @@
"saIASg": ["Śēćōńď ĩţēḿ"],
"saYiIO": ["Ƥàţĥ ćàńńōţ ćōńţàĩń ńũĺĺ ƀŷţēś"],
"seeS6l": ["Śēţũƥ ŌƥēńĶńōŵĺēďĝē ĩń ţĥĩś ƒōĺďēŕ?"],
+ "sgmRY8": ["Śķĩƥƥēď ďōŵńĺōàďĩńĝ ", ["0"], "."],
"shNd9t": ["Śĺàśĥ ćōḿḿàńď ḿēńũ"],
"si3L24": [
"Ōƥēń àń àďďĩţĩōńàĺ ţēŕḿĩńàĺ ţàƀ. Ŵĩţĥ ţēxţ śēĺēćţēď, śţàĝē ĩţ ĩń ţĥē ńēŵ ţàƀ'ś ÀĨ ĩńƥũţ."
@@ -2536,6 +2640,7 @@
"sxTdZI": ["Ĺōàďĩńĝ ƥàţĥś…"],
"sxjyRq": ["Ŵōŕķţŕēēś"],
"sxkWRg": ["Àďvàńćēď"],
+ "syi2ye": [["percent"], "% ũśēď (", ["left"], "% ĺēƒţ)"],
"t-JXbf": ["Ńōţĩōń-śţŷĺē ĩńĺĩńē ŕōŵ ƒōŕ à ďōŵńĺōàďàƀĺē ƒĩĺē. Ďŕàĝ-ďŕōƥ àĺśō ŵōŕķś."],
"t18QYR": ["Ũńƥĩń ", ["accessibleLabel"]],
"t2TkQ3": ["Śŷńć ƥàũśēď — ŕēśōĺvē ćōńƒĺĩćţś ţō ŕēśũḿē."],
@@ -2546,6 +2651,7 @@
"</0> ŵĩĺĺ ƀē ćŕēàţēď ƒŕōḿ ţĥē ćũŕŕēńţ ćōḿḿĩţ, ĩń ĩţś ōŵń ŵōŕķţŕēē ũńďēŕ <1>.ōķ/ŵōŕķţŕēēś/</1>."
],
"t6w1cq": ["Ōƥēń à ƀĺàńķ ēďĩţōŕ ţàƀ."],
+ "t9Qn8y": ["Ńō àĝēńţś ēńàƀĺēď"],
"tAPZEx": ["ßēĺōŵ"],
"tHKQ6j": ["Ŕēńàḿĩńĝ"],
"tP5DDk": ["Àƥƥĺŷ ĺĩńķ"],
@@ -2566,6 +2672,7 @@
"u3BOHd": [["fileCount", "plural", { "one": ["#", " ƒĩĺē"], "other": ["#", " ƒĩĺēś"] }]],
"u3YnKw": ["Ćōũĺď ńōţ ćōńśţŕũćţ śĥàŕē ŨŔĹ."],
"u3wRF-": ["Ƥũƀĺĩśĥēď"],
+ "u5Utjn": [["0"], " ńēēďś ", ["1"]],
"u6Hp4N": ["Ḿàŕķďōŵń"],
"u7H-Wn": ["Śĥōŵ ƥàńēĺ (", ["panelShortcutLabel"], ")"],
"u7U_Ij": ["Ĺĩńķ ţĥē śēĺēćţēď ţēxţ, ōŕ ēďĩţ ţĥē ĺĩńķ ũńďēŕ ţĥē ćàŕēţ."],
@@ -2596,6 +2703,7 @@
"u_lS4C": ["Ćĺōńē ćōḿƥĺēţē — ōƥēńĩńĝ ƥŕōĴēćţ"],
"uaUc6t": ["Ŕēśţàŕţ śēŕvēŕ"],
"ubMwcO": ["Ţĥē ţēŕḿĩńàĺ śēśśĩōń ēńďēď (śĩĝńàĺ ", ["0"], ")."],
+ "ucXZ0k": ["Ĺōàďĩńĝ àĝēńţś…"],
"ugoTXs": ["ƒōĺďēŕ"],
"uhJEA2": [
[
@@ -2630,6 +2738,7 @@
"vGeNNQ": ["Ćōƥŷ à ƥŕōḿƥţ àńď ƥàśţē ĩţ ĩńţō ŷōũŕ àĝēńţ ţō śēţ ũƥ ŷōũŕ ƥŕōĴēćţ."],
"vIxrEk": ["Ƒĩţ ŵĩďţĥ"],
"vLyv1R": ["Ĥĩďē"],
+ "vPKX2i": ["Ĩń àƥƥ (ƀēţà)"],
"vQIVHc": ["Ƒōĺďēŕ ƥŕōƥēŕţĩēś"],
"vWc9a0": ["Ţŷƥē ţō ēďĩţ; <0>⌘ Ēńţēŕ</0> śàvēś, <1>Ēść</1> ćàńćēĺś."],
"vZVeFG": ["Ũƥĺōàď ƒàĩĺēď — ƥĺēàśē ţŕŷ àĝàĩń"],
@@ -2639,6 +2748,7 @@
"vfWA_g": ["Ŷōũ ƥĩćķēď ~/Ďēśķţōƥ. ŌƥēńĶńōŵĺēďĝē ŵĩĺĺ ĩńďēx ēvēŕŷţĥĩńĝ ōń ŷōũŕ ďēśķţōƥ."],
"vhAnzJ": ["Ţũŕń ōń śēḿàńţĩć śēàŕćĥ?"],
"viwC-K": ["Ƒàĩĺēď ţō ŕēḿōvē ƥŕōĴēćţ."],
+ "vja0Dg": ["Ōƥēń śēśśĩōń ďōćķ"],
"vppAju": ["Ŵĥēŕē ńēŵĺŷ àďďēď àţţàćĥḿēńţś àŕē ƥĺàćēď."],
"vv7kpg": ["Ćàńćēĺĺēď"],
"vvWZnu": ["Ďĩƒƒ ũńàvàĩĺàƀĺē"],
@@ -2648,6 +2758,7 @@
"Ćōũĺď ńōţ ŕēàď ƀŕàńćĥ śţàţē ƒōŕ ţĥĩś ƥŕōĴēćţ. Ćĺōśē ţĥĩś ďĩàĺōĝ àńď ōƥēń ţĥē śĥàŕē ĺĩńķ àĝàĩń."
],
"w6sBjd": ["Ţēŕḿĩńàĺ śēţţĩńĝś ńōţ ŷēţ ĺōàďēď — ţŕŷ àĝàĩń ĩń à ḿōḿēńţ"],
+ "w6sT-y": ["Ƒōĺĺōŵ ţĥē àĝēńţ'ś ēďĩţś"],
"w7SsvI": ["Ţĥàţ ƒōĺďēŕ ĩśń'ţ àń ŌƥēńĶńōŵĺēďĝē ƥŕōĴēćţ ŷēţ. Ĩńĩţĩàĺĩźē ĩţ àńď ōƥēń?"],
"w7nm4K": ["Ĩńďēńţēď ƀĺōćķǫũōţē ƒōŕ ćĩţàţĩōńś."],
"wDgmsr": ["\"", ["0"], "\" ĩńśţàĺĺ ŕēƒŕēśĥēď (", ["1"], ")"],
@@ -2722,6 +2833,7 @@
"xnP32l": ["Ńō ďēśćŕĩƥţĩōń ŷēţ — àďď ōńē śō àĝēńţś ķńōŵ ŵĥēń ţō ũśē ţĥĩś śķĩĺĺ."],
"xrVr_k": ["Ćōũĺďń'ţ ćŕēàţē śķĩĺĺ: ", ["0"]],
"xsZhu-": ["Ƥàĝē ńũḿƀēŕ"],
+ "xzAmL_": ["Àũţō-àƥƥŕōvēď"],
"xzktOa": ["Ēďĩţ ŵĩķĩ ĺĩńķ"],
"y1t8bQ": ["Śēţţĩńĝś śēćţĩōńś"],
"y3aU20": ["Śàvē ćĥàńĝēś"],
@@ -2768,6 +2880,7 @@
["typeLabel"],
" (ĩńĥēŕĩţēď ƒŕōḿ ƒōĺďēŕ ƥŕōƥēŕţĩēś; ńōţ ēďĩţàƀĺē ĥēŕē)"
],
+ "ygCKqB": ["Śţōƥ"],
"yhdqox": [
"Ĩńśţàĺĺēď — ōķ ĩś àvàĩĺàƀĺē ĩń ēxţēŕńàĺ ţēŕḿĩńàĺś. Ũńćĥēćķĩńĝ ŕēḿōvēś ĩţ; ŌƥēńĶńōŵĺēďĝē'ś ƀũĩĺţ-ĩń ţēŕḿĩńàĺ àńď ÀĨ ţōōĺś ķēēƥ ŵōŕķĩńĝ."
],
diff --git a/packages/app/src/locales/pseudo/messages.po b/packages/app/src/locales/pseudo/messages.po
index 028278dfc..050f02889 100644
--- a/packages/app/src/locales/pseudo/messages.po
+++ b/packages/app/src/locales/pseudo/messages.po
@@ -25,6 +25,10 @@ msgstr ""
msgid " Your selection has been restored."
msgstr ""
+#: src/components/acp/ThreadView.tsx
+msgid "… earlier output trimmed"
+msgstr ""
+
#: src/components/FileSidebar.tsx
msgid ".ok folders"
msgstr ""
@@ -200,11 +204,27 @@ msgstr ""
msgid "{0} added, {1} removed"
msgstr ""
+#. placeholder {0}: info.agent.name
+#: src/components/acp/ThreadView.tsx
+msgid "{0} can't continue this conversation — the transcript is kept, but the agent session is gone."
+msgstr ""
+
#. placeholder {0}: labels[key]
#: src/components/settings/CustomThemeEditor.tsx
msgid "{0} hex value"
msgstr ""
+#. placeholder {0}: resolvedTarget.displayName
+#: src/components/BottomComposer.tsx
+msgid "{0} isn't installed yet — opening its download page."
+msgstr ""
+
+#. placeholder {0}: item.agentName
+#. placeholder {1}: item.displayName
+#: src/components/acp/ThreadView.tsx
+msgid "{0} needs {1}"
+msgstr ""
+
#. placeholder {0}: templates.length
#: src/components/empty-state/CreateView.tsx
msgid "{0} templates available"
@@ -329,6 +349,10 @@ msgstr ""
msgid "{days, plural, one {# day ago} other {# days ago}}"
msgstr ""
+#: src/components/acp/ThreadHistoryMenu.tsx
+msgid "{days}d ago"
+msgstr ""
+
#: src/components/FileTree.tsx
msgid "{deleteCount, plural, one {Delete} other {Delete # items}}"
msgstr ""
@@ -362,6 +386,7 @@ msgstr ""
#: src/components/handoff/OpenInAgentContextSubmenu.tsx
#: src/components/handoff/OpenInAgentEmptySpaceSubmenu.tsx
#: src/components/handoff/OpenInAgentMenu.tsx
+#: src/components/settings/ConfigureAgentsSection.tsx
msgid "{displayName} CLI"
msgstr ""
@@ -401,6 +426,7 @@ msgstr ""
msgid "{formatted} GitHub stars"
msgstr ""
+#: src/components/acp/ThreadHistoryMenu.tsx
#: src/components/ActivityModeContent.tsx
#: src/components/ActivityPanelFileRow.tsx
#: src/components/SyncStatusBadge.tsx
@@ -458,6 +484,7 @@ msgstr ""
msgid "{minutes} min ago"
msgstr ""
+#: src/components/acp/ThreadHistoryMenu.tsx
#: src/components/ActivityModeContent.tsx
#: src/components/ActivityPanelBurstRow.tsx
#: src/components/ActivityPanelFileRow.tsx
@@ -492,6 +519,10 @@ msgstr ""
msgid "{packName} was already set up. Nothing to do."
msgstr ""
+#: src/components/acp/ThreadView.tsx
+msgid "{percent}% used ({left}% left)"
+msgstr ""
+
#: src/lib/share/clone-controller.ts
msgid "{phase} — {pct}%"
msgstr ""
@@ -550,6 +581,10 @@ msgstr ""
msgid "{uploadedCount, plural, one {Uploaded one file} other {Uploaded {uploadedCount} files}}"
msgstr ""
+#: src/components/acp/ThreadView.tsx
+msgid "{usedLabel} / {sizeLabel} tokens used"
+msgstr ""
+
#: src/presence/PresenceBar.tsx
msgid "{userName} · {tabCount, plural, one {# tab} other {# tabs}}"
msgstr ""
@@ -619,6 +654,11 @@ msgstr ""
msgid "<0>ok</0> won't run in external terminals until you add it later from the File menu. OpenKnowledge's built-in terminal and AI tools keep working."
msgstr ""
+#. placeholder {0}: row.count
+#: src/components/acp/ThreadView.tsx
+msgid "⋯ {0} unchanged lines"
+msgstr ""
+
#: src/components/PageHeaderWidgets.tsx
msgid "📝 or assets/icon.png"
msgstr ""
@@ -920,6 +960,7 @@ msgstr ""
msgid "Advanced settings"
msgstr ""
+#: src/components/TerminalSessionsHost.tsx
#: src/presence/PresenceBar.tsx
msgid "Agent"
msgstr ""
@@ -932,6 +973,14 @@ msgstr ""
msgid "Agent configuration file"
msgstr ""
+#: src/components/acp/ThreadView.tsx
+msgid "Agent mode"
+msgstr ""
+
+#: src/components/acp/ThreadView.tsx
+msgid "Agent settings"
+msgstr ""
+
#. Group label above the skill rows in Settings → AI tools & CLI
#. Section label above the skill checkboxes in the first-launch dialog
#: src/components/McpConsentDialogBody.tsx
@@ -1042,6 +1091,19 @@ msgstr ""
msgid "Applying your change"
msgstr ""
+#: src/components/acp/ThreadView.tsx
+msgid "Approved"
+msgstr ""
+
+#. placeholder {0}: outcome.optionName
+#: src/components/acp/ThreadView.tsx
+msgid "Approved — {0}"
+msgstr ""
+
+#: src/components/acp/ThreadView.tsx
+msgid "Archived"
+msgstr ""
+
#: src/components/FileTree.tsx
msgid "Are you sure you want to convert this file into a template? The original file will be deleted. This action cannot be undone."
msgstr ""
@@ -1072,6 +1134,10 @@ msgstr ""
msgid "Ask {0} CLI"
msgstr ""
+#: src/components/acp/ThreadView.tsx
+msgid "Ask {agentName}"
+msgstr ""
+
#: src/components/BottomComposer.tsx
#: src/components/EditorFooter.tsx
#: src/components/OnboardingCard.tsx
@@ -1130,6 +1196,14 @@ msgstr ""
msgid "Auto-approve settings not yet loaded — try again in a moment"
msgstr ""
+#: src/components/acp/ThreadView.tsx
+msgid "Auto-approved"
+msgstr ""
+
+#: src/components/acp/ThreadView.tsx
+msgid "Auto-denied"
+msgstr ""
+
#: src/components/FolderTimelineCard.tsx
#: src/components/TimelinePanel.tsx
msgid "Auto-save"
@@ -1217,6 +1291,10 @@ msgstr ""
msgid "Below"
msgstr ""
+#: src/components/acp/AgentBetaBadge.tsx
+msgid "Beta"
+msgstr ""
+
#: src/components/BetaBadge.tsx
msgid "BETA"
msgstr ""
@@ -1380,6 +1458,7 @@ msgstr ""
msgid "Can't safely edit this tool's config"
msgstr ""
+#: src/components/acp/ThreadHistoryMenu.tsx
#: src/components/ActivityPanelBurstRow.tsx
#: src/components/AuthModal.tsx
#: src/components/CloneDialog.tsx
@@ -1441,9 +1520,10 @@ msgid "Checkbox"
msgstr ""
#: src/components/BottomComposer.tsx
+msgid "Checking for agents"
+msgstr ""
+
#: src/components/handoff/EditWithAiPopover.tsx
-#: src/components/handoff/OpenInAgentContextSubmenu.tsx
-#: src/components/handoff/OpenInAgentMenu.tsx
msgid "Checking for installed agents"
msgstr ""
@@ -1482,13 +1562,17 @@ msgid "Choose agent"
msgstr ""
#: src/components/TerminalNewChatButton.tsx
-msgid "Choose CLI for new chat"
+msgid "Choose what a new session starts"
msgstr ""
#: src/components/settings/SharingSection.tsx
msgid "Choose whether this project's OpenKnowledge setup, including its AI-tool connections, is saved with the project so teammates get it too, or kept only on your computer."
msgstr ""
+#: src/components/settings/ConfigureAgentsSection.tsx
+msgid "Choose which agents appear in the agent selector. Turn one off to hide it everywhere."
+msgstr ""
+
#: src/components/settings/SkillTargetsPicker.tsx
msgid "Choose which editors every skill in this project installs into."
msgstr ""
@@ -1711,7 +1795,7 @@ msgid "Collapse graph"
msgstr ""
#: src/components/TerminalTabStrip.tsx
-msgid "Collapse terminal"
+msgid "Collapse session dock"
msgstr ""
#: src/editor/slash-command/component-items.tsx
@@ -1808,6 +1892,17 @@ msgstr ""
msgid "Configuration warnings"
msgstr ""
+#: src/components/empty-state/CreatePromptComposer.tsx
+#: src/components/handoff/AgentSplitButton.tsx
+#: src/components/handoff/OpenInAgentContextSubmenu.tsx
+#: src/components/handoff/OpenInAgentEmptySpaceSubmenu.tsx
+#: src/components/handoff/OpenInAgentMenu.tsx
+#: src/components/settings/ConfigureAgentsSection.tsx
+#: src/components/settings/SettingsDialogShell.tsx
+#: src/components/TerminalNewChatButton.tsx
+msgid "Configure agents"
+msgstr ""
+
#: src/components/settings/SettingsDialogShell.tsx
msgid "Configure user, project, and integration settings."
msgstr ""
@@ -1892,6 +1987,10 @@ msgstr ""
msgid "Connecting — waiting for collab server"
msgstr ""
+#: src/components/acp/ThreadView.tsx
+msgid "Connecting to {agentName}…"
+msgstr ""
+
#: src/components/DocumentErrorBoundary.tsx
msgid "Connection dropped"
msgstr ""
@@ -1925,6 +2024,14 @@ msgstr ""
msgid "Content rules not yet loaded — try again in a moment"
msgstr ""
+#: src/components/acp/ThreadView.tsx
+msgid "Context window:"
+msgstr ""
+
+#: src/components/acp/ThreadView.tsx
+msgid "Context window: {percent}% used, {usedLabel} of {sizeLabel} tokens"
+msgstr ""
+
#: src/components/FileTree.tsx
msgid "Convert"
msgstr ""
@@ -2185,6 +2292,10 @@ msgstr ""
msgid "Couldn't connect OpenKnowledge tools to Claude Code. Please try again."
msgstr ""
+#: src/lib/acp/launch-agent-thread.ts
+msgid "Couldn't connect to the agent service. Make sure the OpenKnowledge server is running and up to date (restart it if it was already running), then try again."
+msgstr ""
+
#: src/components/PublishToGitHubDialog.tsx
msgid "Couldn't construct the share URL. Try Done and re-share."
msgstr ""
@@ -2236,6 +2347,11 @@ msgstr ""
msgid "Couldn't duplicate \"{0}\": {1}"
msgstr ""
+#. placeholder {0}: item.displayName
+#: src/components/acp/ThreadView.tsx
+msgid "Couldn't finish installing {0} — see below."
+msgstr ""
+
#. placeholder {0}: result.error
#: src/components/skill-actions.tsx
msgid "Couldn't install skill: {0}"
@@ -2306,6 +2422,10 @@ msgstr ""
msgid "Couldn't reach GitHub. Try again?"
msgstr ""
+#: src/components/settings/ConfigureAgentsSection.tsx
+msgid "Couldn't reach the agent registry."
+msgstr ""
+
#: src/components/CommandPalette.tsx
msgid "Couldn't reach the embeddings provider — press ↵ to retry"
msgstr ""
@@ -2354,6 +2474,11 @@ msgstr ""
msgid "Couldn't restart the server. Try `ok start` in this folder."
msgstr ""
+#. placeholder {0}: resumeError.message
+#: src/components/acp/ThreadView.tsx
+msgid "Couldn't resume this conversation: {0}"
+msgstr ""
+
#: src/components/TemplateForm.tsx
msgid "Couldn't save template: {error}"
msgstr ""
@@ -2390,6 +2515,10 @@ msgstr ""
msgid "Couldn't share skills: internal error. Please restart the app."
msgstr ""
+#: src/lib/acp/launch-agent-thread.ts
+msgid "Couldn't start the agent thread — please try again."
+msgstr ""
+
#. placeholder {0}: result.error
#: src/components/skill-actions.tsx
msgid "Couldn't uninstall skill: {0}"
@@ -2615,6 +2744,7 @@ msgstr ""
msgid "Default: <0>{0}</0>"
msgstr ""
+#: src/components/acp/ThreadHistoryMenu.tsx
#: src/components/DeleteConfirmationDialog.tsx
#: src/components/skill-actions.tsx
#: src/components/TemplateRow.tsx
@@ -2622,6 +2752,11 @@ msgstr ""
msgid "Delete"
msgstr ""
+#. placeholder {0}: thread.title
+#: src/components/acp/ThreadHistoryMenu.tsx
+msgid "Delete {0}"
+msgstr ""
+
#: src/editor/extensions/JsxComponentView.tsx
msgid "Delete {deleteDescriptorLabel}"
msgstr ""
@@ -2670,6 +2805,10 @@ msgstr ""
msgid "Delete selected table"
msgstr ""
+#: src/components/acp/ThreadHistoryMenu.tsx
+msgid "Delete this conversation?"
+msgstr ""
+
#: src/components/FolderTimelineCard.tsx
msgid "deleted template"
msgstr ""
@@ -2679,6 +2818,19 @@ msgstr ""
msgid "Deleting"
msgstr ""
+#: src/components/acp/ThreadView.tsx
+msgid "Denied"
+msgstr ""
+
+#. placeholder {0}: outcome.optionName
+#: src/components/acp/ThreadView.tsx
+msgid "Denied — {0}"
+msgstr ""
+
+#: src/components/acp/ThreadView.tsx
+msgid "Deny"
+msgstr ""
+
#: src/components/empty-state/CreatePromptComposer.tsx
msgid "Describe the project you want to create"
msgstr ""
@@ -2713,6 +2865,7 @@ msgstr ""
#: src/components/handoff/OpenInAgentContextSubmenu.tsx
#: src/components/handoff/OpenInAgentEmptySpaceSubmenu.tsx
#: src/components/handoff/OpenInAgentMenu.tsx
+#: src/components/settings/ConfigureAgentsSection.tsx
msgid "Desktop"
msgstr ""
@@ -2840,11 +2993,11 @@ msgid "Doc mention suggestions"
msgstr ""
#: src/components/TerminalTabStrip.tsx
-msgid "Dock terminal to the bottom"
+msgid "Dock sessions at the bottom"
msgstr ""
#: src/components/TerminalTabStrip.tsx
-msgid "Dock terminal to the right"
+msgid "Dock sessions on the right"
msgstr ""
#: src/components/HelpPopover.tsx
@@ -2902,6 +3055,10 @@ msgstr ""
msgid "Don't see <0>Skills</0>? Enable <1>Settings <2/> Capabilities <3/> Code execution and file creation</1> first."
msgstr ""
+#: src/components/acp/ThreadView.tsx
+msgid "done"
+msgstr ""
+
#: src/components/InstallInClaudeDesktopDialog.tsx
#: src/components/PublishToGitHubDialog.tsx
#: src/components/ReportBugDialogBody.tsx
@@ -2911,6 +3068,11 @@ msgstr ""
msgid "Done"
msgstr ""
+#. placeholder {0}: item.displayName
+#: src/components/acp/ThreadView.tsx
+msgid "Download {0}"
+msgstr ""
+
#: src/editor/bubble-menu/FileBubbleButtons.tsx
msgid "Download file"
msgstr ""
@@ -2919,6 +3081,12 @@ msgstr ""
msgid "Download started"
msgstr ""
+#. placeholder {0}: item.displayName
+#. placeholder {1}: item.version
+#: src/components/acp/ThreadView.tsx
+msgid "Downloading {0} {1}…"
+msgstr ""
+
#: src/components/ShareReceiveDialog.tsx
msgid "Downloads a fresh copy from GitHub."
msgstr ""
@@ -3142,13 +3310,19 @@ msgstr ""
msgid "Empty starting content"
msgstr ""
+#. placeholder {0}: agent.name
#. placeholder {0}: plugin.label
#. placeholder {0}: rule.name
+#: src/components/settings/ConfigureAgentsSection.tsx
#: src/components/settings/LintingSection.tsx
#: src/components/settings/markdownlint-rule-browser.tsx
msgid "Enable {0}"
msgstr ""
+#: src/components/settings/ConfigureAgentsSection.tsx
+msgid "Enable {displayName} CLI"
+msgstr ""
+
#: src/components/AutoSyncOnboardingDialog.tsx
#: src/components/EnableSyncConfirmDialog.tsx
#: src/components/share-receive-miss-content.tsx
@@ -3241,6 +3415,11 @@ msgstr ""
msgid "Existing branch <0>{trimmed}</0> will be checked out into its own window, under <1>.ok/worktrees/</1>."
msgstr ""
+#. placeholder {0}: exit.exitCode ?? 0
+#: src/components/acp/ThreadView.tsx
+msgid "exit {0}"
+msgstr ""
+
#: src/components/DiffView.tsx
msgid "Exit merge"
msgstr ""
@@ -3292,6 +3471,10 @@ msgstr ""
msgid "External wiki link"
msgstr ""
+#: src/components/acp/ThreadView.tsx
+msgid "failed"
+msgstr ""
+
#: src/components/ArrayOfObjectsWidget.tsx
msgid "Failed to add item"
msgstr ""
@@ -3761,6 +3944,10 @@ msgstr ""
msgid "Folders"
msgstr ""
+#: src/components/acp/ThreadView.tsx
+msgid "Follow the agent's edits"
+msgstr ""
+
#: src/components/SubscribeCard.tsx
msgid "Follow us on"
msgstr ""
@@ -3773,10 +3960,18 @@ msgstr ""
msgid "Follow us on X"
msgstr ""
+#: src/components/acp/ThreadView.tsx
+msgid "Following the agent's edits"
+msgstr ""
+
#: src/editor/slash-command/items.tsx
msgid "Footnote"
msgstr ""
+#: src/components/acp/ThreadView.tsx
+msgid "Force stop"
+msgstr ""
+
#: src/components/LinksPanel.tsx
msgid "Forward-links response did not match expected shape."
msgstr ""
@@ -4168,6 +4363,24 @@ msgstr ""
msgid "In a subfolder"
msgstr ""
+#: src/components/empty-state/CreatePromptComposer.tsx
+#: src/components/handoff/AgentSplitButton.tsx
+#: src/components/handoff/OpenInAgentContextSubmenu.tsx
+#: src/components/handoff/OpenInAgentEmptySpaceSubmenu.tsx
+#: src/components/handoff/OpenInAgentMenu.tsx
+#: src/components/settings/ConfigureAgentsSection.tsx
+#: src/components/TerminalNewChatButton.tsx
+msgid "In app"
+msgstr ""
+
+#: src/components/empty-state/CreatePromptComposer.tsx
+#: src/components/handoff/AgentSplitButton.tsx
+#: src/components/handoff/OpenInAgentContextSubmenu.tsx
+#: src/components/handoff/OpenInAgentEmptySpaceSubmenu.tsx
+#: src/components/TerminalNewChatButton.tsx
+msgid "In app (beta)"
+msgstr ""
+
#: src/components/InstallInClaudeDesktopDialog.tsx
msgid "In the Claude Desktop App"
msgstr ""
@@ -4269,6 +4482,10 @@ msgstr ""
msgid "Inline Math Properties"
msgstr ""
+#: src/components/acp/ThreadView.tsx
+msgid "Input"
+msgstr ""
+
#: src/editor/slash-command/items.tsx
msgid "Insert a footnote reference + matching definition stub."
msgstr ""
@@ -4296,10 +4513,6 @@ msgstr ""
msgid "Install {brand} →"
msgstr ""
-#: src/components/empty-state/CreatePromptComposer.tsx
-msgid "Install an AI agent to create with AI"
-msgstr ""
-
#. Dialog title — installing the OpenKnowledge skill into the Claude Desktop App
#: src/components/InstallInClaudeDesktopDialog.tsx
msgid "Install for Claude Chat & Cowork"
@@ -4347,6 +4560,12 @@ msgstr ""
msgid "Installed \"{0}\" into {1}"
msgstr ""
+#. placeholder {0}: item.displayName
+#. placeholder {1}: item.version
+#: src/components/acp/ThreadView.tsx
+msgid "Installed {0} {1}"
+msgstr ""
+
#: src/components/SkillRow.tsx
msgid "Installed into"
msgstr ""
@@ -4355,6 +4574,10 @@ msgstr ""
msgid "Installing"
msgstr ""
+#: src/components/acp/ThreadView.tsx
+msgid "Installing {agentName}…"
+msgstr ""
+
#: src/components/handoff/EditWithAiPopover.tsx
#: src/components/handoff/OpenInAgentMenu.tsx
msgid "Instruction for the AI"
@@ -4398,6 +4621,7 @@ msgstr ""
msgid "Jump to tab 1-8"
msgstr ""
+#: src/components/acp/ThreadHistoryMenu.tsx
#: src/components/FolderOverview.tsx
#: src/components/FolderTimelineCard.tsx
#: src/components/SyncStatusBadge.tsx
@@ -4562,6 +4786,10 @@ msgstr ""
msgid "Loading agent activity"
msgstr ""
+#: src/components/settings/ConfigureAgentsSection.tsx
+msgid "Loading agents…"
+msgstr ""
+
#: src/components/ShareBranchSwitchDialog.tsx
msgid "Loading branch state"
msgstr ""
@@ -4647,6 +4875,10 @@ msgstr ""
msgid "Loading templates"
msgstr ""
+#: src/components/acp/ThreadView.tsx
+msgid "Loading the conversation"
+msgstr ""
+
#: src/components/TimelinePanel.tsx
msgid "Loading timeline history"
msgstr ""
@@ -4753,6 +4985,10 @@ msgstr ""
msgid "Match case"
msgstr ""
+#: src/components/TerminalNewChatButton.tsx
+msgid "Maximum agents already running"
+msgstr ""
+
#. Group label above the per-editor MCP list in Settings → AI tools & CLI — each row wires OpenKnowledge's MCP server into that tool
#. Group label above the per-editor project MCP list in Settings → This project → AI tools
#. Section label above the editor checkbox list in the first-launch dialog — each row wires OpenKnowledge's MCP server into that tool
@@ -4778,6 +5014,15 @@ msgstr ""
msgid "Mermaid diagram failed to render."
msgstr ""
+#: src/components/acp/ThreadView.tsx
+msgid "Message {agentName}"
+msgstr ""
+
+#. placeholder {0}: frame.message
+#: src/lib/acp/thread-client.ts
+msgid "Message not sent: {0}"
+msgstr ""
+
#: src/editor/components/Mirror.tsx
msgid "Mirror loading <0>{mirrorRef}</0>"
msgstr ""
@@ -4999,7 +5244,8 @@ msgstr ""
msgid "New"
msgstr ""
-#. placeholder {0}: TERMINAL_CLIS[selected].displayName
+#. placeholder {0}: TERMINAL_CLIS[selected.cli].displayName
+#. placeholder {0}: selected.agent.name
#: src/components/TerminalNewChatButton.tsx
msgid "New {0} chat"
msgstr ""
@@ -5012,10 +5258,6 @@ msgstr ""
msgid "New branch <0>{trimmed}</0> will be created from the current commit, in its own worktree under <1>.ok/worktrees/</1>."
msgstr ""
-#: src/components/TerminalNewChatButton.tsx
-msgid "New chat"
-msgstr ""
-
#: src/components/command-palette-commands.ts
#: src/components/FileSidebar.tsx
#: src/components/FileTree.tsx
@@ -5088,6 +5330,11 @@ msgstr ""
msgid "New terminal tab"
msgstr ""
+#. placeholder {0}: info.agent.name
+#: src/components/acp/ThreadView.tsx
+msgid "New thread with {0}"
+msgstr ""
+
#: src/components/command-palette-commands.ts
#: src/components/NewWorktreeDialog.tsx
#: src/components/ProjectSwitcher.tsx
@@ -5114,6 +5361,18 @@ msgstr ""
msgid "No <0>.markdownlint.*</0> file yet — every rule runs on the same defaults as the VS Code markdownlint extension: all on, except line length."
msgstr ""
+#: src/components/settings/ConfigureAgentsSection.tsx
+msgid "No agents available."
+msgstr ""
+
+#: src/components/BottomComposer.tsx
+msgid "No agents enabled"
+msgstr ""
+
+#: src/components/settings/ConfigureAgentsSection.tsx
+msgid "No agents match your search."
+msgstr ""
+
#: src/components/FileSidebar.tsx
msgid "No AI agents installed"
msgstr ""
@@ -5211,10 +5470,7 @@ msgstr ""
msgid "No Incoming"
msgstr ""
-#: src/components/BottomComposer.tsx
#: src/components/handoff/EditWithAiPopover.tsx
-#: src/components/handoff/OpenInAgentContextSubmenu.tsx
-#: src/components/handoff/OpenInAgentMenu.tsx
msgid "No installed agents found"
msgstr ""
@@ -5262,6 +5518,10 @@ msgstr ""
msgid "No matching worktrees or branches."
msgstr ""
+#: src/components/acp/ThreadHistoryMenu.tsx
+msgid "No open conversations. Reopen a past one, or start a session with the + button."
+msgstr ""
+
#: src/components/GraphPanel.tsx
msgid "No Outgoing"
msgstr ""
@@ -5382,6 +5642,14 @@ msgstr ""
msgid "None"
msgstr ""
+#: src/components/acp/ThreadView.tsx
+msgid "Not answered"
+msgstr ""
+
+#: src/components/settings/ConfigureAgentsSection.tsx
+msgid "Not available on this platform"
+msgstr ""
+
#: src/components/settings/AccountSection.tsx
msgid "Not connected"
msgstr ""
@@ -5396,9 +5664,11 @@ msgstr ""
#: src/components/CommandPalette.tsx
#: src/components/handoff/OpenInAgentMenuItem.tsx
+#: src/components/settings/ConfigureAgentsSection.tsx
msgid "Not installed"
msgstr ""
+#: src/components/acp/ThreadView.tsx
#: src/components/ReportBugDialogBody.tsx
#: src/components/SkillsSidebarSection.tsx
#: src/lib/install-server-drift-listener.ts
@@ -5701,6 +5971,10 @@ msgstr ""
msgid "Open recent project"
msgstr ""
+#: src/components/TerminalRevealTab.tsx
+msgid "Open session dock"
+msgstr ""
+
#: src/components/ShareBranchSwitchDialog.tsx
#: src/components/ShareReceiveDialog.tsx
msgid "Open shared {targetNoun}"
@@ -6030,6 +6304,10 @@ msgstr ""
msgid "Pattern warnings: {summary}"
msgstr ""
+#: src/components/acp/ThreadView.tsx
+msgid "pending"
+msgstr ""
+
#: src/components/CreateProjectDialog.tsx
msgid "Permanently deletes <0>{targetGitPath}</0> and all its git history. Working files stay in place. If the parent git repo is intentional (e.g. you cloned it), cancel and pick a location outside it."
msgstr ""
@@ -6070,6 +6348,10 @@ msgstr ""
msgid "Pick the folder where you've cloned it."
msgstr ""
+#: src/components/acp/ThreadView.tsx
+msgid "Pick up where you left off"
+msgstr ""
+
#: src/components/EditorTabs.tsx
msgid "Pin tab"
msgstr ""
@@ -6078,6 +6360,11 @@ msgstr ""
msgid "Plain"
msgstr ""
+#. placeholder {0}: plan.length
+#: src/components/acp/ThreadView.tsx
+msgid "Plan ({done}/{0})"
+msgstr ""
+
#: src/components/SubscribeForm.tsx
msgid "Please enter a valid email address."
msgstr ""
@@ -6359,6 +6646,10 @@ msgstr ""
msgid "Reconnecting after server restart"
msgstr ""
+#: src/components/TerminalSessionsHost.tsx
+msgid "Reconnecting to the agent service…"
+msgstr ""
+
#: src/components/FileTree.tsx
msgid "Reconnecting…"
msgstr ""
@@ -6408,6 +6699,10 @@ msgstr ""
msgid "Reload"
msgstr ""
+#: src/components/acp/ThreadView.tsx
+msgid "Remember this for future agents"
+msgstr ""
+
#: src/components/NewWorktreeDialog.tsx
msgid "remote"
msgstr ""
@@ -6723,6 +7018,10 @@ msgstr ""
msgid "Restore failed — document unchanged"
msgstr ""
+#: src/components/acp/ThreadHistoryMenu.tsx
+msgid "Restore sessions"
+msgstr ""
+
#: src/components/ActivityPanelBurstRow.tsx
msgid "Restore to edit {burstNumber} of {docName}"
msgstr ""
@@ -6758,9 +7057,14 @@ msgstr ""
msgid "Results capped — this workspace has more files than search can index. A missing file may be a cap artifact, not a typo."
msgstr ""
+#: src/components/acp/ThreadView.tsx
+msgid "Resuming the conversation"
+msgstr ""
+
#: src/components/ActivityModeContent.tsx
#: src/components/ConnectingBanner.tsx
#: src/components/PublishToGitHubDialog.tsx
+#: src/components/settings/ConfigureAgentsSection.tsx
#: src/components/SyncStatusBadge.tsx
#: src/components/TrashFailureModal.tsx
msgid "Retry"
@@ -6838,6 +7142,10 @@ msgstr ""
msgid "Run this in your terminal"
msgstr ""
+#: src/components/acp/ThreadView.tsx
+msgid "running"
+msgstr ""
+
#: src/components/ProblemsPanel.tsx
msgid "Running project audit"
msgstr ""
@@ -6920,6 +7228,10 @@ msgstr ""
msgid "Search ({searchShortcut})"
msgstr ""
+#: src/components/settings/ConfigureAgentsSection.tsx
+msgid "Search agents"
+msgstr ""
+
#: src/components/NewWorktreeDialog.tsx
msgid "Search branches"
msgstr ""
@@ -7093,6 +7405,10 @@ msgstr ""
msgid "Semantic search is on, but no API key is set — search falls back to keyword matching. Add one in <0>Settings → Account</0> (it's stored once for your whole machine)."
msgstr ""
+#: src/components/acp/ThreadView.tsx
+msgid "Send"
+msgstr ""
+
#: src/components/ReportBugDialogBody.tsx
msgid "Send report"
msgstr ""
@@ -7146,6 +7462,10 @@ msgstr ""
msgid "Session ended — undo unavailable"
msgstr ""
+#: src/components/TerminalTabStrip.tsx
+msgid "Sessions"
+msgstr ""
+
#: src/components/AuthModal.tsx
msgid "Set git identity"
msgstr ""
@@ -7174,6 +7494,7 @@ msgstr ""
msgid "Setting up"
msgstr ""
+#: src/components/acp/ThreadView.tsx
#: src/components/command-palette-commands.ts
#: src/components/settings/SettingsDialogShell.tsx
#: src/components/SettingsButton.tsx
@@ -7281,6 +7602,10 @@ msgstr ""
msgid "Show {hidden} more"
msgstr ""
+#: src/components/settings/ConfigureAgentsSection.tsx
+msgid "Show {inAppHiddenCount} more"
+msgstr ""
+
#: src/components/settings/LinkPreviewsSection.tsx
msgid "Show a preview card when you hover an external link in the editor. This setting applies only to this computer."
msgstr ""
@@ -7328,6 +7653,7 @@ msgid "Show HTML preview"
msgstr ""
#: src/components/PackCardGrid.tsx
+#: src/components/settings/ConfigureAgentsSection.tsx
msgid "Show less"
msgstr ""
@@ -7382,10 +7708,6 @@ msgstr ""
msgid "Show source"
msgstr ""
-#: src/components/TerminalRevealTab.tsx
-msgid "Show terminal"
-msgstr ""
-
#: src/components/command-palette-commands.ts
msgid "Show Terminal"
msgstr ""
@@ -7421,6 +7743,10 @@ msgstr ""
msgid "Sign in"
msgstr ""
+#: src/components/acp/ThreadView.tsx
+msgid "Sign in to {agentName} first"
+msgstr ""
+
#: src/components/AuthModal.tsx
msgid "Sign-in stream ended without confirmation — please try again"
msgstr ""
@@ -7476,6 +7802,11 @@ msgstr ""
msgid "Skip"
msgstr ""
+#. placeholder {0}: item.displayName
+#: src/components/acp/ThreadView.tsx
+msgid "Skipped downloading {0}."
+msgstr ""
+
#: src/lib/keyboard-shortcuts.ts
msgid "Slash command menu"
msgstr ""
@@ -7563,10 +7894,32 @@ msgstr ""
msgid "Star us on GitHub"
msgstr ""
+#: src/components/BottomComposer.tsx
+#: src/components/empty-state/CreatePromptComposer.tsx
+#: src/components/handoff/OpenInAgentContextSubmenu.tsx
+#: src/components/handoff/OpenInAgentEmptySpaceSubmenu.tsx
+#: src/components/handoff/OpenInAgentMenu.tsx
+msgid "Start {agentName}"
+msgstr ""
+
+#: src/components/handoff/OpenInAgentContextSubmenu.tsx
+#: src/components/handoff/OpenInAgentEmptySpaceSubmenu.tsx
+msgid "Start {agentName}, {hint}"
+msgstr ""
+
#: src/components/NavigatorApp.tsx
msgid "Start a new OpenKnowledge project."
msgstr ""
+#: src/components/TerminalSessionsHost.tsx
+msgid "Start a session with the + button, or launch an agent from a page."
+msgstr ""
+
+#: src/components/BottomComposer.tsx
+#: src/components/TerminalNewChatButton.tsx
+msgid "Start an agent"
+msgstr ""
+
#: src/components/NewItemDialog.tsx
msgid "Start from"
msgstr ""
@@ -7591,6 +7944,10 @@ msgstr ""
msgid "starter pack"
msgstr ""
+#: src/components/acp/ThreadView.tsx
+msgid "Starting {agentName}…"
+msgstr ""
+
#: src/components/CloneDialog.tsx
msgid "Starting clone"
msgstr ""
@@ -7599,6 +7956,10 @@ msgstr ""
msgid "Starting sign-in flow"
msgstr ""
+#: src/components/acp/ThreadView.tsx
+msgid "Starting the agent…"
+msgstr ""
+
#: src/components/TemplateForm.tsx
msgid "status"
msgstr ""
@@ -7617,6 +7978,14 @@ msgstr ""
msgid "Still loading"
msgstr ""
+#: src/components/acp/ThreadView.tsx
+msgid "Stop"
+msgstr ""
+
+#: src/components/acp/ThreadView.tsx
+msgid "Stopping"
+msgstr ""
+
#: src/components/settings/ProjectTemplatesSection.tsx
msgid "Stored at <0>.ok/templates/</0> in this project. Available in every folder (folder-scoped templates can override by filename)."
msgstr ""
@@ -7907,6 +8276,7 @@ msgstr ""
#: src/components/handoff/OpenInAgentMenu.tsx
#: src/components/McpConsentDialogBody.tsx
#: src/components/settings/AiToolsSection.tsx
+#: src/components/settings/ConfigureAgentsSection.tsx
#: src/components/settings/SettingsDialogShell.tsx
#: src/components/settings/TerminalSection.tsx
#: src/components/TerminalNewChatButton.tsx
@@ -7931,10 +8301,6 @@ msgstr ""
msgid "Terminal failed to load"
msgstr ""
-#: src/components/TerminalTabStrip.tsx
-msgid "Terminal sessions"
-msgstr ""
-
#: src/components/TerminalGate.tsx
msgid "Terminal settings not loaded yet — try again in a moment."
msgstr ""
@@ -7965,6 +8331,11 @@ msgstr ""
msgid "That folder isn't an OpenKnowledge project yet. Initialize it and open?"
msgstr ""
+#. placeholder {0}: item.displayName
+#: src/components/acp/ThreadView.tsx
+msgid "The {0} download request timed out."
+msgstr ""
+
#: src/components/ShareBranchSwitchDialog.tsx
msgid "The {targetNoun} could not be opened — try navigating to it manually."
msgstr ""
@@ -7973,6 +8344,10 @@ msgstr ""
msgid "The <0>type</0> every document created from this template gets (e.g. <1>research-note</1>). Keeps new docs Open Knowledge Format–conformant."
msgstr ""
+#: src/components/acp/ThreadView.tsx
+msgid "The agent isn't stopping. Force stop closes this thread and quits the agent."
+msgstr ""
+
#: src/components/CreatedItemsList.tsx
msgid "The agent's persona, values, and voice."
msgstr ""
@@ -8134,6 +8509,19 @@ msgstr ""
msgid "This {targetNoun} was shared from branch <0>{shareBranch}</0>. You're currently on <1>{currentLabel}</1>."
msgstr ""
+#: src/components/acp/ThreadView.tsx
+msgid "This agent needs you to sign in first — see the notice below."
+msgstr ""
+
+#. placeholder {0}: item.provides
+#. placeholder {1}: item.displayName
+#. placeholder {2}: item.version
+#. placeholder {3}: item.approxSizeMB
+#. placeholder {4}: item.sourceHost
+#: src/components/acp/ThreadView.tsx
+msgid "This agent runs through {0}, which isn't installed. Open Knowledge can download a private copy of {1} {2} (about {3} MB from {4}) that won't touch the rest of your system."
+msgstr ""
+
#: src/components/ShareReceiveDialog.tsx
msgid "This branch is checked out in:"
msgstr ""
@@ -8276,6 +8664,10 @@ msgstr ""
msgid "This replaces the current skill content with the bundled version {0}. Any local edits will be replaced — your current version is saved to history first, so you can restore it."
msgstr ""
+#: src/components/acp/ThreadView.tsx
+msgid "This request is no longer active."
+msgstr ""
+
#: src/components/settings/SearchSection.tsx
msgid "This sends content off your machine"
msgstr ""
@@ -8420,6 +8812,10 @@ msgstr ""
msgid "Turn on"
msgstr ""
+#: src/components/empty-state/CreatePromptComposer.tsx
+msgid "Turn on an agent to create with AI"
+msgstr ""
+
#: src/components/settings/LinkPreviewsSection.tsx
msgid "Turn on external link previews?"
msgstr ""
@@ -8774,6 +9170,10 @@ msgstr ""
msgid "Waiting for authorization"
msgstr ""
+#: src/components/acp/ThreadView.tsx
+msgid "Waiting for your approval"
+msgstr ""
+
#: src/components/settings/AccountSection.tsx
msgid "We couldn't check your GitHub connection."
msgstr ""
@@ -8927,6 +9327,10 @@ msgstr ""
msgid "Working"
msgstr ""
+#: src/components/acp/ThreadView.tsx
+msgid "Working…"
+msgstr ""
+
#: src/lib/keyboard-shortcuts.ts
msgid "Workspace"
msgstr ""
diff --git a/packages/app/src/main.tsx b/packages/app/src/main.tsx
index 4e5ab7c4d..12ce35083 100644
--- a/packages/app/src/main.tsx
+++ b/packages/app/src/main.tsx
@@ -26,12 +26,14 @@ import { ThemeProvider } from 'next-themes';
import { StrictMode } from 'react';
import { createRoot } from 'react-dom/client';
import { AppErrorBoundary, CrashReportingBoundary } from '@/components/AppErrorBoundary';
+import { AcpHarnessAgentDetection } from '@/components/acp/AcpHarnessAgentDetection';
import { selectDesktopRootApp } from '@/components/desktop-root-app';
import { ReportBugCrashInviteTrigger } from '@/components/ReportBugCrashInviteTrigger';
import { Toaster } from '@/components/ui/sonner';
import { TooltipProvider } from '@/components/ui/tooltip';
// Side-effect import to load the `Window.okDesktop?` global augmentation.
import '@/lib/desktop-bridge-types';
+import { useHydrateRegisteredAgentMeta } from '@/lib/acp/catalog';
import { installClientFetchWrapper } from '@/lib/client-fetch';
import { installConsentListener } from '@/lib/consent-store';
import { installCrashInviteListener } from '@/lib/crash-invite-store';
@@ -209,10 +211,19 @@ if (!root) throw new Error('Root element not found');
// always the editor (`App`) path.
const desktopBridge = typeof window === 'undefined' ? undefined : window.okDesktop;
+// Fetches the registry catalog on cold start and fills in the seeded agents'
+// brand icons + display names, so the launcher menus never strand on the neutral
+// glyph for users who don't open Configure agents. Renders nothing.
+function RegisteredAgentHydrator(): null {
+ useHydrateRegisteredAgentMeta();
+ return null;
+}
+
createRoot(root).render(
<StrictMode>
<I18nProvider i18n={i18n}>
<QueryClientProvider client={queryClient}>
+ <AcpHarnessAgentDetection />
<ThemeProvider
attribute="class"
defaultTheme="system"
@@ -220,6 +231,7 @@ createRoot(root).render(
disableTransitionOnChange
storageKey="ok-theme-v1"
>
+ <RegisteredAgentHydrator />
{/*
* Last-resort shell boundary: catches render crashes that escape
* every inner boundary (per-Activity DocumentErrorBoundary, settings
diff --git a/packages/app/src/presence/PresenceBar.tsx b/packages/app/src/presence/PresenceBar.tsx
index aaa14d33a..9030a9756 100644
--- a/packages/app/src/presence/PresenceBar.tsx
+++ b/packages/app/src/presence/PresenceBar.tsx
@@ -3,6 +3,7 @@ import {
type AgentPresenceEntry,
computeInitials,
deriveIconColor,
+ isPresenceSentinelDocName,
} from '@inkeep/open-knowledge-core';
import { plural, t } from '@lingui/core/macro';
import { Trans, useLingui } from '@lingui/react/macro';
@@ -269,15 +270,17 @@ function AgentAvatar({
// touch targets.
const writing = !crossDoc && heldWriting;
- // Sentinel currentDoc values (e.g. `(connected)` from the keepalive WS
- // bootstrap in `mcp-mount.ts`) are non-null so the entry survives the
- // client-side filter, but they don't represent a real document.
- // Match the sentinel set exactly — `isSafeDocName` (api-extension.ts)
- // permits `(` in real docNames (e.g. `(WIP) draft`, `(2026-05-13) standup`),
- // so a leading-`(` heuristic would over-suppress the "editing X" copy
- // for legitimate parenthesised filenames.
+ // Sentinel currentDoc values (`(connected)` from the keepalive WS bootstrap,
+ // `(agent thread)` from a doc-less in-app thread) are non-null so the entry
+ // survives the client-side filter, but they don't represent a real document.
+ // `isPresenceSentinelDocName` matches the sentinel set exactly — `isSafeDocName`
+ // (api-extension.ts) permits `(` in real docNames (e.g. `(WIP) draft`,
+ // `(2026-05-13) standup`), so a leading-`(` heuristic would over-suppress the
+ // "editing X" copy for legitimate parenthesised filenames.
const realCurrentDoc =
- presence.currentDoc && presence.currentDoc !== '(connected)' ? presence.currentDoc : null;
+ presence.currentDoc && !isPresenceSentinelDocName(presence.currentDoc)
+ ? presence.currentDoc
+ : null;
// The click opens the Activity Panel in the current doc's panel, or — when
// no doc is selected — navigates to the agent's doc first (the panel can't
diff --git a/packages/app/src/server/hocuspocus-plugin.ts b/packages/app/src/server/hocuspocus-plugin.ts
index ef04abbc1..70001e1ea 100644
--- a/packages/app/src/server/hocuspocus-plugin.ts
+++ b/packages/app/src/server/hocuspocus-plugin.ts
@@ -20,6 +20,9 @@ import {
INLINE_RENDERABLE_EXTENSIONS,
} from '@inkeep/open-knowledge-core';
import {
+ AcpThreadManager,
+ attachAcpThreadSocket,
+ buildOkMcpStdioCommand,
createAssetServeMiddleware,
createServer,
getLogger,
@@ -174,6 +177,42 @@ export function hocuspocusPlugin(): Plugin {
const { hocuspocus, sessionManager, agentFocusBroadcaster, agentPresenceBroadcaster } =
currentSrv;
+ // ACP thread host — the dev twin of boot.ts's construction (the
+ // documented dual-upgrade-handler drift hazard applies to this whole
+ // plugin; keep the two in step). Ephemeral test mode mirrors prod's
+ // off-switch: no manager, `/collab/thread` fail-closes.
+ const acpThreadManager = isEphemeralTest
+ ? null
+ : new AcpThreadManager({
+ contentDir: CONTENT_DIR,
+ localDir: currentSrv.lockDir,
+ registry: currentSrv.acpRegistry,
+ permissions: currentSrv.acpPermissions,
+ sessionManager,
+ agentPresenceBroadcaster,
+ resolveEmbed: currentSrv.resolveEmbed,
+ isExcludedPath: (rel) => currentSrv.contentFilter.isExcluded(rel),
+ isIgnoredPath: (rel) => currentSrv.contentFilter.isPathIgnored(rel),
+ getLoadedDocText: (docName) =>
+ hocuspocus.documents.get(docName)?.getText('source').toString() ?? null,
+ getServerUrl: () => {
+ const addr = server.httpServer?.address();
+ const port = typeof addr === 'object' && addr !== null ? addr.port : 5173;
+ return `http://localhost:${port}`;
+ },
+ // Non-HTTP agents (e.g. Claude's ACP adapter) get a stdio `ok mcp`
+ // shim pinned to this dev port. Relies on `open-knowledge` being on
+ // PATH here (no CLI entrypoint to resolve in the Vite dev server).
+ getMcpStdioCommand: () => {
+ const addr = server.httpServer?.address();
+ const port = typeof addr === 'object' && addr !== null ? addr.port : 5173;
+ return buildOkMcpStdioCommand(undefined, port);
+ },
+ log: getLogger('acp-threads'),
+ });
+ // Rehydrate archived threads before the first `list` can arrive.
+ await acpThreadManager?.init();
+
const wss = new WebSocketServer({ noServer: true, maxPayload: MAX_COLLAB_MESSAGE_BYTES });
wss.on('error', (err) => {
console.error('[collab] WebSocketServer error:', err);
@@ -200,6 +239,32 @@ export function hocuspocusPlugin(): Plugin {
`[collab] upgrade received url=${req.url} protocol=${req.headers['sec-websocket-protocol'] ?? 'none'} host=${req.headers.host ?? 'none'} origin=${req.headers.origin ?? 'none'}`,
);
+ // ACP agent-thread frames — bare WS, never Hocuspocus. Mirrors the
+ // `/collab/thread` branch in mcp-mount.ts (drift hazard: keep both).
+ if (req.url.startsWith('/collab/thread')) {
+ if (acpThreadManager === null) {
+ socket.destroy();
+ return;
+ }
+ socket.on('error', (err: NodeJS.ErrnoException) => {
+ if (handleCollabSocketError(err)) return;
+ console.error('[collab] ACP thread socket error:', err);
+ });
+ try {
+ wss.handleUpgrade(req, socket, head, (ws) => {
+ attachAcpThreadSocket(ws, acpThreadManager, getLogger('acp-threads'));
+ });
+ } catch (err) {
+ console.error(`[collab] thread handleUpgrade threw for ${req.url}:`, err);
+ try {
+ socket.destroy();
+ } catch {
+ // Already-destroyed — swallow.
+ }
+ }
+ return;
+ }
+
// `ok mcp` holds a persistent WS to /collab/keepalive?connectionId=<id>
// to register as an active client. Must route as a bare WS — MCP
// never sends sync-step-1 that Hocuspocus waits for, so routing
@@ -498,6 +563,11 @@ export function hocuspocusPlugin(): Plugin {
if (keepaliveGraceInflight.size > 0) {
await Promise.allSettled(keepaliveGraceInflight);
}
+ try {
+ await acpThreadManager?.destroy();
+ } catch (err) {
+ console.error('[hocuspocus] acpThreadManager.destroy() failed:', err);
+ }
try {
await currentSrv.destroy();
} catch (err) {
diff --git a/packages/app/tests/integration/attribution-sweep-coverage.test.ts b/packages/app/tests/integration/attribution-sweep-coverage.test.ts
index eaa92a3a7..0d88db47c 100644
--- a/packages/app/tests/integration/attribution-sweep-coverage.test.ts
+++ b/packages/app/tests/integration/attribution-sweep-coverage.test.ts
@@ -9,9 +9,10 @@
* `principalId` — server's `getPrincipal()` is the sole source (HTTP body
* is unauthenticated; structurally enforcing the trust boundary).
*/
-import { describe, expect, test } from 'bun:test';
+
import { readFileSync } from 'node:fs';
import { join } from 'node:path';
+import { describe, expect, test } from 'vitest';
const API_EXT_PATH = join(import.meta.dirname, '../../../server/src/api-extension.ts');
const source = readFileSync(API_EXT_PATH, 'utf8');
@@ -81,6 +82,11 @@ const REQUIRED_HANDLERS = [
const EXEMPT_HANDLERS = new Set([
'handleDocumentRead',
'handleDocumentList',
+ // GET /api/acp/catalog — read-only ACP agent-catalog listing (registry +
+ // custom entries); performs no writes, so there is nothing to attribute.
+ // Agent-thread writes flow through the /collab/thread WS and are attributed
+ // per-session there (agent-<id> writer taxonomy), not via this route.
+ 'handleAcpCatalog',
// `/api/__embed-detect` — read-only loopback + host-gated diagnostic
// (embedded-viewer detection spike); reads the UA ring buffer and performs
// no writes, so there is nothing to attribute.
diff --git a/packages/app/tests/integration/conflict-gate-coverage.test.ts b/packages/app/tests/integration/conflict-gate-coverage.test.ts
index 8f5fa0023..2ad0461cf 100644
--- a/packages/app/tests/integration/conflict-gate-coverage.test.ts
+++ b/packages/app/tests/integration/conflict-gate-coverage.test.ts
@@ -19,9 +19,10 @@
* `lifecycle.status === 'conflict'`. The meta-test forces a categorization
* decision at every PR boundary.
*/
-import { describe, expect, test } from 'bun:test';
+
import { readFileSync } from 'node:fs';
import { join } from 'node:path';
+import { describe, expect, test } from 'vitest';
const API_EXT_PATH = join(import.meta.dirname, '../../../server/src/api-extension.ts');
const source = readFileSync(API_EXT_PATH, 'utf8');
@@ -83,6 +84,10 @@ const EXEMPT_HANDLERS = new Set([
// Read paths.
'handleDocumentRead',
'handleDocumentList',
+ // GET /api/acp/catalog — read-only ACP agent-catalog listing (registry +
+ // custom entries); no Y.Doc mutation, so the conflict-refusal gate doesn't
+ // apply. Agent-thread writes ride the /collab/thread WS, not this route.
+ 'handleAcpCatalog',
'handleAsset',
'handleAssetText',
'handleBacklinks',
diff --git a/packages/app/tests/stress/fixtures/handoff-mocks.ts b/packages/app/tests/stress/fixtures/handoff-mocks.ts
index c7b7b751c..fbc196de1 100644
--- a/packages/app/tests/stress/fixtures/handoff-mocks.ts
+++ b/packages/app/tests/stress/fixtures/handoff-mocks.ts
@@ -605,7 +605,8 @@ export async function installHandoffMocks(page: Page, cfg: HandoffMockConfig): P
adopt: async () => ({ ok: true as const, replay: '' }),
setMeta: () => {},
setOrder: () => {},
- getDockState: async () => ({ visible: false }),
+ getDockState: async () => ({ visible: false, order: [], activeKey: null }),
+ setDockState: () => {},
onData: () => () => {},
onExit: () => () => {},
claudePreflight: async () => ({ claude: 'present' as const, mcp: 'wired' as const }),
diff --git a/packages/app/tests/stress/frozen-table-headers.e2e.ts b/packages/app/tests/stress/frozen-table-headers.e2e.ts
index 3e74cbde1..fa8764761 100644
--- a/packages/app/tests/stress/frozen-table-headers.e2e.ts
+++ b/packages/app/tests/stress/frozen-table-headers.e2e.ts
@@ -330,6 +330,14 @@ test('no freeze before the table reaches the toolbar', async ({
api,
workerServer,
}, testInfo) => {
+ // The follow-the-file activation replay auto-scrolls to the seeded write's
+ // changed range (the seed IS an agent write, and it lands within the replay
+ // window) — which would legitimately freeze the header mid-table. This test
+ // measures the AT-REST transform, so pin the viewport to the top by
+ // disabling the follow pref before the app loads.
+ await page.addInitScript(() => {
+ localStorage.setItem('ok-acp-follow-file-v1', '0');
+ });
await api.seedDocs([{ name: 'frozen-hdr-long-1', markdown: LONG_TABLE_MARKDOWN }]);
await page.goto(`${workerServer.baseURL}/#/frozen-hdr-long-1`);
await waitForActiveProviderSynced(page);
diff --git a/packages/app/tests/stress/graph-panel-surfaces.e2e.ts b/packages/app/tests/stress/graph-panel-surfaces.e2e.ts
index 0261cd87e..d41be281b 100644
--- a/packages/app/tests/stress/graph-panel-surfaces.e2e.ts
+++ b/packages/app/tests/stress/graph-panel-surfaces.e2e.ts
@@ -132,10 +132,8 @@ async function openGraph(
);
if (fullscreen) {
- await page.getByLabel('Full screen').click();
- await page.waitForFunction(() => Boolean(document.fullscreenElement), null, {
- timeout: 5_000,
- });
+ await page.getByLabel('Expand graph').click();
+ await expect(getExpandedGraphIndicator(page)).toBeVisible();
}
}
@@ -157,6 +155,14 @@ function getGraphSurface(page: Page) {
return page.getByRole('img', { name: 'Graph visualization of document links' });
}
+// The expanded-graph signal. The control moved off the browser Fullscreen API
+// (document.fullscreenElement) to in-app panel expansion, so the Explore/
+// Orphans/Hubs mode toggle — which renders only while expanded — is the
+// authoritative "expanded" indicator. Visible ⇒ expanded; count 0 ⇒ collapsed.
+function getExpandedGraphIndicator(page: Page) {
+ return page.getByRole('group', { name: 'Expanded graph mode' });
+}
+
async function clickGraphDoc(page: Page, docName: string) {
return page.evaluate(
(targetDoc) =>
@@ -361,9 +367,7 @@ test('fullscreen graph selects a document before explicitly opening it', async (
expect(await getGraphNodeVisualState(page, fixtures.beta)).toBe('selected');
await selectedDoc.getByRole('button', { name: 'Open' }).click();
- await page.waitForFunction(() => !document.fullscreenElement, null, {
- timeout: 5_000,
- });
+ await expect(getExpandedGraphIndicator(page)).toHaveCount(0);
await expect(page).toHaveURL(new RegExp(`#/${escapeRegex(fixtures.beta)}#deep-link$`));
});
@@ -385,9 +389,7 @@ test('fullscreen graph selecting the active document shows the already-open stat
expect(await getGraphNodeVisualState(page, fixtures.alpha)).toBe('active-selected');
await selectedDoc.getByRole('button', { name: 'Open' }).click();
- await page.waitForFunction(() => !document.fullscreenElement, null, {
- timeout: 5_000,
- });
+ await expect(getExpandedGraphIndicator(page)).toHaveCount(0);
await expect(page).toHaveURL(new RegExp(`#/${escapeRegex(fixtures.alpha)}$`));
});
@@ -414,10 +416,8 @@ test('graph canvas fills the available height in docked and fullscreen modes', a
await waitForGraphNode(page, fixtures.alpha);
await expectGraphToFillAvailableHeight(page);
- await page.getByLabel('Full screen').click();
- await page.waitForFunction(() => Boolean(document.fullscreenElement), null, {
- timeout: 5_000,
- });
+ await page.getByLabel('Expand graph').click();
+ await expect(getExpandedGraphIndicator(page)).toBeVisible();
await waitForGraphNode(page, fixtures.alpha);
await expectGraphToFillAvailableHeight(page);
});
@@ -552,15 +552,11 @@ test('fullscreen graph selection clears after exiting fullscreen', async ({
const selectedDoc = page.getByRole('status', { name: 'Selected graph item' });
await expect(selectedDoc).toBeVisible();
- await page.getByLabel('Exit fullscreen').click();
- await page.waitForFunction(() => !document.fullscreenElement, null, {
- timeout: 5_000,
- });
+ await page.getByLabel('Collapse graph').click();
+ await expect(getExpandedGraphIndicator(page)).toHaveCount(0);
- await page.getByLabel('Full screen').click();
- await page.waitForFunction(() => Boolean(document.fullscreenElement), null, {
- timeout: 5_000,
- });
+ await page.getByLabel('Expand graph').click();
+ await expect(getExpandedGraphIndicator(page)).toBeVisible();
await expect(selectedDoc).toHaveCount(0);
});
diff --git a/packages/app/tests/stress/handoff.e2e.ts b/packages/app/tests/stress/handoff.e2e.ts
index eb581d5fe..733a89f18 100644
--- a/packages/app/tests/stress/handoff.e2e.ts
+++ b/packages/app/tests/stress/handoff.e2e.ts
@@ -5,39 +5,35 @@
* (`OpenInAgentContextSubmenu`, mounted inside `FileTree`'s row context menu).
* The top-toolbar Open-with-AI trigger was removed when Ask AI became the
* single editor entry point; this is the surviving deep-link handoff surface.
- * It renders the SAME target set with the SAME install-state gating + the same
- * `claude-cowork` exclusion (`VISIBLE_TARGETS`) the old toolbar menu used, so
- * every cell's dispatch coverage carries over — only the way the menu is OPENED
+ * It renders the SAME target set with the same `claude-cowork` exclusion
+ * (`VISIBLE_TARGETS`) the old toolbar menu used, so every cell's dispatch
+ * coverage carries over — only the way the menu is OPENED
* changes (right-click the seeded doc's sidebar row → expand the "Open with AI"
* submenu → click `file-tree-open-in-<target>`).
*
* Per-target rows carry `data-testid="file-tree-open-in-<target.id>"`
- * (e.g. `file-tree-open-in-cursor`); the empty-state hint is
- * `file-tree-open-in-empty`. Unlike the old toolbar menu, this submenu FILTERS
- * to `installed === true` targets — not-installed rows are absent entirely
- * (no disabled "Install →" affordance), so the install-state assertions read
- * the same as before (hidden pre-flip, visible post-flip).
- *
- * The submenu does NOT re-probe install state on open (the old toolbar menu's
- * on-open `refresh()` is gone). Install state updates via the mount probe and
- * the `window` focus listener in `useInstalledAgents`. Cell 3 therefore drives
- * the install-state flip by advancing the throttle clock, flipping the mock,
- * then dispatching a `window` focus event to re-probe — rather than the old
- * close+reopen-triggers-refresh path.
+ * (e.g. `file-tree-open-in-cursor`); seeded in-app agent rows carry
+ * `file-tree-open-in-thread-<agent.id>`. Desktop rows are gated by ENABLEMENT
+ * (the Configure-agents toggle), not install detection: Desktop targets are OFF
+ * by default, so a cell that expects a Desktop row seeds an enable override via
+ * `enableDesktopTargets` before boot. Install state only decides, for an enabled
+ * row, whether selecting it dispatches (installed) or opens the installer (not).
*
* Cell coverage:
* - Cells 1, 4: cowork-UI-hidden invariant — `claude-cowork` is filtered
- * out of the submenu by `VISIBLE_TARGETS` even when `claude: true`.
+ * out of the submenu by `VISIBLE_TARGETS` even when enabled + `claude: true`.
* Dispatch by ID still works through `KNOWN_TARGETS` (covered by
* `useHandoffDispatch.test.ts`); these cells guard only the render-surface
- * hide. Cells 2, 8: happy paths for installed targets.
- * - Cell 3: install-state flip — row is HIDDEN pre-flip (filter removes
- * `installed:false` rows) and APPEARS post-flip.
+ * hide. Cells 2, 8: happy paths for enabled + installed targets.
+ * - Cell 3: an enabled-but-not-installed Desktop target still renders
+ * (visibility is enablement-based) and selecting it opens the installer
+ * instead of dispatching.
* - Cell 5: Web Cursor happy path — POSTs to `/api/handoff` (target:
* `cursor`, with `workspacePath`) and asserts on the captured request.
* Server owns the `cursor <path>` + `open <url>` recipe; renderer just
* builds the URL and POSTs. This cell is the web mirror of cell 2.
- * - Cell 7: empty-state — every per-target row hidden, disabled hint shown.
+ * - Cell 7: with Desktop off and nothing installed, every per-target row is
+ * hidden, but the seeded in-app agent rows still render.
* Each cell maps to the numbered scenarios in that section. Mocking at the
* `window.okDesktop` bridge boundary (Electron host) + `page.route` on
* `/api/installed-agents` (web host) via `fixtures/handoff-mocks.ts`.
@@ -52,11 +48,10 @@
* navigate to `claude://` etc., triggering a protocol-handler dialog
* (ignored in headless) OR a real navigation to `https://claude.ai/...`
* (would leave the app). See `handoff-mocks.ts` for the full rationale.
- * - Cell 3 (install-state flip) advances the fake clock past the 10s probe
- * throttle, flips the mock, then dispatches a `window` focus event to force
- * a re-probe (the only natural user path that re-probes on this surface).
- * We assert the transition by re-opening the submenu and polling the codex
- * row's visibility.
+ * - Cell 3 seeds an enable override for a Desktop target the probe reports NOT
+ * installed, then asserts the row still renders (visibility is enablement-
+ * based) and that selecting it opens the installer rather than dispatching a
+ * handoff.
*
* Host-specific notes:
* - Electron host cells MUST inject `window.okDesktop` via `addInitScript`
@@ -75,11 +70,9 @@ import { realpathSync } from 'node:fs';
import type { Page } from '@playwright/test';
import { expect, test, waitForActiveProviderSynced } from './_helpers';
import {
- advanceHandoffFakeTime,
type HandoffMockConfig,
installHandoffMocks,
readCapturedHandoff,
- updateElectronInstallMap,
} from './fixtures/handoff-mocks';
const DOC_NAME = 'handoff-test-doc';
@@ -139,12 +132,41 @@ async function openHandoffSubmenu(page: Page): Promise<void> {
await submenuTrigger.click();
}
-/** Close any open file-tree context menu (Escape collapses the submenu then
- * the root menu). Used by the install-state-flip cell between probes. */
-async function closeHandoffMenu(page: Page): Promise<void> {
- await page.keyboard.press('Escape');
- await page.keyboard.press('Escape');
- await expect(page.getByRole('menuitem', { name: 'Open with AI' })).toHaveCount(0);
+/**
+ * Enable Desktop targets in the Configure-agents store before boot. Desktop
+ * hand-offs are OFF by default (opt-in), so a cell that expects a Desktop row
+ * must enable it first — the same override the user writes by flipping the
+ * toggle in Settings → Configure agents. Visibility now derives from enablement,
+ * not install detection; install state only decides dispatch-vs-installer.
+ *
+ * Call BEFORE `page.goto(...)` — `addInitScript` runs on the fresh document.
+ */
+async function enableDesktopTargets(page: Page, targetIds: readonly string[]): Promise<void> {
+ await page.addInitScript((ids: readonly string[]) => {
+ const overrides: Record<string, boolean> = {};
+ for (const id of ids) overrides[`desktop:${id}`] = true;
+ window.localStorage.setItem('ok-acp-enabled-agents-v1', JSON.stringify(overrides));
+ }, targetIds);
+}
+
+/**
+ * Register in-app agents in the Configure-agents store before boot. Seeding was
+ * retired — per-agent thread rows now render for the user's ENABLED in-app
+ * agents — so a cell that expects a thread row registers it here, the same store
+ * `registerAgent` writes when the user turns one on in Settings. Call BEFORE
+ * `page.goto(...)`.
+ */
+async function registerInAppAgents(
+ page: Page,
+ agents: ReadonlyArray<{ source: string; id: string; name: string }>,
+): Promise<void> {
+ await page.addInitScript((list: ReadonlyArray<{ source: string; id: string }>) => {
+ const first = list[0];
+ window.localStorage.setItem(
+ 'ok-acp-registered-agents-v1',
+ JSON.stringify({ agents: list, defaultKey: first ? `${first.source}:${first.id}` : null }),
+ );
+ }, agents);
}
/**
@@ -200,19 +222,19 @@ test.describe('handoff — 8-cell matrix', () => {
workerContentDir: resolvedContentDir(workerServer.contentDir),
};
await installHandoffMocks(page, cfg);
+ // Desktop rows are opt-in — enable the visible targets so their rows render.
+ await enableDesktopTargets(page, ['claude-code', 'codex', 'cursor']);
await seedAndNavigate(page, api);
- // Probe must settle first: the submenu filters out `installed: null` rows,
- // so the installed siblings only appear after detectProtocol resolves.
await waitForProbeSettled(page, 'electron');
await openHandoffSubmenu(page);
- // Sibling installed rows render…
+ // Enabled sibling rows render…
await expect(page.getByTestId('file-tree-open-in-claude-code')).toBeVisible();
await expect(page.getByTestId('file-tree-open-in-codex')).toBeVisible();
await expect(page.getByTestId('file-tree-open-in-cursor')).toBeVisible();
- // …but the cowork row is filtered out by VISIBLE_TARGETS even with
+ // …but the cowork row is filtered out by VISIBLE_TARGETS even when enabled +
// `claude: true`. No way to click it, no way to dispatch from the UI.
await expect(page.getByTestId('file-tree-open-in-claude-cowork')).toHaveCount(0);
});
@@ -229,6 +251,7 @@ test.describe('handoff — 8-cell matrix', () => {
workerContentDir: resolvedContentDir(workerServer.contentDir),
};
await installHandoffMocks(page, cfg);
+ await enableDesktopTargets(page, ['claude-code', 'codex', 'cursor']);
await seedAndNavigate(page, api);
await waitForProbeSettled(page, 'electron');
@@ -261,11 +284,15 @@ test.describe('handoff — 8-cell matrix', () => {
await expect(page.getByText('Opened in Cursor.')).toBeVisible();
});
- test('cell 3: Electron install-state flip — disabled → enabled via refresh after throttle window', async ({
+ test('cell 3: Electron enabled-but-not-installed Desktop target renders and routes to its installer', async ({
page,
api,
workerServer,
}) => {
+ // Codex is enabled in Configure agents but the probe reports it not
+ // installed. Visibility is enablement-based now (not install-based), so the
+ // row renders anyway; selecting it opens the installer (openInstallUrl →
+ // openExternal) instead of dispatching a handoff.
const cfg: HandoffMockConfig = {
host: 'electron',
install: { claude: true, codex: false, cursor: true },
@@ -273,32 +300,26 @@ test.describe('handoff — 8-cell matrix', () => {
workerContentDir: resolvedContentDir(workerServer.contentDir),
};
await installHandoffMocks(page, cfg);
+ await enableDesktopTargets(page, ['codex', 'cursor']);
await seedAndNavigate(page, api);
- // v1: Codex starts NOT rendered (filter excludes installed:false rows).
- // After flipping the mock + re-probing past the 10s throttle, the row
- // appears.
await waitForProbeSettled(page, 'electron');
await openHandoffSubmenu(page);
- // Siblings that ARE installed prove the submenu populated (so the codex
- // absence below is a filtered row, not an unsettled probe).
- await expect(page.getByTestId('file-tree-open-in-cursor')).toBeVisible();
- const codexRow = page.getByTestId('file-tree-open-in-codex');
- await expect(codexRow).toHaveCount(0);
-
- // Close the menu, advance past the 10s throttle, flip the mock, and force
- // a re-probe. Unlike the old toolbar menu, this submenu doesn't refresh on
- // open — `useInstalledAgents` re-probes on `window` focus, so we dispatch
- // a focus event under the advanced clock to bypass the throttle.
- await closeHandoffMenu(page);
- await advanceHandoffFakeTime(page, 11_000);
- await updateElectronInstallMap(page, { claude: true, codex: true, cursor: true });
- await page.evaluate(() => window.dispatchEvent(new Event('focus')));
+ // Enabled → visible, even though codex is not installed on this host.
+ const codexRow = page.getByTestId('file-tree-open-in-codex');
+ await expect(codexRow).toBeVisible();
+ await codexRow.click();
- // After the re-probe lands, reopening the submenu shows the codex row.
- await openHandoffSubmenu(page);
- await expect(codexRow).toBeVisible({ timeout: 5_000 });
+ // Not installed → the installer opens; no handoff dispatch fires.
+ await expect
+ .poll(async () => (await readCapturedHandoff(page)).openExternalCalls.length, {
+ timeout: 5_000,
+ })
+ .toBe(1);
+ const captured = await readCapturedHandoff(page);
+ expect(captured.openExternalCalls[0]).toBe('https://openai.com/codex');
+ expect(captured.handoffApiCalls.length).toBe(0);
});
test('cell 4: Web — claude-cowork row stays hidden even when probe reports installed', async ({
@@ -317,6 +338,7 @@ test.describe('handoff — 8-cell matrix', () => {
workerContentDir: resolvedContentDir(workerServer.contentDir),
};
await installHandoffMocks(page, cfg);
+ await enableDesktopTargets(page, ['claude-code', 'codex', 'cursor']);
await seedAndNavigate(page, api);
await waitForProbeSettled(page, 'web');
@@ -341,14 +363,15 @@ test.describe('handoff — 8-cell matrix', () => {
workerContentDir: resolvedContentDir(workerServer.contentDir),
};
await installHandoffMocks(page, cfg);
+ await enableDesktopTargets(page, ['claude-code', 'codex', 'cursor']);
await seedAndNavigate(page, api);
await waitForProbeSettled(page, 'web');
await openHandoffSubmenu(page);
- // Web-host Cursor row is rendered when the install probe says
- // `cursor: true` (the previous `forceWebCursorDisabled` override was
- // removed; the filter still hides rows when probe says false).
+ // Cursor row is rendered because it is enabled in Configure agents; the
+ // probe says `cursor: true`, so selecting it dispatches (rather than routing
+ // to the installer).
await page.getByTestId('file-tree-open-in-cursor').click();
await expect
@@ -380,7 +403,7 @@ test.describe('handoff — 8-cell matrix', () => {
expect(captured.anchorClicks.length).toBe(0);
});
- test('cell 7: Web empty-state — every per-target row hidden, disabled "No installed agents found" hint shown, no claude.ai fallback', async ({
+ test('cell 7: Web — every per-target Desktop row hidden, seeded in-app agent rows still offered, no claude.ai fallback', async ({
page,
api,
workerServer,
@@ -392,6 +415,9 @@ test.describe('handoff — 8-cell matrix', () => {
workerContentDir: resolvedContentDir(workerServer.contentDir),
};
await installHandoffMocks(page, cfg);
+ // The user has an enabled in-app agent (seeding is retired; enablement is the
+ // source of truth), so its per-agent thread row is offered below.
+ await registerInAppAgents(page, [{ source: 'registry', id: 'claude-acp', name: 'Claude' }]);
await seedAndNavigate(page, api);
const consoleErrors: string[] = [];
@@ -403,14 +429,17 @@ test.describe('handoff — 8-cell matrix', () => {
await waitForProbeSettled(page, 'web');
await openHandoffSubmenu(page);
- // Every per-target row is hidden. On the web host there's no terminal
- // launcher, so the submenu falls back to a disabled "No installed agents
- // found" hint — NOT the removed claude.ai web fallback.
+ // Every per-target Desktop row is hidden (Desktop is opt-in and nothing is
+ // enabled here), and there's no claude.ai web fallback. The submenu is still
+ // not a dead end: the enabled in-app agent is server-hosted, so its per-agent
+ // thread row renders even with zero installed editors (the old generic "Start
+ // an agent" row + "no installed agents" hint are gone).
for (const id of ['claude-cowork', 'claude-code', 'codex', 'cursor']) {
await expect(page.getByTestId(`file-tree-open-in-${id}`)).toHaveCount(0);
}
await expect(page.getByTestId('open-in-agent-claude-web-fallback')).toHaveCount(0);
- await expect(page.getByTestId('file-tree-open-in-empty')).toBeVisible();
+ await expect(page.getByTestId('file-tree-open-in-thread-claude-acp')).toBeVisible();
+ await expect(page.getByTestId('file-tree-open-in-empty')).toHaveCount(0);
// Defensive: the menu render path must not have thrown.
expect(consoleErrors.filter((e) => !e.includes('net::') && !e.includes('favicon'))).toEqual([]);
@@ -450,6 +479,7 @@ test.describe('handoff — 8-cell matrix', () => {
}),
});
});
+ await enableDesktopTargets(page, ['claude-code', 'codex', 'cursor']);
await seedAndNavigate(page, api);
await waitForProbeSettled(page, 'electron');
diff --git a/packages/app/tests/stress/markdown-lint.e2e.ts b/packages/app/tests/stress/markdown-lint.e2e.ts
index 6818ac1b0..4c97495a3 100644
--- a/packages/app/tests/stress/markdown-lint.e2e.ts
+++ b/packages/app/tests/stress/markdown-lint.e2e.ts
@@ -98,6 +98,18 @@ test.beforeEach(async ({ page, api, workerServer }) => {
}
});
+ // Follow-the-file (ACP) defaults ON, so an agent write — including the
+ // `seed()` used to set up these fixtures — scrolls the shared editor
+ // container to follow the write. That viewport side-effect is orthogonal to
+ // lint navigation and defeats the source-mode scroll assertion (the container
+ // arrives at the violation before the click can move it). Pin it OFF so these
+ // tests measure lint navigation from a stable top-of-doc baseline.
+ await page.addInitScript(() => {
+ try {
+ localStorage.setItem('ok-acp-follow-file-v1', '0');
+ } catch {}
+ });
+
testDocName = `mdlint-${randomUUID().slice(0, 8)}`;
await api.createPage(`${testDocName}.md`);
await page.goto(`/#/${testDocName}`);
diff --git a/packages/app/tests/stress/outline-toolbar-occlusion.e2e.ts b/packages/app/tests/stress/outline-toolbar-occlusion.e2e.ts
index f9462f8eb..73c0c3e1a 100644
--- a/packages/app/tests/stress/outline-toolbar-occlusion.e2e.ts
+++ b/packages/app/tests/stress/outline-toolbar-occlusion.e2e.ts
@@ -106,6 +106,11 @@ const TARGET_SLUG = 'target-heading';
async function seedDoc(api: ApiHelpers, page: Page): Promise<string> {
const docName = `occlusion-${randomUUID().slice(0, 8)}`;
await api.createPage(`${docName}.md`);
+ await page.addInitScript(() => {
+ try {
+ localStorage.setItem('ok-acp-follow-file-v1', '0');
+ } catch {}
+ });
await page.goto(`/#/${docName}`);
await page.waitForFunction(() => Boolean(window.__activeProvider?.isSynced), null, {
timeout: 15_000,
diff --git a/packages/app/tests/stress/qa-sidebar-responsive.e2e.ts b/packages/app/tests/stress/qa-sidebar-responsive.e2e.ts
index eed87e880..55671cc74 100644
--- a/packages/app/tests/stress/qa-sidebar-responsive.e2e.ts
+++ b/packages/app/tests/stress/qa-sidebar-responsive.e2e.ts
@@ -239,9 +239,13 @@ test.describe('non-embedded UA', () => {
await page.goto('/#/qa-doc-handle-collapse');
await waitForActiveProviderSynced(page);
- // On the web host the doc-panel handle is the only resizable separator (no
- // terminal column mounts), so it is unambiguous.
- const docPanelHandle = page.locator('[data-slot="resizable-handle"]');
+ // The sessions dock's bottom shell renders on every host now, so its
+ // (disabled, horizontal) handle coexists with the doc-panel handle.
+ // The doc panel's is the only VERTICAL separator while the right dock
+ // column is hidden, so scope by orientation.
+ const docPanelHandle = page.locator(
+ '[data-slot="resizable-handle"][aria-orientation="vertical"]',
+ );
await expect(docPanelHandle).toHaveCount(1);
// Expanded (default at WIDE): interactive — focusable and not disabled.
@@ -476,8 +480,13 @@ test.describe('non-embedded UA', () => {
await expect(page.locator('.ProseMirror:not(.composer-prosemirror)').first()).toBeVisible({
timeout: 30_000,
});
- // Find the resize handle — our wrapper uses data-slot="resizable-handle"
- const handle = page.locator('[data-slot="resizable-handle"]').first();
+ // Find the doc-panel resize handle — our wrapper uses
+ // data-slot="resizable-handle"; scope by orientation because the sessions
+ // dock's bottom shell contributes a second (horizontal, disabled) handle
+ // on every host.
+ const handle = page
+ .locator('[data-slot="resizable-handle"][aria-orientation="vertical"]')
+ .first();
await expect(handle).toBeVisible({ timeout: 10_000 });
const box = await handle.boundingBox();
expect(box).not.toBeNull();
@@ -815,7 +824,11 @@ test.describe('non-embedded UA', () => {
)
.toBeLessThanOrEqual(360);
- const handle = page.locator('[role="separator"][data-separator]').first();
+ // Scope by orientation: the sessions dock's bottom shell contributes a
+ // second (horizontal, disabled) separator on every host.
+ const handle = page
+ .locator('[role="separator"][data-separator][aria-orientation="vertical"]')
+ .first();
const handleBox = await handle.boundingBox();
if (handleBox == null) throw new Error('right handle not laid out');
// Drag handle leftward by ~100px (panel grows by ~100px from ~340 → ~440)
diff --git a/packages/cli/src/commands/acp-harness-probe.test.ts b/packages/cli/src/commands/acp-harness-probe.test.ts
new file mode 100644
index 000000000..3ce701015
--- /dev/null
+++ b/packages/cli/src/commands/acp-harness-probe.test.ts
@@ -0,0 +1,279 @@
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { dirname, join } from 'node:path';
+import { stringify as stringifyToml } from 'smol-toml';
+import { afterEach, describe, expect, test } from 'vitest';
+import { probeOwnManagedEditorMcpEntry } from './acp-harness-probe.ts';
+import {
+ buildManagedServerEntry,
+ CHAIN_V1,
+ entryRunsOwnManagedServer,
+ openCodeEntryRunsOwnManagedServer,
+} from './editors.ts';
+
+let dirs: string[] = [];
+function tmp(): string {
+ const d = mkdtempSync(join(tmpdir(), 'acp-harness-probe-'));
+ dirs.push(d);
+ return d;
+}
+afterEach(() => {
+ for (const d of dirs) rmSync(d, { recursive: true, force: true });
+ dirs = [];
+});
+
+function writeJson(path: string, value: unknown): void {
+ mkdirSync(dirname(path), { recursive: true });
+ writeFileSync(path, JSON.stringify(value, null, 2));
+}
+
+const publishedEntry = () => buildManagedServerEntry({ mode: 'published' });
+
+const openCodePublished = () => ({
+ type: 'local',
+ enabled: true,
+ command: ['/bin/sh', '-l', '-c', CHAIN_V1],
+});
+
+describe('probeOwnManagedEditorMcpEntry', () => {
+ test('hits the claude project .mcp.json before the user config', () => {
+ const cwd = tmp();
+ const home = tmp();
+ writeJson(join(cwd, '.mcp.json'), {
+ mcpServers: { 'open-knowledge': publishedEntry() },
+ });
+ writeJson(join(home, '.claude.json'), {
+ mcpServers: { 'open-knowledge': publishedEntry() },
+ });
+ const hit = probeOwnManagedEditorMcpEntry('claude', cwd, home);
+ expect(hit).toEqual({
+ editorId: 'claude',
+ scope: 'project',
+ configPath: join(cwd, '.mcp.json'),
+ });
+ });
+
+ test('falls back to the user-global claude config when the project has none', () => {
+ const cwd = tmp();
+ const home = tmp();
+ writeJson(join(home, '.claude.json'), {
+ mcpServers: { 'open-knowledge': publishedEntry() },
+ });
+ const hit = probeOwnManagedEditorMcpEntry('claude', cwd, home);
+ expect(hit).toEqual({
+ editorId: 'claude',
+ scope: 'user',
+ configPath: join(home, '.claude.json'),
+ });
+ });
+
+ test('misses on absent configs and foreign command/args', () => {
+ const cwd = tmp();
+ const home = tmp();
+ expect(probeOwnManagedEditorMcpEntry('claude', cwd, home)).toBeNull();
+
+ // Foreign command — never stand down for a server that isn't ours.
+ writeJson(join(cwd, '.mcp.json'), {
+ mcpServers: { 'open-knowledge': { command: 'evil', args: [] } },
+ });
+ expect(probeOwnManagedEditorMcpEntry('claude', cwd, home)).toBeNull();
+
+ // Canonical command but tampered args — a different chain body, not ours.
+ writeJson(join(cwd, '.mcp.json'), {
+ mcpServers: { 'open-knowledge': { command: '/bin/sh', args: ['-l', '-c', 'rm -rf /'] } },
+ });
+ expect(probeOwnManagedEditorMcpEntry('claude', cwd, home)).toBeNull();
+
+ // Unparseable config — never throws, counts as a miss.
+ writeFileSync(join(cwd, '.mcp.json'), '{not json');
+ expect(probeOwnManagedEditorMcpEntry('claude', cwd, home)).toBeNull();
+ });
+
+ test('hits when the canonical entry carries harness policy siblings (an env overlay)', () => {
+ const cwd = tmp();
+ const home = tmp();
+ // command+args are OK's canonical chain → the harness launches OK's server
+ // regardless of the extra `env` key, so we still skip injecting a duplicate.
+ writeJson(join(cwd, '.mcp.json'), {
+ mcpServers: { 'open-knowledge': { ...publishedEntry(), env: { X: '1' } } },
+ });
+ expect(probeOwnManagedEditorMcpEntry('claude', cwd, home)?.scope).toBe('project');
+ });
+
+ test("hits despite Codex's churny per-tool approval policy (the tools subtable)", () => {
+ const cwd = tmp();
+ const home = tmp();
+ // Exactly the shape Codex writes as the user approves tools mid-session:
+ // `[mcp_servers.open-knowledge.tools.exec] approval_mode = "approve"` parses
+ // to a `tools` key on the entry. It must NOT break the match.
+ mkdirSync(join(cwd, '.codex'), { recursive: true });
+ writeFileSync(
+ join(cwd, '.codex', 'config.toml'),
+ stringifyToml({
+ mcp_servers: {
+ 'open-knowledge': {
+ ...publishedEntry(),
+ tools: { exec: { approval_mode: 'approve' } },
+ },
+ },
+ }),
+ );
+ expect(probeOwnManagedEditorMcpEntry('codex', cwd, home)).toEqual({
+ editorId: 'codex',
+ scope: 'project',
+ configPath: join(cwd, '.codex', 'config.toml'),
+ });
+ });
+
+ test('reads the codex TOML config on both scopes', () => {
+ const cwd = tmp();
+ const home = tmp();
+ mkdirSync(join(cwd, '.codex'), { recursive: true });
+ writeFileSync(
+ join(cwd, '.codex', 'config.toml'),
+ stringifyToml({ mcp_servers: { 'open-knowledge': publishedEntry() } }),
+ );
+ expect(probeOwnManagedEditorMcpEntry('codex', cwd, home)).toEqual({
+ editorId: 'codex',
+ scope: 'project',
+ configPath: join(cwd, '.codex', 'config.toml'),
+ });
+
+ const cwd2 = tmp();
+ mkdirSync(join(home, '.codex'), { recursive: true });
+ writeFileSync(
+ join(home, '.codex', 'config.toml'),
+ stringifyToml({ mcp_servers: { 'open-knowledge': publishedEntry() } }),
+ );
+ expect(probeOwnManagedEditorMcpEntry('codex', cwd2, home)).toEqual({
+ editorId: 'codex',
+ scope: 'user',
+ configPath: join(home, '.codex', 'config.toml'),
+ });
+ });
+
+ test('hits the cursor project config', () => {
+ const cwd = tmp();
+ const home = tmp();
+ writeJson(join(cwd, '.cursor', 'mcp.json'), {
+ mcpServers: { 'open-knowledge': publishedEntry() },
+ });
+ expect(probeOwnManagedEditorMcpEntry('cursor', cwd, home)?.scope).toBe('project');
+ });
+
+ test('version-proof: hits a future chain body carrying the ok-mcp marker', () => {
+ const cwd = tmp();
+ const home = tmp();
+ // A hypothetical bumped chain (`# ok-mcp-v2`) an existing install would
+ // carry after we ship a new CHAIN — must still count as ours, or the
+ // duplicate-injection collision resurfaces until everyone re-runs `ok init`.
+ writeJson(join(cwd, '.mcp.json'), {
+ mcpServers: {
+ 'open-knowledge': { command: '/bin/sh', args: ['-l', '-c', '# ok-mcp-v2\nexec foo mcp'] },
+ },
+ });
+ expect(probeOwnManagedEditorMcpEntry('claude', cwd, home)?.scope).toBe('project');
+ });
+
+ test('misses an explicitly disabled same-named entry (harness will not load it)', () => {
+ const cwd = tmp();
+ const home = tmp();
+ writeJson(join(cwd, '.mcp.json'), {
+ mcpServers: { 'open-knowledge': { ...publishedEntry(), enabled: false } },
+ });
+ expect(probeOwnManagedEditorMcpEntry('claude', cwd, home)).toBeNull();
+ });
+
+ test('opencode: hits the enabled published envelope, misses disabled/foreign', () => {
+ const cwd = tmp();
+ const home = tmp();
+ writeJson(join(cwd, 'opencode.json'), {
+ mcp: { 'open-knowledge': openCodePublished() },
+ });
+ expect(probeOwnManagedEditorMcpEntry('opencode', cwd, home)).toEqual({
+ editorId: 'opencode',
+ scope: 'project',
+ configPath: join(cwd, 'opencode.json'),
+ });
+
+ // Disabled entry means the harness will NOT load it — keep injecting.
+ writeJson(join(cwd, 'opencode.json'), {
+ mcp: { 'open-knowledge': { ...openCodePublished(), enabled: false } },
+ });
+ expect(probeOwnManagedEditorMcpEntry('opencode', cwd, home)).toBeNull();
+
+ // Chain-shape (split command/args) inside opencode's config is foreign.
+ writeJson(join(cwd, 'opencode.json'), {
+ mcp: { 'open-knowledge': publishedEntry() },
+ });
+ expect(probeOwnManagedEditorMcpEntry('opencode', cwd, home)).toBeNull();
+ });
+});
+
+describe('entryRunsOwnManagedServer', () => {
+ test('matches OK chain shapes by marker, ignoring policy siblings', () => {
+ expect(entryRunsOwnManagedServer(publishedEntry())).toBe(true);
+ // Version bump: a future body still carries the stable marker → hit.
+ expect(
+ entryRunsOwnManagedServer({ command: '/bin/sh', args: ['-l', '-c', '# ok-mcp-v9\nexec x'] }),
+ ).toBe(true);
+ // Windows chain shape.
+ expect(
+ entryRunsOwnManagedServer({
+ command: 'powershell',
+ args: ['-NoProfile', '-NonInteractive', '-Command', '# ok-mcp-win-v1\nexit 0'],
+ }),
+ ).toBe(true);
+ // Churny/benign siblings don't change what runs → hit.
+ expect(entryRunsOwnManagedServer({ ...publishedEntry(), env: { X: '1' } })).toBe(true);
+ expect(
+ entryRunsOwnManagedServer({
+ ...publishedEntry(),
+ tools: { exec: { approval_mode: 'approve' } },
+ }),
+ ).toBe(true);
+ });
+
+ test('misses disabled, foreign, and non-chain entries', () => {
+ // Explicitly disabled → the harness will not load it → inject.
+ expect(entryRunsOwnManagedServer({ ...publishedEntry(), enabled: false })).toBe(false);
+ // Right interpreter + flags but a body without the marker → foreign.
+ expect(entryRunsOwnManagedServer({ command: '/bin/sh', args: ['-l', '-c', 'rm -rf /'] })).toBe(
+ false,
+ );
+ // Foreign interpreter → miss.
+ expect(entryRunsOwnManagedServer({ command: 'evil', args: [] })).toBe(false);
+ // Wrong flag prefix even with the marker in the body → miss.
+ expect(entryRunsOwnManagedServer({ command: '/bin/sh', args: ['-c', '# ok-mcp-v1'] })).toBe(
+ false,
+ );
+ expect(entryRunsOwnManagedServer(null)).toBe(false);
+ });
+});
+
+describe('openCodeEntryRunsOwnManagedServer', () => {
+ test('matches on identity (type + enabled + argv), ignoring policy siblings', () => {
+ expect(openCodeEntryRunsOwnManagedServer(openCodePublished())).toBe(true);
+ // enabled: false → the harness will not load it → does not cover us.
+ expect(openCodeEntryRunsOwnManagedServer({ ...openCodePublished(), enabled: false })).toBe(
+ false,
+ );
+ // An extra `environment` sibling doesn't change which server runs → hit.
+ expect(
+ openCodeEntryRunsOwnManagedServer({ ...openCodePublished(), environment: { X: '1' } }),
+ ).toBe(true);
+ // Foreign argv → miss.
+ expect(
+ openCodeEntryRunsOwnManagedServer({
+ type: 'local',
+ enabled: true,
+ command: ['/bin/sh', '-c', 'x'],
+ }),
+ ).toBe(false);
+ // Chain-shape (wrong envelope) → miss.
+ expect(openCodeEntryRunsOwnManagedServer(buildManagedServerEntry({ mode: 'published' }))).toBe(
+ false,
+ );
+ expect(openCodeEntryRunsOwnManagedServer(null)).toBe(false);
+ });
+});
diff --git a/packages/cli/src/commands/acp-harness-probe.ts b/packages/cli/src/commands/acp-harness-probe.ts
new file mode 100644
index 000000000..da40009ca
--- /dev/null
+++ b/packages/cli/src/commands/acp-harness-probe.ts
@@ -0,0 +1,73 @@
+/**
+ * ACP-thread duplicate-injection guard — the CLI-side probe behind the
+ * thread manager's `probeHarnessManagedMcpEntry` seam.
+ *
+ * ACP agents spawn with the project as cwd, so an agent's harness (Claude
+ * Code, Codex, Cursor, OpenCode) ALSO loads its own project/user MCP config
+ * — the very files `ok init` / the Desktop consent flow write. Both copies
+ * claim the `open-knowledge` server name, and harnesses resolve that
+ * collision in their own favor (verified with Codex: its config entry
+ * shadows the ACP-injected server). This probe reports whether the harness
+ * will already load OK's OWN managed entry, so the thread manager can skip
+ * injecting a colliding duplicate.
+ *
+ * Match discipline is FUNCTIONAL, not exact (`entryRunsOwnManagedServer` /
+ * `openCodeEntryRunsOwnManagedServer`): we stand down when the harness entry
+ * would launch OK's own server — its `command`+`args` (or OpenCode argv) are
+ * OK's canonical chain — regardless of harness policy siblings like Codex's
+ * `tools.<name>.approval_mode`, which churns as the user approves tools
+ * mid-session. A foreign or tampered `command`/`args` still fails and
+ * injection proceeds, and every other miss (absent file, unparseable config,
+ * dev-shape entry) falls back to injection, i.e. prior behavior. This is a
+ * looser gate than the docked-terminal pre-approval's `isOwnManagedEntry` on
+ * purpose — see `entryRunsOwnManagedServer` for why the risk is inverted.
+ *
+ * Project surfaces are probed at exactly `<cwd>/…` — no upward walk. A
+ * harness that discovers a config higher up (Claude Code walks toward the
+ * repo root) simply keeps the injected duplicate in that layout:
+ * conservative in the safe direction.
+ */
+import {
+ EDITOR_TARGETS,
+ type EditorId,
+ entryRunsOwnManagedServer,
+ openCodeEntryRunsOwnManagedServer,
+} from './editors.ts';
+import { readExistingMcpEntry } from './init.ts';
+
+export interface OwnManagedMcpEntryHit {
+ editorId: EditorId;
+ scope: 'project' | 'user';
+ configPath: string;
+}
+
+/**
+ * Whether `editorId`'s project-local (probed first) or user-global MCP
+ * config already carries OK's own canonical managed entry. Never throws —
+ * unresolvable paths and unreadable configs count as misses.
+ */
+export function probeOwnManagedEditorMcpEntry(
+ editorId: EditorId,
+ cwd: string,
+ home?: string,
+): OwnManagedMcpEntryHit | null {
+ const target = EDITOR_TARGETS[editorId];
+ const runsOwnServer =
+ editorId === 'opencode' ? openCodeEntryRunsOwnManagedServer : entryRunsOwnManagedServer;
+ const surfaces: Array<{ scope: 'project' | 'user'; configPath: string }> = [];
+ const projectPath = target.projectConfigPath?.(cwd);
+ if (projectPath !== undefined) surfaces.push({ scope: 'project', configPath: projectPath });
+ try {
+ surfaces.push({ scope: 'user', configPath: target.configPath(cwd, home) });
+ } catch {
+ // Platform-unavailable user config (e.g. Claude Desktop off macOS/Windows)
+ // — keep whatever project surface exists.
+ }
+ for (const surface of surfaces) {
+ const entry = readExistingMcpEntry(target, cwd, home, surface.configPath);
+ if (entry !== null && runsOwnServer(entry)) {
+ return { editorId, scope: surface.scope, configPath: surface.configPath };
+ }
+ }
+ return null;
+}
diff --git a/packages/cli/src/commands/editors.ts b/packages/cli/src/commands/editors.ts
index bd5eca842..23a379222 100644
--- a/packages/cli/src/commands/editors.ts
+++ b/packages/cli/src/commands/editors.ts
@@ -107,6 +107,19 @@ exit 127`;
/** @internal */
export const CHAIN_WIN_VERSION_SENTINEL = '# ok-mcp-win-v1';
+/**
+ * Version- and platform-agnostic prefix shared by every OK managed chain body
+ * (`# ok-mcp-v1`, `# ok-mcp-win-v1`, and any future `-v2`/`-win-v2`). The ACP
+ * injection-skip predicates key on THIS rather than a specific sentinel or the
+ * exact CHAIN bytes, so a chain version bump can't make already-installed
+ * harness entries look foreign — that would resurface the duplicate-injection
+ * name collision until every user re-ran `ok init`. A foreign `sh -c` script
+ * won't carry it. `@internal` — same non-re-export rule as the sentinels.
+ */
+/** @internal — used only within this module (no importer); keep unexported so
+ * knip does not flag it, per the same non-re-export rule as the sentinels. */
+const OK_MCP_CHAIN_MARKER = '# ok-mcp';
+
/**
* Resilient chain (win v1) — the Windows member of the two-shape canonical
* set. `powershell -NoProfile -NonInteractive -Command CHAIN_WIN_V1` resolves
@@ -489,8 +502,22 @@ function matchesCanonicalExactly(
): boolean {
// Exactly the canonical key set — any extra field (e.g. an injected `env`
// on the Unix shape) means it is not OK's own entry, so refuse. Key-count
- // equality plus the per-key checks below pin the exact set.
+ // equality plus the command/args identity check pin the exact set.
if (Object.keys(e).length !== Object.keys(canonical).length) return false;
+ return commandArgsMatchCanonical(e, canonical);
+}
+
+/**
+ * The `command` + `args` of `e` equal the canonical chain's — the pair that
+ * fully determines which process a chain-shape MCP entry spawns. Says nothing
+ * about OTHER keys the entry may carry; callers decide whether extras matter
+ * (`matchesCanonicalExactly` layers a key-count check on top for the exact
+ * security gate; `entryRunsOwnManagedServer` does not).
+ */
+function commandArgsMatchCanonical(
+ e: Record<string, unknown>,
+ canonical: Record<string, unknown>,
+): boolean {
if (e.command !== canonical.command) return false;
// `canonical` is OK's own output, but `buildManagedServerEntry` is typed
// `Record<string, unknown>`; narrow with `Array.isArray` rather than an
@@ -502,6 +529,80 @@ function matchesCanonicalExactly(
return e.args.every((v, i) => v === canonicalArgs[i]);
}
+/**
+ * True iff a chain argv (`['/bin/sh','-l','-c',body]` or the PowerShell
+ * equivalent) launches OK's managed server — the flag prefix is OK's shape and
+ * `body` carries the {@link OK_MCP_CHAIN_MARKER}. `offset` is where the argv
+ * begins in the array: `0` for a split `command`/`args` entry passed its
+ * `args`, but OpenCode inlines the interpreter as `command[0]`, so it passes
+ * the whole `command` argv with the flags one slot later.
+ */
+function chainArgvRunsOwnManagedServer(argv: unknown[], interpreter: string): boolean {
+ const bodyIsOk = (body: unknown): boolean =>
+ typeof body === 'string' && body.includes(OK_MCP_CHAIN_MARKER);
+ if (interpreter === '/bin/sh') {
+ return argv[0] === '-l' && argv[1] === '-c' && bodyIsOk(argv[2]);
+ }
+ if (interpreter === 'powershell') {
+ return (
+ argv[0] === '-NoProfile' &&
+ argv[1] === '-NonInteractive' &&
+ argv[2] === '-Command' &&
+ bodyIsOk(argv[3])
+ );
+ }
+ return false;
+}
+
+/**
+ * Injection-skip predicate for the ACP thread manager — a FUNCTIONAL sibling
+ * of {@link isOwnManagedEntry}, not a security one. True iff `entry` would
+ * launch OK's own managed server: it is a chain-shape entry (`/bin/sh -l -c`
+ * or `powershell …`) whose body carries the {@link OK_MCP_CHAIN_MARKER}. It
+ * keys on the stable marker, NOT the exact CHAIN bytes, so a chain version
+ * bump doesn't make installed entries look foreign. Every non-identity key is
+ * ignored — Codex's `tools.<name>.approval_mode` (which parses to a `tools`
+ * key and CHURNS as the user approves/denies tools mid-session), an `env`
+ * overlay, timeout knobs — those are harness metadata about how to TREAT the
+ * server, not what process it runs. An explicit `enabled: false` is the one
+ * sibling that means "the harness will NOT load it", so it does not cover us
+ * and we still inject.
+ *
+ * Deliberately distinct from `isOwnManagedEntry`, which stays EXACT because it
+ * gates the docked-terminal pre-approval — auto-running a server without the
+ * trust prompt is RCE-class, so any extra/tampered key there must fail. The
+ * risk here is inverted and mild: the probe only READS the config to decide
+ * whether to skip injecting a duplicate; the harness runs its own entry
+ * regardless, and it wins the `open-knowledge` name collision either way (a
+ * same-named injected server is shadowed). So a permissive match can only ever
+ * avoid a redundant duplicate — it can never hand the agent a foreign server,
+ * because a foreign body lacks the marker and injection proceeds.
+ */
+export function entryRunsOwnManagedServer(entry: unknown): boolean {
+ if (typeof entry !== 'object' || entry === null) return false;
+ const e = entry as Record<string, unknown>;
+ if (e.enabled === false) return false;
+ if (typeof e.command !== 'string' || !Array.isArray(e.args)) return false;
+ return chainArgvRunsOwnManagedServer(e.args, e.command);
+}
+
+/**
+ * OpenCode sibling of {@link entryRunsOwnManagedServer}. OpenCode's envelope is
+ * `{type: 'local', enabled, command: [interpreter, ...argv]}` — the chain is
+ * ONE argv with the interpreter at `command[0]`, not a split `command`/`args`.
+ * True iff `type: 'local'`, not explicitly disabled, and that argv launches
+ * OK's managed server (marker in the body). Other keys (e.g. `environment`)
+ * are ignored — same functional-not-exact, version-proof rationale.
+ */
+export function openCodeEntryRunsOwnManagedServer(entry: unknown): boolean {
+ if (typeof entry !== 'object' || entry === null) return false;
+ const e = entry as Record<string, unknown>;
+ if (e.type !== 'local' || e.enabled === false) return false;
+ if (!Array.isArray(e.command)) return false;
+ const [interpreter, ...argv] = e.command;
+ return typeof interpreter === 'string' && chainArgvRunsOwnManagedServer(argv, interpreter);
+}
+
export interface AppSupportOptions {
home?: string;
platformName?: NodeJS.Platform;
diff --git a/packages/cli/src/commands/start.test.ts b/packages/cli/src/commands/start.test.ts
index 7d435c651..0d5c6b501 100644
--- a/packages/cli/src/commands/start.test.ts
+++ b/packages/cli/src/commands/start.test.ts
@@ -1,4 +1,3 @@
-import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
import type { spawn as NativeSpawn } from 'node:child_process';
import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
import { mkdtemp, rm } from 'node:fs/promises';
@@ -8,6 +7,7 @@ import { join, resolve } from 'node:path';
import { setTimeout as wait } from 'node:timers/promises';
import { LOCAL_DIR } from '@inkeep/open-knowledge-core';
import { type Config, ConfigSchema } from '@inkeep/open-knowledge-server';
+import { afterEach, beforeEach, describe, expect, test } from 'vitest';
import {
awaitUiSiblingPort,
type BootedStartServer,
@@ -185,6 +185,7 @@ describe('buildIdleShutdownHandler', () => {
let alive = true;
const onShutdown = buildIdleShutdownHandler({
readUiLock: () => ({ pid: 1234, port: 3000 }),
+ spawnedUiPid: () => 1234,
isAlive: () => alive,
killPid: (pid, sig) => {
events.push(`kill:${pid}:${sig}`);
@@ -207,6 +208,7 @@ describe('buildIdleShutdownHandler', () => {
const warned: object[] = [];
const onShutdown = buildIdleShutdownHandler({
readUiLock: () => ({ pid: 1234, port: 3000 }),
+ spawnedUiPid: () => 1234,
isAlive: () => true,
killPid: (pid, sig) => {
events.push(`kill:${pid}:${sig}`);
@@ -232,6 +234,7 @@ describe('buildIdleShutdownHandler', () => {
const events: string[] = [];
const onShutdown = buildIdleShutdownHandler({
readUiLock: () => null,
+ spawnedUiPid: () => 1234,
isAlive: () => true,
killPid: (pid, sig) => events.push(`kill:${pid}:${sig}`),
destroy: async () => {
@@ -246,6 +249,7 @@ describe('buildIdleShutdownHandler', () => {
const events: string[] = [];
const onShutdown = buildIdleShutdownHandler({
readUiLock: () => ({ pid: 4242, port: 3000 }),
+ spawnedUiPid: () => 4242,
isAlive: () => false,
killPid: (pid, sig) => events.push(`kill:${pid}:${sig}`),
destroy: async () => {
@@ -261,6 +265,7 @@ describe('buildIdleShutdownHandler', () => {
const warned: object[] = [];
const onShutdown = buildIdleShutdownHandler({
readUiLock: () => ({ pid: 4242, port: 3000 }),
+ spawnedUiPid: () => 4242,
isAlive: () => true,
killPid: () => {
throw new Error('EPERM');
@@ -285,6 +290,7 @@ describe('buildIdleShutdownHandler', () => {
readUiLock: () => {
throw new Error('lock read failed');
},
+ spawnedUiPid: () => null,
isAlive: () => true,
killPid: () => {},
destroy: async () => {
@@ -295,6 +301,49 @@ describe('buildIdleShutdownHandler', () => {
await onShutdown();
expect(events).toEqual(['destroy']);
});
+
+ test('leaves a live ui.lock holder alone when this process spawned no sibling', async () => {
+ // The incident shape: a stale server goes WS-idle while a desktop-spawned
+ // server (which advertises ITS OWN pid in ui.lock while serving the React
+ // shell) is live with active clients. The stale server must not kill it.
+ const events: string[] = [];
+ const infos: object[] = [];
+ const onShutdown = buildIdleShutdownHandler({
+ readUiLock: () => ({ pid: 52425, port: 64430 }),
+ spawnedUiPid: () => null,
+ isAlive: () => true,
+ killPid: (pid, sig) => events.push(`kill:${pid}:${sig}`),
+ destroy: async () => {
+ events.push('destroy');
+ },
+ log: {
+ info: (obj) => infos.push(obj),
+ warn: () => {},
+ error: () => {},
+ },
+ });
+ await onShutdown();
+ expect(events).toEqual(['destroy']);
+ expect(infos.find((entry) => (entry as { pid?: number }).pid === 52425)).toBeDefined();
+ });
+
+ test('leaves a live ui.lock holder alone when it is not the spawned sibling', async () => {
+ // Our spawned sibling died and another process now holds the lock (or the
+ // lock was rewritten by a newer session). Not ours — leave it alone.
+ const events: string[] = [];
+ const onShutdown = buildIdleShutdownHandler({
+ readUiLock: () => ({ pid: 9999, port: 3000 }),
+ spawnedUiPid: () => 1234,
+ isAlive: () => true,
+ killPid: (pid, sig) => events.push(`kill:${pid}:${sig}`),
+ destroy: async () => {
+ events.push('destroy');
+ },
+ log: { info: () => {}, warn: () => {}, error: () => {} },
+ });
+ await onShutdown();
+ expect(events).toEqual(['destroy']);
+ });
});
describe('spawnOkUi', () => {
diff --git a/packages/cli/src/commands/start.ts b/packages/cli/src/commands/start.ts
index 368db5f98..1a6ae2626 100644
--- a/packages/cli/src/commands/start.ts
+++ b/packages/cli/src/commands/start.ts
@@ -43,6 +43,7 @@ import { makeLazyEmbeddingsKeyStore } from '../auth/embeddings-key-store.ts';
import { detectGh } from '../auth/gh-detect.ts';
import { makeLazyProbeTokenStore } from '../auth/token-store.ts';
import { OK_DIR, PACKAGE_VERSION } from '../constants.ts';
+import { probeOwnManagedEditorMcpEntry } from './acp-harness-probe.ts';
import {
createRealDetectDeps,
detectDesktop,
@@ -389,6 +390,16 @@ export async function awaitUiSiblingPort(deps: AwaitUiSiblingPortInput): Promise
interface BuildIdleShutdownHandlerInput {
readUiLock: () => { pid: number; port: number } | null;
+ /**
+ * Pid of the `ok ui` child THIS process spawned, or null when it spawned
+ * none (sibling reused, auto-spawn skipped, or desktop single-origin mode).
+ * The idle handler only ever signals this pid — `ui.lock` is advertisement,
+ * not ownership: a desktop-spawned server serving the React shell holds it
+ * with its OWN pid, and a stale server blindly killing the lock holder was
+ * exactly how a live server (active ACP threads, MCP sessions, keepalive)
+ * got SIGTERMed mid-session.
+ */
+ spawnedUiPid: () => number | null;
isAlive: (pid: number) => boolean;
killPid: (pid: number, signal: NodeJS.Signals) => void;
destroy: () => Promise<void>;
@@ -417,7 +428,10 @@ const DEFAULT_SIGTERM_POLL_MS = SHARED_DEFAULT_SIGTERM_POLL_MS;
/**
* Build the idle-shutdown `onShutdown` closure. On fire:
- * (1) look up `ui.lock`; SIGTERM the sibling if it's still alive;
+ * (1) look up `ui.lock`; SIGTERM the sibling if it's still alive AND it is
+ * the pid this process spawned (`spawnedUiPid`) — a live holder we did
+ * not spawn is left alone (see the field's docstring for the incident
+ * class this prevents);
* (2) poll its liveness up to `sigtermGraceMs` (default 10s);
* (3) if still alive after the grace window, escalate to SIGKILL;
* (4) await `destroy()`, which releases `server.lock` as its final step.
@@ -551,7 +565,17 @@ export function buildIdleShutdownHandler(
return async () => {
try {
const lock = input.readUiLock();
- if (lock && input.isAlive(lock.pid)) {
+ const ownPid = input.spawnedUiPid();
+ if (lock && input.isAlive(lock.pid) && lock.pid !== ownPid) {
+ // The lock holder is alive but is NOT the sibling we spawned — a
+ // desktop-spawned server advertising its shell, or another session's
+ // UI. It is not ours to kill; it has its own lifecycle (idle-shutdown
+ // or the `ok ui` 12h safety net).
+ input.log?.info(
+ { pid: lock.pid, port: lock.port, spawnedUiPid: ownPid },
+ 'idle-shutdown: ui.lock holder is not our spawned sibling — leaving it alone',
+ );
+ } else if (lock && input.isAlive(lock.pid)) {
try {
input.killPid(lock.pid, 'SIGTERM');
input.log?.info({ pid: lock.pid, port: lock.port }, 'idle-shutdown: SIGTERM UI sibling');
@@ -903,6 +927,9 @@ export async function bootStartServer(opts: BootStartServerOptions): Promise<Boo
// Capture uiSpawnDecision from inside the spawnUiSiblingFn callback so we
// can return it on the BootedStartServer handle for tests + status output.
let uiSpawnDecision: UiSpawnDecision | null = null;
+ // Pid of the `ok ui` child this boot actually spawned — the ONLY pid the
+ // idle-shutdown handler may signal. Stays null on reuse/skip paths.
+ let spawnedUiPid: number | null = null;
const spawnUiSiblingFn = async ({
lockDir: resolvedLockDir,
}: {
@@ -922,7 +949,13 @@ export async function bootStartServer(opts: BootStartServerOptions): Promise<Boo
// `ok start` keeps kernel-allocated sibling ports.
const uiArgs =
opts.uiPort !== undefined ? ['ui', '--port', String(opts.uiPort)] : undefined;
- spawnOkUi({ lockDir: resolvedLockDir, cwd, spawn: opts.spawn, args: uiArgs });
+ const uiChild = spawnOkUi({
+ lockDir: resolvedLockDir,
+ cwd,
+ spawn: opts.spawn,
+ args: uiArgs,
+ });
+ spawnedUiPid = uiChild.pid ?? null;
log.info(
{ reason: uiSpawnDecision.reason, uiPort: opts.uiPort },
'[start] auto-spawned ok ui sibling',
@@ -1021,6 +1054,10 @@ export async function bootStartServer(opts: BootStartServerOptions): Promise<Boo
// Pass the exact runtime that started this server so /api/local-op/* can
// spawn additional CLI processes without needing open-knowledge on PATH.
localOpCliArgs: [process.execPath, process.argv[1]],
+ // ACP threads skip injecting the `open-knowledge` MCP server when the
+ // agent's own harness already loads OK's managed editor-config entry.
+ probeHarnessManagedMcpEntry: (editorId, agentCwd) =>
+ probeOwnManagedEditorMcpEntry(editorId, agentCwd),
// CLI-specific opt-ins
attachUiSibling,
idleShutdownMs: idleThresholdMs,
@@ -1029,6 +1066,7 @@ export async function bootStartServer(opts: BootStartServerOptions): Promise<Boo
idleShutdownHandler: (destroyServer) => {
const handler = buildIdleShutdownHandler({
readUiLock: () => readUiLock(booted.lockDir),
+ spawnedUiPid: () => spawnedUiPid,
isAlive: isProcessAlive,
killPid: (pid, signal) => {
process.kill(pid, signal);
diff --git a/packages/cli/src/index.ts b/packages/cli/src/index.ts
index 1849b1d0a..618c2e82d 100644
--- a/packages/cli/src/index.ts
+++ b/packages/cli/src/index.ts
@@ -16,6 +16,12 @@ export {
makeLazyProbeTokenStore,
type TokenStore,
} from './auth/token-store.ts';
+// Desktop's utility process wires this into `bootServer()` as the ACP thread
+// manager's `probeHarnessManagedMcpEntry` seam (same wiring as `ok start`).
+export {
+ type OwnManagedMcpEntryHit,
+ probeOwnManagedEditorMcpEntry,
+} from './commands/acp-harness-probe.ts';
export {
type BundleExtraFile,
type BundleLogger,
diff --git a/packages/core/package.json b/packages/core/package.json
index fad28a6c9..41126e82e 100644
--- a/packages/core/package.json
+++ b/packages/core/package.json
@@ -34,6 +34,11 @@
"development": "./src/helper-bundle.ts",
"types": "./src/helper-bundle.ts",
"default": "./dist/helper-bundle.mjs"
+ },
+ "./acp/thread-protocol": {
+ "development": "./src/acp/thread-protocol.ts",
+ "types": "./src/acp/thread-protocol.ts",
+ "default": "./dist/acp-thread-protocol.mjs"
}
},
"files": [
@@ -41,6 +46,7 @@
"src"
],
"dependencies": {
+ "@agentclientprotocol/sdk": "^1.1.0",
"@handlewithcare/remark-prosemirror": "0.1.5",
"@opentelemetry/api": "^1.9.0",
"@orama/orama": "^3.1.18",
diff --git a/packages/core/src/acp/thread-protocol.test.ts b/packages/core/src/acp/thread-protocol.test.ts
new file mode 100644
index 000000000..94aa249a0
--- /dev/null
+++ b/packages/core/src/acp/thread-protocol.test.ts
@@ -0,0 +1,212 @@
+import { describe, expect, test } from 'vitest';
+import { parseThreadClientFrame } from './thread-protocol.ts';
+
+describe('parseThreadClientFrame', () => {
+ test('rejects non-JSON, non-object, and unknown ops', () => {
+ expect(parseThreadClientFrame('not json')).toBeNull();
+ expect(parseThreadClientFrame('42')).toBeNull();
+ expect(parseThreadClientFrame('null')).toBeNull();
+ expect(parseThreadClientFrame(JSON.stringify({ op: 'reboot' }))).toBeNull();
+ });
+
+ test('create requires reqId and a well-formed agent ref', () => {
+ expect(
+ parseThreadClientFrame(
+ JSON.stringify({ op: 'create', reqId: 'r1', agent: { source: 'registry', id: 'gemini' } }),
+ ),
+ ).toMatchObject({ op: 'create', reqId: 'r1' });
+ expect(
+ parseThreadClientFrame(
+ JSON.stringify({ op: 'create', agent: { source: 'registry', id: 'x' } }),
+ ),
+ ).toBeNull();
+ expect(
+ parseThreadClientFrame(
+ JSON.stringify({ op: 'create', reqId: 'r1', agent: { source: 'ftp', id: 'x' } }),
+ ),
+ ).toBeNull();
+ expect(
+ parseThreadClientFrame(
+ JSON.stringify({ op: 'create', reqId: 'r1', agent: { source: 'custom' } }),
+ ),
+ ).toBeNull();
+ });
+
+ test('prompt requires threadId, reqId, and string content (empty ok)', () => {
+ expect(
+ parseThreadClientFrame(
+ JSON.stringify({ op: 'prompt', threadId: 't', reqId: 'r', content: '' }),
+ ),
+ ).toMatchObject({ op: 'prompt' });
+ expect(
+ parseThreadClientFrame(JSON.stringify({ op: 'prompt', threadId: 't', reqId: 'r' })),
+ ).toBeNull();
+ });
+
+ test('permission_response validates the outcome union', () => {
+ expect(
+ parseThreadClientFrame(
+ JSON.stringify({
+ op: 'permission_response',
+ threadId: 't',
+ requestId: 'p',
+ outcome: { kind: 'selected', optionId: 'allow' },
+ }),
+ ),
+ ).toMatchObject({ op: 'permission_response' });
+ expect(
+ parseThreadClientFrame(
+ JSON.stringify({
+ op: 'permission_response',
+ threadId: 't',
+ requestId: 'p',
+ outcome: { kind: 'cancelled' },
+ }),
+ ),
+ ).toMatchObject({ outcome: { kind: 'cancelled' } });
+ expect(
+ parseThreadClientFrame(
+ JSON.stringify({
+ op: 'permission_response',
+ threadId: 't',
+ requestId: 'p',
+ outcome: { kind: 'selected' },
+ }),
+ ),
+ ).toBeNull();
+ });
+
+ test('runtime_consent_response validates the granted/declined outcome', () => {
+ expect(
+ parseThreadClientFrame(
+ JSON.stringify({
+ op: 'runtime_consent_response',
+ threadId: 't',
+ requestId: 'c',
+ outcome: { kind: 'granted', remember: true },
+ }),
+ ),
+ ).toMatchObject({
+ op: 'runtime_consent_response',
+ outcome: { kind: 'granted', remember: true },
+ });
+ expect(
+ parseThreadClientFrame(
+ JSON.stringify({
+ op: 'runtime_consent_response',
+ threadId: 't',
+ requestId: 'c',
+ outcome: { kind: 'declined' },
+ }),
+ ),
+ ).toMatchObject({ outcome: { kind: 'declined' } });
+ // Unknown outcome kind, non-boolean remember, and missing ids all reject.
+ expect(
+ parseThreadClientFrame(
+ JSON.stringify({
+ op: 'runtime_consent_response',
+ threadId: 't',
+ requestId: 'c',
+ outcome: { kind: 'maybe' },
+ }),
+ ),
+ ).toBeNull();
+ expect(
+ parseThreadClientFrame(
+ JSON.stringify({
+ op: 'runtime_consent_response',
+ threadId: 't',
+ requestId: 'c',
+ outcome: { kind: 'granted', remember: 'yes' },
+ }),
+ ),
+ ).toBeNull();
+ expect(
+ parseThreadClientFrame(
+ JSON.stringify({
+ op: 'runtime_consent_response',
+ threadId: 't',
+ outcome: { kind: 'granted' },
+ }),
+ ),
+ ).toBeNull();
+ });
+
+ test('subscribe accepts optional numeric sinceSeq only', () => {
+ expect(
+ parseThreadClientFrame(JSON.stringify({ op: 'subscribe', threadId: 't', sinceSeq: 4 })),
+ ).toMatchObject({ sinceSeq: 4 });
+ expect(
+ parseThreadClientFrame(JSON.stringify({ op: 'subscribe', threadId: 't', sinceSeq: 'x' })),
+ ).toBeNull();
+ });
+
+ test('resume requires threadId and reqId; prompt optional but string-typed', () => {
+ expect(
+ parseThreadClientFrame(JSON.stringify({ op: 'resume', threadId: 't', reqId: 'r' })),
+ ).toMatchObject({ op: 'resume', threadId: 't', reqId: 'r' });
+ expect(
+ parseThreadClientFrame(
+ JSON.stringify({ op: 'resume', threadId: 't', reqId: 'r', prompt: 'continue' }),
+ ),
+ ).toMatchObject({ prompt: 'continue' });
+ expect(parseThreadClientFrame(JSON.stringify({ op: 'resume', threadId: 't' }))).toBeNull();
+ expect(
+ parseThreadClientFrame(
+ JSON.stringify({ op: 'resume', threadId: 't', reqId: 'r', prompt: 7 }),
+ ),
+ ).toBeNull();
+ });
+
+ test('rename requires threadId and a non-empty title', () => {
+ expect(
+ parseThreadClientFrame(JSON.stringify({ op: 'rename', threadId: 't', title: 'New name' })),
+ ).toMatchObject({ op: 'rename', threadId: 't', title: 'New name' });
+ expect(parseThreadClientFrame(JSON.stringify({ op: 'rename', threadId: 't' }))).toBeNull();
+ expect(
+ parseThreadClientFrame(JSON.stringify({ op: 'rename', threadId: 't', title: '' })),
+ ).toBeNull();
+ expect(parseThreadClientFrame(JSON.stringify({ op: 'rename', title: 'x' }))).toBeNull();
+ });
+
+ test('delete requires threadId', () => {
+ expect(parseThreadClientFrame(JSON.stringify({ op: 'delete', threadId: 't' }))).toMatchObject({
+ op: 'delete',
+ threadId: 't',
+ });
+ expect(parseThreadClientFrame(JSON.stringify({ op: 'delete' }))).toBeNull();
+ });
+
+ test('set_config_option carries a string valueId or a boolean toggle', () => {
+ expect(
+ parseThreadClientFrame(
+ JSON.stringify({
+ op: 'set_config_option',
+ threadId: 't',
+ configId: 'model',
+ value: 'opus',
+ }),
+ ),
+ ).toMatchObject({ op: 'set_config_option', configId: 'model', value: 'opus' });
+ expect(
+ parseThreadClientFrame(
+ JSON.stringify({ op: 'set_config_option', threadId: 't', configId: 'web', value: true }),
+ ),
+ ).toMatchObject({ value: true });
+ expect(
+ parseThreadClientFrame(
+ JSON.stringify({ op: 'set_config_option', threadId: 't', configId: 'model', value: 3 }),
+ ),
+ ).toBeNull();
+ expect(
+ parseThreadClientFrame(
+ JSON.stringify({ op: 'set_config_option', threadId: 't', configId: 'model', value: '' }),
+ ),
+ ).toBeNull();
+ expect(
+ parseThreadClientFrame(
+ JSON.stringify({ op: 'set_config_option', threadId: 't', value: 'opus' }),
+ ),
+ ).toBeNull();
+ });
+});
diff --git a/packages/core/src/acp/thread-protocol.ts b/packages/core/src/acp/thread-protocol.ts
new file mode 100644
index 000000000..7fb6f19fb
--- /dev/null
+++ b/packages/core/src/acp/thread-protocol.ts
@@ -0,0 +1,424 @@
+/**
+ * Wire protocol for the `/collab/thread` WebSocket — the transport between
+ * the server-hosted ACP thread manager and the app's thread UI.
+ *
+ * Shared between `packages/server` (producer) and `packages/app` (consumer);
+ * lives in core so both sides compile against one contract. ACP payloads
+ * (`SessionUpdate`, permission options, content blocks) pass through as the
+ * SDK's own generated types — imported TYPE-ONLY so no SDK runtime code
+ * reaches the browser bundle.
+ *
+ * Delivery contract: every thread event carries a per-thread monotonically
+ * increasing `seq`. The server retains a bounded in-memory event log per
+ * thread; `subscribe` with `sinceSeq` replays the retained tail and then
+ * streams live. A reconnecting client re-subscribes with its last-seen seq —
+ * the same recovery shape the CRDT layer's "durable truth + live push"
+ * channels use, without a second HTTP surface.
+ */
+
+import type {
+ ContentBlock,
+ PermissionOption,
+ SessionConfigOption,
+ SessionModeState,
+ SessionUpdate,
+ StopReason,
+ ToolCallUpdate,
+} from '@agentclientprotocol/sdk';
+
+/**
+ * Lifecycle of a server-hosted agent thread. `awaiting_permission` is
+ * `running` refined: the turn is parked on a permission prompt, so the tab
+ * strip can show "blocked on you" instead of a generic spinner. Terminal
+ * failures always win over it — a dead turn's stale prompt must never read
+ * as still inviting approval.
+ */
+export type ThreadStatus =
+ | 'installing'
+ | 'spawning'
+ | 'ready'
+ | 'auth_required'
+ | 'running'
+ | 'awaiting_permission'
+ | 'exited'
+ | 'error';
+
+/** Runtimes OK can download on demand to launch an agent (see `managed-runtime.ts`). */
+export type ManagedRuntimeKind = 'node' | 'uv';
+
+/** Agent identity as the catalog + thread UI render it. */
+export interface ThreadAgentInfo {
+ /** Registry manifest id (or custom-agent id). */
+ id: string;
+ /** Display name ("Claude Agent", "Gemini CLI"). */
+ name: string;
+ /** SVG icon URL from the registry manifest, when available. */
+ iconUrl?: string;
+ /** 'registry' manifest or user-configured 'custom' entry. */
+ source: 'registry' | 'custom';
+}
+
+/** Snapshot metadata for one thread (tab strip + thread header). */
+export interface ThreadInfo {
+ threadId: string;
+ agent: ThreadAgentInfo;
+ title: string;
+ status: ThreadStatus;
+ createdAt: number;
+ lastActivityAt: number;
+ /** Present once the agent advertised modes (Ask / Architect / Code …). */
+ modes?: SessionModeState | null;
+ /**
+ * Present once the agent advertised session config options — the
+ * generalized selector surface (model picker, thought level, …). The
+ * array is the agent's authoritative current state; each
+ * `config_option_update` / set response replaces it wholesale.
+ */
+ configOptions?: SessionConfigOption[] | null;
+ /** Last event seq in the server's retained log (replay upper bound). */
+ lastSeq: number;
+ /**
+ * The thread's agent process is gone but its transcript is retained on
+ * disk (`.ok/local/threads/`). Archived threads are listed, viewable via
+ * `subscribe` (replayed from disk), resumable via `resume`, and deletable
+ * via `delete`. Optional on the wire for version skew — servers always set
+ * it; clients treat absence as `false`.
+ */
+ archived?: boolean;
+}
+
+/** One entry in a thread's event log. */
+export type ThreadEvent =
+ | { kind: 'user_message'; content: string; ts: number }
+ | { kind: 'session_update'; update: SessionUpdate; ts: number }
+ | {
+ kind: 'permission_request';
+ requestId: string;
+ toolCall: ToolCallUpdate;
+ options: PermissionOption[];
+ ts: number;
+ }
+ | {
+ kind: 'permission_resolved';
+ requestId: string;
+ /** Chosen optionId, or null when cancelled/auto-rejected. */
+ optionId: string | null;
+ /** True when policy resolved it without asking the user. */
+ auto: boolean;
+ ts: number;
+ }
+ | { kind: 'turn_started'; ts: number }
+ | { kind: 'turn_ended'; stopReason: StopReason; ts: number }
+ | { kind: 'status'; status: ThreadStatus; detail?: string; ts: number }
+ | { kind: 'title_changed'; title: string; ts: number }
+ | { kind: 'agent_stderr'; line: string; ts: number }
+ | {
+ /**
+ * The agent's launch needs an interpreter (npx/uvx) the machine lacks;
+ * OK offers to download a private, pinned copy. The thread is parked
+ * until the user answers with a `runtime_consent_response` frame (or the
+ * request times out). Retained + replayed like `permission_request`, so
+ * a client that subscribes after it was emitted still sees the prompt.
+ */
+ kind: 'runtime_consent_request';
+ requestId: string;
+ runtime: ManagedRuntimeKind;
+ /** Human runtime name — "Node.js" / "uv". */
+ displayName: string;
+ /** The interpreter it unlocks — "npx" / "uvx". */
+ provides: string;
+ version: string;
+ /** Approximate download size (MB) for the disclosure. */
+ approxSizeMB: number;
+ /** Download host ("nodejs.org"), so the user sees where bytes come from. */
+ sourceHost: string;
+ /** The agent whose launch is blocked on this decision. */
+ agentName: string;
+ ts: number;
+ }
+ | {
+ kind: 'runtime_consent_resolved';
+ requestId: string;
+ /** `timeout` when nobody answered before the launch gave up. */
+ decision: 'granted' | 'declined' | 'timeout';
+ ts: number;
+ }
+ | {
+ /** Download/verify/extract progress while a consented runtime installs. */
+ kind: 'runtime_install_progress';
+ runtime: ManagedRuntimeKind;
+ phase: 'downloading' | 'verifying' | 'extracting';
+ receivedBytes?: number;
+ totalBytes?: number;
+ ts: number;
+ }
+ | {
+ /**
+ * The agent ran a command through the ACP terminal surface (OK executes
+ * it; the agent embeds the terminal in a tool call by id). Emitted at
+ * spawn so the transcript can show the command line even before any
+ * output arrives.
+ */
+ kind: 'terminal_created';
+ terminalId: string;
+ command: string;
+ args: string[];
+ ts: number;
+ }
+ | {
+ /** A chunk of combined stdout+stderr from a terminal OK is running. */
+ kind: 'terminal_output';
+ terminalId: string;
+ chunk: string;
+ ts: number;
+ }
+ | {
+ /** The terminal's command finished (or was killed). */
+ kind: 'terminal_exit';
+ terminalId: string;
+ /** Process exit code; null when terminated by signal. */
+ exitCode: number | null;
+ /** Terminating signal; null on a normal exit. */
+ signal: string | null;
+ ts: number;
+ };
+
+/** Client → server frames. */
+export type ThreadClientFrame =
+ | {
+ op: 'create';
+ /** Echoed on the matching `created` / `error` response frame. */
+ reqId: string;
+ agent: { source: 'registry' | 'custom'; id: string };
+ /** Optional first prompt, sent as soon as the session is ready. */
+ prompt?: string;
+ /** Optional doc context: extension-less docName the launch came from. */
+ docName?: string;
+ /**
+ * The user's raw typed text (create brief / instruction), carried
+ * separately from `prompt` so the thread title derives from it rather
+ * than from the composed launch prompt — which opens with a fixed
+ * handoff preamble that would otherwise become every tab's label.
+ * Absent for bare launches (no typed text); the server falls back to
+ * deriving from `prompt`.
+ */
+ titleHint?: string;
+ }
+ | { op: 'subscribe'; threadId: string; sinceSeq?: number }
+ | { op: 'unsubscribe'; threadId: string }
+ | { op: 'prompt'; threadId: string; reqId: string; content: string }
+ | {
+ op: 'permission_response';
+ threadId: string;
+ requestId: string;
+ outcome: { kind: 'selected'; optionId: string } | { kind: 'cancelled' };
+ }
+ | { op: 'cancel'; threadId: string }
+ | {
+ /**
+ * Answer a `runtime_consent_request`: allow (or refuse) OK to download
+ * the managed runtime a blocked launch needs. `remember` persists the
+ * decision for future launches on this machine.
+ */
+ op: 'runtime_consent_response';
+ threadId: string;
+ requestId: string;
+ outcome: { kind: 'granted'; remember?: boolean } | { kind: 'declined'; remember?: boolean };
+ }
+ | { op: 'set_mode'; threadId: string; modeId: string }
+ | {
+ op: 'set_config_option';
+ threadId: string;
+ configId: string;
+ /** Select options carry the chosen valueId; boolean options a toggle. */
+ value: string | boolean;
+ }
+ | { op: 'close'; threadId: string }
+ | {
+ /**
+ * Manually retitle a thread (tab rename). Works on live and archived
+ * threads; the server clamps the title and confirms via an `info`
+ * frame (plus a `title_changed` transcript event).
+ */
+ op: 'rename';
+ threadId: string;
+ title: string;
+ }
+ | {
+ /**
+ * Resume an archived thread: respawn its agent and continue the same
+ * ACP session (`session/resume` preferred, `session/load` fallback).
+ * Responds with `resumed` (or an `error` carrying this `reqId`) once
+ * the handshake settles; `prompt` is sent as the first turn on success.
+ */
+ op: 'resume';
+ threadId: string;
+ reqId: string;
+ prompt?: string;
+ }
+ | {
+ /** Permanently delete an ARCHIVED thread's transcript (refused live). */
+ op: 'delete';
+ threadId: string;
+ }
+ | { op: 'list' };
+
+/** Server → client frames. */
+export type ThreadServerFrame =
+ | { op: 'created'; reqId: string; info: ThreadInfo }
+ | { op: 'resumed'; reqId: string; info: ThreadInfo }
+ | { op: 'subscribed'; threadId: string; fromSeq: number; info: ThreadInfo }
+ | { op: 'event'; threadId: string; seq: number; event: ThreadEvent }
+ | {
+ /**
+ * Consecutive events starting at `fromSeq` (`events[i]` has seq
+ * `fromSeq + i`). The normal delivery shape: replay arrives in chunks
+ * and live events coalesce on a short trailing debounce, so one frame
+ * (one JSON parse, one store update, one render) carries a burst
+ * instead of one frame per streamed chunk. `event` remains for
+ * single-event sends (e.g. the terminal close notice).
+ */
+ op: 'events';
+ threadId: string;
+ fromSeq: number;
+ events: ThreadEvent[];
+ }
+ | { op: 'info'; info: ThreadInfo }
+ | { op: 'threads'; threads: ThreadInfo[] }
+ | {
+ op: 'error';
+ code: ThreadErrorCode;
+ message: string;
+ reqId?: string;
+ threadId?: string;
+ };
+
+export type ThreadErrorCode =
+ | 'bad-frame'
+ | 'unknown-thread'
+ | 'unknown-agent'
+ | 'capacity'
+ | 'spawn-failed'
+ | 'install-failed'
+ | 'agent-error'
+ | 'not-ready'
+ /** The agent advertises neither `session/resume` nor `session/load` (or
+ * rejected the stored sessionId) — the transcript stays archived; the
+ * client offers a fresh thread instead. */
+ | 'resume-unsupported'
+ | 'internal';
+
+const CLIENT_OPS = new Set([
+ 'create',
+ 'subscribe',
+ 'unsubscribe',
+ 'prompt',
+ 'permission_response',
+ 'runtime_consent_response',
+ 'cancel',
+ 'set_mode',
+ 'set_config_option',
+ 'close',
+ 'rename',
+ 'resume',
+ 'delete',
+ 'list',
+]);
+
+/**
+ * Parse a raw WS message into a `ThreadClientFrame`, or `null` when the
+ * bytes are not a recognizable frame. Structural (per-op field presence)
+ * only — semantic validation (thread existence, status) is the manager's.
+ */
+export function parseThreadClientFrame(raw: string): ThreadClientFrame | null {
+ let value: unknown;
+ try {
+ value = JSON.parse(raw);
+ } catch {
+ return null;
+ }
+ if (typeof value !== 'object' || value === null) return null;
+ const frame = value as Record<string, unknown>;
+ if (typeof frame.op !== 'string' || !CLIENT_OPS.has(frame.op)) return null;
+ const str = (k: string): boolean => typeof frame[k] === 'string' && frame[k] !== '';
+ switch (frame.op) {
+ case 'create': {
+ if (!str('reqId')) return null;
+ const agent = frame.agent as Record<string, unknown> | undefined;
+ if (
+ typeof agent !== 'object' ||
+ agent === null ||
+ (agent.source !== 'registry' && agent.source !== 'custom') ||
+ typeof agent.id !== 'string' ||
+ agent.id === ''
+ ) {
+ return null;
+ }
+ if (frame.prompt !== undefined && typeof frame.prompt !== 'string') return null;
+ if (frame.docName !== undefined && typeof frame.docName !== 'string') return null;
+ return frame as unknown as ThreadClientFrame;
+ }
+ case 'subscribe':
+ if (!str('threadId')) return null;
+ if (frame.sinceSeq !== undefined && typeof frame.sinceSeq !== 'number') return null;
+ return frame as unknown as ThreadClientFrame;
+ case 'prompt':
+ if (!str('threadId') || !str('reqId') || typeof frame.content !== 'string') return null;
+ return frame as unknown as ThreadClientFrame;
+ case 'permission_response': {
+ if (!str('threadId') || !str('requestId')) return null;
+ const outcome = frame.outcome as Record<string, unknown> | undefined;
+ if (typeof outcome !== 'object' || outcome === null) return null;
+ if (outcome.kind === 'selected') {
+ if (typeof outcome.optionId !== 'string' || outcome.optionId === '') return null;
+ } else if (outcome.kind !== 'cancelled') {
+ return null;
+ }
+ return frame as unknown as ThreadClientFrame;
+ }
+ case 'runtime_consent_response': {
+ if (!str('threadId') || !str('requestId')) return null;
+ const outcome = frame.outcome as Record<string, unknown> | undefined;
+ if (typeof outcome !== 'object' || outcome === null) return null;
+ if (outcome.kind !== 'granted' && outcome.kind !== 'declined') return null;
+ if (outcome.remember !== undefined && typeof outcome.remember !== 'boolean') return null;
+ return frame as unknown as ThreadClientFrame;
+ }
+ case 'set_mode':
+ if (!str('threadId') || !str('modeId')) return null;
+ return frame as unknown as ThreadClientFrame;
+ case 'rename':
+ if (!str('threadId') || !str('title')) return null;
+ return frame as unknown as ThreadClientFrame;
+ case 'set_config_option':
+ if (!str('threadId') || !str('configId')) return null;
+ if (typeof frame.value !== 'string' && typeof frame.value !== 'boolean') return null;
+ if (frame.value === '') return null;
+ return frame as unknown as ThreadClientFrame;
+ case 'resume':
+ if (!str('threadId') || !str('reqId')) return null;
+ if (frame.prompt !== undefined && typeof frame.prompt !== 'string') return null;
+ return frame as unknown as ThreadClientFrame;
+ case 'unsubscribe':
+ case 'cancel':
+ case 'close':
+ case 'delete':
+ if (!str('threadId')) return null;
+ return frame as unknown as ThreadClientFrame;
+ case 'list':
+ return frame as unknown as ThreadClientFrame;
+ default:
+ return null;
+ }
+}
+
+/** Type-only re-exports the app's renderer needs alongside the frames. */
+export type {
+ ContentBlock,
+ PermissionOption,
+ SessionConfigOption,
+ SessionModeState,
+ SessionUpdate,
+ StopReason,
+ ToolCallUpdate,
+};
diff --git a/packages/core/src/acp/thread-protocol.typelock.ts b/packages/core/src/acp/thread-protocol.typelock.ts
new file mode 100644
index 000000000..3725a55d6
--- /dev/null
+++ b/packages/core/src/acp/thread-protocol.typelock.ts
@@ -0,0 +1,137 @@
+/**
+ * Compile-time pins on the `@agentclientprotocol/sdk` unions and shapes this
+ * codebase attaches BEHAVIOR to. Nothing here runs — each alias fails
+ * `tsc --noEmit` when an SDK upgrade changes the pinned contract, turning
+ * silent semantic drift (a new union member falling through a `default:`
+ * branch, a reshaped field read through a cast) into a loud, located build
+ * error on the upgrade PR. When a pin fires: review the dependents named on
+ * it, adapt them if needed, then update the pin to the new shape.
+ */
+
+import type {
+ ClientCapabilities,
+ CreateTerminalRequest,
+ EnvVariable,
+ PermissionOption,
+ RequestPermissionResponse,
+ SessionUpdate,
+ StopReason,
+ TerminalExitStatus,
+ TerminalOutputResponse,
+ ToolCallContent,
+ WaitForTerminalExitResponse,
+} from '@agentclientprotocol/sdk';
+
+/** Invariant type equality — strict enough to catch `any` and member drift. */
+type Equal<A, B> =
+ (<T>() => T extends A ? 1 : 2) extends <T>() => T extends B ? 1 : 2 ? true : false;
+type Expect<T extends true> = T;
+
+// Dependents: the thread model's `applyUpdate` switch routes on this
+// discriminant with a permissive `default:` (forward compatibility), so a
+// NEW member never breaks the build — it silently renders as nothing. This
+// pin makes the addition loud so someone decides how it should render.
+export type PinSessionUpdateKinds = Expect<
+ Equal<
+ SessionUpdate['sessionUpdate'],
+ | 'user_message_chunk'
+ | 'agent_message_chunk'
+ | 'agent_thought_chunk'
+ | 'tool_call'
+ | 'tool_call_update'
+ | 'plan'
+ | 'plan_update'
+ | 'plan_removed'
+ | 'available_commands_update'
+ | 'current_mode_update'
+ | 'config_option_update'
+ | 'session_info_update'
+ | 'usage_update'
+ >
+>;
+
+// Dependents: `resolvePermissionOutcome` classifies by kind PREFIX
+// (`startsWith('reject')` → denied, everything else → approved), and the
+// permission card renders its own Deny only when no reject-kind option
+// exists. A fifth kind outside these four would silently classify as an
+// approval.
+export type PinPermissionOptionKind = Expect<
+ Equal<PermissionOption['kind'], 'allow_once' | 'allow_always' | 'reject_once' | 'reject_always'>
+>;
+
+// Dependents: `resolvePermissionOutcome` looks the chosen option up by
+// `optionId` (an unmatched id classifies as dismissed, so this going
+// optional would dismiss every resolution) and renders `name` in the
+// summary; the card keys its buttons by `optionId`.
+export type PinPermissionOptionId = Expect<Equal<PermissionOption['optionId'], string>>;
+export type PinPermissionOptionName = Expect<Equal<PermissionOption['name'], string>>;
+
+// Dependents: the explicit Deny button, permission timeouts, and turn-cancel
+// all express refusal as `cancelled` — the protocol's only non-selection
+// outcome today. If ACP grows a first-class per-tool deny, those mappings
+// should adopt it.
+export type PinPermissionOutcome = Expect<
+ Equal<RequestPermissionResponse['outcome']['outcome'], 'selected' | 'cancelled'>
+>;
+
+// Dependents: the server maps a user-cancelled turn to `cancelled` and the
+// UI treats every stop reason as a plain turn end.
+export type PinStopReason = Expect<
+ Equal<StopReason, 'end_turn' | 'max_tokens' | 'max_turn_requests' | 'refusal' | 'cancelled'>
+>;
+
+// Dependents: `mergeToolContent` dispatches on these block types ('diff' →
+// diff rows, 'terminal' → terminal ids, 'content' → text); a new type falls
+// into the plain-text fallback unnoticed.
+export type PinToolCallContentTypes = Expect<
+ Equal<ToolCallContent['type'], 'content' | 'diff' | 'terminal'>
+>;
+
+// Dependents: the model's `usage_update` fold reads `used`/`size` at the TOP
+// level of the update, and the composer footer renders them. (A nested-key
+// misread of this exact shape once shipped; the pin keeps it from
+// re-forming.)
+type UsageUpdate = Extract<SessionUpdate, { sessionUpdate: 'usage_update' }>;
+export type PinUsageUsed = Expect<Equal<UsageUpdate['used'], number>>;
+export type PinUsageSize = Expect<Equal<UsageUpdate['size'], number>>;
+
+// Dependents: the thread manager advertises `terminal: true`, and
+// `AcpTerminalSet` consumes exactly these request fields / produces exactly
+// these response shapes.
+export type PinTerminalCapability = Expect<
+ Equal<ClientCapabilities['terminal'], boolean | undefined>
+>;
+export type PinCreateTerminalCommand = Expect<Equal<CreateTerminalRequest['command'], string>>;
+export type PinCreateTerminalArgs = Expect<
+ Equal<CreateTerminalRequest['args'], string[] | undefined>
+>;
+export type PinCreateTerminalEnv = Expect<
+ Equal<CreateTerminalRequest['env'], EnvVariable[] | undefined>
+>;
+export type PinEnvVariableName = Expect<Equal<EnvVariable['name'], string>>;
+export type PinEnvVariableValue = Expect<Equal<EnvVariable['value'], string>>;
+export type PinCreateTerminalCwd = Expect<
+ Equal<CreateTerminalRequest['cwd'], string | null | undefined>
+>;
+export type PinCreateTerminalOutputByteLimit = Expect<
+ Equal<CreateTerminalRequest['outputByteLimit'], number | null | undefined>
+>;
+export type PinTerminalOutputText = Expect<Equal<TerminalOutputResponse['output'], string>>;
+export type PinTerminalOutputTruncated = Expect<
+ Equal<TerminalOutputResponse['truncated'], boolean>
+>;
+export type PinTerminalOutputExitStatus = Expect<
+ Equal<TerminalOutputResponse['exitStatus'], TerminalExitStatus | null | undefined>
+>;
+export type PinTerminalExitCode = Expect<
+ Equal<TerminalExitStatus['exitCode'], number | null | undefined>
+>;
+export type PinTerminalExitSignal = Expect<
+ Equal<TerminalExitStatus['signal'], string | null | undefined>
+>;
+export type PinWaitForExitCode = Expect<
+ Equal<WaitForTerminalExitResponse['exitCode'], number | null | undefined>
+>;
+export type PinWaitForExitSignal = Expect<
+ Equal<WaitForTerminalExitResponse['signal'], string | null | undefined>
+>;
diff --git a/packages/core/src/constants/activity.test.ts b/packages/core/src/constants/activity.test.ts
new file mode 100644
index 000000000..15cb02e42
--- /dev/null
+++ b/packages/core/src/constants/activity.test.ts
@@ -0,0 +1,44 @@
+import { describe, expect, test } from 'vitest';
+import { changedBlockRange } from './activity.ts';
+
+describe('changedBlockRange', () => {
+ test('identical block lists → null', () => {
+ expect(changedBlockRange(['a', 'b'], ['a', 'b'])).toBeNull();
+ expect(changedBlockRange([], [])).toBeNull();
+ });
+
+ test('append → only the new tail blocks (not the whole doc)', () => {
+ expect(changedBlockRange(['a', 'b'], ['a', 'b', 'c'])).toEqual({ from: 2, to: 3 });
+ expect(changedBlockRange(['a', 'b'], ['a', 'b', 'c', 'd'])).toEqual({ from: 2, to: 4 });
+ });
+
+ test('a whole-body replace that only appends collapses to the appended tail', () => {
+ // The write is a `replace`, but the shared prefix is byte-identical — the
+ // reason follow mode flashes the section, not the whole doc.
+ expect(changedBlockRange(['heading', 'intro'], ['heading', 'intro', 'new-section'])).toEqual({
+ from: 2,
+ to: 3,
+ });
+ });
+
+ test('prepend → the leading blocks', () => {
+ expect(changedBlockRange(['b', 'c'], ['a', 'b', 'c'])).toEqual({ from: 0, to: 1 });
+ });
+
+ test('an edited middle block is bounded to that block', () => {
+ expect(changedBlockRange(['a', 'b', 'c'], ['a', 'B', 'c'])).toEqual({ from: 1, to: 2 });
+ });
+
+ test('empty before → the whole after', () => {
+ expect(changedBlockRange([], ['a', 'b'])).toEqual({ from: 0, to: 2 });
+ });
+
+ test('pure deletion → null (no new block to flash)', () => {
+ expect(changedBlockRange(['a', 'b', 'c'], ['a', 'c'])).toBeNull();
+ expect(changedBlockRange(['a', 'b'], ['a'])).toBeNull();
+ });
+
+ test('delete-and-replace still reports the changed block', () => {
+ expect(changedBlockRange(['a', 'b', 'c'], ['a', 'X'])).toEqual({ from: 1, to: 2 });
+ });
+});
diff --git a/packages/core/src/constants/activity.ts b/packages/core/src/constants/activity.ts
index 17fef80f2..dbb7c097e 100644
--- a/packages/core/src/constants/activity.ts
+++ b/packages/core/src/constants/activity.ts
@@ -39,3 +39,33 @@ export function hasNewEntries(activityMap: Y.Map<unknown>, since: number): boole
}
return false;
}
+
+/**
+ * The top-level block index range `[from, to)` that differs between two block
+ * snapshots, in AFTER coordinates, or null when `after` gained no blocks.
+ *
+ * A block snapshot is the serialized form of each top-level node (the server
+ * takes it from the XmlFragment's children, which map 1:1 to PM top-level
+ * nodes). A prefix/suffix scan collapses a whole-body `replace` that only
+ * appended a section down to just the appended blocks — so follow mode flashes
+ * and scrolls to where the agent actually wrote, not the whole doc. Pure
+ * deletion (no new/changed blocks in `after`) returns null: there is nothing
+ * to flash.
+ */
+export function changedBlockRange(
+ before: readonly string[],
+ after: readonly string[],
+): { from: number; to: number } | null {
+ const n = before.length;
+ const m = after.length;
+ let start = 0;
+ while (start < n && start < m && before[start] === after[start]) start++;
+ let endBefore = n;
+ let endAfter = m;
+ while (endBefore > start && endAfter > start && before[endBefore - 1] === after[endAfter - 1]) {
+ endBefore--;
+ endAfter--;
+ }
+ if (endAfter <= start) return null;
+ return { from: start, to: endAfter };
+}
diff --git a/packages/core/src/desktop-bridge.ts b/packages/core/src/desktop-bridge.ts
index 76ba13e03..8d4ef2166 100644
--- a/packages/core/src/desktop-bridge.ts
+++ b/packages/core/src/desktop-bridge.ts
@@ -1659,8 +1659,10 @@ export interface OkDesktopBridge {
* survives a renderer reload. Fire-and-forget.
*/
setOrder(orderedPtyIds: readonly string[]): void;
- /** Per-window dock visibility. Canonical JSDoc in `bridge-contract.ts`; mirrored verbatim (drift-tested). */
- getDockState(): Promise<{ visible: boolean }>;
+ /** Per-window sessions-dock state (visibility + unified tab order + active key). Canonical JSDoc in `bridge-contract.ts`; mirrored verbatim (drift-tested). */
+ getDockState(): Promise<{ visible: boolean; order?: string[]; activeKey?: string | null }>;
+ /** Persist the unified sessions-dock order + active key per window. Canonical JSDoc in `bridge-contract.ts`; mirrored verbatim (drift-tested). */
+ setDockState(state: { order: string[]; activeKey: string | null }): void;
onData(cb: (msg: OkPtyData) => void): OkUnsubscribe;
onExit(cb: (msg: OkPtyExit) => void): OkUnsubscribe;
claudePreflight(): Promise<ClaudeReadiness>;
diff --git a/packages/core/src/handoff/index.ts b/packages/core/src/handoff/index.ts
index 6328a5f3c..06feebbe6 100644
--- a/packages/core/src/handoff/index.ts
+++ b/packages/core/src/handoff/index.ts
@@ -24,9 +24,11 @@ export {
composeSelectionPrompt,
composeSkillPrompt,
composeTerminalBareLaunchPrompt,
+ composeThreadBareLaunchPrompt,
type LintFixPromptInput,
OK_PROJECT_SKILL_POINTER,
OK_TERMINAL_SURFACE_PREAMBLE,
+ OK_THREAD_SURFACE_PREAMBLE,
type PromptTransport,
TERMINAL_INLINE_PROMPT_BUDGET,
withSkillPointer,
diff --git a/packages/core/src/handoff/prompt-composer.ts b/packages/core/src/handoff/prompt-composer.ts
index df59965da..867d63619 100644
--- a/packages/core/src/handoff/prompt-composer.ts
+++ b/packages/core/src/handoff/prompt-composer.ts
@@ -155,6 +155,28 @@ export function withSkillPointer(directive: string): string {
export const OK_TERMINAL_SURFACE_PREAMBLE =
"You're running in the terminal of the OpenKnowledge desktop app.";
+/**
+ * Agent-thread surface preamble — the ACP twin of
+ * {@link OK_TERMINAL_SURFACE_PREAMBLE}. Emitted when a launch opens an
+ * in-app agent thread (server-hosted, browser or desktop) rather than a
+ * terminal CLI. States the surface so the composed handoff reads coherently.
+ */
+export const OK_THREAD_SURFACE_PREAMBLE =
+ "You're an agent working inside OpenKnowledge, with its MCP tools available to you.";
+
+/**
+ * In-app-thread *bare*-launch prompt — the ACP twin of
+ * {@link composeTerminalBareLaunchPrompt}. Same shape (surface + skill
+ * pointer + optional file pointer + stop), with the thread preamble.
+ */
+export function composeThreadBareLaunchPrompt(relativePath: string | null): string {
+ const tail =
+ relativePath === null
+ ? 'Then stop.'
+ : `Read \`${sanitizePathForPrompt(relativePath)}\` via the OpenKnowledge MCP server, then stop.`;
+ return `${OK_THREAD_SURFACE_PREAMBLE} ${OK_PROJECT_SKILL_POINTER} ${tail}`;
+}
+
/**
* Docked-terminal *bare*-launch prompt — what lands when the user opens a
* terminal on a file / folder / project WITHOUT typing an instruction or a
diff --git a/packages/core/src/handoff/urn-ipc-registry.ts b/packages/core/src/handoff/urn-ipc-registry.ts
index 311089c6c..e2dab6a79 100644
--- a/packages/core/src/handoff/urn-ipc-registry.ts
+++ b/packages/core/src/handoff/urn-ipc-registry.ts
@@ -292,6 +292,10 @@ export const URN_HTTP_ONLY: ReadonlySet<ProblemType> = new Set<ProblemType>([
'urn:ok:error:handoff-target-not-installed',
'urn:ok:error:handoff-spawn-timeout',
'urn:ok:error:handoff-spawn-failed',
+ // `GET /api/acp/catalog` — HTTP-only. The agent catalog is fetched over the
+ // embedded server's HTTP API by both web and Electron renderers; there is no
+ // IPC counterpart.
+ 'urn:ok:error:registry-unreachable',
// Lint config write (`POST /api/lint/markdownlint-config` → 409 when the
// native `.markdownlint.*` file can't be written). HTTP-only — the lint
// config surface is REST, with no IPC counterpart.
diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts
index 22e7d8ee2..39f0d847a 100644
--- a/packages/core/src/index.ts
+++ b/packages/core/src/index.ts
@@ -167,6 +167,7 @@ export {
// Constants
export {
ACTIVITY_TTL_MS,
+ changedBlockRange,
evictStaleEntries,
FLASH_DEBOUNCE_MS,
FLASH_DURATION_MS,
@@ -402,6 +403,7 @@ export {
composeSelectionPrompt,
composeSkillPrompt,
composeTerminalBareLaunchPrompt,
+ composeThreadBareLaunchPrompt,
type DocContext,
type HandoffFailureReason,
type HandoffOutcome,
@@ -416,6 +418,7 @@ export {
OK_GATED_TOOL_NAMES,
OK_PROJECT_SKILL_POINTER,
OK_TERMINAL_SURFACE_PREAMBLE,
+ OK_THREAD_SURFACE_PREAMBLE,
type PromptTransport,
shellSingleQuote,
startupInjectionFor,
@@ -1325,6 +1328,11 @@ export type {
AwarenessState,
AwarenessUser,
} from './types/awareness.ts';
+export {
+ AGENT_THREAD_SENTINEL_DOC,
+ CONNECTED_SENTINEL_DOC,
+ isPresenceSentinelDocName,
+} from './types/awareness.ts';
export type { Identity } from './types/identity.ts';
export type { Principal } from './types/principal.ts';
export type {
diff --git a/packages/core/src/schemas/api/_envelope.ts b/packages/core/src/schemas/api/_envelope.ts
index 07ebc92c5..72ff7128a 100644
--- a/packages/core/src/schemas/api/_envelope.ts
+++ b/packages/core/src/schemas/api/_envelope.ts
@@ -379,6 +379,9 @@ export const ProblemTypeSchema = z.enum([
'urn:ok:error:handoff-target-not-installed',
'urn:ok:error:handoff-spawn-timeout',
'urn:ok:error:handoff-spawn-failed',
+ // ACP agent-catalog route: the registry CDN was unreachable and no cache
+ // exists yet — the client renders an offline state, not an error toast.
+ 'urn:ok:error:registry-unreachable',
// `POST /api/lint/markdownlint-config` refuses (409) to rewrite a native
// markdownlint config that is an executable module (`.cjs`/`.mjs`). Distinct
// from `invalid-request` (400 shape) so SDK consumers read it as a Conflict —
diff --git a/packages/core/src/types/awareness.test.ts b/packages/core/src/types/awareness.test.ts
new file mode 100644
index 000000000..77f3e9a27
--- /dev/null
+++ b/packages/core/src/types/awareness.test.ts
@@ -0,0 +1,25 @@
+import { describe, expect, test } from 'vitest';
+import {
+ AGENT_THREAD_SENTINEL_DOC,
+ CONNECTED_SENTINEL_DOC,
+ isPresenceSentinelDocName,
+} from './awareness.ts';
+
+describe('isPresenceSentinelDocName', () => {
+ test('matches the presence sentinels', () => {
+ expect(isPresenceSentinelDocName(CONNECTED_SENTINEL_DOC)).toBe(true);
+ expect(isPresenceSentinelDocName(AGENT_THREAD_SENTINEL_DOC)).toBe(true);
+ });
+
+ test('null / undefined are not sentinels', () => {
+ expect(isPresenceSentinelDocName(null)).toBe(false);
+ expect(isPresenceSentinelDocName(undefined)).toBe(false);
+ });
+
+ test('exact match only — real parenthesised docNames are not sentinels', () => {
+ // A leading-`(` heuristic would over-match these legitimate filenames.
+ expect(isPresenceSentinelDocName('(WIP) draft')).toBe(false);
+ expect(isPresenceSentinelDocName('(2026-05-13) standup')).toBe(false);
+ expect(isPresenceSentinelDocName('articles/tea/terroir')).toBe(false);
+ });
+});
diff --git a/packages/core/src/types/awareness.ts b/packages/core/src/types/awareness.ts
index 97ddb8c30..2ae1f7efa 100644
--- a/packages/core/src/types/awareness.ts
+++ b/packages/core/src/types/awareness.ts
@@ -110,10 +110,52 @@ export interface AgentPresenceEntry {
ts: number;
}
+/**
+ * Placeholder `currentDoc` values the server publishes to keep an agent
+ * visible in presence when it is NOT writing a real document:
+ * `'(connected)'` from the MCP keepalive bootstrap (agent connected, no
+ * write yet) and `'(agent thread)'` from an in-app thread launched without a
+ * doc context. They are display sentinels, never navigable paths — see
+ * `isPresenceSentinelDocName`.
+ */
+export const CONNECTED_SENTINEL_DOC = '(connected)';
+export const AGENT_THREAD_SENTINEL_DOC = '(agent thread)';
+
+const PRESENCE_SENTINEL_DOC_NAMES: ReadonlySet<string> = new Set([
+ CONNECTED_SENTINEL_DOC,
+ AGENT_THREAD_SENTINEL_DOC,
+]);
+
+/**
+ * True when a presence `currentDoc` is a sentinel, not a real doc path.
+ * Consumers that treat `currentDoc` as a document — follow-the-file
+ * navigation, the presence bar's "editing X" label — MUST skip these, or they
+ * navigate to / render a doc that doesn't exist.
+ *
+ * Matched by exact string, deliberately: a real docName may start with `(`
+ * (e.g. `(WIP) draft`, `(2026-05-13) standup`), so a leading-`(` heuristic
+ * would over-suppress legitimate parenthesised filenames.
+ */
+export function isPresenceSentinelDocName(name: string | null | undefined): boolean {
+ return name != null && PRESENCE_SENTINEL_DOC_NAMES.has(name);
+}
+
/** Entry in Y.Map('agent-flash') side-channel for agent write attribution. */
export interface AgentFlashEntry {
agentId: string;
timestamp: number;
type: 'insert' | 'replace' | 'delete';
description?: string;
+ /**
+ * Top-level block index range `[from, to)` the write changed, in the
+ * POST-write document. Lets a follow-mode editor that becomes active AFTER
+ * the write already applied still scroll to + flash the changed section:
+ * the live-transaction flash can't fire then (the editor mounts to
+ * already-final content, so there is no before→after transaction to diff).
+ * Block indices map 1:1 to ProseMirror top-level nodes because y-prosemirror
+ * mirrors the XmlFragment's children onto the PM doc's children. Omitted when
+ * the write changed no top-level blocks (frontmatter-only / no-op) or when a
+ * writer can't compute it.
+ */
+ changedBlocks?: { from: number; to: number };
}
diff --git a/packages/core/tsdown.config.ts b/packages/core/tsdown.config.ts
index f5eb5eb99..2e60cb490 100644
--- a/packages/core/tsdown.config.ts
+++ b/packages/core/tsdown.config.ts
@@ -8,6 +8,7 @@ export default defineConfig({
server: 'src/server.ts',
keepalive: 'src/keepalive/keepalive.ts',
'helper-bundle': 'src/helper-bundle.ts',
+ 'acp-thread-protocol': 'src/acp/thread-protocol.ts',
},
unbundle: false,
format: 'esm',
diff --git a/packages/desktop/src/main/index.ts b/packages/desktop/src/main/index.ts
index 8f0e9777e..252947148 100644
--- a/packages/desktop/src/main/index.ts
+++ b/packages/desktop/src/main/index.ts
@@ -788,6 +788,14 @@ let terminalReaper: TerminalReaper | null = null;
* sessions restores nothing and the dock correctly stays hidden.
*/
const dockVisibleForWindow = new Map<number, boolean>();
+/**
+ * Per-window unified sessions-dock order + active key, recorded from the
+ * renderer's `ok:terminal:set-dock-state` push so a reloaded renderer restores the
+ * interleaved cross-kind tab arrangement (terminal ptyIds + thread threadIds) and
+ * the active tab. Same windowId-keyed lifetime as {@link dockVisibleForWindow} —
+ * cleared on window-close and app-quit.
+ */
+const dockOrderForWindow = new Map<number, { order: string[]; activeKey: string | null }>();
/**
* Singleton show-gate registry — coordinates window.show() against the
* dual-signal contract (`ready-to-show` + `ok:theme:applied`). Module-level
@@ -1175,9 +1183,10 @@ function ensureWindowManager() {
// onReap clears the window's retained dock-visibility so it can't restore
// a stale "visible" for a future window that reuses the id.
if (terminalReaper)
- wireWindowTerminalReap(win, terminalReaper, (windowId) =>
- dockVisibleForWindow.delete(windowId),
- );
+ wireWindowTerminalReap(win, terminalReaper, (windowId) => {
+ dockVisibleForWindow.delete(windowId);
+ dockOrderForWindow.delete(windowId);
+ });
return win as unknown as BrowserWindowLike;
},
// App-level foreground activation for the bring-to-front recipe. macOS
@@ -3473,7 +3482,19 @@ function registerIpcHandlers() {
handle('ok:terminal:dock-state', async (event) => {
const win = BrowserWindow.fromWebContents(event.sender);
- return { visible: win ? (dockVisibleForWindow.get(win.id) ?? false) : false };
+ if (!win) return { visible: false, order: [], activeKey: null };
+ const dockOrder = dockOrderForWindow.get(win.id);
+ return {
+ visible: dockVisibleForWindow.get(win.id) ?? false,
+ order: dockOrder?.order ?? [],
+ activeKey: dockOrder?.activeKey ?? null,
+ };
+ });
+
+ handle('ok:terminal:set-dock-state', async (event, req) => {
+ const win = BrowserWindow.fromWebContents(event.sender);
+ if (win) dockOrderForWindow.set(win.id, { order: req.order, activeKey: req.activeKey });
+ return undefined;
});
handle('ok:dialog:open-folder', async (_event, opts) => {
@@ -5115,6 +5136,19 @@ if (instanceLabel) {
setWindowInstanceLabel(instanceLabel);
}
+// Opt-in: force Chromium to build the renderer accessibility tree so the
+// web-view UI (composer, buttons, tabs — all already carry aria-labels / roles)
+// is exposed to the macOS accessibility API. Electron/Chromium otherwise builds
+// that tree lazily, only once it detects an assistive technology, so an AX
+// client (VoiceOver, or a GUI-automation driver like peekaboo) sees only the
+// native window chrome and none of the React controls. Gated behind an env var
+// because the always-on AX tree carries a small perpetual cost — set
+// `OK_FORCE_A11Y=1` when driving the app with an accessibility/automation tool.
+// Must run before `app` is ready (command-line switches are read at that point).
+if (process.env.OK_FORCE_A11Y === '1') {
+ app.commandLine.appendSwitch('force-renderer-accessibility');
+}
+
if (isDriverBootSmokeMode(process.env)) {
app.whenReady().then(() => {
runDriverBootSmokeInProduction();
@@ -6014,6 +6048,7 @@ function bootPrimaryInstance(): void {
// outlives the app. Idempotent (clears the map; a second pass no-ops).
terminalReaper?.killAll();
dockVisibleForWindow.clear();
+ dockOrderForWindow.clear();
autoUpdaterHandle?.destroy();
autoUpdaterHandle = null;
bundleReplaceWatcherHandle?.stop();
diff --git a/packages/desktop/src/preload/index.ts b/packages/desktop/src/preload/index.ts
index 545925e77..322e18c2e 100644
--- a/packages/desktop/src/preload/index.ts
+++ b/packages/desktop/src/preload/index.ts
@@ -757,6 +757,12 @@ const bridge: OkDesktopBridge = {
invoke('ok:pty:set-order', { orderedPtyIds: [...orderedPtyIds] }).catch(() => {});
},
getDockState: () => invoke('ok:terminal:dock-state'),
+ setDockState: (state) => {
+ invoke('ok:terminal:set-dock-state', {
+ order: [...state.order],
+ activeKey: state.activeKey,
+ }).catch(() => {});
+ },
onData(cb) {
const listener = (_event: IpcRendererEvent, msg: OkPtyData) => cb(msg);
// biome-ignore lint/plugin/no-loosely-typed-webcontents-ipc: preload-side subscription wrapper (precedent #14)
diff --git a/packages/desktop/src/renderer/index.html b/packages/desktop/src/renderer/index.html
index e7e82b0f5..9126775a4 100644
--- a/packages/desktop/src/renderer/index.html
+++ b/packages/desktop/src/renderer/index.html
@@ -2,7 +2,7 @@
<html lang="en">
<head>
<meta charset="UTF-8" />
- <meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; connect-src 'self' ws: http: https:;" />
+ <meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' https://cdn.agentclientprotocol.com; connect-src 'self' ws: http: https:;" />
<meta name="viewport" content="width=device-width,initial-scale=1" />
<title>OpenKnowledge</title>
</head>
diff --git a/packages/desktop/src/shared/bridge-contract.ts b/packages/desktop/src/shared/bridge-contract.ts
index d21fe1bc0..629ba3f8b 100644
--- a/packages/desktop/src/shared/bridge-contract.ts
+++ b/packages/desktop/src/shared/bridge-contract.ts
@@ -1970,11 +1970,19 @@ export interface OkDesktopBridge {
*/
setOrder(orderedPtyIds: readonly string[]): void;
/**
- * Per-window dock visibility retained in main, read once on reload so the
- * dock re-expands when it was open before the reload (and stays hidden after
- * a fresh launch where no sessions survived).
+ * Per-window sessions-dock state retained in main, read once on reload so the
+ * dock re-expands (`visible`) and restores its interleaved cross-kind tab order
+ * (`order` = terminal ptyIds + thread threadIds) + active tab (`activeKey`) when
+ * it was open before the reload. `order`/`activeKey` are optional for version
+ * skew (an older main returns just `visible`).
*/
- getDockState(): Promise<{ visible: boolean }>;
+ getDockState(): Promise<{ visible: boolean; order?: string[]; activeKey?: string | null }>;
+ /**
+ * Persist the unified sessions-dock order + active key in main (per window) so a
+ * renderer reload restores the interleaved cross-kind arrangement. `order` holds
+ * reload-stable keys (ptyIds + threadIds) in tab order. Fire-and-forget.
+ */
+ setDockState(state: { order: string[]; activeKey: string | null }): void;
onData(cb: (msg: OkPtyData) => void): OkUnsubscribe;
onExit(cb: (msg: OkPtyExit) => void): OkUnsubscribe;
/**
diff --git a/packages/desktop/src/shared/ipc-channels.ts b/packages/desktop/src/shared/ipc-channels.ts
index 12e77612a..f5f3d08b5 100644
--- a/packages/desktop/src/shared/ipc-channels.ts
+++ b/packages/desktop/src/shared/ipc-channels.ts
@@ -1576,14 +1576,26 @@ export interface RequestChannels {
result: Record<TerminalCli, boolean>;
};
/**
- * Per-window docked-terminal visibility, recorded from the renderer's
- * view-menu push. A reloaded renderer reads it to restore an expanded dock —
- * visibility recovers by the same mechanism and lifetime as the sessions it
- * gates (windowId-keyed; gone after window-close / app-quit, so a fresh launch
- * with no surviving sessions restores nothing).
+ * Per-window sessions-dock state, read once on reload to restore the dock.
+ * `visible` is recorded from the renderer's view-menu push; `order` (the unified
+ * cross-kind tab order — terminal ptyIds + thread threadIds) and `activeKey` are
+ * recorded from `ok:terminal:set-dock-state`. All windowId-keyed, gone after
+ * window-close / app-quit (so a fresh launch with no surviving sessions restores
+ * nothing). `order`/`activeKey` are optional so an older renderer that only reads
+ * `visible` keeps working.
*/
'ok:terminal:dock-state': {
args: [];
- result: { visible: boolean };
+ result: { visible: boolean; order?: string[]; activeKey?: string | null };
+ };
+ /**
+ * Persist the unified sessions-dock order + active key in main (per window) so a
+ * renderer reload restores the interleaved cross-kind tab arrangement + active
+ * tab. `order` holds reload-stable keys (terminal ptyIds + thread threadIds) in
+ * tab order. Fire-and-forget, the sibling of `ok:pty:set-order` for the mixed dock.
+ */
+ 'ok:terminal:set-dock-state': {
+ args: [req: { order: string[]; activeKey: string | null }];
+ result: undefined;
};
}
diff --git a/packages/desktop/src/utility/server-entry.ts b/packages/desktop/src/utility/server-entry.ts
index accc125ff..74a08c66a 100644
--- a/packages/desktop/src/utility/server-entry.ts
+++ b/packages/desktop/src/utility/server-entry.ts
@@ -22,7 +22,11 @@
import { rename, writeFile } from 'node:fs/promises';
import { isAbsolute, relative, resolve } from 'node:path';
-import { detectGh, makeLazyProbeTokenStore } from '@inkeep/open-knowledge';
+import {
+ detectGh,
+ makeLazyProbeTokenStore,
+ probeOwnManagedEditorMcpEntry,
+} from '@inkeep/open-knowledge';
import { readConfigSafely, resolveConfigPath } from '@inkeep/open-knowledge-core/server';
import {
type BootedServer,
@@ -350,6 +354,11 @@ export function setupUtility(deps: SetupUtilityDeps): UtilityHandle {
detectGh,
tokenStore,
embeddingsKeyStore,
+ // ACP threads skip injecting the `open-knowledge` MCP server when the
+ // agent's own harness already loads OK's managed editor-config entry
+ // (same wiring as `ok start`).
+ probeHarnessManagedMcpEntry: (editorId, agentCwd) =>
+ probeOwnManagedEditorMcpEntry(editorId, agentCwd),
// The renderer page origin (Vite dev URL / `file://`) has no asset
// middleware — serve content assets from this utility server so the
// renderer can resolve `/<contentDir-relative>` srcs against `apiOrigin`.
diff --git a/packages/desktop/tests/integration/ipc-channel-count-ratchet.test.ts b/packages/desktop/tests/integration/ipc-channel-count-ratchet.test.ts
index 08f864260..50a01ca2b 100644
--- a/packages/desktop/tests/integration/ipc-channel-count-ratchet.test.ts
+++ b/packages/desktop/tests/integration/ipc-channel-count-ratchet.test.ts
@@ -20,9 +20,9 @@
* run check` gating.
*/
-import { describe, expect, test } from 'bun:test';
import { readFileSync } from 'node:fs';
import { join } from 'node:path';
+import { describe, expect, test } from 'vitest';
const SRC_PATH = join(__dirname, '..', '..', 'src', 'shared', 'ipc-channels.ts');
const CHANNELS_SRC = readFileSync(SRC_PATH, 'utf-8');
@@ -312,48 +312,46 @@ const CHANNELS_SRC = readFileSync(SRC_PATH, 'utf-8');
* single channel over two distinct operations against a namespace that
* deliberately keeps each PTY operation on its own channel.
*
- * Bumped from 81 to 82 for the in-app "Report a bug" surface:
- *
- * - `ok:bug-report:dispatch` — builds the redacted diagnostic zip for the
- * sender window's project (system-wide when the window has no project)
- * via the CLI package's leveled `collectReportBundle`, in-process. Main
- * owns it because the inputs are main-process state: the window-manager
- * project context, `app.getVersion()`/`app.isPackaged`/the update
- * channel (stamped as `OK_DESKTOP_*` metadata), and the `~/.ok/bug-reports/`
- * write. A single discriminated channel per the `ok:sharing:dispatch`
- * precedent: the report surface's upload (`send`) and crash-ack
- * operations widen this channel's payload — the preferred
- * payload-widening path — instead of adding channels, so the whole
- * surface costs one slot. Could not fold into any existing channel: no
- * diagnostics/reporting surface exists — `ok:shell:*` is scoped to
- * asset reveal/open, `ok:update:*` to the updater lifecycle, and the
- * `ok:project:*` reads carry unrelated schemas. New `ok:bug-report:*`
- * namespace, single member. The typed-ipc migration remains the
- * committed end state; scoped exception with the `ipc-channels.ts`
- * header commitment updated in lock-step.
- *
- * Bumped from 82 to 83 for the terminal clickable-links out-of-project reveal
- * (`ok:shell:reveal-external`): when a terminal link points at an existing file
- * OUTSIDE the window's project, main pops a "reveal in Finder?" confirmation and
- * reveals on confirm. It is a distinct trust boundary from `ok:shell:reveal-asset`
- * — deliberately UNCONTAINED (the whole feature) but dialog-gated — so folding it
- * onto the containment-checked asset reveal would wear one channel over two
- * opposite security contracts. Single member; the typed-ipc migration remains the
- * committed end state, with the `ipc-channels.ts` header updated in lock-step.
- *
- * Bumped from 83 to 85 for the two Cmd+K / native-menu command invokes:
+ * Bumped from 81 to 84 across a main merge for three independent single-member
+ * additions:
+ *
+ * - `ok:shell:reveal-external` — the terminal clickable-links out-of-project
+ * reveal: when a terminal link points at a file OUTSIDE the window's project,
+ * main pops a "reveal in Finder?" confirmation and reveals on confirm. A
+ * distinct trust boundary from `ok:shell:reveal-asset` — deliberately
+ * UNCONTAINED (the whole feature) but dialog-gated — so folding it onto the
+ * containment-checked asset reveal would wear one channel over two opposite
+ * security contracts.
+ * - `ok:terminal:set-dock-state` — the window's unified cross-kind tab order
+ * (terminal ptyIds + thread threadIds) + active key, persisted in main so a
+ * ⌘R renderer reload restores the interleaved arrangement. The `get`
+ * counterpart (`ok:terminal:dock-state`) already exists and gained the extra
+ * fields; the setter is its own channel (fire-and-forget write vs the read),
+ * the sibling of `ok:pty:set-order` for the mixed dock.
+ * - `ok:bug-report:dispatch` — the in-app "Report a bug" surface: builds the
+ * redacted diagnostic zip for the sender window's project via the CLI
+ * package's leveled `collectReportBundle`, in-process. Main owns it because
+ * the inputs are main-process state (window-manager project context,
+ * app version / packaged / update channel, the `~/.ok/bug-reports/` write);
+ * its upload + crash-ack operations widen this channel's payload rather than
+ * adding channels, so the whole surface costs one slot.
+ *
+ * The typed-ipc migration remains the committed end state, with the
+ * `ipc-channels.ts` header updated in lock-step.
+ *
+ * Bumped from 84 to 86 for the two Cmd+K / native-menu command invokes:
* `ok:mcp-wiring:reconfigure` (File → "Set up OpenKnowledge integrations…")
* and `ok:spellcheck:toggle` (Edit → "Check spelling while typing"). Each
* delegates to an existing main-side function; the typed-ipc migration remains
* the committed end state, with the `ipc-channels.ts` header in lock-step.
*
- * Bumped from 85 to 86 for File → "Open file…" (`ok:project:open-file-picker`):
+ * Bumped from 86 to 87 for File → "Open file…" (`ok:project:open-file-picker`):
* the palette / Navigator entry point to the temporary single-file session,
* delegating to the existing main-side picker + `openEphemeralFile` (the
* desktop side of `ok <file>`). Single member; the typed-ipc migration remains
* the committed end state, with the `ipc-channels.ts` header in lock-step.
*/
-const REQUEST_CHANNEL_CAP = 86;
+const REQUEST_CHANNEL_CAP = 87;
/**
* Extract the body of an interface block by name. Returns the substring
diff --git a/packages/desktop/tests/unit/renderer-csp.test.ts b/packages/desktop/tests/unit/renderer-csp.test.ts
new file mode 100644
index 000000000..411137662
--- /dev/null
+++ b/packages/desktop/tests/unit/renderer-csp.test.ts
@@ -0,0 +1,14 @@
+import { readFileSync } from 'node:fs';
+import { join } from 'node:path';
+import { describe, expect, test } from 'vitest';
+
+const rendererHtml = readFileSync(join(import.meta.dir, '../../src/renderer/index.html'), 'utf8');
+
+describe('renderer content security policy', () => {
+ test('allows agent icons from the ACP registry CDN', () => {
+ const csp = rendererHtml.match(/Content-Security-Policy" content="([^"]+)"/)?.[1];
+
+ expect(csp).toBeDefined();
+ expect(csp).toContain("img-src 'self' https://cdn.agentclientprotocol.com");
+ });
+});
diff --git a/packages/server/assets/skills/packs/knowledge-base/SKILL.md b/packages/server/assets/skills/packs/knowledge-base/SKILL.md
index 5af9cb00b..a1f86d4e8 100644
--- a/packages/server/assets/skills/packs/knowledge-base/SKILL.md
+++ b/packages/server/assets/skills/packs/knowledge-base/SKILL.md
@@ -14,6 +14,10 @@ This project uses the **source-grounded knowledge-base** layout. The whole point
> This skill is pack guidance. The platform `open-knowledge` skill (read/write/preview/grounding rules) still governs every markdown operation — this layers the KB workflow on top.
+## Link at creation
+
+The user watches your build live — the editor follows the file you're writing, and the knowledge graph assembles on screen as pages get linked. No view management on your part; just author well: every page carries its links from the moment it's written (at minimum the hub/index page and its most related siblings — an unlinked page is invisible in the graph), and related pages share a `cluster:` frontmatter value (e.g. `cluster: architecture`) so the graph's cluster coloring makes the map read at a glance.
+
## The three layers
```
diff --git a/packages/server/package.json b/packages/server/package.json
index e82664aa1..262d1c9dc 100644
--- a/packages/server/package.json
+++ b/packages/server/package.json
@@ -16,6 +16,7 @@
"src"
],
"dependencies": {
+ "@agentclientprotocol/sdk": "^1.1.0",
"@hocuspocus/server": "4.0.0-rc.1",
"@inkeep/open-knowledge-core": "workspace:*",
"@modelcontextprotocol/sdk": "^1.28.0",
diff --git a/packages/server/src/acp/archive.ts b/packages/server/src/acp/archive.ts
new file mode 100644
index 000000000..c6b597ef1
--- /dev/null
+++ b/packages/server/src/acp/archive.ts
@@ -0,0 +1,164 @@
+/**
+ * Download + extraction primitives shared by the two ACP install paths:
+ * proprietary agent binaries (`launch.ts` → `ensureBinaryInstalled`) and the
+ * managed language runtimes OK downloads when the user has no system
+ * npx/uvx (`managed-runtime.ts`).
+ *
+ * Both download an archive over HTTPS, verify a publisher-supplied SHA-256,
+ * extract with the platform's own tar/unzip, and rename the result into a
+ * per-version cache dir. Kept here so there is one audited copy of the
+ * path-escape guard and the streaming-hash download.
+ */
+
+import { type ChildProcess, spawn } from 'node:child_process';
+import { createHash } from 'node:crypto';
+import { createWriteStream } from 'node:fs';
+import { normalize, sep } from 'node:path';
+import { Readable } from 'node:stream';
+
+/** True when `candidate` is `root` itself or a descendant — the extract-escape guard. */
+export function isWithin(root: string, candidate: string): boolean {
+ const normalizedRoot = normalize(root) + sep;
+ const normalizedCandidate = normalize(candidate);
+ return `${normalizedCandidate}${sep}`.startsWith(normalizedRoot);
+}
+
+/** Reduce an arbitrary id/version to a single safe path segment. */
+export function sanitizeSegment(s: string): string {
+ const cleaned = s.replace(/[^a-zA-Z0-9._-]/g, '_');
+ if (cleaned === '' || cleaned === '.' || cleaned === '..') return '_';
+ return cleaned;
+}
+
+/**
+ * Extract `.tar.gz`/`.tar.xz` via tar; `.zip` via ditto (macOS), bundled
+ * bsdtar (`tar.exe`, Windows 10 1803+), or unzip (other POSIX). Windows has no
+ * `unzip` on PATH by default, but its bundled `tar` reads zip — so route
+ * Windows zips through tar rather than a tool that isn't there.
+ */
+export function extractArchive(
+ archivePath: string,
+ destDir: string,
+ isZip: boolean,
+ timeoutMs = 120_000,
+): Promise<void> {
+ const [cmd, args] = isZip
+ ? process.platform === 'darwin'
+ ? ['ditto', ['-x', '-k', archivePath, destDir]]
+ : process.platform === 'win32'
+ ? ['tar', ['-xf', archivePath, '-C', destDir]]
+ : ['unzip', ['-q', archivePath, '-d', destDir]]
+ : ['tar', ['-xf', archivePath, '-C', destDir]];
+ return new Promise((resolvePromise, rejectPromise) => {
+ const child: ChildProcess = spawn(cmd, args as string[], {
+ stdio: ['ignore', 'ignore', 'pipe'],
+ shell: false,
+ windowsHide: true,
+ });
+ // A hung extractor (corrupt archive, filesystem stall) would otherwise
+ // block its caller forever — both install paths await this in the agent
+ // startup path, matching the download's own 120s abort.
+ const timer = setTimeout(() => {
+ child.kill('SIGKILL');
+ rejectPromise(new Error(`${cmd} timed out after ${timeoutMs}ms extracting ${archivePath}`));
+ }, timeoutMs);
+ timer.unref?.();
+ let stderr = '';
+ child.stderr?.on('data', (d: Buffer) => {
+ stderr = (stderr + d.toString()).slice(-2000);
+ });
+ child.on('error', (err) => {
+ clearTimeout(timer);
+ rejectPromise(err);
+ });
+ child.on('exit', (code) => {
+ clearTimeout(timer);
+ if (code === 0) resolvePromise();
+ else rejectPromise(new Error(`${cmd} exited ${code}: ${stderr}`));
+ });
+ });
+}
+
+export interface DownloadProgress {
+ receivedBytes: number;
+ /** From `Content-Length`, or null when the server didn't send one. */
+ totalBytes: number | null;
+}
+
+export interface DownloadOptions {
+ signal?: AbortSignal;
+ onProgress?: (p: DownloadProgress) => void;
+ /** Test seam — defaults to global `fetch`. */
+ fetchImpl?: typeof fetch;
+}
+
+/**
+ * Stream `url` to `destPath`, hashing the bytes as they arrive, and return
+ * the lowercase hex SHA-256. Hashing inline (rather than re-reading the file)
+ * keeps a single pass over the ~30 MB payload. `onProgress` fires per chunk.
+ */
+export async function downloadToFileWithSha(
+ url: string,
+ destPath: string,
+ opts: DownloadOptions = {},
+): Promise<string> {
+ const fetchImpl = opts.fetchImpl ?? fetch;
+ const res = await fetchImpl(url, { signal: opts.signal });
+ if (!res.ok || res.body === null) {
+ throw new Error(`download failed: HTTP ${res.status} for ${url}`);
+ }
+ const lenHeader = res.headers.get('content-length');
+ const totalBytes = lenHeader !== null && lenHeader !== '' ? Number(lenHeader) : null;
+ const hash = createHash('sha256');
+ let receivedBytes = 0;
+ const sink = createWriteStream(destPath);
+ const source = Readable.fromWeb(
+ res.body as unknown as import('node:stream/web').ReadableStream<Uint8Array>,
+ );
+ source.on('data', (chunk: Buffer) => {
+ hash.update(chunk);
+ receivedBytes += chunk.length;
+ opts.onProgress?.({
+ receivedBytes,
+ totalBytes: Number.isFinite(totalBytes) ? totalBytes : null,
+ });
+ });
+ await new Promise<void>((resolvePromise, rejectPromise) => {
+ source
+ .pipe(sink)
+ .on('finish', () => resolvePromise())
+ .on('error', rejectPromise);
+ source.on('error', rejectPromise);
+ });
+ return hash.digest('hex');
+}
+
+/** Fetch a small text sidecar (SHASUMS256.txt, `.sha256`). */
+export async function fetchText(
+ url: string,
+ opts: { signal?: AbortSignal; fetchImpl?: typeof fetch } = {},
+): Promise<string> {
+ const fetchImpl = opts.fetchImpl ?? fetch;
+ const res = await fetchImpl(url, { signal: opts.signal });
+ if (!res.ok) throw new Error(`fetch failed: HTTP ${res.status} for ${url}`);
+ return res.text();
+}
+
+/**
+ * Find the hex digest for `filename` in a checksum file. Handles both the
+ * Node `SHASUMS256.txt` layout (many `"<sha> <name>"` lines) and the uv
+ * per-asset `.sha256` layout (`"<sha> <name>"` on its own). Match is on the
+ * basename so a `*` binary-mode marker or a path prefix on the name is fine.
+ */
+export function shaForFile(checksums: string, filename: string): string | null {
+ for (const line of checksums.split('\n')) {
+ const trimmed = line.trim();
+ if (trimmed === '') continue;
+ const match = /^([a-fA-F0-9]{64})\s+\*?(.+)$/.exec(trimmed);
+ if (match === null) continue;
+ const [, sha, name] = match;
+ const base = name.trim().split(/[\\/]/).pop();
+ if (base === filename) return sha.toLowerCase();
+ }
+ return null;
+}
diff --git a/packages/server/src/acp/confine-path.test.ts b/packages/server/src/acp/confine-path.test.ts
new file mode 100644
index 000000000..ff405a964
--- /dev/null
+++ b/packages/server/src/acp/confine-path.test.ts
@@ -0,0 +1,86 @@
+import { mkdirSync, mkdtempSync, rmSync, symlinkSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { afterEach, describe, expect, test } from 'vitest';
+import { confineToContentDir } from './thread-manager.ts';
+
+const notExcluded = (): boolean => false;
+
+let dirs: string[] = [];
+function tmp(): string {
+ const d = mkdtempSync(join(tmpdir(), 'acp-confine-test-'));
+ dirs.push(d);
+ return d;
+}
+afterEach(() => {
+ for (const d of dirs) rmSync(d, { recursive: true, force: true });
+ dirs = [];
+});
+
+describe('confineToContentDir', () => {
+ test('maps in-scope markdown to an extension-less docName', async () => {
+ const root = tmp();
+ mkdirSync(join(root, 'notes'));
+ writeFileSync(join(root, 'notes', 'idea.md'), '# hi');
+ const result = await confineToContentDir(root, join(root, 'notes', 'idea.md'), notExcluded);
+ expect(result.docName).toBe('notes/idea');
+ expect(result.rel).toBe('notes/idea.md');
+ });
+
+ test('resolves relative paths against the content root', async () => {
+ const root = tmp();
+ writeFileSync(join(root, 'a.mdx'), 'x');
+ const result = await confineToContentDir(root, 'a.mdx', notExcluded);
+ expect(result.docName).toBe('a');
+ });
+
+ test('maps not-yet-existing markdown (agent creating a doc)', async () => {
+ const root = tmp();
+ const result = await confineToContentDir(root, join(root, 'new', 'doc.md'), notExcluded);
+ expect(result.docName).toBe('new/doc');
+ });
+
+ test('non-markdown stays docName-null (plain disk IO path)', async () => {
+ const root = tmp();
+ const result = await confineToContentDir(root, join(root, 'assets', 'x.png'), notExcluded);
+ expect(result.docName).toBeNull();
+ });
+
+ test('filter-excluded markdown stays docName-null', async () => {
+ const root = tmp();
+ const result = await confineToContentDir(root, join(root, 'secret.md'), () => true);
+ expect(result.docName).toBeNull();
+ });
+
+ test('reserved namespaces stay docName-null', async () => {
+ const root = tmp();
+ const result = await confineToContentDir(root, join(root, '__system__.md'), notExcluded);
+ expect(result.docName).toBeNull();
+ });
+
+ test('refuses .. traversal out of the root', async () => {
+ const root = tmp();
+ await expect(
+ confineToContentDir(root, join(root, '..', 'outside.md'), notExcluded),
+ ).rejects.toThrow('escapes');
+ });
+
+ test('refuses a symlink that points outside the root', async () => {
+ const root = tmp();
+ const outside = tmp();
+ writeFileSync(join(outside, 'target.md'), 'secret');
+ symlinkSync(join(outside, 'target.md'), join(root, 'inside.md'));
+ await expect(confineToContentDir(root, join(root, 'inside.md'), notExcluded)).rejects.toThrow(
+ 'escapes',
+ );
+ });
+
+ test('refuses new paths under an escaping symlinked directory', async () => {
+ const root = tmp();
+ const outside = tmp();
+ symlinkSync(outside, join(root, 'linked'));
+ await expect(
+ confineToContentDir(root, join(root, 'linked', 'new.md'), notExcluded),
+ ).rejects.toThrow('escapes');
+ });
+});
diff --git a/packages/server/src/acp/event-log-bounds.test.ts b/packages/server/src/acp/event-log-bounds.test.ts
new file mode 100644
index 000000000..bcda53d75
--- /dev/null
+++ b/packages/server/src/acp/event-log-bounds.test.ts
@@ -0,0 +1,180 @@
+import type { SessionUpdate } from '@agentclientprotocol/sdk';
+import type { ThreadEvent } from '@inkeep/open-knowledge-core/acp/thread-protocol';
+import { describe, expect, test } from 'vitest';
+import { boundSessionUpdateForLog, coalesceChunkInto } from './event-log-bounds.ts';
+
+const big = 'x'.repeat(50_000);
+
+/** A `session_update` transcript event carrying a streamed text chunk. */
+function chunk(
+ sessionUpdate: string,
+ text: string,
+ extra: { messageId?: string; type?: string } = {},
+): ThreadEvent {
+ const content = extra.type === undefined ? { type: 'text', text } : { type: extra.type, text };
+ const update = { sessionUpdate, content } as Record<string, unknown>;
+ if (extra.messageId !== undefined) update.messageId = extra.messageId;
+ return { kind: 'session_update', update: update as unknown as SessionUpdate, ts: 1 };
+}
+
+/** Read the folded text off a `session_update` chunk event. */
+function textOf(event: ThreadEvent): string {
+ if (event.kind !== 'session_update') throw new Error('not a session_update');
+ return (event.update as unknown as { content: { text: string } }).content.text;
+}
+
+describe('boundSessionUpdateForLog', () => {
+ test('oversized diff payloads are truncated with a marker', () => {
+ const update = {
+ sessionUpdate: 'tool_call_update',
+ toolCallId: 't1',
+ content: [{ type: 'diff', path: 'a.md', oldText: big, newText: big }],
+ } as unknown as SessionUpdate;
+ const bounded = boundSessionUpdateForLog(update) as unknown as {
+ content: Array<{ oldText: string; newText: string }>;
+ };
+ expect(bounded).not.toBe(update);
+ expect(bounded.content[0].oldText.length).toBeLessThan(17_000);
+ expect(bounded.content[0].oldText).toContain('[truncated');
+ expect(bounded.content[0].newText).toContain('[truncated');
+ });
+
+ test('oversized text content blocks are truncated', () => {
+ const update = {
+ sessionUpdate: 'tool_call',
+ toolCallId: 't1',
+ content: [{ type: 'content', content: { type: 'text', text: big } }],
+ } as unknown as SessionUpdate;
+ const bounded = boundSessionUpdateForLog(update) as unknown as {
+ content: Array<{ content: { text: string } }>;
+ };
+ expect(bounded.content[0].content.text.length).toBeLessThan(17_000);
+ });
+
+ test('within-cap updates pass through by reference (no allocation)', () => {
+ const update = {
+ sessionUpdate: 'tool_call_update',
+ toolCallId: 't1',
+ content: [{ type: 'diff', path: 'a.md', oldText: 'small', newText: 'tiny' }],
+ } as unknown as SessionUpdate;
+ expect(boundSessionUpdateForLog(update)).toBe(update);
+ });
+
+ test('non-tool updates pass through by reference', () => {
+ const update = {
+ sessionUpdate: 'agent_message_chunk',
+ content: { type: 'text', text: big },
+ } as unknown as SessionUpdate;
+ // Message chunks arrive pre-chunked by the agent; only tool payloads
+ // carry whole-file text.
+ expect(boundSessionUpdateForLog(update)).toBe(update);
+ });
+});
+
+describe('coalesceChunkInto', () => {
+ test('folds consecutive same-stream text chunks into the tail, in order', () => {
+ const prev = chunk('agent_message_chunk', 'Hello');
+ expect(coalesceChunkInto(prev, chunk('agent_message_chunk', ', '))).toBe(true);
+ expect(coalesceChunkInto(prev, chunk('agent_message_chunk', 'world'))).toBe(true);
+ expect(textOf(prev)).toBe('Hello, world');
+ });
+
+ test('folds thought and user chunks too (both coalesce client-side)', () => {
+ const thought = chunk('agent_thought_chunk', 'think');
+ expect(coalesceChunkInto(thought, chunk('agent_thought_chunk', 'ing'))).toBe(true);
+ expect(textOf(thought)).toBe('thinking');
+ const user = chunk('user_message_chunk', 'a');
+ expect(coalesceChunkInto(user, chunk('user_message_chunk', 'b'))).toBe(true);
+ expect(textOf(user)).toBe('ab');
+ });
+
+ test('does not fold across differing chunk kinds', () => {
+ const message = chunk('agent_message_chunk', 'answer');
+ expect(coalesceChunkInto(message, chunk('agent_thought_chunk', 'thought'))).toBe(false);
+ expect(textOf(message)).toBe('answer');
+ });
+
+ test('does not fold non-streaming session updates', () => {
+ const toolCall = chunk('tool_call', 'x');
+ expect(coalesceChunkInto(toolCall, chunk('tool_call', 'y'))).toBe(false);
+ });
+
+ test('does not fold across differing messageId (separate bubbles client-side)', () => {
+ const a = chunk('agent_message_chunk', 'a', { messageId: 'm1' });
+ expect(coalesceChunkInto(a, chunk('agent_message_chunk', 'b', { messageId: 'm2' }))).toBe(
+ false,
+ );
+ // Same explicit messageId still folds.
+ const c = chunk('agent_message_chunk', 'c', { messageId: 'm1' });
+ expect(coalesceChunkInto(c, chunk('agent_message_chunk', 'd', { messageId: 'm1' }))).toBe(true);
+ expect(textOf(c)).toBe('cd');
+ });
+
+ test('missing messageId matches missing messageId (both default)', () => {
+ const a = chunk('agent_message_chunk', 'a');
+ expect(coalesceChunkInto(a, chunk('agent_message_chunk', 'b'))).toBe(true);
+ expect(textOf(a)).toBe('ab');
+ });
+
+ test('does not fold when either side is non-text content (image chunk)', () => {
+ const image = chunk('agent_message_chunk', '', { type: 'image' });
+ expect(coalesceChunkInto(image, chunk('agent_message_chunk', 'text'))).toBe(false);
+ const text = chunk('agent_message_chunk', 'text');
+ expect(coalesceChunkInto(text, chunk('agent_message_chunk', '', { type: 'image' }))).toBe(
+ false,
+ );
+ });
+
+ test('does not fold non-session_update events', () => {
+ const userMsg: ThreadEvent = { kind: 'user_message', content: 'hi', ts: 1 };
+ expect(coalesceChunkInto(userMsg, chunk('agent_message_chunk', 'x'))).toBe(false);
+ expect(coalesceChunkInto(chunk('agent_message_chunk', 'x'), userMsg)).toBe(false);
+ });
+
+ test('stops folding once the tail hits the size cap (bounds one line)', () => {
+ const prev = chunk('agent_message_chunk', 'x'.repeat(16_000));
+ // At the cap: refuses further folds so no single line grows unbounded.
+ expect(coalesceChunkInto(prev, chunk('agent_message_chunk', 'more'))).toBe(false);
+ expect(textOf(prev)).toBe('x'.repeat(16_000));
+ // Just under the cap still folds once (may exceed the cap by the added
+ // chunk — the cap gates the NEXT fold, it doesn't truncate).
+ const under = chunk('agent_message_chunk', 'y'.repeat(15_999));
+ expect(coalesceChunkInto(under, chunk('agent_message_chunk', 'zz'))).toBe(true);
+ expect(coalesceChunkInto(under, chunk('agent_message_chunk', 'no'))).toBe(false);
+ });
+});
+
+describe('coalesceChunkInto — terminal output', () => {
+ const terminalChunk = (terminalId: string, chunk: string): ThreadEvent => ({
+ kind: 'terminal_output',
+ terminalId,
+ chunk,
+ ts: 1,
+ });
+
+ test('folds consecutive chunks of the same terminal', () => {
+ const prev = terminalChunk('t1', 'line one\n');
+ expect(coalesceChunkInto(prev, terminalChunk('t1', 'line two\n'))).toBe(true);
+ if (prev.kind !== 'terminal_output') throw new Error('unreachable');
+ expect(prev.chunk).toBe('line one\nline two\n');
+ });
+
+ test('does not fold across terminals or event kinds', () => {
+ const prev = terminalChunk('t1', 'a');
+ expect(coalesceChunkInto(prev, terminalChunk('t2', 'b'))).toBe(false);
+ expect(
+ coalesceChunkInto(prev, {
+ kind: 'terminal_exit',
+ terminalId: 't1',
+ exitCode: 0,
+ signal: null,
+ ts: 2,
+ }),
+ ).toBe(false);
+ });
+
+ test('stops folding once the tail chunk hits the size cap', () => {
+ const prev = terminalChunk('t1', 'x'.repeat(16_000));
+ expect(coalesceChunkInto(prev, terminalChunk('t1', 'more'))).toBe(false);
+ });
+});
diff --git a/packages/server/src/acp/event-log-bounds.ts b/packages/server/src/acp/event-log-bounds.ts
new file mode 100644
index 000000000..155aff19f
--- /dev/null
+++ b/packages/server/src/acp/event-log-bounds.ts
@@ -0,0 +1,139 @@
+/**
+ * Size bounds for the retained thread event log. Tool-call diffs can embed
+ * whole-file before/after text; the log keeps thousands of events per thread
+ * and re-sends them on every replay, so unbounded payloads turn one busy
+ * doc-rewriting agent into hundreds of MB of server memory and replay
+ * traffic. Only the transcript's retained copy is bounded — the live
+ * document content is untouched.
+ */
+
+import type { SessionUpdate } from '@agentclientprotocol/sdk';
+import type { ThreadEvent } from '@inkeep/open-knowledge-core/acp/thread-protocol';
+
+const EVENT_TEXT_CAP = 16_000;
+
+function truncateEventText(text: string): string {
+ if (text.length <= EVENT_TEXT_CAP) return text;
+ return `${text.slice(0, EVENT_TEXT_CAP)}\n… [truncated ${text.length - EVENT_TEXT_CAP} chars]`;
+}
+
+/**
+ * Bound oversized tool-call payloads (diffs, content blocks) before
+ * retention. Returns the input unchanged (same reference) when nothing
+ * exceeds the cap — the common path allocates nothing.
+ */
+export function boundSessionUpdateForLog(update: SessionUpdate): SessionUpdate {
+ const u = update as { sessionUpdate?: string; content?: unknown };
+ if (
+ (u.sessionUpdate !== 'tool_call' && u.sessionUpdate !== 'tool_call_update') ||
+ !Array.isArray(u.content)
+ ) {
+ return update;
+ }
+ let changed = false;
+ const content = u.content.map((block) => {
+ const b = block as Record<string, unknown>;
+ if (b.type === 'diff') {
+ const oldText = typeof b.oldText === 'string' ? truncateEventText(b.oldText) : b.oldText;
+ const newText = typeof b.newText === 'string' ? truncateEventText(b.newText) : b.newText;
+ if (oldText !== b.oldText || newText !== b.newText) {
+ changed = true;
+ return { ...b, oldText, newText };
+ }
+ return block;
+ }
+ if (b.type === 'content') {
+ const inner = b.content as { type?: string; text?: string } | undefined;
+ if (inner?.type === 'text' && typeof inner.text === 'string') {
+ const text = truncateEventText(inner.text);
+ if (text !== inner.text) {
+ changed = true;
+ return { ...b, content: { ...inner, text } };
+ }
+ }
+ return block;
+ }
+ return block;
+ });
+ if (!changed) return update;
+ return { ...update, content } as SessionUpdate;
+}
+
+/**
+ * Streaming `session_update` chunk kinds the app coalesces into one message
+ * bubble (see `pushMessageChunk` in the app's thread-event-model). Folding the
+ * retained transcript along the same lines keeps disk == what the UI renders.
+ */
+const COALESCIBLE_CHUNK_KINDS = new Set([
+ 'agent_message_chunk',
+ 'agent_thought_chunk',
+ 'user_message_chunk',
+]);
+
+/**
+ * Stop growing a folded chunk past this many chars — the next chunk starts a
+ * fresh event instead. Bounds a single streamed answer to a handful of NDJSON
+ * lines rather than one unbounded one (mirrors EVENT_TEXT_CAP for tool diffs).
+ */
+const COALESCE_TEXT_CAP = 16_000;
+
+interface ChunkUpdate {
+ sessionUpdate: string;
+ messageId?: unknown;
+ content?: { type?: string; text?: string } | unknown;
+}
+
+/** The chunk's single text block, or null when it isn't a `{type:'text'}` block. */
+function chunkText(content: unknown): string | null {
+ if (typeof content !== 'object' || content === null) return null;
+ const c = content as { type?: string; text?: string };
+ return c.type === 'text' && typeof c.text === 'string' ? c.text : null;
+}
+
+/** Matches the app's `messageId(update)`: string messageId, else 'default'. */
+function chunkMessageId(u: ChunkUpdate): string {
+ return typeof u.messageId === 'string' ? u.messageId : 'default';
+}
+
+/**
+ * Fold `next` into `prev` when both are consecutive streamed text chunks of
+ * the SAME stream — same `sessionUpdate` kind and messageId, both text
+ * content — by appending next's text onto prev's in place. Returns true when
+ * folded (the caller then drops `next`, so it consumes no seq); false when the
+ * pair isn't mergeable or prev already hit {@link COALESCE_TEXT_CAP}.
+ *
+ * The predicate is a safe subset of the app's own role:messageId chunk
+ * coalescing: it never folds two chunks the UI would keep in separate bubbles
+ * (a thought↔message switch, a differing messageId, or an interleaved tool
+ * call / permission all break the run), so concatenation stays faithful. It
+ * may leave adjacent chunks unfolded across a flush boundary — the app merges
+ * those on its side, exactly as it already does with today's per-word events.
+ *
+ * Callable ONLY on the not-yet-flushed tail event: growing an event whose seq
+ * was already broadcast/persisted would break the line-index-IS-the-seq
+ * contract. A fold assigns no new seq, so that contract is preserved.
+ */
+export function coalesceChunkInto(prev: ThreadEvent, next: ThreadEvent): boolean {
+ // Terminal output folds along the same lines as streamed text: the app
+ // concatenates a terminal's chunks anyway, so consecutive chunks of the
+ // SAME terminal merge into one retained event (and one seq).
+ if (prev.kind === 'terminal_output' && next.kind === 'terminal_output') {
+ if (prev.terminalId !== next.terminalId) return false;
+ if (prev.chunk.length >= COALESCE_TEXT_CAP) return false;
+ prev.chunk += next.chunk;
+ return true;
+ }
+ if (prev.kind !== 'session_update' || next.kind !== 'session_update') return false;
+ const p = prev.update as ChunkUpdate;
+ const n = next.update as ChunkUpdate;
+ if (p.sessionUpdate !== n.sessionUpdate || !COALESCIBLE_CHUNK_KINDS.has(n.sessionUpdate)) {
+ return false;
+ }
+ if (chunkMessageId(p) !== chunkMessageId(n)) return false;
+ const prevText = chunkText(p.content);
+ const nextText = chunkText(n.content);
+ if (prevText === null || nextText === null) return false;
+ if (prevText.length >= COALESCE_TEXT_CAP) return false;
+ p.content = { type: 'text', text: prevText + nextText };
+ return true;
+}
diff --git a/packages/server/src/acp/harness-availability.test.ts b/packages/server/src/acp/harness-availability.test.ts
new file mode 100644
index 000000000..62cd9ca90
--- /dev/null
+++ b/packages/server/src/acp/harness-availability.test.ts
@@ -0,0 +1,57 @@
+import type { TerminalCli } from '@inkeep/open-knowledge-core';
+import { describe, expect, test } from 'vitest';
+import {
+ ACP_AGENT_HARNESS_CLIS,
+ createAcpHarnessAvailabilityProbe,
+ type HarnessAvailability,
+} from './harness-availability.ts';
+
+describe('ACP harness availability', () => {
+ test('maps the registry-backed harness agents to their real CLI ids', () => {
+ expect(ACP_AGENT_HARNESS_CLIS).toEqual({
+ 'claude-acp': 'claude',
+ 'codex-acp': 'codex',
+ cursor: 'cursor',
+ opencode: 'opencode',
+ });
+ });
+
+ test('probes every mapped harness once and caches the in-flight result', async () => {
+ const calls: TerminalCli[] = [];
+ let timestamp = 100;
+ const availability: Partial<Record<TerminalCli, HarnessAvailability>> = {
+ claude: 'present',
+ codex: 'not-found',
+ cursor: 'unknown',
+ opencode: 'present',
+ };
+ const probe = createAcpHarnessAvailabilityProbe({
+ probe: async (cli) => {
+ calls.push(cli);
+ return availability[cli] ?? 'unknown';
+ },
+ now: () => timestamp,
+ ttlMs: 50,
+ });
+
+ const first = probe();
+ expect(probe()).toBe(first);
+ expect(await first).toEqual(availability);
+ expect(calls).toEqual(['claude', 'codex', 'cursor', 'opencode']);
+
+ timestamp = 151;
+ await probe();
+ expect(calls).toHaveLength(8);
+ });
+
+ test('contains a rejected per-harness probe as unknown', async () => {
+ const probe = createAcpHarnessAvailabilityProbe({
+ probe: async (cli) => {
+ if (cli === 'codex') throw new Error('probe failed');
+ return 'not-found';
+ },
+ });
+
+ expect((await probe()).codex).toBe('unknown');
+ });
+});
diff --git a/packages/server/src/acp/harness-availability.ts b/packages/server/src/acp/harness-availability.ts
new file mode 100644
index 000000000..1854217ec
--- /dev/null
+++ b/packages/server/src/acp/harness-availability.ts
@@ -0,0 +1,83 @@
+/**
+ * Local harness detection for registry-backed ACP agents.
+ *
+ * The ACP adapter distribution and the underlying harness are different
+ * things: a registry row may be runnable through npx while the corresponding
+ * first-party CLI is absent. This probe is only a defaulting/presentation
+ * signal. Launch resolution remains authoritative.
+ */
+
+import type { TerminalCli } from '@inkeep/open-knowledge-core';
+import { AgentLaunchError, mergedEnv, preflightLaunch } from './launch.ts';
+
+export type HarnessAvailability = 'present' | 'not-found' | 'unknown';
+
+export const ACP_AGENT_HARNESS_CLIS: Readonly<Record<string, TerminalCli | undefined>> = {
+ 'claude-acp': 'claude',
+ 'codex-acp': 'codex',
+ cursor: 'cursor',
+ opencode: 'opencode',
+};
+
+const HARNESS_BINS: Readonly<Record<TerminalCli, string>> = {
+ claude: 'claude',
+ codex: 'codex',
+ cursor: 'cursor-agent',
+ opencode: 'opencode',
+ pi: 'pi',
+ antigravity: 'agy',
+ copilot: 'copilot',
+ openclaw: 'openclaw',
+ hermes: 'hermes',
+};
+
+export type AcpHarnessAvailability = Readonly<Partial<Record<TerminalCli, HarnessAvailability>>>;
+
+const DEFAULT_TTL_MS = 60_000;
+
+async function detectHarness(cli: TerminalCli): Promise<HarnessAvailability> {
+ try {
+ await preflightLaunch({
+ cmd: HARNESS_BINS[cli],
+ args: [],
+ env: mergedEnv(),
+ kind: 'custom',
+ });
+ return 'present';
+ } catch (err) {
+ if (err instanceof AgentLaunchError && err.code === 'command-not-found') return 'not-found';
+ return 'unknown';
+ }
+}
+
+export function createAcpHarnessAvailabilityProbe(
+ opts: {
+ probe?: (cli: TerminalCli) => Promise<HarnessAvailability>;
+ now?: () => number;
+ ttlMs?: number;
+ } = {},
+): () => Promise<AcpHarnessAvailability> {
+ const probe = opts.probe ?? detectHarness;
+ const now = opts.now ?? Date.now;
+ const ttlMs = opts.ttlMs ?? DEFAULT_TTL_MS;
+ const harnesses = [...new Set(Object.values(ACP_AGENT_HARNESS_CLIS))].filter(
+ (cli): cli is TerminalCli => cli !== undefined,
+ );
+ let cached: { expiresAt: number; value: Promise<AcpHarnessAvailability> } | null = null;
+
+ return () => {
+ const timestamp = now();
+ if (cached !== null && cached.expiresAt > timestamp) return cached.value;
+ const value = Promise.all(
+ harnesses.map(async (cli) => {
+ try {
+ return [cli, await probe(cli)] as const;
+ } catch {
+ return [cli, 'unknown'] as const;
+ }
+ }),
+ ).then((entries) => Object.fromEntries(entries) as AcpHarnessAvailability);
+ cached = { expiresAt: timestamp + ttlMs, value };
+ return value;
+ };
+}
diff --git a/packages/server/src/acp/launch.test.ts b/packages/server/src/acp/launch.test.ts
new file mode 100644
index 000000000..3c8ea0fbe
--- /dev/null
+++ b/packages/server/src/acp/launch.test.ts
@@ -0,0 +1,209 @@
+/**
+ * Kill-semantics tests for `spawnAcpAgent` + `terminateAgentTree` — the
+ * process-tree death guarantee behind thread close and server shutdown.
+ *
+ * The stubborn fixture simulates the npx shape that motivated group-kill: a
+ * SIGTERM-ignoring wrapper whose SIGTERM-ignoring child is the "real" agent.
+ * Killing only the direct child orphans the grandchild (verified on macOS:
+ * SIGKILL to npx reparents its bin to PID 1, still running).
+ */
+
+import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { afterEach, describe, expect, test } from 'vitest';
+import {
+ AgentLaunchError,
+ preflightLaunch,
+ type ResolvedLaunch,
+ resolveWindowsCommand,
+ spawnAcpAgent,
+ terminateAgentTree,
+ windowsCmdWrap,
+} from './launch.ts';
+
+const isAlive = (pid: number): boolean => {
+ try {
+ process.kill(pid, 0);
+ return true;
+ } catch {
+ return false;
+ }
+};
+
+const plainEnv = (overlay: Record<string, string> = {}): Record<string, string> => {
+ const env: Record<string, string> = {};
+ for (const [k, v] of Object.entries(process.env)) {
+ if (v !== undefined) env[k] = v;
+ }
+ return { ...env, ...overlay };
+};
+
+const launchFor = (script: string, overlay?: Record<string, string>): ResolvedLaunch => ({
+ cmd: 'node',
+ args: [script],
+ env: plainEnv(overlay),
+ kind: 'custom',
+});
+
+async function waitFor(pred: () => boolean, ms: number, what: string): Promise<void> {
+ const deadline = Date.now() + ms;
+ while (!pred()) {
+ if (Date.now() > deadline) throw new Error(`timed out waiting for ${what}`);
+ await new Promise((r) => setTimeout(r, 25));
+ }
+}
+
+let dirs: string[] = [];
+let strayPids: number[] = [];
+function tmp(): string {
+ const d = mkdtempSync(join(tmpdir(), 'acp-launch-test-'));
+ dirs.push(d);
+ return d;
+}
+afterEach(() => {
+ for (const pid of strayPids) {
+ try {
+ process.kill(pid, 'SIGKILL');
+ } catch {
+ // Already gone — the desired state.
+ }
+ }
+ strayPids = [];
+ for (const d of dirs) rmSync(d, { recursive: true, force: true });
+ dirs = [];
+});
+
+describe('preflightLaunch', () => {
+ const catchErr = (p: Promise<unknown>): Promise<unknown> => p.then(() => null).catch((e) => e);
+
+ test('a path-qualified command that exists resolves', async () => {
+ // process.execPath is an absolute, executable path → no PATH search.
+ await expect(
+ preflightLaunch({ cmd: process.execPath, args: [], env: {}, kind: 'custom' }),
+ ).resolves.toBeUndefined();
+ });
+
+ test('a missing npx surfaces an actionable Node.js hint', async () => {
+ // Empty PATH guarantees `npx` cannot resolve on any platform.
+ const err = await catchErr(
+ preflightLaunch({ cmd: 'npx', args: ['-y', 'x'], env: { PATH: '' }, kind: 'npx' }),
+ );
+ expect(err).toBeInstanceOf(AgentLaunchError);
+ expect((err as AgentLaunchError).code).toBe('command-not-found');
+ expect((err as AgentLaunchError).message).toContain('Node.js');
+ });
+
+ test('a missing uvx surfaces an actionable uv hint', async () => {
+ const err = await catchErr(
+ preflightLaunch({ cmd: 'uvx', args: [], env: { PATH: '' }, kind: 'uvx' }),
+ );
+ expect(err).toBeInstanceOf(AgentLaunchError);
+ expect((err as AgentLaunchError).message).toContain('uv');
+ });
+
+ test('a bare command is found via a PATH search', async () => {
+ const dir = tmp();
+ const name = process.platform === 'win32' ? 'fakeagent.cmd' : 'fakeagent';
+ writeFileSync(join(dir, name), '#!/bin/sh\nexit 0\n', { mode: 0o755 });
+ await expect(
+ preflightLaunch({ cmd: 'fakeagent', args: [], env: { PATH: dir }, kind: 'custom' }),
+ ).resolves.toBeUndefined();
+ });
+
+ test('a missing binary distribution reports the offending path', async () => {
+ const missing = join(tmp(), 'does-not-exist-agent');
+ const err = await catchErr(
+ preflightLaunch({ cmd: missing, args: [], env: {}, kind: 'binary' }),
+ );
+ expect(err).toBeInstanceOf(AgentLaunchError);
+ expect((err as AgentLaunchError).code).toBe('command-not-found');
+ expect((err as AgentLaunchError).message).toContain(missing);
+ });
+});
+
+describe('windows cmd wrapping (spawn on Windows)', () => {
+ test('resolveWindowsCommand leaves path-qualified commands untouched', () => {
+ expect(resolveWindowsCommand('C:\\x\\uvx.exe', 'C:\\x')).toBe('C:\\x\\uvx.exe');
+ expect(resolveWindowsCommand('/usr/bin/uvx', undefined)).toBe('/usr/bin/uvx');
+ });
+
+ test('resolveWindowsCommand picks the .cmd/.exe, never a bare extensionless file', () => {
+ // Mirror the C:\Program Files\nodejs layout: an extensionless `npx` shell
+ // script next to `npx.cmd`. PATHEXT resolution must pick npx.cmd.
+ const dir = tmp();
+ writeFileSync(join(dir, 'npx'), '#!/bin/sh\n'); // git-bash script, not exec'able on Windows
+ writeFileSync(join(dir, 'npx.cmd'), '@echo off\n');
+ const resolved = resolveWindowsCommand('npx', dir);
+ // Never the extensionless script. On Windows it resolves to npx.cmd; on a
+ // case-sensitive FS with no PATHEXT it returns the input unchanged.
+ expect(resolved).not.toBe(join(dir, 'npx'));
+ if (resolved !== 'npx') expect(/\.cmd$/i.test(resolved)).toBe(true);
+ });
+
+ test('outer-quotes the whole command so a spaced launcher path survives /s', () => {
+ const { cmd, args } = windowsCmdWrap('C:\\Program Files\\nodejs\\npx.cmd', ['-y', 'pkg']);
+ expect(cmd.toLowerCase()).toContain('cmd');
+ expect(args.slice(0, 3)).toEqual(['/d', '/s', '/c']);
+ // The command line is wrapped in an outer pair of quotes (cmd /s strips
+ // the first + last quote), with the spaced launcher path quoted inside.
+ expect(args[3]).toBe('""C:\\Program Files\\nodejs\\npx.cmd" -y pkg"');
+ });
+
+ test('quotes args that would otherwise split or be interpreted by cmd', () => {
+ const { args } = windowsCmdWrap('tool', ['a b', 'safe', 'a&b', '']);
+ expect(args[3]).toBe('""tool" "a b" safe "a&b" """');
+ });
+});
+
+describe('terminateAgentTree', () => {
+ test('a compliant agent exits on SIGTERM within the grace window', async () => {
+ const dir = tmp();
+ const script = join(dir, 'compliant.mjs');
+ writeFileSync(script, 'setInterval(() => {}, 1000);\n');
+ const child = spawnAcpAgent(launchFor(script), dir);
+ if (child.pid !== undefined) strayPids.push(child.pid);
+ await waitFor(() => child.pid !== undefined, 2_000, 'spawn');
+
+ const dead = await terminateAgentTree(child, { graceMs: 3_000 });
+ expect(dead).toBe(true);
+ expect(child.pid !== undefined && isAlive(child.pid)).toBe(false);
+ // Graceful path: killed by the group SIGTERM, not the escalation.
+ expect(child.signalCode).toBe('SIGTERM');
+ });
+
+ test('a SIGTERM-ignoring wrapper AND its grandchild both die via group escalation', async () => {
+ const dir = tmp();
+ const kidPidFile = join(dir, 'kid.pid');
+ const script = join(dir, 'stubborn.mjs');
+ writeFileSync(
+ script,
+ [
+ "import { spawn } from 'node:child_process';",
+ "import { writeFileSync } from 'node:fs';",
+ "process.on('SIGTERM', () => {});",
+ 'const kid = spawn(process.execPath, [',
+ " '-e',",
+ ' "process.on(\'SIGTERM\', () => {}); setInterval(() => {}, 1000);",',
+ "], { stdio: 'ignore' });",
+ 'writeFileSync(process.env.KID_PID_FILE, String(kid.pid));',
+ 'setInterval(() => {}, 1000);',
+ '',
+ ].join('\n'),
+ );
+ const child = spawnAcpAgent(launchFor(script, { KID_PID_FILE: kidPidFile }), dir);
+ if (child.pid !== undefined) strayPids.push(child.pid);
+ await waitFor(() => existsSync(kidPidFile), 5_000, 'grandchild pid file');
+ const kidPid = Number(readFileSync(kidPidFile, 'utf8'));
+ strayPids.push(kidPid);
+ expect(Number.isInteger(kidPid) && kidPid > 0).toBe(true);
+ expect(isAlive(kidPid)).toBe(true);
+
+ const dead = await terminateAgentTree(child, { graceMs: 250 });
+ expect(dead).toBe(true);
+ expect(child.pid !== undefined && isAlive(child.pid)).toBe(false);
+ // The load-bearing assertion: the grandchild died with the group. A
+ // direct-child SIGKILL would leave it running (the npx orphan bug).
+ await waitFor(() => !isAlive(kidPid), 2_000, 'grandchild death');
+ });
+});
diff --git a/packages/server/src/acp/launch.ts b/packages/server/src/acp/launch.ts
new file mode 100644
index 000000000..f2e905b84
--- /dev/null
+++ b/packages/server/src/acp/launch.ts
@@ -0,0 +1,477 @@
+/**
+ * Resolve + spawn ACP agent processes.
+ *
+ * Security envelope (spec 2026-07-02-acp-external-agents §9): spawnable
+ * commands come ONLY from (a) registry manifests (npx / uvx / binary
+ * distribution specs) or (b) the machine-local custom-agents file. Nothing
+ * arriving over HTTP/WS names a command — frames carry agent IDS which
+ * resolve through this module. `shell: false` + argv arrays throughout.
+ *
+ * Never bundled, never redistributed: npx/uvx packages install into the
+ * user's package-manager cache at launch time; binary archives download to
+ * `~/.ok/acp-agents/<id>/<version>/` (user-level so N projects share one
+ * install). Proprietary agents therefore stay entirely outside OK's GPL
+ * distribution.
+ */
+
+import { type ChildProcess, spawn } from 'node:child_process';
+import { constants, statSync } from 'node:fs';
+import { access, chmod, stat } from 'node:fs/promises';
+import { homedir, tmpdir } from 'node:os';
+import { delimiter, isAbsolute, join, resolve } from 'node:path';
+import { OK_DIR } from '@inkeep/open-knowledge-core';
+import { tracedMkdir, tracedRename, tracedRm } from '../fs-traced.ts';
+import type { PinoLogger } from '../logger.ts';
+import { downloadToFileWithSha, extractArchive, isWithin, sanitizeSegment } from './archive.ts';
+import type { ManagedRuntime } from './managed-runtime.ts';
+import type { CustomAgentEntry, RegistryAgent, RegistryBinaryTarget } from './registry.ts';
+
+export interface ResolvedLaunch {
+ cmd: string;
+ args: string[];
+ env: Record<string, string>;
+ kind: 'npx' | 'uvx' | 'binary' | 'custom';
+}
+
+export class AgentLaunchError extends Error {
+ readonly code:
+ | 'unsupported-platform'
+ | 'no-distribution'
+ | 'install-failed'
+ | 'command-not-found';
+ constructor(code: AgentLaunchError['code'], message: string) {
+ super(message);
+ this.name = 'AgentLaunchError';
+ this.code = code;
+ }
+}
+
+/** User-level cache for extracted binary distributions. */
+function defaultBinaryCacheDir(): string {
+ return join(homedir(), OK_DIR, 'acp-agents');
+}
+
+export function mergedEnv(overlay?: Record<string, string>): Record<string, string> {
+ const env: Record<string, string> = {};
+ for (const [k, v] of Object.entries(process.env)) {
+ if (v !== undefined) env[k] = v;
+ }
+ return { ...env, ...overlay };
+}
+
+/**
+ * Resolve a registry agent to a spawnable command, downloading + extracting
+ * a binary distribution when that's the only option. Preference order
+ * npx → uvx → binary: package-manager launches self-update via the pinned
+ * version in the manifest and need no archive plumbing.
+ */
+export async function resolveRegistryLaunch(
+ agent: RegistryAgent,
+ platformKey: string | null,
+ log: PinoLogger,
+ binaryCacheDir: string = defaultBinaryCacheDir(),
+): Promise<ResolvedLaunch> {
+ const dist = agent.distribution;
+ if (dist.npx !== undefined) {
+ return {
+ cmd: 'npx',
+ args: ['-y', dist.npx.package, ...(dist.npx.args ?? [])],
+ env: mergedEnv(dist.npx.env),
+ kind: 'npx',
+ };
+ }
+ if (dist.uvx !== undefined) {
+ return {
+ cmd: 'uvx',
+ args: [dist.uvx.package, ...(dist.uvx.args ?? [])],
+ env: mergedEnv(dist.uvx.env),
+ kind: 'uvx',
+ };
+ }
+ if (dist.binary !== undefined) {
+ if (platformKey === null || dist.binary[platformKey] === undefined) {
+ throw new AgentLaunchError(
+ 'unsupported-platform',
+ `${agent.name} has no build for this platform`,
+ );
+ }
+ const target = dist.binary[platformKey];
+ const root = await ensureBinaryInstalled(agent.id, agent.version, target, binaryCacheDir, log);
+ // `cmd` is relative to the archive root (e.g. `./dist-package/cursor-agent`).
+ const cmd = resolve(root, target.cmd.replace(/\\/g, '/'));
+ if (!isWithin(root, cmd)) {
+ throw new AgentLaunchError(
+ 'install-failed',
+ `${agent.name} manifest cmd escapes its archive`,
+ );
+ }
+ return { cmd, args: [...(target.args ?? [])], env: mergedEnv(target.env), kind: 'binary' };
+ }
+ throw new AgentLaunchError('no-distribution', `${agent.name} has no supported distribution`);
+}
+
+export function resolveCustomLaunch(entry: CustomAgentEntry): ResolvedLaunch {
+ return {
+ cmd: entry.command,
+ args: [...(entry.args ?? [])],
+ env: mergedEnv(entry.env),
+ kind: 'custom',
+ };
+}
+
+/**
+ * Rewrite an npx/uvx launch to run through a runtime OK downloaded — used
+ * when the system interpreter is absent. Swaps the command for the managed
+ * tree's own `npx`/`uvx` (which behaves identically to the system one, so the
+ * args carry over unchanged), prepends the runtime's bin dir to PATH so
+ * nested `node`/`uv` resolve to the managed copy, and points the package
+ * cache at a private dir so package installs never touch the user's global
+ * `~/.npm` / uv cache. Only npx/uvx launches are rewritable — a binary or
+ * custom command has no managed fallback.
+ */
+export function rewriteLaunchToManagedRuntime(
+ launch: ResolvedLaunch,
+ runtime: ManagedRuntime,
+): ResolvedLaunch {
+ const env = { ...launch.env };
+ env[pathKey(env)] = prependPath(runtime.binDir, envPath(env));
+ if (runtime.kind === 'node') {
+ env.npm_config_cache = runtime.cacheDir;
+ return { cmd: runtime.npxBin, args: [...launch.args], env, kind: 'npx' };
+ }
+ env.UV_CACHE_DIR = runtime.cacheDir;
+ return { cmd: runtime.uvxBin, args: [...launch.args], env, kind: 'uvx' };
+}
+
+/** The env's PATH key (Windows spells it `Path`), for case-preserving overwrite. */
+function pathKey(env: Record<string, string>): string {
+ for (const k of Object.keys(env)) {
+ if (k.toLowerCase() === 'path') return k;
+ }
+ return 'PATH';
+}
+
+function prependPath(dir: string, existing: string | undefined): string {
+ return existing !== undefined && existing !== '' ? `${dir}${delimiter}${existing}` : dir;
+}
+
+/**
+ * Download + extract a binary distribution once per (id, version); later
+ * launches reuse the extracted tree. Extraction lands in a temp dir first
+ * and is renamed into place so a crash mid-extract never leaves a
+ * half-populated version dir that would satisfy the fast-path check.
+ */
+async function ensureBinaryInstalled(
+ id: string,
+ version: string,
+ target: RegistryBinaryTarget,
+ cacheDir: string,
+ log: PinoLogger,
+): Promise<string> {
+ const versionDir = join(cacheDir, sanitizeSegment(id), sanitizeSegment(version));
+ try {
+ const st = await stat(versionDir);
+ if (st.isDirectory()) return versionDir;
+ } catch {
+ // Not installed yet.
+ }
+
+ log.info({ id, version, archive: target.archive }, '[acp-launch] downloading agent binary');
+ const stagingDir = join(tmpdir(), `ok-acp-install-${process.pid}-${Date.now()}`);
+ await tracedMkdir(stagingDir, { recursive: true });
+ const isZip = /\.zip$/i.test(new URL(target.archive).pathname);
+ const archivePath = join(stagingDir, isZip ? 'archive.zip' : 'archive.tar.gz');
+ try {
+ const sha = await downloadToFileWithSha(target.archive, archivePath, {
+ signal: AbortSignal.timeout(120_000),
+ });
+ // Binary distributions are opaque executables — verify the publisher's
+ // checksum whenever the manifest carries one, mirroring the managed-
+ // runtime download path. A manifest without one installs with a loud
+ // warning rather than silently skipping verification.
+ if (target.sha256 !== undefined) {
+ if (sha !== target.sha256.toLowerCase()) {
+ throw new Error(`archive checksum mismatch: expected ${target.sha256}, got ${sha}`);
+ }
+ } else {
+ log.warn(
+ { id, version, archive: target.archive },
+ '[acp-launch] manifest carries no sha256 for the binary archive — installing unverified',
+ );
+ }
+
+ const extractDir = join(stagingDir, 'extracted');
+ await tracedMkdir(extractDir, { recursive: true });
+ await extractArchive(archivePath, extractDir, isZip);
+ const cmdPath = resolve(extractDir, target.cmd.replace(/\\/g, '/'));
+ if (!isWithin(extractDir, cmdPath)) {
+ throw new Error('manifest cmd escapes the extracted archive');
+ }
+ await chmod(cmdPath, 0o755).catch(() => {
+ // Windows / already-executable — non-fatal.
+ });
+
+ await tracedMkdir(join(cacheDir, sanitizeSegment(id)), { recursive: true });
+ await tracedRm(versionDir, { recursive: true, force: true });
+ await tracedRename(extractDir, versionDir);
+ log.info({ id, version, versionDir }, '[acp-launch] agent binary installed');
+ return versionDir;
+ } catch (err) {
+ throw new AgentLaunchError(
+ 'install-failed',
+ `installing ${id}@${version} failed: ${err instanceof Error ? err.message : String(err)}`,
+ );
+ } finally {
+ await tracedRm(stagingDir, { recursive: true, force: true }).catch(() => {
+ // Best-effort temp cleanup.
+ });
+ }
+}
+
+/**
+ * Verify the resolved command is launchable BEFORE spawning, so a missing
+ * interpreter surfaces as an actionable "install X" message instead of the
+ * child's asynchronous, opaque `spawn <cmd> ENOENT` (which today lands as a
+ * generic `spawn-failed` / `agent failed to start` status).
+ *
+ * `npx`/`uvx`/a bare custom command are searched across `PATH` the way the OS
+ * would — honoring `PATHEXT` on Windows, where `npx` is really `npx.cmd`. A
+ * path-qualified command (binary distributions, path-qualified custom agents)
+ * is checked in place. Throws `AgentLaunchError('command-not-found')` with a
+ * per-kind remediation hint when nothing is executable.
+ */
+export async function preflightLaunch(launch: ResolvedLaunch): Promise<void> {
+ if (await isLaunchable(launch.cmd, envPath(launch.env))) return;
+ throw new AgentLaunchError('command-not-found', missingCommandHint(launch));
+}
+
+function missingCommandHint(launch: ResolvedLaunch): string {
+ switch (launch.kind) {
+ case 'npx':
+ return `\`${launch.cmd}\` was not found. This agent runs through npx, which ships with Node.js — install Node.js (https://nodejs.org) and make sure it is on your PATH.`;
+ case 'uvx':
+ return `\`${launch.cmd}\` was not found. This agent runs through uvx, which ships with uv — install uv (https://docs.astral.sh/uv/getting-started/installation/) and make sure it is on your PATH.`;
+ case 'binary':
+ return `the agent binary at ${launch.cmd} is missing or not executable.`;
+ case 'custom':
+ return `\`${launch.cmd}\` was not found on your PATH — check the command configured for this custom agent.`;
+ }
+}
+
+/** Case-insensitive `PATH` lookup (Windows spells it `Path`), falling back to the process env. */
+export function envPath(env: Record<string, string>): string | undefined {
+ for (const [k, v] of Object.entries(env)) {
+ if (k.toLowerCase() === 'path') return v;
+ }
+ return process.env.PATH;
+}
+
+/** Resolve `cmd` to an executable the way the OS would at spawn time. */
+async function isLaunchable(cmd: string, pathEnv: string | undefined): Promise<boolean> {
+ const win = process.platform === 'win32';
+ // A path-qualified command is checked in place — no PATH search.
+ if (isAbsolute(cmd) || cmd.includes('/') || (win && cmd.includes('\\'))) {
+ return isExecutableFile(cmd);
+ }
+ const exts = win
+ ? [
+ '',
+ ...(process.env.PATHEXT ?? '.COM;.EXE;.BAT;.CMD')
+ .split(';')
+ .map((e) => e.trim())
+ .filter((e) => e !== ''),
+ ]
+ : [''];
+ for (const dir of (pathEnv ?? '').split(delimiter)) {
+ if (dir === '') continue;
+ for (const ext of exts) {
+ if (await isExecutableFile(join(dir, cmd + ext))) return true;
+ }
+ }
+ return false;
+}
+
+async function isExecutableFile(candidate: string): Promise<boolean> {
+ try {
+ const st = await stat(candidate);
+ if (!st.isFile()) return false;
+ // Windows has no execute bit; a matching PATHEXT entry (already applied by
+ // the caller) is the executability signal there.
+ if (process.platform === 'win32') return true;
+ await access(candidate, constants.X_OK);
+ return true;
+ } catch {
+ return false;
+ }
+}
+
+/**
+ * Resolve a bare Windows command to its absolute launcher via PATH + PATHEXT,
+ * searching only executable extensions (`.EXE`/`.CMD`/…) — never the bare file.
+ * `C:\Program Files\nodejs` ships both an extensionless `npx` (a git-bash shell
+ * script Windows can't exec) and `npx.cmd`; resolving to the real `npx.cmd` is
+ * what lets it launch, and it fixes npm's `%~dp0` too (invoking `npx.cmd` by
+ * its absolute path resolves its own dir correctly, where a quoted bare `"npx"`
+ * resolves it to the cwd). Returns the input unchanged when already
+ * path-qualified or unresolved. VM-verified against real `npx`.
+ */
+export function resolveWindowsCommand(cmd: string, pathEnv: string | undefined): string {
+ if (isAbsolute(cmd) || cmd.includes('\\') || cmd.includes('/')) return cmd;
+ const exts = (process.env.PATHEXT ?? '.COM;.EXE;.BAT;.CMD')
+ .split(';')
+ .map((e) => e.trim())
+ .filter((e) => e !== '');
+ for (const dir of (pathEnv ?? '').split(delimiter)) {
+ if (dir === '') continue;
+ for (const ext of exts) {
+ const candidate = join(dir, cmd + ext);
+ try {
+ if (statSync(candidate).isFile()) return candidate;
+ } catch {
+ // Not this candidate.
+ }
+ }
+ }
+ return cmd;
+}
+
+/** Double-quote a token if cmd.exe would otherwise split or interpret it. */
+function quoteCmdArg(arg: string): string {
+ if (arg === '') return '""';
+ return /[\s"&()<>^|%]/.test(arg) ? `"${arg.replace(/"/g, '""')}"` : arg;
+}
+
+/**
+ * On Windows, route a `.cmd`/bare launcher through `cmd.exe /d /s /c`. The
+ * whole command is wrapped in an OUTER pair of quotes (`cmd /c ""exe" args"`)
+ * because `/s` strips the first and last quote — without it a launcher path
+ * containing a space (e.g. `C:\Program Files\nodejs\npx.cmd`) is mis-split by
+ * cmd. Passed verbatim so we, not Node, own the quoting. Args come only from
+ * the trusted registry/custom sources (spec §9), and double-quoting neutralizes
+ * cmd metacharacters for the package-name/flag arguments in practice.
+ * VM-verified: real `npx` runs and bidirectional stdio (the ACP handshake)
+ * round-trips through the wrapper.
+ */
+export function windowsCmdWrap(cmd: string, args: string[]): { cmd: string; args: string[] } {
+ const inner = [`"${cmd}"`, ...args.map(quoteCmdArg)].join(' ');
+ return { cmd: process.env.ComSpec ?? 'cmd.exe', args: ['/d', '/s', '/c', `"${inner}"`] };
+}
+
+/**
+ * Spawn the resolved agent. Its lifetime is owned by its thread (killed on
+ * thread close and on server shutdown), the opposite of the fire-and-forget
+ * `spawn-detached.ts` handoff path.
+ *
+ * POSIX spawns are `detached: true` for group-kill, NOT for independence:
+ * npx/uvx launches make the real agent a *grandchild*, and SIGKILL cannot be
+ * forwarded by a dead wrapper — killing only the direct child orphans a
+ * stuck agent mid-LLM-turn (verified: SIGKILL to `npx` leaves its bin
+ * running, reparented to PID 1). `detached` makes the wrapper a process-group
+ * leader so `terminateAgentTree` can signal the whole tree at once.
+ *
+ * On Windows, Node can't spawn a `.cmd`/`.bat` with `shell: false`
+ * (CVE-2024-27980) and does no PATHEXT resolution for bare names — so a bare
+ * launcher (system `npx`) is resolved to its absolute `npx.cmd` and any
+ * `.cmd`/`.bat` is run through cmd.exe. Native `.exe`s (`uvx`, agent binaries,
+ * the managed node) spawn directly. `taskkill /T` still reaps the whole tree.
+ */
+export function spawnAcpAgent(launch: ResolvedLaunch, cwd: string): ChildProcess {
+ if (!isAbsolute(cwd)) {
+ throw new Error(`spawnAcpAgent requires an absolute cwd, got: ${cwd}`);
+ }
+ const win = process.platform === 'win32';
+ const resolved = win ? resolveWindowsCommand(launch.cmd, envPath(launch.env)) : launch.cmd;
+ const wrap = win && /\.(cmd|bat)$/i.test(resolved);
+ const { cmd, args } = wrap
+ ? windowsCmdWrap(resolved, launch.args)
+ : { cmd: resolved, args: launch.args };
+ return spawn(cmd, args, {
+ cwd,
+ env: launch.env,
+ stdio: ['pipe', 'pipe', 'pipe'],
+ shell: false,
+ detached: !win,
+ windowsHide: true,
+ // We built the cmd.exe command line ourselves (outer-quoted for spaced
+ // paths); tell Node not to re-quote it.
+ windowsVerbatimArguments: wrap,
+ });
+}
+
+function hasExited(child: ChildProcess): boolean {
+ return child.exitCode !== null || child.signalCode !== null;
+}
+
+/** Resolve true when the child exits within `timeoutMs`, false otherwise. */
+function awaitExit(child: ChildProcess, timeoutMs: number): Promise<boolean> {
+ if (hasExited(child)) return Promise.resolve(true);
+ return new Promise((resolvePromise) => {
+ const onExit = (): void => {
+ clearTimeout(timer);
+ resolvePromise(true);
+ };
+ const timer = setTimeout(() => {
+ child.removeListener('exit', onExit);
+ resolvePromise(false);
+ }, timeoutMs);
+ timer.unref?.();
+ child.once('exit', onExit);
+ });
+}
+
+/** Signal the agent's whole process group, falling back to the direct child. */
+function signalAgentGroup(child: ChildProcess, signal: NodeJS.Signals): void {
+ const pid = child.pid;
+ if (pid === undefined || hasExited(child)) return;
+ try {
+ process.kill(-pid, signal);
+ return;
+ } catch {
+ // No such group (already gone) or the spawn predates group leadership —
+ // fall back to the direct child.
+ }
+ try {
+ child.kill(signal);
+ } catch {
+ // Already gone.
+ }
+}
+
+/**
+ * Kill the agent and everything it spawned, and only resolve once it is
+ * actually dead (or `false` if it somehow survived SIGKILL). POSIX: group
+ * SIGTERM → `graceMs` wait → group SIGKILL. Windows: `taskkill /T /F`
+ * immediately — there is no graceful console signal to try first, and a
+ * TerminateProcess on the root would orphan the tree before taskkill could
+ * enumerate it.
+ */
+export async function terminateAgentTree(
+ child: ChildProcess,
+ opts: { graceMs: number; forceWaitMs?: number },
+): Promise<boolean> {
+ const forceWaitMs = opts.forceWaitMs ?? 2_000;
+ if (hasExited(child)) return true;
+ if (process.platform === 'win32') {
+ if (child.pid !== undefined) {
+ try {
+ spawn('taskkill', ['/pid', String(child.pid), '/T', '/F'], {
+ stdio: 'ignore',
+ shell: false,
+ windowsHide: true,
+ }).unref();
+ } catch {
+ // taskkill unavailable — degrade to the direct child.
+ try {
+ child.kill('SIGKILL');
+ } catch {
+ // Already gone.
+ }
+ }
+ }
+ return awaitExit(child, Math.max(opts.graceMs, forceWaitMs));
+ }
+ signalAgentGroup(child, 'SIGTERM');
+ if (await awaitExit(child, opts.graceMs)) return true;
+ signalAgentGroup(child, 'SIGKILL');
+ return awaitExit(child, forceWaitMs);
+}
diff --git a/packages/server/src/acp/managed-runtime-flow.integration.test.ts b/packages/server/src/acp/managed-runtime-flow.integration.test.ts
new file mode 100644
index 000000000..77335324e
--- /dev/null
+++ b/packages/server/src/acp/managed-runtime-flow.integration.test.ts
@@ -0,0 +1,274 @@
+/**
+ * The consent-gated managed-runtime launch path, driven through the real
+ * `AcpThreadManager`. A registry agent distributed via `npx` is launched with
+ * an empty `PATH` (so the system `npx` can't resolve), which forces the
+ * download flow: the manager emits a `runtime_consent_request`, parks the
+ * launch, and — once granted through `respondRuntimeConsent` — downloads +
+ * verifies a synthetic Node runtime served through a fake `fetch`.
+ *
+ * Everything but the network + `~/.ok` is real: the archive is extracted,
+ * checksum-verified, installed, and the launcher relocated by the same code
+ * production uses.
+ */
+
+import { execFileSync } from 'node:child_process';
+import { createHash } from 'node:crypto';
+import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import type {
+ ThreadEvent,
+ ThreadServerFrame,
+} from '@inkeep/open-knowledge-core/acp/thread-protocol';
+import { afterEach, describe, expect, test } from 'vitest';
+import type { AgentSessionManager } from '../agent-sessions.ts';
+import { getLogger } from '../logger.ts';
+import { findManagedRuntime, readRuntimeConsent } from './managed-runtime.ts';
+import { AcpPermissionStore } from './permissions.ts';
+import { AcpRegistry } from './registry.ts';
+import { AcpThreadManager } from './thread-manager.ts';
+
+const log = getLogger('managed-runtime-flow-test');
+
+const fakeSessionManager = {
+ getSession: async () => {
+ throw new Error('unused');
+ },
+ closeAllForAgent: async () => {},
+} as unknown as AgentSessionManager;
+
+let dirs: string[] = [];
+let managers: AcpThreadManager[] = [];
+function tmp(): string {
+ const d = mkdtempSync(join(tmpdir(), 'runtime-flow-test-'));
+ dirs.push(d);
+ return d;
+}
+afterEach(async () => {
+ await Promise.allSettled(managers.map((m) => m.destroy()));
+ managers = [];
+ for (const d of dirs) rmSync(d, { recursive: true, force: true });
+ dirs = [];
+});
+
+const NPX_AGENT = {
+ id: 'npxagent',
+ name: 'NPX Agent',
+ version: '1.0.0',
+ // Empty PATH forces the system `npx` to be unresolvable → download flow.
+ distribution: { npx: { package: '@fake/agent', env: { PATH: '' } } },
+};
+
+/** Synthetic Node runtime tree (`node-vTEST/bin/{node,npx}`) as a `.tar.gz`. */
+function fakeNodeTarball(dir: string): { bytes: Buffer; sha: string } {
+ const treeRoot = join(dir, 'tree');
+ const binDir = join(treeRoot, 'node-vTEST', 'bin');
+ mkdirSync(binDir, { recursive: true });
+ writeFileSync(join(binDir, 'node'), '#!/bin/sh\nexit 0\n', { mode: 0o755 });
+ writeFileSync(join(binDir, 'npx'), '#!/bin/sh\nexit 0\n', { mode: 0o755 });
+ const tarPath = join(dir, 'node.tar.gz');
+ execFileSync('tar', ['-czf', tarPath, '-C', treeRoot, 'node-vTEST']);
+ const bytes = readFileSync(tarPath);
+ return { bytes, sha: createHash('sha256').update(bytes).digest('hex') };
+}
+
+function fakeNodeFetch(bytes: Buffer, sha: string): typeof fetch {
+ return (async (url: string | URL | Request) => {
+ const u = String(url);
+ if (u.includes('agentclientprotocol')) {
+ return new Response(JSON.stringify({ agents: [NPX_AGENT] }), { status: 200 });
+ }
+ if (u.endsWith('SHASUMS256.txt')) {
+ const names = ['darwin-arm64', 'darwin-x64', 'linux-arm64', 'linux-x64'].map(
+ (n) => `${sha} node-v24.18.0-${n}.tar.gz`,
+ );
+ return new Response(`${names.join('\n')}\n`, { status: 200 });
+ }
+ return new Response(new Uint8Array(bytes), {
+ status: 200,
+ headers: { 'content-length': String(bytes.length) },
+ });
+ }) as unknown as typeof fetch;
+}
+
+function makeManager(opts: {
+ contentDir: string;
+ localDir: string;
+ runtimeRoot: string;
+ consentHome: string;
+ fetchImpl: typeof fetch;
+}): AcpThreadManager {
+ const manager = new AcpThreadManager({
+ contentDir: opts.contentDir,
+ localDir: opts.localDir,
+ registry: new AcpRegistry({ localDir: opts.localDir, log, fetchImpl: opts.fetchImpl }),
+ permissions: new AcpPermissionStore(opts.localDir, log),
+ sessionManager: fakeSessionManager,
+ isExcludedPath: () => false,
+ isIgnoredPath: () => false,
+ runtimeInstall: {
+ root: opts.runtimeRoot,
+ consentHome: opts.consentHome,
+ fetchImpl: opts.fetchImpl,
+ },
+ log,
+ });
+ managers.push(manager);
+ return manager;
+}
+
+/** Subscribe and collect every thread event into `sink`. */
+async function collect(
+ manager: AcpThreadManager,
+ threadId: string,
+ sink: ThreadEvent[],
+): Promise<void> {
+ await manager.subscribe(threadId, 0, (frame: ThreadServerFrame) => {
+ if (frame.op === 'event') sink.push(frame.event);
+ else if (frame.op === 'events') sink.push(...frame.events);
+ });
+}
+
+async function waitFor(pred: () => boolean, ms: number, what: string): Promise<void> {
+ const deadline = Date.now() + ms;
+ while (!pred()) {
+ if (Date.now() > deadline) throw new Error(`timed out waiting for ${what}`);
+ await new Promise((r) => setTimeout(r, 20));
+ }
+}
+
+function findConsentRequest(
+ events: ThreadEvent[],
+): Extract<ThreadEvent, { kind: 'runtime_consent_request' }> | undefined {
+ return events.find(
+ (e): e is Extract<ThreadEvent, { kind: 'runtime_consent_request' }> =>
+ e.kind === 'runtime_consent_request',
+ );
+}
+
+describe('managed-runtime consent + download flow', () => {
+ test('grant → download → install + persist consent', async () => {
+ const contentDir = tmp();
+ const localDir = tmp();
+ const runtimeRoot = tmp();
+ const consentHome = tmp();
+ const stage = tmp();
+ const { bytes, sha } = fakeNodeTarball(stage);
+ const manager = makeManager({
+ contentDir,
+ localDir,
+ runtimeRoot,
+ consentHome,
+ fetchImpl: fakeNodeFetch(bytes, sha),
+ });
+
+ const events: ThreadEvent[] = [];
+ const info = await manager.createThread({ agent: { source: 'registry', id: 'npxagent' } });
+ await collect(manager, info.threadId, events);
+
+ await waitFor(() => findConsentRequest(events) !== undefined, 5_000, 'consent request');
+ const req = findConsentRequest(events);
+ expect(req?.runtime).toBe('node');
+ expect(req?.provides).toBe('npx');
+ expect(req?.agentName).toBe('NPX Agent');
+
+ if (req === undefined) throw new Error('unreachable');
+ manager.respondRuntimeConsent(info.threadId, req.requestId, {
+ kind: 'granted',
+ remember: true,
+ });
+
+ // The runtime downloads, verifies, and installs into the seam's root.
+ await waitFor(
+ () => events.some((e) => e.kind === 'runtime_consent_resolved'),
+ 3_000,
+ 'consent resolved',
+ );
+ const installed = await pollInstalled(runtimeRoot);
+ expect(installed).not.toBeNull();
+ expect(installed?.kind).toBe('node');
+
+ // "Remember" persisted the decision.
+ expect((await readRuntimeConsent(consentHome)).node).toBe('granted');
+ });
+
+ test('decline → actionable error, no download', async () => {
+ const contentDir = tmp();
+ const localDir = tmp();
+ const runtimeRoot = tmp();
+ const consentHome = tmp();
+ const manager = makeManager({
+ contentDir,
+ localDir,
+ runtimeRoot,
+ consentHome,
+ // No tarball needed — the decline path never downloads.
+ fetchImpl: fakeNodeFetch(Buffer.from('unused'), 'x'.repeat(64)),
+ });
+
+ const events: ThreadEvent[] = [];
+ const info = await manager.createThread({ agent: { source: 'registry', id: 'npxagent' } });
+ await collect(manager, info.threadId, events);
+
+ await waitFor(() => findConsentRequest(events) !== undefined, 5_000, 'consent request');
+ const req = findConsentRequest(events);
+ if (req === undefined) throw new Error('unreachable');
+ manager.respondRuntimeConsent(info.threadId, req.requestId, { kind: 'declined' });
+
+ await waitFor(
+ () => events.some((e) => e.kind === 'status' && e.status === 'error'),
+ 3_000,
+ 'error status',
+ );
+ const errEvent = events.find(
+ (e): e is Extract<ThreadEvent, { kind: 'status' }> =>
+ e.kind === 'status' && e.status === 'error',
+ );
+ expect(errEvent?.detail).toContain('npx');
+ expect(await findManagedRuntime('node', runtimeRoot)).toBeNull();
+ expect((await readRuntimeConsent(consentHome)).node).toBeUndefined();
+ });
+
+ test('a persisted grant skips the prompt entirely', async () => {
+ const contentDir = tmp();
+ const localDir = tmp();
+ const runtimeRoot = tmp();
+ const consentHome = tmp();
+ const stage = tmp();
+ const { bytes, sha } = fakeNodeTarball(stage);
+ // Pre-record consent so the manager should download without asking.
+ writeFileSync(
+ join(consentHome, 'acp-runtime-consent.json'),
+ JSON.stringify({ version: 1, node: 'granted' }),
+ );
+ const manager = makeManager({
+ contentDir,
+ localDir,
+ runtimeRoot,
+ consentHome,
+ fetchImpl: fakeNodeFetch(bytes, sha),
+ });
+
+ const events: ThreadEvent[] = [];
+ const info = await manager.createThread({ agent: { source: 'registry', id: 'npxagent' } });
+ await collect(manager, info.threadId, events);
+
+ const installed = await pollInstalled(runtimeRoot);
+ expect(installed).not.toBeNull();
+ // No consent prompt was ever emitted.
+ expect(findConsentRequest(events)).toBeUndefined();
+ });
+});
+
+/** Poll for the installed runtime (the download resolves asynchronously). */
+async function pollInstalled(
+ runtimeRoot: string,
+): Promise<Awaited<ReturnType<typeof findManagedRuntime>>> {
+ const deadline = Date.now() + 8_000;
+ while (Date.now() < deadline) {
+ const found = await findManagedRuntime('node', runtimeRoot);
+ if (found !== null) return found;
+ await new Promise((r) => setTimeout(r, 30));
+ }
+ return null;
+}
diff --git a/packages/server/src/acp/managed-runtime.test.ts b/packages/server/src/acp/managed-runtime.test.ts
new file mode 100644
index 000000000..89264aa23
--- /dev/null
+++ b/packages/server/src/acp/managed-runtime.test.ts
@@ -0,0 +1,216 @@
+/**
+ * Managed-runtime download path: checksum verification, atomic install,
+ * fast-path reuse, and consent persistence. The download is exercised
+ * end-to-end against a real `tar` extract of a synthetic runtime tree served
+ * through a fake `fetch` — no network, but the archive → verify → extract →
+ * rename → locate-launcher pipeline runs for real.
+ */
+
+import { execFileSync } from 'node:child_process';
+import { createHash } from 'node:crypto';
+import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { afterEach, describe, expect, test } from 'vitest';
+import { getLogger } from '../logger.ts';
+import { shaForFile } from './archive.ts';
+import {
+ describeRuntime,
+ ensureManagedRuntime,
+ findManagedRuntime,
+ type ManagedRuntimeKind,
+ RuntimeInstallError,
+ readRuntimeConsent,
+ runtimeForInterpreter,
+ writeRuntimeConsent,
+} from './managed-runtime.ts';
+
+const log = getLogger('managed-runtime-test');
+
+let dirs: string[] = [];
+function tmp(): string {
+ const d = mkdtempSync(join(tmpdir(), 'managed-runtime-test-'));
+ dirs.push(d);
+ return d;
+}
+afterEach(() => {
+ for (const d of dirs) rmSync(d, { recursive: true, force: true });
+ dirs = [];
+});
+
+/** Build a `.tar.gz` containing `<innerDir>/<file>` entries and return its sha. */
+function buildTarball(
+ dir: string,
+ innerDir: string,
+ files: string[],
+): { bytes: Buffer; sha: string } {
+ const treeRoot = join(dir, `tree-${innerDir}`);
+ const inner = join(treeRoot, innerDir);
+ mkdirSync(inner, { recursive: true });
+ for (const f of files) {
+ const path = join(inner, f);
+ mkdirSync(join(path, '..'), { recursive: true });
+ writeFileSync(path, `#!/bin/sh\necho ${f}\n`, { mode: 0o755 });
+ }
+ const tarPath = join(dir, `${innerDir}.tar.gz`);
+ execFileSync('tar', ['-czf', tarPath, '-C', treeRoot, innerDir]);
+ const bytes = readFileSync(tarPath);
+ return { bytes, sha: createHash('sha256').update(bytes).digest('hex') };
+}
+
+const NODE_NAMES = [
+ 'darwin-arm64.tar.gz',
+ 'darwin-x64.tar.gz',
+ 'linux-arm64.tar.gz',
+ 'linux-x64.tar.gz',
+ 'win-x64.zip',
+ 'win-arm64.zip',
+];
+
+/** A fake fetch that serves `bytes` for any archive URL and `sha` in the checksum sidecar. */
+function makeFetch(bytes: Buffer, sha: string): typeof fetch {
+ return (async (url: string | URL | Request) => {
+ const u = String(url);
+ if (u.endsWith('SHASUMS256.txt')) {
+ const body = `${NODE_NAMES.map((n) => `${sha} node-v24.18.0-${n}`).join('\n')}\n`;
+ return new Response(body, { status: 200 });
+ }
+ if (u.endsWith('.sha256')) {
+ const base = u.slice(u.lastIndexOf('/') + 1, -'.sha256'.length);
+ return new Response(`${sha} ${base}\n`, { status: 200 });
+ }
+ return new Response(new Uint8Array(bytes), {
+ status: 200,
+ headers: { 'content-length': String(bytes.length) },
+ });
+ }) as unknown as typeof fetch;
+}
+
+describe('shaForFile', () => {
+ test('parses a multi-line SHASUMS body by basename', () => {
+ const body = [
+ 'aaaa node-v1-darwin-arm64.tar.gz',
+ `${'b'.repeat(64)} node-v1-linux-x64.tar.gz`,
+ ].join('\n');
+ expect(shaForFile(body, 'node-v1-linux-x64.tar.gz')).toBe('b'.repeat(64));
+ });
+
+ test('handles a binary-mode marker and a path prefix on the name', () => {
+ const body = `${'c'.repeat(64)} *dist/uv-x86_64-apple-darwin.tar.gz`;
+ expect(shaForFile(body, 'uv-x86_64-apple-darwin.tar.gz')).toBe('c'.repeat(64));
+ });
+
+ test('returns null when the file is absent', () => {
+ expect(shaForFile(`${'d'.repeat(64)} other.tar.gz`, 'missing.tar.gz')).toBeNull();
+ });
+
+ test('ignores lines that are not a valid checksum', () => {
+ expect(shaForFile('not-a-checksum node.tar.gz', 'node.tar.gz')).toBeNull();
+ });
+});
+
+describe('descriptors', () => {
+ test('runtimeForInterpreter maps npx→node, uvx→uv', () => {
+ expect(runtimeForInterpreter('npx')).toBe('node');
+ expect(runtimeForInterpreter('uvx')).toBe('uv');
+ });
+ test('describeRuntime carries the download disclosure', () => {
+ const node = describeRuntime('node');
+ expect(node.displayName).toBe('Node.js');
+ expect(node.provides).toBe('npx');
+ expect(node.sourceHost).toBe('nodejs.org');
+ expect(node.approxSizeMB).toBeGreaterThan(0);
+ expect(describeRuntime('uv').provides).toBe('uvx');
+ });
+});
+
+describe('findManagedRuntime', () => {
+ test('returns null when nothing is installed', async () => {
+ const root = tmp();
+ expect(await findManagedRuntime('node', root)).toBeNull();
+ });
+});
+
+describe('ensureManagedRuntime', () => {
+ test('downloads, verifies, installs, and locates the launcher (node)', async () => {
+ const stage = tmp();
+ const root = tmp();
+ const { bytes, sha } = buildTarball(stage, 'node-vTEST', ['bin/node', 'bin/npx']);
+ const runtime = await ensureManagedRuntime('node', log, {
+ root,
+ fetchImpl: makeFetch(bytes, sha),
+ });
+ expect(runtime.kind).toBe('node');
+ if (runtime.kind !== 'node') throw new Error('unreachable');
+ expect(existsSync(runtime.npxBin)).toBe(true);
+ expect(runtime.npxBin.endsWith('npx')).toBe(true);
+ // Bin dir (for PATH) holds the sibling node the launcher needs.
+ expect(existsSync(join(runtime.binDir, 'node'))).toBe(true);
+ // Now discoverable via the fast path.
+ const found = await findManagedRuntime('node', root);
+ expect(found?.npxBin).toBe(runtime.npxBin);
+ });
+
+ test('downloads and installs uv via its per-asset .sha256', async () => {
+ const stage = tmp();
+ const root = tmp();
+ const { bytes, sha } = buildTarball(stage, 'uv-TEST', ['uv', 'uvx']);
+ const runtime = await ensureManagedRuntime('uv', log, {
+ root,
+ fetchImpl: makeFetch(bytes, sha),
+ });
+ expect(runtime.kind).toBe('uv');
+ if (runtime.kind !== 'uv') throw new Error('unreachable');
+ expect(existsSync(runtime.uvxBin)).toBe(true);
+ expect(existsSync(join(runtime.binDir, 'uv'))).toBe(true);
+ });
+
+ test('reuses an installed runtime without re-fetching', async () => {
+ const stage = tmp();
+ const root = tmp();
+ const { bytes, sha } = buildTarball(stage, 'node-vTEST', ['bin/node', 'bin/npx']);
+ await ensureManagedRuntime('node', log, { root, fetchImpl: makeFetch(bytes, sha) });
+ // A fetch that would throw proves the second call never hits the network.
+ const throwingFetch = (async () => {
+ throw new Error('should not fetch');
+ }) as unknown as typeof fetch;
+ const again = await ensureManagedRuntime('node', log, { root, fetchImpl: throwingFetch });
+ expect(again.kind).toBe('node');
+ });
+
+ test('rejects a checksum mismatch and installs nothing', async () => {
+ const stage = tmp();
+ const root = tmp();
+ const { bytes } = buildTarball(stage, 'node-vTEST', ['bin/node', 'bin/npx']);
+ const wrongSha = 'e'.repeat(64);
+ await expect(
+ ensureManagedRuntime('node', log, { root, fetchImpl: makeFetch(bytes, wrongSha) }),
+ ).rejects.toThrow(RuntimeInstallError);
+ expect(await findManagedRuntime('node', root)).toBeNull();
+ });
+});
+
+describe('runtime consent persistence', () => {
+ test('round-trips a per-runtime decision and merges without clobbering', async () => {
+ const home = tmp();
+ expect(await readRuntimeConsent(home)).toEqual({});
+ await writeRuntimeConsent('node', 'granted', log, home);
+ expect(await readRuntimeConsent(home)).toEqual({ node: 'granted' });
+ await writeRuntimeConsent('uv', 'declined', log, home);
+ expect(await readRuntimeConsent(home)).toEqual({ node: 'granted', uv: 'declined' });
+ });
+
+ test('ignores an unparseable consent file', async () => {
+ const home = tmp();
+ writeFileSync(join(home, 'acp-runtime-consent.json'), '{ not json');
+ expect(await readRuntimeConsent(home)).toEqual({});
+ });
+
+ const kinds: ManagedRuntimeKind[] = ['node', 'uv'];
+ test.each(kinds)('overwrites a prior %s decision', async (kind) => {
+ const home = tmp();
+ await writeRuntimeConsent(kind, 'declined', log, home);
+ await writeRuntimeConsent(kind, 'granted', log, home);
+ expect((await readRuntimeConsent(home))[kind]).toBe('granted');
+ });
+});
diff --git a/packages/server/src/acp/managed-runtime.ts b/packages/server/src/acp/managed-runtime.ts
new file mode 100644
index 000000000..537c83ff2
--- /dev/null
+++ b/packages/server/src/acp/managed-runtime.ts
@@ -0,0 +1,420 @@
+/**
+ * Managed language runtimes for ACP agents — the "works even without system
+ * npx/uvx" path.
+ *
+ * Most registry agents distribute through `npx <pkg>` (npm) or `uvx <pkg>`
+ * (uv). Those interpreters are absent on plenty of machines: OK Desktop
+ * bundles Electron's Node runtime but NOT npm, and a fresh macOS/Windows box
+ * rarely has uv. Rather than fail the launch (see `preflightLaunch` in
+ * `launch.ts`), OK can download an official, pinned copy of the runtime the
+ * agent needs into a private per-user cache and launch through that — the
+ * same approach Zed's `node_runtime` crate takes.
+ *
+ * Two hard rules distinguish this from Zed's implementation:
+ *
+ * 1. **Consent.** Nothing downloads without the user's explicit go-ahead
+ * (persisted per-runtime under `~/.ok/`). The gate + prompt live in the
+ * thread manager; this module only reads/writes the decision and does the
+ * download once told to.
+ * 2. **Verification.** Every archive is checked against the publisher's
+ * SHA-256 (Node's `SHASUMS256.txt`, uv's per-asset `.sha256`) before it
+ * is trusted — an unverified download is discarded.
+ *
+ * Nothing here ships in OK artifacts: the runtimes are fetched at launch time
+ * into `~/.ok/runtimes/`, so OK's own distribution stays free of Node/uv
+ * redistribution. Extraction + the escape guard are shared with the binary
+ * agent path via `archive.ts`.
+ */
+
+import { access, constants, readdir, stat } from 'node:fs/promises';
+import { arch, homedir, platform, tmpdir } from 'node:os';
+import { dirname, join } from 'node:path';
+import { OK_DIR } from '@inkeep/open-knowledge-core';
+import { tracedMkdir, tracedRename, tracedRm, tracedWriteFile } from '../fs-traced.ts';
+import type { PinoLogger } from '../logger.ts';
+import {
+ type DownloadProgress,
+ downloadToFileWithSha,
+ extractArchive,
+ fetchText,
+ isWithin,
+ sanitizeSegment,
+ shaForFile,
+} from './archive.ts';
+
+export type ManagedRuntimeKind = 'node' | 'uv';
+
+/**
+ * Pinned runtime versions. Bumping is a one-line change here; both hosts keep
+ * every historical version, and the SHA-256 is fetched + verified at download
+ * time, so no in-repo checksum table needs maintaining.
+ */
+const PINNED_NODE_VERSION = 'v24.18.0'; // current LTS line ("Krypton")
+const PINNED_UV_VERSION = '0.11.28';
+
+const NODE_DIST_BASE = 'https://nodejs.org/dist';
+const UV_RELEASE_BASE = 'https://github.com/astral-sh/uv/releases/download';
+
+/** Approximate compressed download sizes (MB), for the consent prompt only. */
+const APPROX_SIZE_MB: Record<ManagedRuntimeKind, number> = { node: 45, uv: 20 };
+
+interface ManagedNode {
+ kind: 'node';
+ /** Prepended to PATH so `npx`/`npm` resolve their sibling `node`. */
+ binDir: string;
+ /** The `npx` launcher (`npx.cmd` on Windows). */
+ npxBin: string;
+ /** Private npm cache so package installs never touch the user's `~/.npm`. */
+ cacheDir: string;
+}
+
+interface ManagedUv {
+ kind: 'uv';
+ binDir: string;
+ /** The `uvx` launcher (`uvx.exe` on Windows). */
+ uvxBin: string;
+ /** Private uv cache dir. */
+ cacheDir: string;
+}
+
+export type ManagedRuntime = ManagedNode | ManagedUv;
+
+/** Consent-prompt payload: what the user is agreeing to download. */
+export interface RuntimeDescriptor {
+ kind: ManagedRuntimeKind;
+ /** Human name — "Node.js" / "uv". */
+ displayName: string;
+ /** The interpreter this unlocks — "npx" / "uvx". */
+ provides: string;
+ version: string;
+ approxSizeMB: number;
+ /** Download host, surfaced so the user sees where bytes come from. */
+ sourceHost: string;
+}
+
+export function runtimeForInterpreter(kind: 'npx' | 'uvx'): ManagedRuntimeKind {
+ return kind === 'npx' ? 'node' : 'uv';
+}
+
+export function describeRuntime(kind: ManagedRuntimeKind): RuntimeDescriptor {
+ return kind === 'node'
+ ? {
+ kind: 'node',
+ displayName: 'Node.js',
+ provides: 'npx',
+ version: PINNED_NODE_VERSION,
+ approxSizeMB: APPROX_SIZE_MB.node,
+ sourceHost: 'nodejs.org',
+ }
+ : {
+ kind: 'uv',
+ displayName: 'uv',
+ provides: 'uvx',
+ version: PINNED_UV_VERSION,
+ approxSizeMB: APPROX_SIZE_MB.uv,
+ sourceHost: 'github.com/astral-sh',
+ };
+}
+
+/** `~/.ok` — the user-level OK home shared across projects. */
+function okHomeDir(): string {
+ return join(homedir(), OK_DIR);
+}
+
+/** Root under which each runtime's per-version tree + private caches live. */
+function defaultRuntimeRoot(): string {
+ return join(okHomeDir(), 'runtimes');
+}
+
+function versionOf(kind: ManagedRuntimeKind): string {
+ return kind === 'node' ? PINNED_NODE_VERSION : PINNED_UV_VERSION;
+}
+
+function launcherNames(kind: ManagedRuntimeKind): string[] {
+ const win = process.platform === 'win32';
+ if (kind === 'node') return win ? ['npx.cmd', 'npx.exe'] : ['npx'];
+ return win ? ['uvx.exe'] : ['uvx'];
+}
+
+interface ArtifactSpec {
+ archiveUrl: string;
+ checksumUrl: string;
+ archiveName: string;
+ isZip: boolean;
+}
+
+/** Node dist naming: `node-<version>-<os>-<arch>.<ext>`. */
+function nodeArtifact(): ArtifactSpec | null {
+ const os = platform();
+ const cpu = arch();
+ const osKey =
+ os === 'darwin' ? 'darwin' : os === 'linux' ? 'linux' : os === 'win32' ? 'win' : null;
+ const cpuKey = cpu === 'arm64' ? 'arm64' : cpu === 'x64' ? 'x64' : null;
+ if (osKey === null || cpuKey === null) return null;
+ const isZip = os === 'win32';
+ const ext = isZip ? 'zip' : 'tar.gz';
+ const archiveName = `node-${PINNED_NODE_VERSION}-${osKey}-${cpuKey}.${ext}`;
+ return {
+ archiveUrl: `${NODE_DIST_BASE}/${PINNED_NODE_VERSION}/${archiveName}`,
+ checksumUrl: `${NODE_DIST_BASE}/${PINNED_NODE_VERSION}/SHASUMS256.txt`,
+ archiveName,
+ isZip,
+ };
+}
+
+/** uv release naming: `uv-<target-triple>.<ext>` with a sibling `.sha256`. */
+function uvArtifact(): ArtifactSpec | null {
+ const key = `${platform()}-${arch()}`;
+ const triple: Record<string, string> = {
+ 'darwin-arm64': 'aarch64-apple-darwin',
+ 'darwin-x64': 'x86_64-apple-darwin',
+ 'linux-arm64': 'aarch64-unknown-linux-gnu',
+ 'linux-x64': 'x86_64-unknown-linux-gnu',
+ 'win32-x64': 'x86_64-pc-windows-msvc',
+ 'win32-arm64': 'aarch64-pc-windows-msvc',
+ };
+ const target = triple[key];
+ if (target === undefined) return null;
+ const isZip = platform() === 'win32';
+ const ext = isZip ? 'zip' : 'tar.gz';
+ const archiveName = `uv-${target}.${ext}`;
+ return {
+ archiveUrl: `${UV_RELEASE_BASE}/${PINNED_UV_VERSION}/${archiveName}`,
+ checksumUrl: `${UV_RELEASE_BASE}/${PINNED_UV_VERSION}/${archiveName}.sha256`,
+ archiveName,
+ isZip,
+ };
+}
+
+function artifactFor(kind: ManagedRuntimeKind): ArtifactSpec | null {
+ return kind === 'node' ? nodeArtifact() : uvArtifact();
+}
+
+/** True when this host has a download target for `kind` (else the user must install it manually). */
+export function runtimeDownloadSupported(kind: ManagedRuntimeKind): boolean {
+ return artifactFor(kind) !== null;
+}
+
+async function isExecutable(path: string): Promise<boolean> {
+ try {
+ const st = await stat(path);
+ if (!st.isFile() && !st.isSymbolicLink()) return false;
+ if (process.platform === 'win32') return true;
+ await access(path, constants.X_OK);
+ return true;
+ } catch {
+ return false;
+ }
+}
+
+/**
+ * Depth-bounded search for a launcher (`npx`/`uvx`) inside an extracted tree.
+ * Node ships it two levels down (`node-v…/bin/npx`, a symlink), uv one level
+ * (`uv-<triple>/uvx`) or at the root (Windows zip) — one search covers all.
+ */
+async function findLauncher(
+ dir: string,
+ names: string[],
+ maxDepth: number,
+): Promise<string | null> {
+ let entries: import('node:fs').Dirent[];
+ try {
+ entries = await readdir(dir, { withFileTypes: true });
+ } catch {
+ return null;
+ }
+ for (const e of entries) {
+ if ((e.isFile() || e.isSymbolicLink()) && names.includes(e.name)) {
+ return join(dir, e.name);
+ }
+ }
+ if (maxDepth <= 0) return null;
+ for (const e of entries) {
+ if (e.isDirectory()) {
+ const found = await findLauncher(join(dir, e.name), names, maxDepth - 1);
+ if (found !== null) return found;
+ }
+ }
+ return null;
+}
+
+function toRuntime(kind: ManagedRuntimeKind, launcher: string, root: string): ManagedRuntime {
+ const binDir = dirname(launcher);
+ const cacheDir = join(root, 'cache', kind);
+ return kind === 'node'
+ ? { kind: 'node', binDir, npxBin: launcher, cacheDir }
+ : { kind: 'uv', binDir, uvxBin: launcher, cacheDir };
+}
+
+/**
+ * Locate an already-installed managed runtime for the pinned version, or null.
+ * Cheap: a directory stat plus a bounded launcher search — the fast path every
+ * launch takes once a runtime is installed.
+ */
+export async function findManagedRuntime(
+ kind: ManagedRuntimeKind,
+ root: string = defaultRuntimeRoot(),
+): Promise<ManagedRuntime | null> {
+ const versionDir = join(root, kind, sanitizeSegment(versionOf(kind)));
+ try {
+ if (!(await stat(versionDir)).isDirectory()) return null;
+ } catch {
+ return null;
+ }
+ const launcher = await findLauncher(versionDir, launcherNames(kind), 3);
+ if (launcher === null || !(await isExecutable(launcher))) return null;
+ return toRuntime(kind, launcher, root);
+}
+
+export interface EnsureRuntimeOptions {
+ root?: string;
+ onProgress?: (p: DownloadProgress) => void;
+ signal?: AbortSignal;
+ /** Test seam — defaults to global `fetch`. */
+ fetchImpl?: typeof fetch;
+}
+
+export class RuntimeInstallError extends Error {
+ constructor(message: string) {
+ super(message);
+ this.name = 'RuntimeInstallError';
+ }
+}
+
+/**
+ * Download + verify + install a managed runtime once per pinned version;
+ * later launches reuse the extracted tree. Verified against the publisher's
+ * SHA-256 before it is trusted. Extraction lands in a temp dir and is renamed
+ * into place so a crash mid-install never leaves a half-tree that the
+ * fast-path check would accept.
+ *
+ * The CALLER is responsible for consent — this only runs once told to.
+ */
+export async function ensureManagedRuntime(
+ kind: ManagedRuntimeKind,
+ log: PinoLogger,
+ opts: EnsureRuntimeOptions = {},
+): Promise<ManagedRuntime> {
+ const root = opts.root ?? defaultRuntimeRoot();
+ const existing = await findManagedRuntime(kind, root);
+ if (existing !== null) return existing;
+
+ const spec = artifactFor(kind);
+ if (spec === null) {
+ throw new RuntimeInstallError(`no ${kind} build for ${platform()}-${arch()}`);
+ }
+
+ const versionDir = join(root, kind, sanitizeSegment(versionOf(kind)));
+ const stagingDir = join(tmpdir(), `ok-runtime-${kind}-${process.pid}-${Date.now()}`);
+ await tracedMkdir(stagingDir, { recursive: true });
+ const archivePath = join(stagingDir, spec.archiveName);
+ log.info(
+ { kind, version: versionOf(kind), url: spec.archiveUrl },
+ '[managed-runtime] downloading runtime',
+ );
+ try {
+ const [actualSha, checksums] = await Promise.all([
+ downloadToFileWithSha(spec.archiveUrl, archivePath, {
+ signal: opts.signal,
+ onProgress: opts.onProgress,
+ fetchImpl: opts.fetchImpl,
+ }),
+ fetchText(spec.checksumUrl, { signal: opts.signal, fetchImpl: opts.fetchImpl }),
+ ]);
+ const expectedSha = shaForFile(checksums, spec.archiveName);
+ if (expectedSha === null) {
+ throw new RuntimeInstallError(`no published checksum for ${spec.archiveName}`);
+ }
+ if (actualSha !== expectedSha) {
+ throw new RuntimeInstallError(
+ `checksum mismatch for ${spec.archiveName}: got ${actualSha}, expected ${expectedSha}`,
+ );
+ }
+
+ const extractDir = join(stagingDir, 'extracted');
+ await tracedMkdir(extractDir, { recursive: true });
+ await extractArchive(archivePath, extractDir, spec.isZip);
+ const launcher = await findLauncher(extractDir, launcherNames(kind), 3);
+ if (launcher === null || !isWithin(extractDir, launcher)) {
+ throw new RuntimeInstallError(`extracted ${kind} archive has no usable launcher`);
+ }
+
+ // A concurrent launch (two npm agents started on a bare machine) may have
+ // finished installing the same version while we downloaded — adopt it and
+ // drop our copy rather than racing on the rename.
+ const raced = await findManagedRuntime(kind, root);
+ if (raced !== null) return raced;
+
+ await tracedMkdir(join(root, kind), { recursive: true });
+ await tracedRm(versionDir, { recursive: true, force: true });
+ await tracedRename(extractDir, versionDir);
+ log.info({ kind, version: versionOf(kind), versionDir }, '[managed-runtime] runtime installed');
+ const installed = await findManagedRuntime(kind, root);
+ if (installed === null) {
+ throw new RuntimeInstallError(`installed ${kind} runtime not found after extract`);
+ }
+ return installed;
+ } catch (err) {
+ if (err instanceof RuntimeInstallError) throw err;
+ throw new RuntimeInstallError(
+ `installing ${kind} ${versionOf(kind)} failed: ${err instanceof Error ? err.message : String(err)}`,
+ );
+ } finally {
+ await tracedRm(stagingDir, { recursive: true, force: true }).catch(() => {
+ // Best-effort temp cleanup.
+ });
+ }
+}
+
+// --- Consent persistence ----------------------------------------------------
+//
+// A machine-/user-level decision (the download is user-level, shared across
+// projects), stored beside the runtime cache rather than in a project's
+// committed config — a teammate's clone must not pre-grant a download on this
+// machine (same locality reasoning as `server.lock` / `acp-agents.json`).
+
+export type RuntimeConsentDecision = 'granted' | 'declined';
+
+export interface RuntimeConsentState {
+ node?: RuntimeConsentDecision;
+ uv?: RuntimeConsentDecision;
+}
+
+const CONSENT_FILE = 'acp-runtime-consent.json';
+
+/** Read the persisted per-runtime consent decisions (empty on any read/parse error). */
+export async function readRuntimeConsent(home: string = okHomeDir()): Promise<RuntimeConsentState> {
+ let text: string;
+ try {
+ const { readFile } = await import('node:fs/promises');
+ text = await readFile(join(home, CONSENT_FILE), 'utf8');
+ } catch {
+ return {};
+ }
+ try {
+ const parsed = JSON.parse(text) as Record<string, unknown>;
+ const pick = (v: unknown): RuntimeConsentDecision | undefined =>
+ v === 'granted' || v === 'declined' ? v : undefined;
+ return { node: pick(parsed.node), uv: pick(parsed.uv) };
+ } catch {
+ return {};
+ }
+}
+
+/** Persist a per-runtime consent decision, merging with any existing state. */
+export async function writeRuntimeConsent(
+ kind: ManagedRuntimeKind,
+ decision: RuntimeConsentDecision,
+ log: PinoLogger,
+ home: string = okHomeDir(),
+): Promise<void> {
+ try {
+ const current = await readRuntimeConsent(home);
+ const next = { version: 1, ...current, [kind]: decision, updatedAt: Date.now() };
+ await tracedMkdir(home, { recursive: true });
+ await tracedWriteFile(join(home, CONSENT_FILE), `${JSON.stringify(next, null, 2)}\n`);
+ } catch (err) {
+ // Non-fatal: a failed persist just means we re-ask next time.
+ log.warn({ err, kind }, '[managed-runtime] consent persist failed');
+ }
+}
diff --git a/packages/server/src/acp/mcp-injection-skip.test.ts b/packages/server/src/acp/mcp-injection-skip.test.ts
new file mode 100644
index 000000000..79b2c4ed1
--- /dev/null
+++ b/packages/server/src/acp/mcp-injection-skip.test.ts
@@ -0,0 +1,136 @@
+/**
+ * `buildMcpServers` duplicate-injection guard: when the
+ * `probeHarnessManagedMcpEntry` seam reports that the agent's own harness
+ * already loads OK's managed editor-config entry, session setup injects NO
+ * `open-knowledge` server; every other outcome (miss, unmapped agent, custom
+ * agent, probe throw, unwired seam) keeps the existing injection.
+ */
+
+import { mkdtempSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { afterEach, describe, expect, test } from 'vitest';
+import type { AgentSessionManager } from '../agent-sessions.ts';
+import { getLogger } from '../logger.ts';
+import { AcpPermissionStore } from './permissions.ts';
+import { AcpRegistry } from './registry.ts';
+import {
+ AcpThreadManager,
+ type AcpThreadManagerOptions,
+ type HarnessManagedMcpEntryHit,
+} from './thread-manager.ts';
+
+const log = getLogger('acp-injection-skip-test');
+
+const fakeSessionManager = {
+ getSession: async () => {
+ throw new Error('not used');
+ },
+ closeAllForAgent: async () => {},
+} as unknown as AgentSessionManager;
+
+let dirs: string[] = [];
+let managers: AcpThreadManager[] = [];
+function tmp(): string {
+ const d = mkdtempSync(join(tmpdir(), 'acp-injection-skip-'));
+ dirs.push(d);
+ return d;
+}
+afterEach(async () => {
+ await Promise.allSettled(managers.map((m) => m.destroy()));
+ managers = [];
+ for (const d of dirs) rmSync(d, { recursive: true, force: true });
+ dirs = [];
+});
+
+type BuildMcpServersSeam = {
+ buildMcpServers: (
+ record: {
+ agentRef: { source: 'registry' | 'custom'; id: string };
+ cwd: string;
+ info: { threadId: string };
+ },
+ init: { agentCapabilities?: { mcpCapabilities?: { http?: boolean } } },
+ ) => Promise<Array<{ name: string; type?: string }>>;
+};
+
+function makeManager(
+ probe?: AcpThreadManagerOptions['probeHarnessManagedMcpEntry'],
+): BuildMcpServersSeam {
+ const localDir = tmp();
+ const manager = new AcpThreadManager({
+ contentDir: tmp(),
+ localDir,
+ registry: new AcpRegistry({
+ localDir,
+ log,
+ fetchImpl: (async () => {
+ throw new Error('offline test');
+ }) as typeof fetch,
+ }),
+ permissions: new AcpPermissionStore(localDir, log),
+ sessionManager: fakeSessionManager,
+ isExcludedPath: () => false,
+ isIgnoredPath: () => false,
+ getServerUrl: () => 'http://127.0.0.1:4242',
+ getMcpStdioCommand: () => ({ command: 'open-knowledge', args: ['mcp', '--port', '4242'] }),
+ probeHarnessManagedMcpEntry: probe,
+ log,
+ });
+ managers.push(manager);
+ return manager as unknown as BuildMcpServersSeam;
+}
+
+const record = (source: 'registry' | 'custom', id: string) => ({
+ agentRef: { source, id },
+ cwd: '/tmp/acp-injection-skip-project',
+ info: { threadId: 'thread-1' },
+});
+
+const HTTP_INIT = { agentCapabilities: { mcpCapabilities: { http: true } } };
+
+const hit: HarnessManagedMcpEntryHit = {
+ editorId: 'codex',
+ scope: 'project',
+ configPath: '/tmp/acp-injection-skip-project/.codex/config.toml',
+};
+
+describe('buildMcpServers × probeHarnessManagedMcpEntry', () => {
+ test('skips injection entirely on a probe hit (http-capable and stdio agents)', async () => {
+ const m = makeManager(() => hit);
+ expect(await m.buildMcpServers(record('registry', 'codex-acp'), HTTP_INIT)).toEqual([]);
+ expect(await m.buildMcpServers(record('registry', 'claude-acp'), {})).toEqual([]);
+ });
+
+ test('injects on a probe miss', async () => {
+ const m = makeManager(() => null);
+ const servers = await m.buildMcpServers(record('registry', 'codex-acp'), HTTP_INIT);
+ expect(servers).toHaveLength(1);
+ expect(servers[0]).toMatchObject({ name: 'open-knowledge', type: 'http' });
+ });
+
+ test('never probes for custom agents or registry agents without an OK config surface', async () => {
+ let calls = 0;
+ const m = makeManager(() => {
+ calls += 1;
+ return hit;
+ });
+ expect(await m.buildMcpServers(record('custom', 'my-agent'), HTTP_INIT)).toHaveLength(1);
+ expect(await m.buildMcpServers(record('registry', 'gemini'), HTTP_INIT)).toHaveLength(1);
+ expect(calls).toBe(0);
+ });
+
+ test('fail-open: a throwing probe still injects', async () => {
+ const m = makeManager(() => {
+ throw new Error('probe exploded');
+ });
+ const servers = await m.buildMcpServers(record('registry', 'claude-acp'), {});
+ expect(servers).toHaveLength(1);
+ expect(servers[0]).toMatchObject({ name: 'open-knowledge', command: 'open-knowledge' });
+ });
+
+ test('unwired seam keeps unconditional injection', async () => {
+ const m = makeManager(undefined);
+ expect(await m.buildMcpServers(record('registry', 'codex-acp'), HTTP_INIT)).toHaveLength(1);
+ });
+});
diff --git a/packages/server/src/acp/mcp-stdio-command.test.ts b/packages/server/src/acp/mcp-stdio-command.test.ts
new file mode 100644
index 000000000..1c60bce8d
--- /dev/null
+++ b/packages/server/src/acp/mcp-stdio-command.test.ts
@@ -0,0 +1,33 @@
+import { describe, expect, test } from 'vitest';
+import { buildOkMcpStdioCommand } from './thread-manager.ts';
+
+/**
+ * The stdio `ok mcp` command is the fallback that carries OK MCP tools to
+ * agents whose ACP adapter doesn't advertise HTTP-MCP support (e.g. Claude
+ * Code's). It must pin to a specific server port (`--port`) so the shim proxies
+ * to THIS server rather than auto-discovering some other install.
+ */
+describe('buildOkMcpStdioCommand', () => {
+ test('uses the host CLI entrypoint when provided (packaged app / ok start)', () => {
+ expect(buildOkMcpStdioCommand(['/usr/bin/ok-bin', '/app/cli.js'], 5174)).toEqual({
+ command: '/usr/bin/ok-bin',
+ args: ['/app/cli.js', 'mcp', '--port', '5174'],
+ });
+ });
+
+ test('falls back to `open-knowledge` on PATH when no entrypoint is resolvable (dev server)', () => {
+ expect(buildOkMcpStdioCommand(undefined, 3000)).toEqual({
+ command: 'open-knowledge',
+ args: ['mcp', '--port', '3000'],
+ });
+ expect(buildOkMcpStdioCommand([], 3000)).toEqual({
+ command: 'open-knowledge',
+ args: ['mcp', '--port', '3000'],
+ });
+ });
+
+ test('always pins to the given port', () => {
+ expect(buildOkMcpStdioCommand(['ok'], 61999).args).toContain('--port');
+ expect(buildOkMcpStdioCommand(['ok'], 61999).args.at(-1)).toBe('61999');
+ });
+});
diff --git a/packages/server/src/acp/permissions.test.ts b/packages/server/src/acp/permissions.test.ts
new file mode 100644
index 000000000..214a751fd
--- /dev/null
+++ b/packages/server/src/acp/permissions.test.ts
@@ -0,0 +1,75 @@
+import { mkdtempSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import type { PermissionOption, ToolCallUpdate } from '@agentclientprotocol/sdk';
+import { afterEach, describe, expect, test } from 'vitest';
+import { getLogger } from '../logger.ts';
+import { AcpPermissionStore } from './permissions.ts';
+
+const log = getLogger('acp-permissions-test');
+
+const OPTIONS: PermissionOption[] = [
+ { optionId: 'allow', name: 'Allow', kind: 'allow_once' },
+ { optionId: 'always', name: 'Always allow', kind: 'allow_always' },
+ { optionId: 'reject', name: 'Reject', kind: 'reject_once' },
+];
+
+function toolCall(kind: ToolCallUpdate['kind']): ToolCallUpdate {
+ return { toolCallId: 'tc1', title: 'test', kind } as ToolCallUpdate;
+}
+
+let dirs: string[] = [];
+function tmp(): string {
+ const d = mkdtempSync(join(tmpdir(), 'acp-perm-test-'));
+ dirs.push(d);
+ return d;
+}
+afterEach(() => {
+ for (const d of dirs) rmSync(d, { recursive: true, force: true });
+ dirs = [];
+});
+
+describe('AcpPermissionStore', () => {
+ test('auto-allows read-kind tool calls', () => {
+ const store = new AcpPermissionStore(tmp(), log);
+ const decision = store.decide('gemini', toolCall('read'), OPTIONS);
+ expect(decision.auto?.optionId).toBe('allow');
+ });
+
+ test('asks for edit/execute kinds with no grant', () => {
+ const store = new AcpPermissionStore(tmp(), log);
+ expect(store.decide('gemini', toolCall('edit'), OPTIONS).auto).toBeNull();
+ expect(store.decide('gemini', toolCall('execute'), OPTIONS).auto).toBeNull();
+ });
+
+ test('never auto-selects when no allow option exists', () => {
+ const store = new AcpPermissionStore(tmp(), log);
+ const rejectOnly = OPTIONS.filter((o) => o.kind === 'reject_once');
+ expect(store.decide('gemini', toolCall('read'), rejectOnly).auto).toBeNull();
+ });
+
+ test('allow_always persists per (agent, kind) across store instances', async () => {
+ const dir = tmp();
+ const store = new AcpPermissionStore(dir, log);
+ const always = OPTIONS.find((o) => o.kind === 'allow_always');
+ if (always === undefined) throw new Error('fixture');
+ await store.recordChoice('gemini', toolCall('edit'), always);
+
+ expect(store.decide('gemini', toolCall('edit'), OPTIONS).auto).not.toBeNull();
+ // Different agent / different kind: still asks.
+ expect(store.decide('cursor', toolCall('edit'), OPTIONS).auto).toBeNull();
+ expect(store.decide('gemini', toolCall('execute'), OPTIONS).auto).toBeNull();
+
+ const rehydrated = new AcpPermissionStore(dir, log);
+ expect(rehydrated.hasAllowAlways('gemini', 'edit')).toBe(true);
+ });
+
+ test('allow_once selections do not persist', async () => {
+ const dir = tmp();
+ const store = new AcpPermissionStore(dir, log);
+ const once = OPTIONS.find((o) => o.kind === 'allow_once');
+ if (once === undefined) throw new Error('fixture');
+ await store.recordChoice('gemini', toolCall('edit'), once);
+ expect(new AcpPermissionStore(dir, log).hasAllowAlways('gemini', 'edit')).toBe(false);
+ });
+});
diff --git a/packages/server/src/acp/permissions.ts b/packages/server/src/acp/permissions.ts
new file mode 100644
index 000000000..904304cb8
--- /dev/null
+++ b/packages/server/src/acp/permissions.ts
@@ -0,0 +1,123 @@
+/**
+ * Permission policy for ACP tool calls.
+ *
+ * Three tiers, checked in order:
+ * 1. Auto-allow: `read`-kind tool calls. Reads that matter route through
+ * OK's own client-fs handler, which independently confines paths to the
+ * content directory — the permission layer guards intent, the fs layer
+ * guards the boundary.
+ * 2. Persisted `allow_always` grants, keyed (agentId, toolKind), stored in
+ * `.ok/local/acp-permissions.json` — machine-local and never committed,
+ * so a grant on this machine can never ride git onto a collaborator's.
+ * 3. Ask: everything else surfaces a permission prompt in the thread UI.
+ *
+ * Tool `kind` is agent-reported; the permission UI guards against accidents,
+ * not adversarial agents — an agent already runs unsandboxed as the user
+ * (the same trust model every ACP client ships).
+ */
+
+import { readFileSync } from 'node:fs';
+import { join } from 'node:path';
+import type { PermissionOption, ToolCallUpdate } from '@agentclientprotocol/sdk';
+import type { PinoLogger } from '../logger.ts';
+
+const PERMISSIONS_FILE = 'acp-permissions.json';
+
+interface PermissionGrant {
+ agentId: string;
+ toolKind: string;
+}
+
+interface PermissionsFileShape {
+ version: 1;
+ grants: PermissionGrant[];
+}
+
+export interface PolicyDecision {
+ /** Auto-resolved without asking; `optionId` is the option to answer with. */
+ auto: { optionId: string } | null;
+}
+
+function toolKindOf(toolCall: ToolCallUpdate): string {
+ return toolCall.kind ?? 'other';
+}
+
+function pickOption(
+ options: PermissionOption[],
+ kinds: readonly string[],
+): PermissionOption | undefined {
+ for (const kind of kinds) {
+ const hit = options.find((o) => o.kind === kind);
+ if (hit !== undefined) return hit;
+ }
+ return undefined;
+}
+
+export class AcpPermissionStore {
+ private readonly filePath: string;
+ private readonly log: PinoLogger;
+ private grants: PermissionGrant[] | null = null;
+
+ constructor(localDir: string, log: PinoLogger) {
+ this.filePath = join(localDir, PERMISSIONS_FILE);
+ this.log = log;
+ }
+
+ /**
+ * Decide a `session/request_permission`. Returns an auto decision (with
+ * the optionId to answer) or `{ auto: null }` meaning "ask the user".
+ */
+ decide(agentId: string, toolCall: ToolCallUpdate, options: PermissionOption[]): PolicyDecision {
+ const kind = toolKindOf(toolCall);
+ const allow = pickOption(options, ['allow_once', 'allow_always']);
+ if (allow === undefined) return { auto: null };
+ if (kind === 'read') return { auto: { optionId: allow.optionId } };
+ if (this.hasAllowAlways(agentId, kind)) return { auto: { optionId: allow.optionId } };
+ return { auto: null };
+ }
+
+ hasAllowAlways(agentId: string, toolKind: string): boolean {
+ return this.loadGrants().some((g) => g.agentId === agentId && g.toolKind === toolKind);
+ }
+
+ /**
+ * Record the user's choice. Only `allow_always` selections persist;
+ * `allow_once` / rejections are session-scoped by definition (a persisted
+ * `reject_always` would silently dead-end an agent with no UI to undo it —
+ * deferred until the settings surface exists).
+ */
+ async recordChoice(
+ agentId: string,
+ toolCall: ToolCallUpdate,
+ chosen: PermissionOption,
+ ): Promise<void> {
+ if (chosen.kind !== 'allow_always') return;
+ const kind = toolKindOf(toolCall);
+ if (this.hasAllowAlways(agentId, kind)) return;
+ const grants = [...this.loadGrants(), { agentId, toolKind: kind }];
+ this.grants = grants;
+ try {
+ const { tracedMkdir, tracedWriteFile } = await import('../fs-traced.ts');
+ await tracedMkdir(join(this.filePath, '..'), { recursive: true });
+ const body: PermissionsFileShape = { version: 1, grants };
+ await tracedWriteFile(this.filePath, `${JSON.stringify(body, null, 2)}\n`);
+ } catch (err) {
+ this.log.warn({ err }, '[acp-permissions] persisting allow_always grant failed');
+ }
+ }
+
+ private loadGrants(): PermissionGrant[] {
+ if (this.grants !== null) return this.grants;
+ try {
+ const parsed = JSON.parse(readFileSync(this.filePath, 'utf8')) as PermissionsFileShape;
+ this.grants = Array.isArray(parsed?.grants)
+ ? parsed.grants.filter(
+ (g) => typeof g?.agentId === 'string' && typeof g?.toolKind === 'string',
+ )
+ : [];
+ } catch {
+ this.grants = [];
+ }
+ return this.grants;
+ }
+}
diff --git a/packages/server/src/acp/registry.test.ts b/packages/server/src/acp/registry.test.ts
new file mode 100644
index 000000000..e0f1188a6
--- /dev/null
+++ b/packages/server/src/acp/registry.test.ts
@@ -0,0 +1,100 @@
+import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { afterEach, describe, expect, test } from 'vitest';
+import { getLogger } from '../logger.ts';
+import { AcpRegistry, loadCustomAgents, registryPlatformKey } from './registry.ts';
+
+const log = getLogger('acp-registry-test');
+
+const CATALOG = JSON.stringify({
+ version: 1,
+ agents: [
+ {
+ id: 'gemini',
+ name: 'Gemini CLI',
+ version: '1.0.0',
+ license: 'Apache-2.0',
+ distribution: { npx: { package: '@google/[email protected]', args: ['--acp'] } },
+ },
+ { id: 'broken' }, // missing required fields — dropped
+ ],
+});
+
+let dirs: string[] = [];
+function tmp(): string {
+ const d = mkdtempSync(join(tmpdir(), 'acp-registry-test-'));
+ dirs.push(d);
+ return d;
+}
+afterEach(() => {
+ for (const d of dirs) rmSync(d, { recursive: true, force: true });
+ dirs = [];
+});
+
+describe('AcpRegistry', () => {
+ test('parses the catalog, drops malformed entries, writes the disk cache', async () => {
+ const localDir = tmp();
+ const registry = new AcpRegistry({
+ localDir,
+ log,
+ fetchImpl: (async () => new Response(CATALOG, { status: 200 })) as typeof fetch,
+ });
+ const result = await registry.getCatalog();
+ expect(result.stale).toBe(false);
+ expect(result.agents.map((a) => a.id)).toEqual(['gemini']);
+ const cached = await Bun.file(join(localDir, 'acp-registry-cache.json')).text();
+ expect(cached).toBe(CATALOG);
+ });
+
+ test('serves the disk cache when the CDN is unreachable', async () => {
+ const localDir = tmp();
+ writeFileSync(join(localDir, 'acp-registry-cache.json'), CATALOG);
+ const registry = new AcpRegistry({
+ localDir,
+ log,
+ fetchImpl: (async () => {
+ throw new Error('offline');
+ }) as typeof fetch,
+ });
+ const result = await registry.getCatalog();
+ expect(result.stale).toBe(true);
+ expect(result.agents[0]?.id).toBe('gemini');
+ });
+
+ test('throws when offline with no cache', async () => {
+ const registry = new AcpRegistry({
+ localDir: tmp(),
+ log,
+ fetchImpl: (async () => {
+ throw new Error('offline');
+ }) as typeof fetch,
+ });
+ await expect(registry.getCatalog()).rejects.toThrow('offline');
+ });
+});
+
+describe('loadCustomAgents', () => {
+ test('returns valid entries, drops malformed ones, tolerates a missing file', async () => {
+ const localDir = tmp();
+ expect(await loadCustomAgents(localDir, log)).toEqual([]);
+ writeFileSync(
+ join(localDir, 'acp-agents.json'),
+ JSON.stringify([
+ { id: 'my-agent', name: 'Mine', command: 'node', args: ['agent.js'] },
+ { id: 'bad id!', name: 'Nope', command: 'x' }, // id fails AGENT_ID charset
+ { id: 'no-command', name: 'Nope' },
+ ]),
+ );
+ const agents = await loadCustomAgents(localDir, log);
+ expect(agents).toHaveLength(1);
+ expect(agents[0]?.id).toBe('my-agent');
+ });
+});
+
+describe('registryPlatformKey', () => {
+ test('returns a supported key on this host', () => {
+ // The dev/CI fleet is darwin/linux on arm64/x64 — all enumerable.
+ expect(registryPlatformKey()).toMatch(/^(darwin|linux|windows)-(aarch64|x86_64)$/);
+ });
+});
diff --git a/packages/server/src/acp/registry.ts b/packages/server/src/acp/registry.ts
new file mode 100644
index 000000000..cf8f6084b
--- /dev/null
+++ b/packages/server/src/acp/registry.ts
@@ -0,0 +1,299 @@
+/**
+ * ACP agent catalog — the registry-driven "support every agent" mechanism.
+ *
+ * Consumes the Agent Client Protocol registry's aggregated catalog
+ * (https://agentclientprotocol.com — Apache-2.0 data; each agent keeps its
+ * own license, surfaced in the manifest's `license` field). The catalog is
+ * cached two ways: in-memory with a TTL for the common path, and on disk
+ * under `.ok/local/` so a server booted offline still lists agents it has
+ * seen before. Registry data never ships in OK artifacts — it is fetched at
+ * runtime, keeping proprietary agents entirely out of our distribution.
+ *
+ * Custom (unlisted) agents come from `.ok/local/acp-agents.json` — a
+ * machine-local, never-committed file so a teammate's clone can't inject a
+ * spawnable command into this machine (same locality reasoning as
+ * `server.lock`).
+ */
+
+import { readFile } from 'node:fs/promises';
+import { arch, platform } from 'node:os';
+import { join } from 'node:path';
+import type { EditorId } from '@inkeep/open-knowledge-core';
+import type { PinoLogger } from '../logger.ts';
+
+const ACP_REGISTRY_URL = 'https://cdn.agentclientprotocol.com/registry/v1/latest/registry.json';
+
+/**
+ * Featured defaults surfaced above the "browse all" fold, in display order.
+ * Ids are pinned to the live registry catalog (verified 2026-07-02).
+ * OpenClaw is not in the registry yet — it remains reachable via a custom
+ * agent entry until its manifest lands.
+ */
+export const FEATURED_AGENT_IDS: readonly string[] = [
+ 'claude-acp',
+ 'codex-acp',
+ 'gemini',
+ 'cursor',
+ 'github-copilot-cli',
+ 'opencode',
+];
+
+/**
+ * Registry agents whose harness independently loads the editor MCP configs
+ * OK's own wiring installs (`ok init` / the Desktop consent flow), keyed to
+ * the editor id that wiring writes for. Agent ids pinned to the live
+ * registry catalog like `FEATURED_AGENT_IDS`; agents absent here (gemini,
+ * github-copilot-cli, custom entries) have no OK-managed config surface, so
+ * the thread manager always injects for them.
+ */
+export const ACP_AGENT_EDITOR_IDS: { readonly [agentId: string]: EditorId | undefined } = {
+ 'claude-acp': 'claude',
+ 'codex-acp': 'codex',
+ cursor: 'cursor',
+ opencode: 'opencode',
+};
+
+/** One platform target inside a manifest's `binary` distribution. */
+export interface RegistryBinaryTarget {
+ archive: string;
+ /**
+ * Lowercase hex SHA-256 of the archive. Verified after download when
+ * present; a manifest without one installs with a loud warning (binary
+ * distributions are opaque executables, so publishers should ship this).
+ */
+ sha256?: string;
+ cmd: string;
+ args?: string[];
+ env?: Record<string, string>;
+}
+
+interface RegistryPackageDistribution {
+ package: string;
+ args?: string[];
+ env?: Record<string, string>;
+}
+
+interface RegistryDistribution {
+ npx?: RegistryPackageDistribution;
+ uvx?: RegistryPackageDistribution;
+ binary?: Record<string, RegistryBinaryTarget>;
+}
+
+/** Agent manifest as served by the registry CDN (`FORMAT.md` schema). */
+export interface RegistryAgent {
+ id: string;
+ name: string;
+ version: string;
+ description?: string;
+ repository?: string;
+ website?: string;
+ authors?: string[];
+ license?: string;
+ icon?: string;
+ distribution: RegistryDistribution;
+}
+
+/** Machine-local custom agent entry (`.ok/local/acp-agents.json`). */
+export interface CustomAgentEntry {
+ id: string;
+ name: string;
+ command: string;
+ args?: string[];
+ env?: Record<string, string>;
+}
+
+export interface CatalogResult {
+ agents: RegistryAgent[];
+ fetchedAt: number;
+ /** True when served from the disk fallback because the CDN was unreachable. */
+ stale: boolean;
+}
+
+const CUSTOM_AGENTS_FILE = 'acp-agents.json';
+const REGISTRY_CACHE_FILE = 'acp-registry-cache.json';
+const DEFAULT_TTL_MS = 60 * 60 * 1000;
+
+/**
+ * The registry's platform key for this host (`<os>-<arch>` in the manifest's
+ * vocabulary), or null on platforms the registry doesn't enumerate.
+ */
+export function registryPlatformKey(): string | null {
+ const os = platform();
+ const cpu = arch();
+ const osKey =
+ os === 'darwin' ? 'darwin' : os === 'linux' ? 'linux' : os === 'win32' ? 'windows' : null;
+ const cpuKey = cpu === 'arm64' ? 'aarch64' : cpu === 'x64' ? 'x86_64' : null;
+ if (osKey === null || cpuKey === null) return null;
+ return `${osKey}-${cpuKey}`;
+}
+
+function isRegistryAgent(value: unknown): value is RegistryAgent {
+ if (typeof value !== 'object' || value === null) return false;
+ const a = value as Record<string, unknown>;
+ return (
+ typeof a.id === 'string' &&
+ a.id.length > 0 &&
+ typeof a.name === 'string' &&
+ typeof a.version === 'string' &&
+ typeof a.distribution === 'object' &&
+ a.distribution !== null
+ );
+}
+
+function parseCatalogJson(text: string): RegistryAgent[] | null {
+ let parsed: unknown;
+ try {
+ parsed = JSON.parse(text);
+ } catch {
+ return null;
+ }
+ const agents = (parsed as { agents?: unknown })?.agents;
+ if (!Array.isArray(agents)) return null;
+ return agents.filter(isRegistryAgent);
+}
+
+export class AcpRegistry {
+ private readonly localDir: string;
+ private readonly log: PinoLogger;
+ private readonly ttlMs: number;
+ private readonly fetchImpl: typeof fetch;
+ private memory: CatalogResult | null = null;
+ private inflight: Promise<CatalogResult> | null = null;
+
+ constructor(opts: {
+ /** Absolute path to `<projectDir>/.ok/local`. */
+ localDir: string;
+ log: PinoLogger;
+ ttlMs?: number;
+ /** Test seam. */
+ fetchImpl?: typeof fetch;
+ }) {
+ this.localDir = opts.localDir;
+ this.log = opts.log;
+ this.ttlMs = opts.ttlMs ?? DEFAULT_TTL_MS;
+ this.fetchImpl = opts.fetchImpl ?? fetch;
+ }
+
+ /** Fresh-enough memory copy, else network, else disk fallback. */
+ async getCatalog(): Promise<CatalogResult> {
+ if (
+ this.memory !== null &&
+ Date.now() - this.memory.fetchedAt < this.ttlMs &&
+ !this.memory.stale
+ ) {
+ return this.memory;
+ }
+ if (this.inflight !== null) return this.inflight;
+ this.inflight = this.refresh().finally(() => {
+ this.inflight = null;
+ });
+ return this.inflight;
+ }
+
+ async getAgent(id: string): Promise<RegistryAgent | undefined> {
+ const { agents } = await this.getCatalog();
+ return agents.find((a) => a.id === id);
+ }
+
+ private async refresh(): Promise<CatalogResult> {
+ try {
+ const res = await this.fetchImpl(ACP_REGISTRY_URL, {
+ signal: AbortSignal.timeout(15_000),
+ });
+ if (!res.ok) throw new Error(`registry fetch failed: HTTP ${res.status}`);
+ const text = await res.text();
+ const agents = parseCatalogJson(text);
+ if (agents === null) throw new Error('registry payload did not parse as a catalog');
+ this.memory = { agents, fetchedAt: Date.now(), stale: false };
+ // Best-effort disk mirror for offline boots. Import lazily so the
+ // traced-fs module (and its telemetry deps) never load on read paths.
+ try {
+ const { tracedMkdir, tracedWriteFile } = await import('../fs-traced.ts');
+ await tracedMkdir(this.localDir, { recursive: true });
+ await tracedWriteFile(join(this.localDir, REGISTRY_CACHE_FILE), text);
+ } catch (err) {
+ this.log.warn({ err }, '[acp-registry] disk cache write failed');
+ }
+ return this.memory;
+ } catch (err) {
+ const fallback = await this.readDiskCache();
+ if (fallback !== null) {
+ this.log.warn({ err }, '[acp-registry] CDN unreachable — serving disk cache');
+ this.memory = fallback;
+ return fallback;
+ }
+ // Keep any previous in-memory copy usable past its TTL rather than
+ // failing the catalog entirely.
+ if (this.memory !== null) {
+ this.log.warn({ err }, '[acp-registry] CDN unreachable — serving stale memory copy');
+ this.memory = { ...this.memory, stale: true };
+ return this.memory;
+ }
+ throw err instanceof Error ? err : new Error(String(err));
+ }
+ }
+
+ private async readDiskCache(): Promise<CatalogResult | null> {
+ try {
+ const text = await readFile(join(this.localDir, REGISTRY_CACHE_FILE), 'utf8');
+ const agents = parseCatalogJson(text);
+ if (agents === null) return null;
+ return { agents, fetchedAt: 0, stale: true };
+ } catch {
+ return null;
+ }
+ }
+}
+
+/**
+ * Read machine-local custom agents. Malformed entries are dropped (warn),
+ * never fatal — a hand-edited file must not take the whole catalog down.
+ */
+export async function loadCustomAgents(
+ localDir: string,
+ log: PinoLogger,
+): Promise<CustomAgentEntry[]> {
+ let text: string;
+ try {
+ text = await readFile(join(localDir, CUSTOM_AGENTS_FILE), 'utf8');
+ } catch {
+ return [];
+ }
+ let parsed: unknown;
+ try {
+ parsed = JSON.parse(text);
+ } catch (err) {
+ log.warn({ err }, `[acp-registry] ${CUSTOM_AGENTS_FILE} is not valid JSON — ignoring`);
+ return [];
+ }
+ if (!Array.isArray(parsed)) return [];
+ const valid: CustomAgentEntry[] = [];
+ for (const entry of parsed) {
+ const e = entry as Record<string, unknown>;
+ if (
+ typeof e?.id === 'string' &&
+ /^[a-zA-Z0-9_-]+$/.test(e.id) &&
+ typeof e.name === 'string' &&
+ typeof e.command === 'string' &&
+ e.command.length > 0 &&
+ (e.args === undefined ||
+ (Array.isArray(e.args) && e.args.every((a) => typeof a === 'string'))) &&
+ (e.env === undefined ||
+ (typeof e.env === 'object' &&
+ e.env !== null &&
+ !Array.isArray(e.env) &&
+ Object.values(e.env).every((v) => typeof v === 'string')))
+ ) {
+ valid.push({
+ id: e.id,
+ name: e.name,
+ command: e.command,
+ args: e.args as string[] | undefined,
+ env: (e.env as Record<string, string> | undefined) ?? undefined,
+ });
+ } else {
+ log.warn({ entry }, `[acp-registry] dropping malformed ${CUSTOM_AGENTS_FILE} entry`);
+ }
+ }
+ return valid;
+}
diff --git a/packages/server/src/acp/terminals.test.ts b/packages/server/src/acp/terminals.test.ts
new file mode 100644
index 000000000..bf4d79bbe
--- /dev/null
+++ b/packages/server/src/acp/terminals.test.ts
@@ -0,0 +1,199 @@
+import type { ThreadEvent } from '@inkeep/open-knowledge-core/acp/thread-protocol';
+import { afterEach, describe, expect, test } from 'vitest';
+import { getLogger } from '../logger.ts';
+import { AcpTerminalSet } from './terminals.ts';
+
+const log = getLogger('acp-terminals-test');
+
+let sets: AcpTerminalSet[] = [];
+function makeSet(events: ThreadEvent[]): AcpTerminalSet {
+ const set = new AcpTerminalSet({
+ defaultCwd: process.cwd(),
+ emit: (event) => events.push(event),
+ log,
+ });
+ sets.push(set);
+ return set;
+}
+afterEach(async () => {
+ await Promise.allSettled(sets.map((s) => s.disposeAll()));
+ sets = [];
+});
+
+function node(code: string): { command: string; args: string[] } {
+ return { command: process.execPath, args: ['-e', code] };
+}
+
+describe('AcpTerminalSet', () => {
+ test('runs a command: output captured, exit 0, transcript events in order', async () => {
+ const events: ThreadEvent[] = [];
+ const set = makeSet(events);
+ const { terminalId } = set.create(node("process.stdout.write('hello from terminal')"));
+ const status = await set.waitForExit(terminalId);
+ expect(status).toEqual({ exitCode: 0, signal: null });
+
+ const out = set.output(terminalId);
+ expect(out.output).toBe('hello from terminal');
+ expect(out.truncated).toBe(false);
+ expect(out.exitStatus).toEqual({ exitCode: 0, signal: null });
+
+ const kinds = events.map((e) => e.kind);
+ expect(kinds[0]).toBe('terminal_created');
+ expect(kinds).toContain('terminal_output');
+ expect(kinds[kinds.length - 1]).toBe('terminal_exit');
+ const created = events[0];
+ if (created.kind !== 'terminal_created') throw new Error('unreachable');
+ expect(created.terminalId).toBe(terminalId);
+ expect(created.command).toBe(process.execPath);
+ });
+
+ test('captures stderr interleaved and a non-zero exit code', async () => {
+ const events: ThreadEvent[] = [];
+ const set = makeSet(events);
+ const { terminalId } = set.create(node("process.stderr.write('boom'); process.exit(3)"));
+ const status = await set.waitForExit(terminalId);
+ expect(status.exitCode).toBe(3);
+ expect(set.output(terminalId).output).toContain('boom');
+ const exit = events[events.length - 1];
+ if (exit.kind !== 'terminal_exit') throw new Error('unreachable');
+ expect(exit.exitCode).toBe(3);
+ expect(exit.signal).toBeNull();
+ });
+
+ test('front-truncates retained output at outputByteLimit', async () => {
+ const events: ThreadEvent[] = [];
+ const set = makeSet(events);
+ const { terminalId } = set.create({
+ ...node("process.stdout.write('a'.repeat(500) + 'TAIL-MARKER')"),
+ outputByteLimit: 128,
+ });
+ await set.waitForExit(terminalId);
+ const out = set.output(terminalId);
+ expect(out.truncated).toBe(true);
+ expect(Buffer.byteLength(out.output, 'utf8')).toBeLessThanOrEqual(128);
+ expect(out.output.endsWith('TAIL-MARKER')).toBe(true);
+ });
+
+ test('front-truncation lands on a character boundary (multi-byte safe)', async () => {
+ const events: ThreadEvent[] = [];
+ const set = makeSet(events);
+ // 3-byte characters against a limit that is not a multiple of 3 forces a
+ // mid-character cut the trimmer must repair.
+ const { terminalId } = set.create({
+ ...node("process.stdout.write('\\u3042'.repeat(200))"),
+ outputByteLimit: 100,
+ });
+ await set.waitForExit(terminalId);
+ const out = set.output(terminalId);
+ expect(out.truncated).toBe(true);
+ expect(out.output).not.toContain('�');
+ expect([...out.output].every((ch) => ch === 'あ')).toBe(true);
+ });
+
+ test('kill terminates a long-running command; output stays readable', async () => {
+ const events: ThreadEvent[] = [];
+ const set = makeSet(events);
+ const { terminalId } = set.create(
+ node("process.stdout.write('started'); setInterval(() => {}, 1000)"),
+ );
+ // Wait for the process to prove it is alive before killing it.
+ const deadline = Date.now() + 5_000;
+ while (!set.output(terminalId).output.includes('started')) {
+ if (Date.now() > deadline) throw new Error('command never produced output');
+ await new Promise((r) => setTimeout(r, 25));
+ }
+ await set.kill(terminalId);
+ const status = await set.waitForExit(terminalId);
+ expect(status.exitCode === null || status.exitCode !== 0).toBe(true);
+ // Killed but not released: output must remain retrievable.
+ expect(set.output(terminalId).output).toContain('started');
+ await set.release(terminalId);
+ expect(() => set.output(terminalId)).toThrow('unknown terminal');
+ });
+
+ test('waitForExit resolves for an already-exited terminal', async () => {
+ const events: ThreadEvent[] = [];
+ const set = makeSet(events);
+ const { terminalId } = set.create(node('process.exit(0)'));
+ await set.waitForExit(terminalId);
+ // Second wait after exit settles immediately from the recorded status.
+ const again = await set.waitForExit(terminalId);
+ expect(again.exitCode).toBe(0);
+ });
+
+ test('a nonexistent command surfaces as exit 127 with the error in output', async () => {
+ const events: ThreadEvent[] = [];
+ const set = makeSet(events);
+ const { terminalId } = set.create({ command: '/definitely/not/a/real/binary' });
+ const status = await set.waitForExit(terminalId);
+ expect(status.exitCode).toBe(127);
+ expect(set.output(terminalId).output.length).toBeGreaterThan(0);
+ });
+
+ test('pauses transcript emission past the cap and replays the tail on exit', async () => {
+ const events: ThreadEvent[] = [];
+ const set = makeSet(events);
+ // Spew well past the 256 KiB transcript cap, then end with a marker that
+ // only the exit-time tail replay can carry into the transcript.
+ const { terminalId } = set.create(
+ node(
+ "for (let i = 0; i < 40; i++) process.stdout.write('x'.repeat(8192)); process.stdout.write('FINAL-MARKER');",
+ ),
+ );
+ await set.waitForExit(terminalId);
+ const chunks = events.filter(
+ (e): e is Extract<ThreadEvent, { kind: 'terminal_output' }> => e.kind === 'terminal_output',
+ );
+ const transcriptBytes = chunks.reduce((n, c) => n + Buffer.byteLength(c.chunk, 'utf8'), 0);
+ // Live budget (256 KiB) + one bounded tail replay (16 KiB + marker line).
+ expect(transcriptBytes).toBeLessThan(300 * 1024);
+ expect(chunks[chunks.length - 1]?.chunk).toContain('FINAL-MARKER');
+ expect(chunks.some((c) => c.chunk.includes('[output truncated'))).toBe(true);
+ });
+
+ test('the exit-time tail replay never repeats bytes the live stream carried', async () => {
+ const events: ThreadEvent[] = [];
+ const set = makeSet(events);
+ // Exactly fill the 256 KiB live budget with x's, then one small unique
+ // suffix that trips the pause — the replay must carry ONLY the suffix.
+ const { terminalId } = set.create(
+ node(
+ "for (let i = 0; i < 32; i++) process.stdout.write('x'.repeat(8192)); setTimeout(() => { process.stdout.write('UNIQUE-SUFFIX'); }, 50);",
+ ),
+ );
+ await set.waitForExit(terminalId);
+ const chunks = events.filter(
+ (e): e is Extract<ThreadEvent, { kind: 'terminal_output' }> => e.kind === 'terminal_output',
+ );
+ const joined = chunks.map((c) => c.chunk).join('');
+ expect(joined.split('UNIQUE-SUFFIX')).toHaveLength(2);
+ // No 16 KiB duplication block: total ≈ live budget + marker + suffix.
+ expect(Buffer.byteLength(joined, 'utf8')).toBeLessThan(256 * 1024 + 200);
+ });
+
+ test('rejects terminal creation past the per-thread cap', async () => {
+ const events: ThreadEvent[] = [];
+ const set = makeSet(events);
+ const ids: string[] = [];
+ for (let i = 0; i < 64; i++) {
+ ids.push(set.create(node('process.exit(0)')).terminalId);
+ }
+ expect(() => set.create(node('process.exit(0)'))).toThrow('terminal limit');
+ // Releasing frees a slot.
+ await set.waitForExit(ids[0]);
+ await set.release(ids[0]);
+ expect(() => set.create(node('process.exit(0)'))).not.toThrow();
+ });
+
+ test('disposeAll kills every live terminal', async () => {
+ const events: ThreadEvent[] = [];
+ const set = makeSet(events);
+ const a = set.create(node('setInterval(() => {}, 1000)'));
+ const b = set.create(node('setInterval(() => {}, 1000)'));
+ expect(set.liveCount()).toBe(2);
+ const exits = Promise.all([set.waitForExit(a.terminalId), set.waitForExit(b.terminalId)]);
+ await set.disposeAll();
+ await exits;
+ expect(set.liveCount()).toBe(0);
+ });
+});
diff --git a/packages/server/src/acp/terminals.ts b/packages/server/src/acp/terminals.ts
new file mode 100644
index 000000000..691c3ad33
--- /dev/null
+++ b/packages/server/src/acp/terminals.ts
@@ -0,0 +1,366 @@
+/**
+ * ACP terminal surface — the client half of `terminal/*`. The agent asks OK
+ * to run a command (`terminal/create`); OK spawns it, retains a byte-bounded
+ * copy of its combined stdout+stderr, and answers `terminal/output` /
+ * `terminal/wait_for_exit` / `terminal/kill` / `terminal/release` against the
+ * live record. One `AcpTerminalSet` per thread; every spawned command dies
+ * with its thread (close/exit/destroy) via {@link AcpTerminalSet.disposeAll}.
+ *
+ * Trust model: the command comes from the agent process, which already runs
+ * arbitrary code with the user's privileges — executing it here grants
+ * nothing new. What gates a command is the agent's own permission flow
+ * (`session/request_permission`) before it calls `terminal/create`, exactly
+ * as when the agent runs commands in-process.
+ *
+ * Transcript emission is bounded separately from the retained buffer: chunks
+ * stream to the sink until {@link TERMINAL_TRANSCRIPT_BYTE_CAP}, then pause;
+ * on exit the final tail of the retained buffer is emitted with a truncation
+ * marker so the transcript always ends with the part that explains the exit
+ * code. `terminal/output` (the agent-facing read) is never truncated beyond
+ * the agent's own `outputByteLimit`.
+ */
+
+import { type ChildProcess, spawn } from 'node:child_process';
+import { isAbsolute, resolve } from 'node:path';
+import type { ThreadEvent } from '@inkeep/open-knowledge-core/acp/thread-protocol';
+import type { PinoLogger } from '../logger.ts';
+import {
+ envPath,
+ mergedEnv,
+ resolveWindowsCommand,
+ terminateAgentTree,
+ windowsCmdWrap,
+} from './launch.ts';
+
+/** Retained-output default when the agent sends no `outputByteLimit`. */
+const DEFAULT_OUTPUT_BYTE_LIMIT = 1024 * 1024;
+/** Live transcript budget per terminal, before emission pauses until exit. */
+const TERMINAL_TRANSCRIPT_BYTE_CAP = 256 * 1024;
+/** Tail of the paused (never-streamed) output replayed into the transcript on exit. */
+const TERMINAL_TRANSCRIPT_TAIL_BYTES = 16 * 1024;
+const KILL_GRACE_MS = 2_000;
+/**
+ * Defense-in-depth resource bound: each record holds a ChildProcess handle
+ * plus a retained buffer, so a looping agent must not grow the map without
+ * limit. Released terminals free their slot.
+ */
+const MAX_TERMINALS_PER_THREAD = 64;
+
+export interface TerminalExitStatus {
+ exitCode: number | null;
+ signal: string | null;
+}
+
+export interface CreateTerminalParams {
+ command: string;
+ args?: string[];
+ env?: Array<{ name: string; value: string }>;
+ cwd?: string | null;
+ outputByteLimit?: number | null;
+}
+
+interface TerminalRecord {
+ child: ChildProcess;
+ /** Combined stdout+stderr, front-truncated to `byteLimit`. */
+ output: string;
+ outputBytes: number;
+ byteLimit: number;
+ truncated: boolean;
+ exitStatus: TerminalExitStatus | null;
+ exitWaiters: Array<(status: TerminalExitStatus) => void>;
+ /** Bytes already streamed to the transcript sink. */
+ transcriptBytes: number;
+ transcriptPaused: boolean;
+ /**
+ * Tail of the output that arrived AFTER the transcript paused (never
+ * streamed live), bounded to {@link TERMINAL_TRANSCRIPT_TAIL_BYTES}. The
+ * exit-time replay sends exactly this — never bytes the live stream
+ * already carried, so the transcript can't repeat itself.
+ */
+ pausedTail: string;
+}
+
+/**
+ * Drop leading UTF-8 continuation bytes so a front-truncated buffer decodes
+ * from a character boundary (the ACP contract for `outputByteLimit`).
+ */
+function trimToCharBoundary(buf: Buffer): Buffer {
+ let start = 0;
+ while (start < buf.length && (buf[start] & 0b1100_0000) === 0b1000_0000) start++;
+ return buf.subarray(start);
+}
+
+/** Keep the last `limit` bytes of `text`, cutting on a character boundary. */
+function tailBytes(text: string, limit: number): string {
+ const buf = Buffer.from(text, 'utf8');
+ if (buf.length <= limit) return text;
+ return trimToCharBoundary(buf.subarray(buf.length - limit)).toString('utf8');
+}
+
+/**
+ * Enforce the retained-output byte limit by dropping the buffer's front.
+ * Called lazily (on read and on exit) plus amortized at 2× the limit during
+ * ingestion — re-encoding the whole buffer per chunk would be quadratic on
+ * the stream's hot path.
+ */
+function trimRecordToLimit(record: TerminalRecord): void {
+ if (record.outputBytes <= record.byteLimit) return;
+ const kept = trimToCharBoundary(
+ Buffer.from(record.output, 'utf8').subarray(record.outputBytes - record.byteLimit),
+ );
+ record.output = kept.toString('utf8');
+ record.outputBytes = kept.length;
+ record.truncated = true;
+}
+
+export class AcpTerminalSet {
+ private readonly terminals = new Map<string, TerminalRecord>();
+ private readonly emit: (event: ThreadEvent) => void;
+ private readonly defaultCwd: string;
+ private readonly log: PinoLogger;
+ private disposed = false;
+
+ constructor(opts: {
+ /** Absolute directory commands run in when the agent sends no `cwd`. */
+ defaultCwd: string;
+ /** Transcript sink — the thread manager's `appendEvent`. */
+ emit: (event: ThreadEvent) => void;
+ log: PinoLogger;
+ }) {
+ this.defaultCwd = opts.defaultCwd;
+ this.emit = opts.emit;
+ this.log = opts.log;
+ }
+
+ /** Live (not yet exited) terminal count — a test/diagnostic seam. */
+ liveCount(): number {
+ let count = 0;
+ for (const record of this.terminals.values()) {
+ if (record.exitStatus === null) count++;
+ }
+ return count;
+ }
+
+ create(params: CreateTerminalParams): { terminalId: string } {
+ // A create dispatched from the agent connection can race thread teardown
+ // — after disposeAll, refusing is the only answer that doesn't spawn a
+ // process nothing will ever kill.
+ if (this.disposed) {
+ throw new Error('thread is closing — no new terminals');
+ }
+ if (this.terminals.size >= MAX_TERMINALS_PER_THREAD) {
+ throw new Error(
+ `terminal limit reached (${MAX_TERMINALS_PER_THREAD} per thread) — release finished terminals first`,
+ );
+ }
+ const terminalId = crypto.randomUUID();
+ const overlay: Record<string, string> = {};
+ for (const entry of params.env ?? []) overlay[entry.name] = entry.value;
+ const env = mergedEnv(overlay);
+ const cwd =
+ params.cwd != null
+ ? isAbsolute(params.cwd)
+ ? params.cwd
+ : resolve(this.defaultCwd, params.cwd)
+ : this.defaultCwd;
+
+ const win = process.platform === 'win32';
+ const resolved = win ? resolveWindowsCommand(params.command, envPath(env)) : params.command;
+ const wrap = win && /\.(cmd|bat)$/i.test(resolved);
+ const { cmd, args } = wrap
+ ? windowsCmdWrap(resolved, params.args ?? [])
+ : { cmd: resolved, args: params.args ?? [] };
+ // Group-leader on POSIX for the same reason agent spawns are: a shell
+ // command's own children must die with it on kill/release.
+ const child = spawn(cmd, args, {
+ cwd,
+ env,
+ stdio: ['ignore', 'pipe', 'pipe'],
+ shell: false,
+ detached: !win,
+ windowsHide: true,
+ windowsVerbatimArguments: wrap,
+ });
+
+ const rawLimit = params.outputByteLimit;
+ const record: TerminalRecord = {
+ child,
+ output: '',
+ outputBytes: 0,
+ byteLimit:
+ typeof rawLimit === 'number' && rawLimit > 0
+ ? Math.floor(rawLimit)
+ : DEFAULT_OUTPUT_BYTE_LIMIT,
+ truncated: false,
+ exitStatus: null,
+ exitWaiters: [],
+ transcriptBytes: 0,
+ transcriptPaused: false,
+ pausedTail: '',
+ };
+ this.terminals.set(terminalId, record);
+ this.safeEmit({
+ kind: 'terminal_created',
+ terminalId,
+ command: params.command,
+ args: params.args ?? [],
+ ts: Date.now(),
+ });
+
+ const onChunk = (chunk: string): void => this.ingestChunk(terminalId, record, chunk);
+ child.stdout?.setEncoding('utf8');
+ child.stdout?.on('data', onChunk);
+ child.stderr?.setEncoding('utf8');
+ child.stderr?.on('data', onChunk);
+ // 'error' also fires on a LIVE process when a later signal can't be
+ // delivered (Node docs) — settling then would stamp a running command as
+ // exited and make kill/release skip it forever. Only a pre-spawn failure
+ // (ENOENT and friends) settles here; everything else waits for 'close'.
+ let spawned = false;
+ child.on('spawn', () => {
+ spawned = true;
+ });
+ child.on('error', (err) => {
+ if (spawned) {
+ this.log.warn({ err, terminalId }, '[acp-terminals] child error after spawn');
+ return;
+ }
+ // Surface it as output + a failed exit so the agent's `wait_for_exit`
+ // never hangs on a process that never started.
+ onChunk(`${err.message}\n`);
+ this.settleExit(terminalId, record, { exitCode: 127, signal: null });
+ });
+ // 'close' (not 'exit'): it fires only after stdio has drained, so the
+ // final output burst of a command is in the buffer before the exit
+ // settles — 'exit' can beat the last 'data' events.
+ child.on('close', (code, signal) => {
+ this.settleExit(terminalId, record, { exitCode: code, signal });
+ });
+ return { terminalId };
+ }
+
+ output(terminalId: string): {
+ output: string;
+ truncated: boolean;
+ exitStatus: TerminalExitStatus | null;
+ } {
+ const record = this.mustGet(terminalId);
+ // Ingestion trims amortized (at 2× the limit); the agent-facing read is
+ // where the exact `outputByteLimit` contract must hold.
+ trimRecordToLimit(record);
+ return {
+ output: record.output,
+ truncated: record.truncated,
+ exitStatus: record.exitStatus,
+ };
+ }
+
+ waitForExit(terminalId: string): Promise<TerminalExitStatus> {
+ const record = this.mustGet(terminalId);
+ if (record.exitStatus !== null) return Promise.resolve(record.exitStatus);
+ return new Promise((resolvePromise) => {
+ record.exitWaiters.push(resolvePromise);
+ });
+ }
+
+ /** Kill the command (tree-wide) without dropping its retained output. */
+ async kill(terminalId: string): Promise<void> {
+ const record = this.mustGet(terminalId);
+ if (record.exitStatus !== null) return;
+ await terminateAgentTree(record.child, { graceMs: KILL_GRACE_MS });
+ }
+
+ /** Kill if still running, then drop the record entirely. */
+ async release(terminalId: string): Promise<void> {
+ const record = this.terminals.get(terminalId);
+ if (record === undefined) return;
+ if (record.exitStatus === null) {
+ await terminateAgentTree(record.child, { graceMs: KILL_GRACE_MS });
+ }
+ this.terminals.delete(terminalId);
+ }
+
+ /** Thread teardown: kill every live command and drop all records. */
+ async disposeAll(): Promise<void> {
+ this.disposed = true;
+ const ids = [...this.terminals.keys()];
+ await Promise.allSettled(ids.map((id) => this.release(id)));
+ }
+
+ private mustGet(terminalId: string): TerminalRecord {
+ const record = this.terminals.get(terminalId);
+ if (record === undefined) throw new Error(`unknown terminal '${terminalId}'`);
+ return record;
+ }
+
+ /**
+ * Transcript emission is best-effort display data; it must never break the
+ * control-flow contracts with the agent (`wait_for_exit` resolution) or
+ * crash the stream 'data' handlers it is called from.
+ */
+ private safeEmit(event: ThreadEvent): void {
+ try {
+ this.emit(event);
+ } catch (err) {
+ this.log.warn({ err, kind: event.kind }, '[acp-terminals] transcript emit failed');
+ }
+ }
+
+ private ingestChunk(terminalId: string, record: TerminalRecord, chunk: string): void {
+ if (chunk === '') return;
+ record.output += chunk;
+ record.outputBytes += Buffer.byteLength(chunk, 'utf8');
+ if (record.outputBytes > record.byteLimit * 2) {
+ trimRecordToLimit(record);
+ } else if (record.outputBytes > record.byteLimit) {
+ // Over the limit but under the amortization threshold: the read path
+ // (`output()`) trims exactly; only the flag must be truthful now.
+ record.truncated = true;
+ }
+ if (!record.transcriptPaused) {
+ const bytes = Buffer.byteLength(chunk, 'utf8');
+ if (record.transcriptBytes + bytes <= TERMINAL_TRANSCRIPT_BYTE_CAP) {
+ record.transcriptBytes += bytes;
+ this.safeEmit({ kind: 'terminal_output', terminalId, chunk, ts: Date.now() });
+ return;
+ }
+ record.transcriptPaused = true;
+ }
+ // Paused: accumulate ONLY never-streamed bytes for the exit-time replay,
+ // keeping just the tail (bounded).
+ record.pausedTail = tailBytes(record.pausedTail + chunk, TERMINAL_TRANSCRIPT_TAIL_BYTES);
+ }
+
+ private settleExit(terminalId: string, record: TerminalRecord, status: TerminalExitStatus): void {
+ if (record.exitStatus !== null) return;
+ record.exitStatus = status;
+ trimRecordToLimit(record);
+ if (record.transcriptPaused && record.pausedTail !== '') {
+ // The live stream stopped at the cap — replay the tail of what was
+ // never streamed so the transcript ends with the output that explains
+ // the exit status, without repeating bytes it already carried.
+ this.safeEmit({
+ kind: 'terminal_output',
+ terminalId,
+ chunk: `\n… [output truncated — resuming at the end]\n${record.pausedTail}`,
+ ts: Date.now(),
+ });
+ }
+ this.safeEmit({
+ kind: 'terminal_exit',
+ terminalId,
+ exitCode: status.exitCode,
+ signal: status.signal,
+ ts: Date.now(),
+ });
+ const waiters = record.exitWaiters;
+ record.exitWaiters = [];
+ for (const waiter of waiters) {
+ try {
+ waiter(status);
+ } catch (err) {
+ this.log.warn({ err, terminalId }, '[acp-terminals] exit waiter threw');
+ }
+ }
+ }
+}
diff --git a/packages/server/src/acp/thread-manager.integration.test.ts b/packages/server/src/acp/thread-manager.integration.test.ts
new file mode 100644
index 000000000..f7b4cdd85
--- /dev/null
+++ b/packages/server/src/acp/thread-manager.integration.test.ts
@@ -0,0 +1,1228 @@
+/**
+ * End-to-end ACP loop against a real spawned agent subprocess — the SDK's
+ * bundled example agent (`dist/examples/agent.js`), registered as a custom
+ * agent. Covers: custom-agent launch, initialize + session/new handshake,
+ * streamed session updates, an edit-kind permission request resolved through
+ * the manager's respondPermission path, and clean thread close (process
+ * killed).
+ *
+ * No fs stubs needed: the example agent never calls `fs/*`; the fake
+ * session manager below exists only to satisfy the constructor and the
+ * close path.
+ */
+
+import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { dirname, join } from 'node:path';
+import type {
+ ThreadEvent,
+ ThreadServerFrame,
+} from '@inkeep/open-knowledge-core/acp/thread-protocol';
+import { afterEach, describe, expect, test } from 'vitest';
+import type { AgentSessionManager } from '../agent-sessions.ts';
+import { getLogger } from '../logger.ts';
+import { AcpPermissionStore } from './permissions.ts';
+import { AcpRegistry } from './registry.ts';
+import { AcpThreadManager } from './thread-manager.ts';
+
+const log = getLogger('acp-thread-test');
+
+// Resolve through the module graph — survives hoisting differences between
+// per-package and workspace-root node_modules.
+const EXAMPLE_AGENT = join(
+ dirname(Bun.resolveSync('@agentclientprotocol/sdk', import.meta.dirname)),
+ 'examples/agent.js',
+);
+
+const fakeSessionManager = {
+ getSession: async () => {
+ throw new Error('example agent never uses client fs');
+ },
+ closeAllForAgent: async () => {},
+} as unknown as AgentSessionManager;
+
+let dirs: string[] = [];
+let managers: AcpThreadManager[] = [];
+function tmp(): string {
+ const d = mkdtempSync(join(tmpdir(), 'acp-thread-test-'));
+ dirs.push(d);
+ return d;
+}
+afterEach(async () => {
+ await Promise.allSettled(managers.map((m) => m.destroy()));
+ managers = [];
+ for (const d of dirs) rmSync(d, { recursive: true, force: true });
+ dirs = [];
+});
+
+function makeManager(
+ contentDir: string,
+ localDir: string,
+ extra?: {
+ unwatchedTurnCancelMs?: number;
+ unwatchedTurnKillMs?: number;
+ isIgnoredPath?: (relPosix: string) => boolean;
+ registry?: AcpRegistry;
+ },
+): AcpThreadManager {
+ const manager = new AcpThreadManager({
+ contentDir,
+ localDir,
+ registry: new AcpRegistry({
+ localDir,
+ log,
+ fetchImpl: (async () => {
+ throw new Error('offline test');
+ }) as typeof fetch,
+ }),
+ permissions: new AcpPermissionStore(localDir, log),
+ sessionManager: fakeSessionManager,
+ isExcludedPath: () => false,
+ isIgnoredPath: () => false,
+ log,
+ ...extra,
+ });
+ managers.push(manager);
+ return manager;
+}
+
+/** Test seams into manager internals (private fields; same-package test). */
+function internals(manager: AcpThreadManager): {
+ sweep: () => void;
+ pendingPermissionCount: (threadId: string) => number;
+ turnActive: (threadId: string) => boolean;
+} {
+ const m = manager as unknown as {
+ reapIdleThreads: () => void;
+ threads: Map<string, { pendingPermissions: Map<unknown, unknown>; turnActive: boolean }>;
+ };
+ return {
+ sweep: () => m.reapIdleThreads(),
+ pendingPermissionCount: (threadId) => m.threads.get(threadId)?.pendingPermissions.size ?? 0,
+ turnActive: (threadId) => m.threads.get(threadId)?.turnActive ?? false,
+ };
+}
+
+function writeExampleAgentEntry(localDir: string): void {
+ writeFileSync(
+ join(localDir, 'acp-agents.json'),
+ JSON.stringify([
+ { id: 'example', name: 'Example Agent', command: 'node', args: [EXAMPLE_AGENT] },
+ ]),
+ );
+}
+
+async function waitUntil(pred: () => boolean, ms: number, what: string): Promise<void> {
+ const deadline = Date.now() + ms;
+ while (!pred()) {
+ if (Date.now() > deadline) throw new Error(`timed out waiting for ${what}`);
+ await new Promise((r) => setTimeout(r, 25));
+ }
+}
+
+describe('AcpThreadManager (real subprocess)', () => {
+ test('runs a full turn against the SDK example agent, permission round-trip included', async () => {
+ expect(existsSync(EXAMPLE_AGENT)).toBe(true);
+ const contentDir = tmp();
+ const localDir = tmp();
+ writeFileSync(
+ join(localDir, 'acp-agents.json'),
+ JSON.stringify([
+ { id: 'example', name: 'Example Agent', command: 'node', args: [EXAMPLE_AGENT] },
+ ]),
+ );
+ const manager = makeManager(contentDir, localDir);
+
+ const events: Array<{ seq: number; event: ThreadEvent }> = [];
+ const info = await manager.createThread({ agent: { source: 'custom', id: 'example' } });
+ // Custom launches resolve synchronously now (no second disk read), so the
+ // create snapshot may already have progressed past 'installing'.
+ expect(['installing', 'spawning']).toContain(info.status);
+ await manager.subscribe(info.threadId, 0, (frame: ThreadServerFrame) => {
+ if (frame.op === 'event') events.push({ seq: frame.seq, event: frame.event });
+ if (frame.op === 'events') {
+ for (const [i, event] of frame.events.entries()) {
+ events.push({ seq: frame.fromSeq + i, event });
+ }
+ }
+ });
+
+ const waitFor = async (pred: () => boolean, ms: number): Promise<void> => {
+ const deadline = Date.now() + ms;
+ while (!pred()) {
+ if (Date.now() > deadline) {
+ throw new Error(
+ `timed out; events so far: ${JSON.stringify(events.map((e) => e.event.kind))}`,
+ );
+ }
+ await new Promise((r) => setTimeout(r, 50));
+ }
+ };
+
+ // Handshake completes → ready.
+ await waitFor(
+ () => events.some((e) => e.event.kind === 'status' && e.event.status === 'ready'),
+ 15_000,
+ );
+
+ manager.sendPrompt(info.threadId, 'Improve my project please');
+
+ // The example agent streams chunks then asks permission for an
+ // edit-kind tool call — policy must ASK (not auto-allow).
+ await waitFor(() => events.some((e) => e.event.kind === 'permission_request'), 20_000);
+ const request = events.find((e) => e.event.kind === 'permission_request')?.event;
+ if (request?.kind !== 'permission_request') throw new Error('unreachable');
+ expect(request.options.map((o) => o.optionId)).toContain('allow');
+
+ manager.respondPermission(info.threadId, request.requestId, {
+ kind: 'selected',
+ optionId: 'allow',
+ });
+
+ await waitFor(() => events.some((e) => e.event.kind === 'turn_ended'), 20_000);
+ const turnEnd = events.find((e) => e.event.kind === 'turn_ended')?.event;
+ if (turnEnd?.kind !== 'turn_ended') throw new Error('unreachable');
+ expect(turnEnd.stopReason).toBe('end_turn');
+
+ // Streamed chunks arrived and seqs are strictly increasing.
+ expect(events.some((e) => e.event.kind === 'session_update')).toBe(true);
+ const seqs = events.map((e) => e.seq);
+ expect([...seqs].sort((a, b) => a - b)).toEqual(seqs);
+
+ // A late subscriber replays the same history from seq 0.
+ const replayed: number[] = [];
+ await manager.subscribe(info.threadId, 0, (frame) => {
+ if (frame.op === 'event') replayed.push(frame.seq);
+ if (frame.op === 'events') {
+ for (let i = 0; i < frame.events.length; i++) {
+ replayed.push(frame.fromSeq + i);
+ }
+ }
+ });
+ expect(replayed.length).toBeGreaterThanOrEqual(events.length);
+
+ // Close archives (transcript kept) rather than destroying.
+ await manager.closeThread(info.threadId);
+ expect(manager.listThreads().filter((t) => t.archived !== true)).toHaveLength(0);
+ expect(manager.listThreads()[0]?.archived).toBe(true);
+ }, 45_000);
+
+ test('closeThread kills a SIGTERM-ignoring agent tree before resolving', async () => {
+ const contentDir = tmp();
+ const localDir = tmp();
+ // Simulates the npx shape: a TERM-ignoring wrapper whose TERM-ignoring
+ // child is the "real" agent. Speaks no ACP — the kill path must not
+ // depend on a completed handshake.
+ const kidPidFile = join(localDir, 'kid.pid');
+ const agentPath = join(localDir, 'stubborn-agent.mjs');
+ writeFileSync(
+ agentPath,
+ [
+ "import { spawn } from 'node:child_process';",
+ "import { writeFileSync } from 'node:fs';",
+ "process.on('SIGTERM', () => {});",
+ 'const kid = spawn(process.execPath, [',
+ " '-e',",
+ ' "process.on(\'SIGTERM\', () => {}); setInterval(() => {}, 1000);",',
+ "], { stdio: 'ignore' });",
+ 'writeFileSync(process.env.KID_PID_FILE, String(kid.pid));',
+ 'setInterval(() => {}, 1000);',
+ '',
+ ].join('\n'),
+ );
+ writeFileSync(
+ join(localDir, 'acp-agents.json'),
+ JSON.stringify([
+ {
+ id: 'stubborn',
+ name: 'Stubborn Agent',
+ command: 'node',
+ args: [agentPath],
+ env: { KID_PID_FILE: kidPidFile },
+ },
+ ]),
+ );
+ const manager = makeManager(contentDir, localDir);
+ const info = await manager.createThread({ agent: { source: 'custom', id: 'stubborn' } });
+
+ const deadline = Date.now() + 5_000;
+ while (!existsSync(kidPidFile)) {
+ if (Date.now() > deadline) throw new Error('agent tree never spawned');
+ await new Promise((r) => setTimeout(r, 25));
+ }
+ const kidPid = Number(readFileSync(kidPidFile, 'utf8'));
+ const rootPid = (
+ manager as unknown as { threads: Map<string, { child: { pid?: number } | null }> }
+ ).threads.get(info.threadId)?.child?.pid;
+ const isAlive = (pid: number): boolean => {
+ try {
+ process.kill(pid, 0);
+ return true;
+ } catch {
+ return false;
+ }
+ };
+ expect(typeof rootPid).toBe('number');
+ expect(isAlive(kidPid)).toBe(true);
+
+ await manager.closeThread(info.threadId, { killGraceMs: 250 });
+
+ // closeThread resolving IS the death guarantee — no grace-period sleep.
+ expect(rootPid !== undefined && isAlive(rootPid)).toBe(false);
+ const kidDeadline = Date.now() + 2_000;
+ while (isAlive(kidPid)) {
+ if (Date.now() > kidDeadline) throw new Error('grandchild survived closeThread');
+ await new Promise((r) => setTimeout(r, 25));
+ }
+ expect(manager.listThreads().filter((t) => t.archived !== true)).toHaveLength(0);
+ }, 15_000);
+
+ test('unwatched turn backstop: cancel stage ends a zero-subscriber turn', async () => {
+ const localDir = tmp();
+ writeExampleAgentEntry(localDir);
+ // Never subscribed → unwatched since creation; cancel threshold is
+ // effectively immediate, kill threshold far away.
+ const manager = makeManager(tmp(), localDir, {
+ unwatchedTurnCancelMs: 1,
+ unwatchedTurnKillMs: 10 * 60 * 1000,
+ });
+ const info = await manager.createThread({ agent: { source: 'custom', id: 'example' } });
+ const { sweep, pendingPermissionCount, turnActive } = internals(manager);
+
+ await waitUntil(
+ () => manager.getInfo(info.threadId)?.status === 'ready',
+ 15_000,
+ 'agent ready',
+ );
+ manager.sendPrompt(info.threadId, 'Improve my project please');
+ // Deterministic mid-turn point: the agent is blocked awaiting our
+ // permission response — exactly the shape a headless runaway takes.
+ await waitUntil(
+ () => pendingPermissionCount(info.threadId) > 0,
+ 20_000,
+ 'pending permission request',
+ );
+
+ sweep();
+
+ // Cancel resolves the pending permission as 'cancelled'; the example
+ // agent then ends the turn with stopReason 'cancelled'.
+ await waitUntil(() => !turnActive(info.threadId), 10_000, 'turn cancelled');
+ expect(manager.getInfo(info.threadId)?.status).toBe('ready');
+ // Cancel stage never closes the thread — reattach still works.
+ expect(manager.listThreads()).toHaveLength(1);
+ }, 45_000);
+
+ test('unwatched turn backstop: kill stage force-closes when past the kill threshold', async () => {
+ const localDir = tmp();
+ writeExampleAgentEntry(localDir);
+ const manager = makeManager(tmp(), localDir, {
+ unwatchedTurnCancelMs: 1,
+ unwatchedTurnKillMs: 1,
+ });
+ const info = await manager.createThread({ agent: { source: 'custom', id: 'example' } });
+ const { sweep } = internals(manager);
+
+ await waitUntil(
+ () => manager.getInfo(info.threadId)?.status === 'ready',
+ 15_000,
+ 'agent ready',
+ );
+ manager.sendPrompt(info.threadId, 'Improve my project please');
+
+ sweep();
+
+ await waitUntil(
+ () => manager.listThreads().filter((t) => t.archived !== true).length === 0,
+ 10_000,
+ 'thread force-closed',
+ );
+ }, 45_000);
+
+ test('unknown agents and capacity are refused cleanly', async () => {
+ const manager = makeManager(tmp(), tmp());
+ await expect(manager.createThread({ agent: { source: 'custom', id: 'nope' } })).rejects.toThrow(
+ "no custom agent 'nope'",
+ );
+ // makeManager's registry fetch is offline with no cache — that's a
+ // registry FAILURE, which must surface as such, not as "unknown agent".
+ await expect(
+ manager.createThread({ agent: { source: 'registry', id: 'ghost' } }),
+ ).rejects.toThrow('agent registry unavailable');
+
+ // A working registry that simply lacks the id IS "unknown agent".
+ const emptyCatalogRegistry = new AcpRegistry({
+ localDir: tmp(),
+ log,
+ fetchImpl: (async () =>
+ new Response(JSON.stringify({ agents: [] }), { status: 200 })) as typeof fetch,
+ });
+ const manager2 = makeManager(tmp(), tmp(), { registry: emptyCatalogRegistry });
+ await expect(
+ manager2.createThread({ agent: { source: 'registry', id: 'ghost' } }),
+ ).rejects.toThrow('not in the registry');
+ });
+
+ test('session config options: advertised at session/new, set round-trips', async () => {
+ const contentDir = tmp();
+ const localDir = tmp();
+ // Minimal stdio ACP agent that advertises a model selector and applies
+ // `session/set_config_option` — the surface the SDK example agent lacks.
+ const agentPath = join(localDir, 'config-option-agent.mjs');
+ writeFileSync(
+ agentPath,
+ `
+let current = 'sonnet';
+const configOptions = () => [
+ {
+ id: 'model',
+ name: 'Model',
+ category: 'model',
+ type: 'select',
+ currentValue: current,
+ options: [
+ { value: 'sonnet', name: 'Sonnet' },
+ { value: 'opus', name: 'Opus' },
+ ],
+ },
+];
+let buffer = '';
+process.stdin.setEncoding('utf8');
+process.stdin.on('data', (chunk) => {
+ buffer += chunk;
+ let idx = buffer.indexOf('\\n');
+ while (idx !== -1) {
+ const line = buffer.slice(0, idx);
+ buffer = buffer.slice(idx + 1);
+ idx = buffer.indexOf('\\n');
+ if (line.trim() === '') continue;
+ const msg = JSON.parse(line);
+ const reply = (result) =>
+ process.stdout.write(JSON.stringify({ jsonrpc: '2.0', id: msg.id, result }) + '\\n');
+ if (msg.method === 'initialize') {
+ reply({ protocolVersion: 1, agentCapabilities: {} });
+ } else if (msg.method === 'session/new') {
+ reply({ sessionId: 's1', configOptions: configOptions() });
+ } else if (msg.method === 'session/set_config_option') {
+ current = msg.params.value;
+ reply({ configOptions: configOptions() });
+ } else if (msg.method === 'session/prompt') {
+ reply({ stopReason: 'end_turn' });
+ } else if (msg.id !== undefined) {
+ reply({});
+ }
+ }
+});
+`,
+ );
+ writeFileSync(
+ join(localDir, 'acp-agents.json'),
+ JSON.stringify([
+ { id: 'config-agent', name: 'Config Agent', command: 'node', args: [agentPath] },
+ ]),
+ );
+ const manager = makeManager(contentDir, localDir);
+
+ const info = await manager.createThread({ agent: { source: 'custom', id: 'config-agent' } });
+ const waitFor = async (pred: () => boolean, ms: number): Promise<void> => {
+ const deadline = Date.now() + ms;
+ while (!pred()) {
+ if (Date.now() > deadline) {
+ throw new Error(`timed out; info: ${JSON.stringify(manager.getInfo(info.threadId))}`);
+ }
+ await new Promise((r) => setTimeout(r, 50));
+ }
+ };
+
+ await waitFor(() => manager.getInfo(info.threadId)?.status === 'ready', 15_000);
+ const advertised = manager.getInfo(info.threadId)?.configOptions;
+ expect(advertised).toHaveLength(1);
+ expect(advertised?.[0]).toMatchObject({
+ id: 'model',
+ category: 'model',
+ type: 'select',
+ currentValue: 'sonnet',
+ });
+
+ manager.setConfigOption(info.threadId, 'model', 'opus');
+ await waitFor(
+ () => manager.getInfo(info.threadId)?.configOptions?.[0]?.currentValue === 'opus',
+ 10_000,
+ );
+
+ await manager.closeThread(info.threadId);
+ }, 30_000);
+});
+
+/**
+ * Minimal stdio ACP agent for the persistence/resume matrix. Capabilities
+ * come from FAKE_CAPS ("resume,load" | "load" | ""); FAIL_LOAD=1 rejects
+ * `session/load` with -32002 (the expired-session shape). `session/load`
+ * replays two history chunks BEFORE its response, per protocol — the shape
+ * the manager's replay suppression must swallow.
+ */
+function writeResumableAgentEntry(localDir: string, id: string, env: Record<string, string>): void {
+ const agentPath = join(localDir, `${id}.mjs`);
+ writeFileSync(
+ agentPath,
+ `
+const caps = (process.env.FAKE_CAPS ?? '').split(',').filter(Boolean);
+const write = (msg) => process.stdout.write(JSON.stringify(msg) + '\\n');
+let buffer = '';
+process.stdin.setEncoding('utf8');
+process.stdin.on('data', (chunk) => {
+ buffer += chunk;
+ let idx = buffer.indexOf('\\n');
+ while (idx !== -1) {
+ const line = buffer.slice(0, idx);
+ buffer = buffer.slice(idx + 1);
+ idx = buffer.indexOf('\\n');
+ if (line.trim() === '') continue;
+ const msg = JSON.parse(line);
+ const reply = (result) => write({ jsonrpc: '2.0', id: msg.id, result });
+ const replyErr = (code, message) => write({ jsonrpc: '2.0', id: msg.id, error: { code, message } });
+ const notify = (update) =>
+ write({ jsonrpc: '2.0', method: 'session/update', params: { sessionId: 'sess-fixed', update } });
+ if (msg.method === 'initialize') {
+ const agentCapabilities = {};
+ if (caps.includes('load')) agentCapabilities.loadSession = true;
+ if (caps.includes('resume')) agentCapabilities.sessionCapabilities = { resume: {} };
+ reply({ protocolVersion: 1, agentCapabilities });
+ } else if (msg.method === 'session/new') {
+ reply({ sessionId: 'sess-fixed' });
+ } else if (msg.method === 'session/prompt') {
+ notify({
+ sessionUpdate: 'agent_message_chunk',
+ content: { type: 'text', text: 'echo:' + msg.params.prompt[0].text },
+ });
+ reply({ stopReason: 'end_turn' });
+ } else if (msg.method === 'session/load') {
+ if (process.env.FAIL_LOAD === '1' || msg.params.sessionId !== 'sess-fixed') {
+ replyErr(-32002, 'unknown session');
+ } else {
+ notify({ sessionUpdate: 'user_message_chunk', content: { type: 'text', text: 'old-user' } });
+ notify({ sessionUpdate: 'agent_message_chunk', content: { type: 'text', text: 'old-agent' } });
+ reply({});
+ }
+ } else if (msg.method === 'session/resume') {
+ if (msg.params.sessionId !== 'sess-fixed') replyErr(-32002, 'unknown session');
+ else reply({});
+ } else if (msg.id !== undefined) {
+ reply({});
+ }
+ }
+});
+`,
+ );
+ writeFileSync(
+ join(localDir, 'acp-agents.json'),
+ JSON.stringify([{ id, name: `Fake ${id}`, command: 'node', args: [agentPath], env }]),
+ );
+}
+
+/**
+ * Minimal stdio ACP agent that, on each prompt, streams a burst of single-char
+ * chunks: a message run, an interleaved thought run, then a second message run.
+ * The tight synchronous burst is what the manager's fold-on-flush collapses;
+ * the thought between the two message runs is a fold boundary (different
+ * sessionUpdate kind) that must survive.
+ */
+function writeStreamerAgentEntry(localDir: string, id: string): void {
+ const agentPath = join(localDir, `${id}.mjs`);
+ writeFileSync(
+ agentPath,
+ `
+const write = (msg) => process.stdout.write(JSON.stringify(msg) + '\\n');
+const notify = (update) =>
+ write({ jsonrpc: '2.0', method: 'session/update', params: { sessionId: 'sess-fixed', update } });
+let buffer = '';
+process.stdin.setEncoding('utf8');
+process.stdin.on('data', (chunk) => {
+ buffer += chunk;
+ let idx = buffer.indexOf('\\n');
+ while (idx !== -1) {
+ const line = buffer.slice(0, idx);
+ buffer = buffer.slice(idx + 1);
+ idx = buffer.indexOf('\\n');
+ if (line.trim() === '') continue;
+ const msg = JSON.parse(line);
+ const reply = (result) => write({ jsonrpc: '2.0', id: msg.id, result });
+ if (msg.method === 'initialize') {
+ reply({ protocolVersion: 1, agentCapabilities: {} });
+ } else if (msg.method === 'session/new') {
+ reply({ sessionId: 'sess-fixed' });
+ } else if (msg.method === 'session/prompt') {
+ for (const w of 'ABCDEFGH') notify({ sessionUpdate: 'agent_message_chunk', content: { type: 'text', text: w } });
+ for (const w of 'think') notify({ sessionUpdate: 'agent_thought_chunk', content: { type: 'text', text: w } });
+ for (const w of 'IJKLMNOP') notify({ sessionUpdate: 'agent_message_chunk', content: { type: 'text', text: w } });
+ reply({ stopReason: 'end_turn' });
+ } else if (msg.id !== undefined) {
+ reply({});
+ }
+ }
+});
+`,
+ );
+ writeFileSync(
+ join(localDir, 'acp-agents.json'),
+ JSON.stringify([{ id, name: `Fake ${id}`, command: 'node', args: [agentPath] }]),
+ );
+}
+
+describe('AcpThreadManager persistence + resume', () => {
+ type Collected = Array<{ seq: number; event: ThreadEvent }>;
+ const collector = (into: Collected) => (frame: ThreadServerFrame) => {
+ if (frame.op === 'event') into.push({ seq: frame.seq, event: frame.event });
+ if (frame.op === 'events') {
+ for (const [i, event] of frame.events.entries()) {
+ into.push({ seq: frame.fromSeq + i, event });
+ }
+ }
+ };
+ const kinds = (events: Collected): string[] => events.map((e) => e.event.kind);
+ const agentChunks = (events: Collected): string[] =>
+ events
+ .map((e) => e.event)
+ .filter((e) => e.kind === 'session_update')
+ .map((e) => {
+ const update = (e as { update?: { content?: { text?: string } } }).update;
+ return update?.content?.text ?? '';
+ });
+
+ async function runOneTurn(
+ manager: AcpThreadManager,
+ agentId: string,
+ prompt: string,
+ ): Promise<string> {
+ const info = await manager.createThread({ agent: { source: 'custom', id: agentId } });
+ await waitUntil(
+ () => manager.getInfo(info.threadId)?.status === 'ready',
+ 15_000,
+ 'agent ready',
+ );
+ manager.sendPrompt(info.threadId, prompt);
+ await waitUntil(() => manager.getInfo(info.threadId)?.status === 'ready', 15_000, 'turn ended');
+ return info.threadId;
+ }
+
+ const chunkText = (e: ThreadEvent): string =>
+ e.kind === 'session_update'
+ ? ((e.update as unknown as { content?: { text?: string } }).content?.text ?? '')
+ : '';
+ const chunksOfKind = (events: Collected, kind: string): ThreadEvent[] =>
+ events
+ .map((e) => e.event)
+ .filter(
+ (e) =>
+ e.kind === 'session_update' &&
+ (e.update as unknown as { sessionUpdate?: string }).sessionUpdate === kind,
+ );
+
+ test('a streamed chunk burst folds into far fewer transcript events, boundaries intact', async () => {
+ const contentDir = tmp();
+ const localDir = tmp();
+ writeStreamerAgentEntry(localDir, 'streamer');
+ const manager = makeManager(contentDir, localDir);
+ await manager.init();
+ // The agent streams 16 message chars + 5 thought chars in one burst.
+ const threadId = await runOneTurn(manager, 'streamer', 'go');
+
+ const live: Collected = [];
+ await manager.subscribe(threadId, 0, collector(live));
+
+ // Folding assigns no new seq, so line-index-IS-the-seq still holds.
+ expect(live.map((e) => e.seq)).toEqual(live.map((_, i) => i));
+
+ const messageChunks = chunksOfKind(live, 'agent_message_chunk');
+ const thoughtChunks = chunksOfKind(live, 'agent_thought_chunk');
+ // Exact text survives the fold, and the interleaved thought never bleeds
+ // into the message stream (or vice versa).
+ expect(messageChunks.map(chunkText).join('')).toBe('ABCDEFGHIJKLMNOP');
+ expect(thoughtChunks.map(chunkText).join('')).toBe('think');
+ // 16 streamed message chars collapsed to a handful of events — and at least
+ // two, since the thought run splits the message stream (a fold boundary).
+ expect(messageChunks.length).toBeGreaterThanOrEqual(2);
+ expect(messageChunks.length).toBeLessThan(16);
+ expect(thoughtChunks.length).toBeLessThan(5);
+
+ // The same folded, contiguous log rehydrates from disk on a fresh manager.
+ await manager.closeThread(threadId);
+ const manager2 = makeManager(contentDir, localDir);
+ await manager2.init();
+ const replayed: Collected = [];
+ await manager2.subscribe(threadId, 0, collector(replayed));
+ expect(replayed.map((e) => e.seq)).toEqual(replayed.map((_, i) => i));
+ expect(chunksOfKind(replayed, 'agent_message_chunk').map(chunkText).join('')).toBe(
+ 'ABCDEFGHIJKLMNOP',
+ );
+ }, 45_000);
+
+ test('close archives the transcript; a new manager rehydrates and replays it from disk', async () => {
+ const contentDir = tmp();
+ const localDir = tmp();
+ writeResumableAgentEntry(localDir, 'fake-resume', { FAKE_CAPS: 'resume,load' });
+ const manager = makeManager(contentDir, localDir);
+ await manager.init();
+ const threadId = await runOneTurn(manager, 'fake-resume', 'hello there');
+ const liveEvents: Collected = [];
+ await manager.subscribe(threadId, 0, collector(liveEvents));
+ await manager.closeThread(threadId);
+
+ const archivedInfo = manager.listThreads().find((t) => t.threadId === threadId);
+ expect(archivedInfo?.archived).toBe(true);
+ expect(archivedInfo?.status).toBe('exited');
+ // Title adopted from the first prompt survives into the archive.
+ expect(archivedInfo?.title).toBe('hello there');
+
+ // A second manager on the same localDir sees the thread and replays the
+ // whole transcript from disk with the same seq contract.
+ const manager2 = makeManager(contentDir, localDir);
+ await manager2.init();
+ const rehydrated = manager2.listThreads().find((t) => t.threadId === threadId);
+ expect(rehydrated?.archived).toBe(true);
+ expect(rehydrated?.title).toBe('hello there');
+ const replayed: Collected = [];
+ await manager2.subscribe(threadId, 0, collector(replayed));
+ expect(replayed.length).toBeGreaterThanOrEqual(liveEvents.length);
+ expect(replayed.map((e) => e.seq)).toEqual(replayed.map((_, i) => i));
+ expect(kinds(replayed)).toContain('user_message');
+ expect(agentChunks(replayed)).toContain('echo:hello there');
+ }, 45_000);
+
+ test('closing a never-prompted thread discards it instead of archiving', async () => {
+ const contentDir = tmp();
+ const localDir = tmp();
+ writeExampleAgentEntry(localDir);
+ const manager = makeManager(contentDir, localDir);
+ await manager.init();
+
+ const info = await manager.createThread({ agent: { source: 'custom', id: 'example' } });
+ await waitUntil(
+ () => manager.getInfo(info.threadId)?.status === 'ready',
+ 15_000,
+ 'agent ready',
+ );
+ // No prompt: the user spawned the agent then closed it untouched.
+ await manager.closeThread(info.threadId);
+
+ // Discarded, not archived — gone from the list…
+ expect(manager.listThreads().find((t) => t.threadId === info.threadId)).toBeUndefined();
+ // …and off disk, so a fresh manager doesn't rehydrate it as history.
+ const manager2 = makeManager(contentDir, localDir);
+ await manager2.init();
+ expect(manager2.listThreads().find((t) => t.threadId === info.threadId)).toBeUndefined();
+ }, 45_000);
+
+ test('a manual rename survives archive + rehydration; adoption strips prompt filler', async () => {
+ const contentDir = tmp();
+ const localDir = tmp();
+ writeResumableAgentEntry(localDir, 'fake-resume', { FAKE_CAPS: 'resume,load' });
+ const manager = makeManager(contentDir, localDir);
+ await manager.init();
+ const threadId = await runOneTurn(manager, 'fake-resume', 'please update the roadmap');
+ // First-prompt adoption drops the filler lead-in.
+ expect(manager.getInfo(threadId)?.title).toBe('Update the roadmap');
+
+ await manager.closeThread(threadId);
+ await manager.renameThread(threadId, 'Q3 roadmap thread');
+ expect(manager.getInfo(threadId)?.title).toBe('Q3 roadmap thread');
+
+ // A fresh manager sees the manual title in the rehydrated meta, and the
+ // rename's transcript event replays under the intact seq contract.
+ const manager2 = makeManager(contentDir, localDir);
+ await manager2.init();
+ const rehydrated = manager2.listThreads().find((t) => t.threadId === threadId);
+ expect(rehydrated?.title).toBe('Q3 roadmap thread');
+ const replayed: Collected = [];
+ await manager2.subscribe(threadId, 0, collector(replayed));
+ expect(replayed.map((e) => e.seq)).toEqual(replayed.map((_, i) => i));
+ expect(
+ replayed.some(
+ (e) => e.event.kind === 'title_changed' && e.event.title === 'Q3 roadmap thread',
+ ),
+ ).toBe(true);
+ }, 45_000);
+
+ test('launch title derives from titleHint, not the composed prompt preamble', async () => {
+ const contentDir = tmp();
+ const localDir = tmp();
+ writeExampleAgentEntry(localDir);
+ const manager = makeManager(contentDir, localDir);
+ await manager.init();
+
+ // titleHint (the user's raw ask) is carried on create and stored on the
+ // record; the launch prompt itself opens with the fixed handoff preamble.
+ const info = await manager.createThread({
+ agent: { source: 'custom', id: 'example' },
+ titleHint: 'Fix the login redirect',
+ });
+ await waitUntil(
+ () => manager.getInfo(info.threadId)?.status === 'ready',
+ 15_000,
+ 'agent ready',
+ );
+
+ // The first prompt carries the preamble; without the hint the tab would
+ // read "You're an agent working inside OpenKnowledge, w…". The stored hint
+ // wins, so the title is the user's actual ask.
+ manager.sendPrompt(
+ info.threadId,
+ "You're an agent working inside OpenKnowledge, with its MCP tools available to you. Here's what I'd like to do:\n\n> Fix the login redirect",
+ );
+ await waitUntil(
+ () => manager.getInfo(info.threadId)?.title !== info.agent.name,
+ 15_000,
+ 'title adopted',
+ );
+ expect(manager.getInfo(info.threadId)?.title).toBe('Fix the login redirect');
+ }, 45_000);
+
+ test('resume via session/resume: same thread continues, no history duplication', async () => {
+ const contentDir = tmp();
+ const localDir = tmp();
+ writeResumableAgentEntry(localDir, 'fake-resume', { FAKE_CAPS: 'resume,load' });
+ const manager = makeManager(contentDir, localDir);
+ await manager.init();
+ const threadId = await runOneTurn(manager, 'fake-resume', 'first message');
+ await manager.closeThread(threadId);
+ expect(manager.getInfo(threadId)?.archived).toBe(true);
+
+ const info = await manager.resumeThread(threadId, 'second message');
+ expect(info.archived).toBe(false);
+ await waitUntil(
+ () =>
+ manager.getInfo(threadId)?.status === 'ready' &&
+ !(manager as unknown as { threads: Map<string, { turnActive: boolean }> }).threads.get(
+ threadId,
+ )?.turnActive,
+ 15_000,
+ 'resumed turn ended',
+ );
+
+ const replayed: Collected = [];
+ await manager.subscribe(threadId, 0, collector(replayed));
+ // Contiguous seqs across the disk (pre-archive) + memory (post-resume) stitch.
+ expect(replayed.map((e) => e.seq)).toEqual(replayed.map((_, i) => i));
+ const userMessages = replayed
+ .map((e) => e.event)
+ .filter((e): e is Extract<ThreadEvent, { kind: 'user_message' }> => e.kind === 'user_message')
+ .map((e) => e.content);
+ expect(userMessages).toEqual(['first message', 'second message']);
+ expect(agentChunks(replayed)).toEqual(['echo:first message', 'echo:second message']);
+
+ await manager.closeThread(threadId);
+ }, 45_000);
+
+ test('resume via session/load: protocol replay is suppressed, not duplicated', async () => {
+ const contentDir = tmp();
+ const localDir = tmp();
+ writeResumableAgentEntry(localDir, 'fake-load', { FAKE_CAPS: 'load' });
+ const manager = makeManager(contentDir, localDir);
+ await manager.init();
+ const threadId = await runOneTurn(manager, 'fake-load', 'first message');
+ await manager.closeThread(threadId);
+
+ const info = await manager.resumeThread(threadId, 'second message');
+ expect(info.archived).toBe(false);
+ await waitUntil(
+ () =>
+ manager.getInfo(threadId)?.status === 'ready' &&
+ !(manager as unknown as { threads: Map<string, { turnActive: boolean }> }).threads.get(
+ threadId,
+ )?.turnActive,
+ 20_000,
+ 'resumed turn ended',
+ );
+
+ const replayed: Collected = [];
+ await manager.subscribe(threadId, 0, collector(replayed));
+ // The fixture replayed 'old-user'/'old-agent' chunks during session/load —
+ // they duplicate the retained log and must NOT appear as new events.
+ expect(agentChunks(replayed)).toEqual(['echo:first message', 'echo:second message']);
+ expect(agentChunks(replayed)).not.toContain('old-user');
+ expect(agentChunks(replayed)).not.toContain('old-agent');
+
+ await manager.closeThread(threadId);
+ }, 45_000);
+
+ test('resume-unsupported: no capability, and expired sessions, both stay archived', async () => {
+ const contentDir = tmp();
+ const localDir = tmp();
+ writeResumableAgentEntry(localDir, 'fake-none', { FAKE_CAPS: '' });
+ const manager = makeManager(contentDir, localDir);
+ await manager.init();
+ const threadId = await runOneTurn(manager, 'fake-none', 'first message');
+ await manager.closeThread(threadId);
+
+ // No session/resume, no session/load advertised.
+ await expect(manager.resumeThread(threadId, 'again')).rejects.toMatchObject({
+ code: 'resume-unsupported',
+ });
+ expect(manager.getInfo(threadId)?.archived).toBe(true);
+
+ // Advertises load but rejects the stored sessionId (agent-side expiry).
+ writeResumableAgentEntry(localDir, 'fake-none', { FAKE_CAPS: 'load', FAIL_LOAD: '1' });
+ await expect(manager.resumeThread(threadId, 'again')).rejects.toMatchObject({
+ code: 'resume-unsupported',
+ });
+ expect(manager.getInfo(threadId)?.archived).toBe(true);
+ // The transcript survived both failed attempts.
+ const replayed: Collected = [];
+ await manager.subscribe(threadId, 0, collector(replayed));
+ expect(agentChunks(replayed)).toContain('echo:first message');
+ }, 45_000);
+
+ test('delete refuses live threads, removes archived ones and their files', async () => {
+ const contentDir = tmp();
+ const localDir = tmp();
+ writeResumableAgentEntry(localDir, 'fake-resume', { FAKE_CAPS: 'resume' });
+ const manager = makeManager(contentDir, localDir);
+ await manager.init();
+ const threadId = await runOneTurn(manager, 'fake-resume', 'to be deleted');
+
+ await expect(manager.deleteThread(threadId)).rejects.toMatchObject({ code: 'not-ready' });
+
+ await manager.closeThread(threadId);
+ const threadsDir = join(localDir, 'threads');
+ expect(existsSync(join(threadsDir, `${threadId}.ndjson`))).toBe(true);
+ expect(existsSync(join(threadsDir, `${threadId}.meta.json`))).toBe(true);
+
+ await manager.deleteThread(threadId);
+ expect(manager.listThreads()).toHaveLength(0);
+ expect(existsSync(join(threadsDir, `${threadId}.ndjson`))).toBe(false);
+ expect(existsSync(join(threadsDir, `${threadId}.meta.json`))).toBe(false);
+ }, 45_000);
+
+ test('destroy() archives running threads; a new manager can resume them', async () => {
+ const contentDir = tmp();
+ const localDir = tmp();
+ writeResumableAgentEntry(localDir, 'fake-resume', { FAKE_CAPS: 'resume' });
+ const manager = makeManager(contentDir, localDir);
+ await manager.init();
+ const threadId = await runOneTurn(manager, 'fake-resume', 'survives shutdown');
+ await manager.destroy();
+
+ const manager2 = makeManager(contentDir, localDir);
+ await manager2.init();
+ const rehydrated = manager2.listThreads().find((t) => t.threadId === threadId);
+ expect(rehydrated?.archived).toBe(true);
+
+ const info = await manager2.resumeThread(threadId, 'and continues');
+ expect(info.archived).toBe(false);
+ await waitUntil(
+ () => manager2.getInfo(threadId)?.status === 'ready',
+ 15_000,
+ 'resumed after restart',
+ );
+ const replayed: Collected = [];
+ await manager2.subscribe(threadId, 0, collector(replayed));
+ expect(agentChunks(replayed)).toContain('echo:survives shutdown');
+ await manager2.closeThread(threadId);
+ }, 45_000);
+});
+
+describe('handleFsWrite exclusion gate', () => {
+ test('non-markdown writes into ignored namespaces are rejected; plain asset writes land', async () => {
+ const contentDir = tmp();
+ const localDir = tmp();
+ const manager = makeManager(contentDir, localDir, {
+ isIgnoredPath: (rel) => rel.startsWith('.ok/') || rel.startsWith('.git/'),
+ });
+ const m = manager as unknown as {
+ handleFsWrite: (record: unknown, path: string, content: string) => Promise<void>;
+ };
+ const record = { info: { lastActivityAt: 0 } };
+
+ await expect(
+ m.handleFsWrite(record, join(contentDir, '.ok', 'local', 'acp-agents.json'), '[]'),
+ ).rejects.toThrow(/excluded from the project content scope/);
+ await expect(
+ m.handleFsWrite(record, join(contentDir, '.git', 'hooks', 'pre-commit'), '#!/bin/sh'),
+ ).rejects.toThrow(/excluded from the project content scope/);
+
+ // A non-markdown write OUTSIDE the ignored namespaces still lands on disk.
+ await m.handleFsWrite(record, join(contentDir, 'assets', 'note.txt'), 'hi');
+ expect(readFileSync(join(contentDir, 'assets', 'note.txt'), 'utf8')).toBe('hi');
+ });
+});
+
+/**
+ * Shared scaffolding for scripted agents that issue their OWN client
+ * requests (terminal/*, fs/*, session/request_permission) and await the
+ * responses — the half of the wire the reply-only fakes above never
+ * exercise. `promptBody` runs per `session/prompt` with `request`,
+ * `notify`, and `finish` in scope.
+ */
+function writeRequestingAgentEntry(localDir: string, id: string, promptBody: string): void {
+ const agentPath = join(localDir, `${id}.mjs`);
+ writeFileSync(
+ agentPath,
+ `
+const write = (msg) => process.stdout.write(JSON.stringify(msg) + '\\n');
+let nextId = 1000;
+const pending = new Map();
+const request = (method, params) =>
+ new Promise((resolve, reject) => {
+ const id = nextId++;
+ pending.set(id, { resolve, reject });
+ write({ jsonrpc: '2.0', id, method, params: { sessionId: 'sess-1', ...params } });
+ });
+const notify = (update) =>
+ write({ jsonrpc: '2.0', method: 'session/update', params: { sessionId: 'sess-1', update } });
+let clientCaps = {};
+async function handlePrompt(msg) {
+ const finish = () => write({ jsonrpc: '2.0', id: msg.id, result: { stopReason: 'end_turn' } });
+${promptBody}
+}
+let buffer = '';
+process.stdin.setEncoding('utf8');
+process.stdin.on('data', (chunk) => {
+ buffer += chunk;
+ let idx = buffer.indexOf('\\n');
+ while (idx !== -1) {
+ const line = buffer.slice(0, idx);
+ buffer = buffer.slice(idx + 1);
+ idx = buffer.indexOf('\\n');
+ if (line.trim() === '') continue;
+ const msg = JSON.parse(line);
+ if (msg.method === undefined && msg.id !== undefined && pending.has(msg.id)) {
+ const p = pending.get(msg.id);
+ pending.delete(msg.id);
+ if (msg.error) p.reject(new Error(msg.error.message));
+ else p.resolve(msg.result);
+ continue;
+ }
+ const reply = (result) => write({ jsonrpc: '2.0', id: msg.id, result });
+ if (msg.method === 'initialize') {
+ clientCaps = (msg.params && msg.params.clientCapabilities) || {};
+ reply({ protocolVersion: 1, agentCapabilities: {} });
+ } else if (msg.method === 'session/new') {
+ reply({ sessionId: 'sess-1' });
+ } else if (msg.method === 'session/prompt') {
+ handlePrompt(msg).catch((err) => {
+ notify({
+ sessionUpdate: 'agent_message_chunk',
+ content: { type: 'text', text: 'agent-error:' + err.message },
+ });
+ write({ jsonrpc: '2.0', id: msg.id, result: { stopReason: 'end_turn' } });
+ });
+ } else if (msg.id !== undefined) {
+ reply({});
+ }
+ }
+});
+`,
+ );
+ writeFileSync(
+ join(localDir, 'acp-agents.json'),
+ JSON.stringify([{ id, name: `Fake ${id}`, command: 'node', args: [agentPath] }]),
+ );
+}
+
+describe('AcpThreadManager terminals + permission effects', () => {
+ type Collected = Array<{ seq: number; event: ThreadEvent }>;
+ const collect = (into: Collected) => (frame: ThreadServerFrame) => {
+ if (frame.op === 'event') into.push({ seq: frame.seq, event: frame.event });
+ if (frame.op === 'events') {
+ for (const [i, event] of frame.events.entries()) {
+ into.push({ seq: frame.fromSeq + i, event });
+ }
+ }
+ };
+ const agentText = (events: Collected): string =>
+ events
+ .map((e) => e.event)
+ .filter((e) => e.kind === 'session_update')
+ .map((e) => {
+ const update = (e as { update?: { sessionUpdate?: string; content?: { text?: string } } })
+ .update;
+ return update?.sessionUpdate === 'agent_message_chunk' ? (update.content?.text ?? '') : '';
+ })
+ .join('');
+
+ test('terminal round-trip: agent runs a command through OK and reads its output back', async () => {
+ const contentDir = tmp();
+ const localDir = tmp();
+ writeRequestingAgentEntry(
+ localDir,
+ 'terminal-agent',
+ `
+ notify({
+ sessionUpdate: 'agent_message_chunk',
+ content: {
+ type: 'text',
+ text:
+ 'terminal-cap:' + String(clientCaps.terminal === true) +
+ ';boolean-config-cap:' +
+ String(clientCaps.session?.configOptions?.boolean != null) +
+ ';',
+ },
+ });
+ const { terminalId } = await request('terminal/create', {
+ command: process.execPath,
+ args: ['-e', "process.stdout.write('terminal says hi')"],
+ });
+ notify({
+ sessionUpdate: 'tool_call',
+ toolCallId: 'tc1',
+ title: 'Run greeting',
+ kind: 'execute',
+ status: 'in_progress',
+ content: [{ type: 'terminal', terminalId }],
+ });
+ const exit = await request('terminal/wait_for_exit', { terminalId });
+ const out = await request('terminal/output', { terminalId });
+ await request('terminal/release', { terminalId });
+ notify({ sessionUpdate: 'tool_call_update', toolCallId: 'tc1', status: 'completed' });
+ notify({
+ sessionUpdate: 'agent_message_chunk',
+ content: { type: 'text', text: 'observed:' + out.output + ';exit=' + String(exit.exitCode) },
+ });
+ finish();
+`,
+ );
+ const manager = makeManager(contentDir, localDir);
+ const info = await manager.createThread({ agent: { source: 'custom', id: 'terminal-agent' } });
+ const events: Collected = [];
+ await manager.subscribe(info.threadId, 0, collect(events));
+ await waitUntil(() => manager.getInfo(info.threadId)?.status === 'ready', 15_000, 'ready');
+
+ manager.sendPrompt(info.threadId, 'run the greeting');
+ await waitUntil(
+ () => events.some((e) => e.event.kind === 'turn_ended'),
+ 20_000,
+ `turn end; got ${JSON.stringify(events.map((e) => e.event.kind))}`,
+ );
+
+ // The client capability was advertised and the agent saw OK's terminal
+ // execute the command: its own message carries the output + exit code.
+ const text = agentText(events);
+ expect(text).toContain('terminal-cap:true;');
+ expect(text).toContain('boolean-config-cap:true;');
+ expect(text).toContain('observed:terminal says hi;exit=0');
+
+ // The transcript carries the terminal lifecycle for the UI to render.
+ const created = events.find((e) => e.event.kind === 'terminal_created')?.event;
+ if (created?.kind !== 'terminal_created') throw new Error('no terminal_created event');
+ // The agent script runs under node, so the command it passed is node's
+ // execPath — not the bun binary this test runs under.
+ expect(created.command).toContain('node');
+ const chunks = events
+ .map((e) => e.event)
+ .filter(
+ (e): e is Extract<ThreadEvent, { kind: 'terminal_output' }> => e.kind === 'terminal_output',
+ );
+ expect(chunks.map((c) => c.chunk).join('')).toContain('terminal says hi');
+ const exited = events.find((e) => e.event.kind === 'terminal_exit')?.event;
+ if (exited?.kind !== 'terminal_exit') throw new Error('no terminal_exit event');
+ expect(exited.exitCode).toBe(0);
+
+ await manager.closeThread(info.threadId);
+ }, 45_000);
+
+ /** Scripted permission agent: asks to write, writes ONLY on approval. */
+ function writePlantingAgentEntry(localDir: string): void {
+ writeRequestingAgentEntry(
+ localDir,
+ 'planting-agent',
+ `
+ const response = await request('session/request_permission', {
+ toolCall: { toolCallId: 'w1', title: 'Write planted.txt', kind: 'edit' },
+ options: [{ optionId: 'allow', name: 'Allow', kind: 'allow_once' }],
+ });
+ const outcome = response.outcome;
+ if (outcome.outcome === 'selected' && outcome.optionId === 'allow') {
+ const { join } = await import('node:path');
+ await request('fs/write_text_file', {
+ path: join(process.cwd(), 'planted.txt'),
+ content: 'planted by approval',
+ });
+ notify({ sessionUpdate: 'agent_message_chunk', content: { type: 'text', text: 'outcome:allowed' } });
+ } else {
+ notify({ sessionUpdate: 'agent_message_chunk', content: { type: 'text', text: 'outcome:' + outcome.outcome } });
+ }
+ finish();
+`,
+ );
+ }
+
+ test('approve → the planted file EXISTS; status parks on awaiting_permission meanwhile', async () => {
+ const contentDir = tmp();
+ const localDir = tmp();
+ writePlantingAgentEntry(localDir);
+ const manager = makeManager(contentDir, localDir);
+ const info = await manager.createThread({ agent: { source: 'custom', id: 'planting-agent' } });
+ const events: Collected = [];
+ await manager.subscribe(info.threadId, 0, collect(events));
+ await waitUntil(() => manager.getInfo(info.threadId)?.status === 'ready', 15_000, 'ready');
+
+ manager.sendPrompt(info.threadId, 'plant the file');
+ await waitUntil(
+ () => events.some((e) => e.event.kind === 'permission_request'),
+ 20_000,
+ 'permission request',
+ );
+ // The parked turn is a first-class status, not a generic "running".
+ await waitUntil(
+ () => manager.getInfo(info.threadId)?.status === 'awaiting_permission',
+ 5_000,
+ 'awaiting_permission status',
+ );
+ expect(existsSync(join(contentDir, 'planted.txt'))).toBe(false);
+
+ const request = events.find((e) => e.event.kind === 'permission_request')?.event;
+ if (request?.kind !== 'permission_request') throw new Error('unreachable');
+ manager.respondPermission(info.threadId, request.requestId, {
+ kind: 'selected',
+ optionId: 'allow',
+ });
+
+ await waitUntil(() => events.some((e) => e.event.kind === 'turn_ended'), 20_000, 'turn end');
+ // Effect oracle: approval produced the real artifact.
+ await waitUntil(() => existsSync(join(contentDir, 'planted.txt')), 5_000, 'planted file');
+ expect(readFileSync(join(contentDir, 'planted.txt'), 'utf8')).toBe('planted by approval');
+ expect(agentText(events)).toContain('outcome:allowed');
+ await waitUntil(() => manager.getInfo(info.threadId)?.status === 'ready', 5_000, 'ready again');
+
+ await manager.closeThread(info.threadId);
+ }, 45_000);
+
+ test('deny (cancelled outcome) → the planted file is ABSENT and the turn still completes', async () => {
+ const contentDir = tmp();
+ const localDir = tmp();
+ writePlantingAgentEntry(localDir);
+ const manager = makeManager(contentDir, localDir);
+ const info = await manager.createThread({ agent: { source: 'custom', id: 'planting-agent' } });
+ const events: Collected = [];
+ await manager.subscribe(info.threadId, 0, collect(events));
+ await waitUntil(() => manager.getInfo(info.threadId)?.status === 'ready', 15_000, 'ready');
+
+ manager.sendPrompt(info.threadId, 'plant the file');
+ await waitUntil(
+ () => events.some((e) => e.event.kind === 'permission_request'),
+ 20_000,
+ 'permission request',
+ );
+ await waitUntil(
+ () => manager.getInfo(info.threadId)?.status === 'awaiting_permission',
+ 5_000,
+ 'awaiting_permission status',
+ );
+
+ const request = events.find((e) => e.event.kind === 'permission_request')?.event;
+ if (request?.kind !== 'permission_request') throw new Error('unreachable');
+ manager.respondPermission(info.threadId, request.requestId, { kind: 'cancelled' });
+
+ await waitUntil(() => events.some((e) => e.event.kind === 'turn_ended'), 20_000, 'turn end');
+ // Effect oracle: absence is the asserted outcome, not just wire traffic.
+ expect(existsSync(join(contentDir, 'planted.txt'))).toBe(false);
+ expect(agentText(events)).toContain('outcome:cancelled');
+ const resolution = events.find((e) => e.event.kind === 'permission_resolved')?.event;
+ if (resolution?.kind !== 'permission_resolved') throw new Error('unreachable');
+ expect(resolution.optionId).toBeNull();
+ expect(resolution.auto).toBe(false);
+ await waitUntil(() => manager.getInfo(info.threadId)?.status === 'ready', 5_000, 'ready again');
+
+ await manager.closeThread(info.threadId);
+ }, 45_000);
+});
diff --git a/packages/server/src/acp/thread-manager.ts b/packages/server/src/acp/thread-manager.ts
new file mode 100644
index 000000000..4e6d0904a
--- /dev/null
+++ b/packages/server/src/acp/thread-manager.ts
@@ -0,0 +1,2043 @@
+/**
+ * Server-hosted ACP threads — one spawned agent subprocess per thread,
+ * bridged to browser/Electron clients over the `/collab/thread` WS.
+ *
+ * Responsibilities:
+ * - Own the agent process lifecycle (spawn → initialize → session/new →
+ * prompt turns → kill on close/shutdown/idle-reap).
+ * - Implement the client side of ACP: session/update fan-out,
+ * permission requests (policy-gated via `AcpPermissionStore`), and the
+ * `fs/*` services — the attribution path that routes agent edits of
+ * in-scope markdown through the CRDT write spine instead of raw disk.
+ * - Retain a bounded per-thread event log so a reconnecting client can
+ * replay from its last-seen seq (the WS-replay analog of the
+ * "durable truth + live push" recovery contract).
+ *
+ * Write attribution: markdown writes reuse `AgentSessionManager` sessions
+ * keyed by a per-thread `acp-<uuid>` agent id, so every edit lands under a
+ * per-session frozen paired-write origin (precedent #24) and books to the
+ * `agent-*` writer namespace (precedent #25) — write-flash, activity panel,
+ * and per-session undo all work exactly as MCP agent writes do.
+ */
+
+import type { ChildProcess } from 'node:child_process';
+import { readFile, realpath } from 'node:fs/promises';
+import { dirname, isAbsolute, join, normalize, relative, resolve, sep } from 'node:path';
+import { Readable, Writable } from 'node:stream';
+import {
+ client as acpClient,
+ methods as acpMethods,
+ type ClientConnection,
+ type InitializeResponse,
+ type McpServer,
+ ndJsonStream,
+ type PermissionOption,
+ PROTOCOL_VERSION,
+ type RequestPermissionResponse,
+ type SessionNotification,
+ type SessionUpdate,
+ type SetSessionConfigOptionRequest,
+ type SetSessionConfigOptionResponse,
+ type ToolCallUpdate,
+} from '@agentclientprotocol/sdk';
+import {
+ AGENT_ICON_COLORS,
+ AGENT_THREAD_SENTINEL_DOC,
+ changedBlockRange,
+ colorFromSeed,
+ type EditorId,
+ iconFromClientName,
+} from '@inkeep/open-knowledge-core';
+import type {
+ ThreadAgentInfo,
+ ThreadEvent,
+ ThreadInfo,
+ ThreadServerFrame,
+ ThreadStatus,
+} from '@inkeep/open-knowledge-core/acp/thread-protocol';
+import { toBroadcasterKey } from '../agent-id.ts';
+import type { AgentPresenceBroadcaster } from '../agent-presence.ts';
+import {
+ type AgentSessionManager,
+ applyAgentMarkdownWrite,
+ snapshotBlocks,
+} from '../agent-sessions.ts';
+import { isConfigDoc, isSystemDoc } from '../cc1-broadcast.ts';
+import type { PinoLogger } from '../logger.ts';
+import { boundSessionUpdateForLog, coalesceChunkInto } from './event-log-bounds.ts';
+import {
+ AgentLaunchError,
+ preflightLaunch,
+ type ResolvedLaunch,
+ resolveCustomLaunch,
+ resolveRegistryLaunch,
+ rewriteLaunchToManagedRuntime,
+ spawnAcpAgent,
+ terminateAgentTree,
+} from './launch.ts';
+import {
+ describeRuntime,
+ ensureManagedRuntime,
+ findManagedRuntime,
+ type ManagedRuntime,
+ type ManagedRuntimeKind,
+ readRuntimeConsent,
+ runtimeDownloadSupported,
+ runtimeForInterpreter,
+ writeRuntimeConsent,
+} from './managed-runtime.ts';
+import type { AcpPermissionStore } from './permissions.ts';
+import {
+ ACP_AGENT_EDITOR_IDS,
+ type AcpRegistry,
+ type CustomAgentEntry,
+ loadCustomAgents,
+ registryPlatformKey,
+} from './registry.ts';
+import { AcpTerminalSet } from './terminals.ts';
+import { type PersistedThreadMeta, ThreadPersistenceStore } from './thread-persistence.ts';
+import { clampThreadTitle, deriveThreadTitle } from './thread-title.ts';
+
+export const MAX_ACP_THREADS = 8;
+const EVENT_LOG_LIMIT = 5_000;
+const DEFAULT_IDLE_REAP_MS = 60 * 60 * 1000;
+const REAP_SWEEP_MS = 5 * 60 * 1000;
+const PERMISSION_TIMEOUT_MS = 10 * 60 * 1000;
+/** How long a launch parks waiting for the user to allow/refuse a runtime download. */
+const RUNTIME_CONSENT_TIMEOUT_MS = 5 * 60 * 1000;
+/** Trailing throttle for runtime-install progress events (bounds the retained log). */
+const RUNTIME_PROGRESS_THROTTLE_MS = 400;
+const KILL_GRACE_MS = 5_000;
+/** TERM→KILL grace during destroy(): TERM + grace + KILL + force-wait must fit boot's 5s destroy-step budget. */
+const DESTROY_KILL_GRACE_MS = 2_000;
+/**
+ * Trailing-edge coalescing window for live event broadcast. Streaming turns
+ * emit one session_update per chunk; sending each as its own WS frame made
+ * the client pay a parse + store update + render per chunk. ~40 fps is
+ * imperceptible for a transcript and collapses a chunk burst into one frame.
+ */
+const EVENT_FLUSH_MS = 25;
+/** Events per `events` frame during subscribe replay (bounds frame size). */
+const REPLAY_CHUNK_SIZE = 512;
+/**
+ * Token-spend backstop for turns running with zero subscribers (window
+ * closed mid-turn, tab crash): the agent keeps generating on the customer's
+ * account with nobody watching, and the idle reaper can never collect it —
+ * reaping requires an idle turn, and a streaming turn refreshes
+ * lastActivityAt on every update. Cancel politely first; force-close if the
+ * agent ignores it. Timing is approximate (checked on the reap sweep).
+ */
+const DEFAULT_UNWATCHED_TURN_CANCEL_MS = 10 * 60 * 1000;
+const DEFAULT_UNWATCHED_TURN_KILL_MS = 20 * 60 * 1000;
+const STDERR_TAIL_LINES = 40;
+/**
+ * `session/load` replays history BEFORE its response resolves per protocol,
+ * but at least one adapter (Gemini) fires the replay as a floating promise
+ * that can straggle past the response. Before opening the first post-resume
+ * turn, wait for a short gap with no replayed updates (bounded so a silent
+ * agent can't stall the resume).
+ */
+const RESUME_REPLAY_QUIESCENCE_MS = 300;
+const RESUME_REPLAY_MAX_WAIT_MS = 3_000;
+
+export class ThreadOpError extends Error {
+ readonly code:
+ | 'unknown-thread'
+ | 'unknown-agent'
+ | 'capacity'
+ | 'spawn-failed'
+ | 'install-failed'
+ | 'not-ready'
+ | 'resume-unsupported';
+ constructor(code: ThreadOpError['code'], message: string) {
+ super(message);
+ this.name = 'ThreadOpError';
+ this.code = code;
+ }
+}
+
+type Subscriber = (frame: ThreadServerFrame) => void;
+
+interface ThreadRecord {
+ info: ThreadInfo;
+ /** Extension-less doc the thread was launched from (context only). */
+ docName?: string;
+ /** Agent reference used to launch — and re-launch on resume. */
+ agentRef: { source: 'registry' | 'custom'; id: string };
+ /** Session cwd — agents key their session stores by it; resume passes it back verbatim. */
+ cwd: string;
+ child: ChildProcess | null;
+ conn: ClientConnection | null;
+ sessionId: string | null;
+ /** Writer id for CRDT attribution — `acp-<uuid>`, AGENT_ID_RE-safe. */
+ agentSessionId: string;
+ events: ThreadEvent[];
+ /** seq of events[0]; grows as the log trims. */
+ baseSeq: number;
+ /** Rehydrated records defer counting disk lines until first subscribe/resume. */
+ logResolved: boolean;
+ logResolution: Promise<void> | null;
+ /** The persisted log ends inside a turn (crash mid-stream) — resume appends a synthetic `turn_ended`. */
+ midTurnOnDisk: boolean;
+ resumeInFlight: boolean;
+ /** Drop incoming `session_update`s (a `session/load` replay duplicating the retained log). */
+ suppressUpdates: boolean;
+ lastSuppressedAt: number;
+ subscribers: Set<Subscriber>;
+ pendingPermissions: Map<
+ string,
+ { resolve: (response: RequestPermissionResponse) => void; timer: ReturnType<typeof setTimeout> }
+ >;
+ /** In-flight runtime-download consent prompts blocking this thread's launch. */
+ pendingRuntimeConsent: Map<
+ string,
+ {
+ runtime: ManagedRuntimeKind;
+ resolve: (decision: 'granted' | 'declined' | 'timeout' | 'closed') => void;
+ timer: ReturnType<typeof setTimeout>;
+ }
+ >;
+ stderrTail: string[];
+ /** ACP terminals this thread's agent asked OK to run; per-spawn, killed with the thread. */
+ terminals: AcpTerminalSet | null;
+ turnActive: boolean;
+ /** A user cancel is in flight for the current turn — a prompt-request
+ * rejection then reads as "cancelled", not an agent error (agents SHOULD
+ * resolve with stopReason 'cancelled', but some abort the request). */
+ cancelRequested: boolean;
+ /** Since when the thread has had zero subscribers; null while watched. */
+ unwatchedSince: number | null;
+ /** The unwatched-turn backstop already sent its cancel for this stretch. */
+ unwatchedCancelSent: boolean;
+ /** Appended-but-unbroadcast events awaiting the coalescing flush. */
+ pendingBroadcast: ThreadEvent[];
+ /** seq of pendingBroadcast[0]. */
+ pendingBroadcastFromSeq: number;
+ flushTimer: ReturnType<typeof setTimeout> | null;
+ closed: boolean;
+ /**
+ * A user message has been recorded at some point in this thread's life
+ * (this session or, for a rehydrated thread, on disk). Closing a thread that
+ * never received one discards it entirely instead of archiving — a spawned
+ * agent the user never talked to shouldn't clutter conversation history.
+ */
+ hadUserMessage: boolean;
+ /**
+ * The user's raw typed text (create brief / instruction), carried on the
+ * launch so the first-prompt title derives from it instead of the composed
+ * prompt's fixed handoff preamble. Consumed and cleared on the first title
+ * adoption in {@link AcpThreadManager.echoUserMessage}; absent (bare launch)
+ * falls back to the prompt content.
+ */
+ titleHint?: string;
+}
+
+/** A `probeHarnessManagedMcpEntry` hit — where OK's own managed entry was found. */
+export interface HarnessManagedMcpEntryHit {
+ editorId: EditorId;
+ scope: 'project' | 'user';
+ configPath: string;
+}
+
+export interface AcpThreadManagerOptions {
+ contentDir: string;
+ /** `<projectDir>/.ok/local` — custom agents, permission grants, registry cache. */
+ localDir: string;
+ registry: AcpRegistry;
+ permissions: AcpPermissionStore;
+ sessionManager: AgentSessionManager;
+ agentPresenceBroadcaster?: AgentPresenceBroadcaster | null;
+ /** Wiki-embed resolver threaded into markdown writes (same seam the HTTP agent-write handlers use). */
+ resolveEmbed?: (basename: string, sourcePath: string) => string | null;
+ /** Membership test for the content scope (ContentFilter.isExcluded complement). */
+ isExcludedPath: (relPath: string) => boolean;
+ /**
+ * Security-boundary test for NON-markdown fs writes: true when the path is
+ * excluded by ignore rules or the builtin skip dirs (`.ok/`, `.git/`,
+ * `node_modules/`, …) — `ContentFilter.isPathIgnored`, which skips the
+ * sibling-asset admission heuristic so legitimate asset writes into
+ * markdown-less directories still land. Without this gate the plain-disk
+ * branch of the fs-write proxy would happily write into `.ok/local/` (custom
+ * agent definitions → arbitrary command execution) or `.git/hooks/`.
+ */
+ isIgnoredPath: (relPosix: string) => boolean;
+ /**
+ * Live `Y.Text('source')` bytes for a currently-loaded doc, or null when the
+ * doc isn't loaded. Lets `fs/read_text_file` serve unsaved editor state for
+ * open docs without opening (and leaking) a tracked agent session — closed
+ * docs fall back to the persisted disk bytes, which equal the CRDT bytes when
+ * quiescent.
+ */
+ getLoadedDocText?: (docName: string) => string | null;
+ /** Origin the auto-forwarded MCP server is reachable at (post-listen). */
+ getServerUrl?: () => string;
+ /**
+ * Build the stdio `ok mcp` command handed to agents that DON'T advertise
+ * HTTP-MCP support, so OK tools still reach them. Returns null when the host
+ * can't resolve a CLI entrypoint (the HTTP path is preferred when available).
+ */
+ getMcpStdioCommand?: () => { command: string; args: readonly string[] } | null | undefined;
+ /**
+ * Whether the agent's own harness will already load OK's managed MCP entry
+ * from the editor config OK's wiring installs at `cwd` (project scope) or in
+ * the user's home (user scope). On a hit, session setup skips injecting the
+ * `open-knowledge` server — both copies claim the same server name and
+ * harnesses resolve that collision in their own favor, so injecting a
+ * duplicate only creates a same-name fight the injected copy loses. Absent
+ * seam / miss / throw all fall back to injecting (prior behavior). Wired by
+ * `bootServer()` callers to the CLI's `probeOwnManagedEditorMcpEntry`; the
+ * Vite dev server leaves it unwired (dev-shape entries never exact-match).
+ */
+ probeHarnessManagedMcpEntry?: (
+ editorId: EditorId,
+ cwd: string,
+ ) => HarnessManagedMcpEntryHit | null | Promise<HarnessManagedMcpEntryHit | null>;
+ /**
+ * Test seam for the managed-runtime download path — override the install
+ * cache root, the download `fetch`, and the consent-store home so a test can
+ * drive the consent/download flow without touching the real `~/.ok` or the
+ * network. Unset in production (defaults resolve to `~/.ok/runtimes` +
+ * global `fetch` + `~/.ok`).
+ */
+ runtimeInstall?: {
+ root?: string;
+ fetchImpl?: typeof fetch;
+ consentHome?: string;
+ };
+ log: PinoLogger;
+ maxThreads?: number;
+ idleReapMs?: number;
+ /** Unwatched-mid-turn backstop: politely cancel after this long with zero subscribers. */
+ unwatchedTurnCancelMs?: number;
+ /** …and force-close the thread if the turn is STILL running after this long. */
+ unwatchedTurnKillMs?: number;
+}
+
+/**
+ * Build the stdio command that launches the OK MCP shim (`ok mcp --port <n>`)
+ * pinned to this server's HTTP MCP endpoint. `localOpCliArgs` is how the host
+ * invokes the OK CLI in its runtime (`[execPath, entry]` under `ok start` / the
+ * packaged app); it degrades to a bare `open-knowledge` on PATH when the host
+ * can't resolve one (e.g. the Vite dev server).
+ */
+export function buildOkMcpStdioCommand(
+ localOpCliArgs: readonly string[] | undefined,
+ port: number,
+): { command: string; args: string[] } {
+ const argv = localOpCliArgs && localOpCliArgs.length > 0 ? localOpCliArgs : ['open-knowledge'];
+ const [command = 'open-knowledge', ...rest] = argv;
+ return { command, args: [...rest, 'mcp', '--port', String(port)] };
+}
+
+export class AcpThreadManager {
+ private readonly opts: AcpThreadManagerOptions;
+ private readonly threads = new Map<string, ThreadRecord>();
+ private readonly reapTimer: ReturnType<typeof setInterval>;
+ private readonly maxThreads: number;
+ private readonly idleReapMs: number;
+ private readonly unwatchedTurnCancelMs: number;
+ private readonly unwatchedTurnKillMs: number;
+ private readonly persistence: ThreadPersistenceStore;
+ private destroyed = false;
+ private initialized = false;
+
+ constructor(opts: AcpThreadManagerOptions) {
+ this.opts = opts;
+ this.maxThreads = opts.maxThreads ?? MAX_ACP_THREADS;
+ this.idleReapMs = opts.idleReapMs ?? DEFAULT_IDLE_REAP_MS;
+ this.unwatchedTurnCancelMs = opts.unwatchedTurnCancelMs ?? DEFAULT_UNWATCHED_TURN_CANCEL_MS;
+ this.unwatchedTurnKillMs = opts.unwatchedTurnKillMs ?? DEFAULT_UNWATCHED_TURN_KILL_MS;
+ this.persistence = new ThreadPersistenceStore(opts.localDir, opts.log);
+ this.reapTimer = setInterval(() => this.reapIdleThreads(), REAP_SWEEP_MS);
+ this.reapTimer.unref?.();
+ }
+
+ /**
+ * Rehydrate archived threads from `.ok/local/threads/` — metadata only;
+ * each thread's event log loads lazily on its first subscribe/resume, so
+ * boot cost stays O(#threads) small-file reads. Await before serving the
+ * `/collab/thread` socket so `list` never races the scan.
+ */
+ async init(): Promise<void> {
+ if (this.initialized) return;
+ this.initialized = true;
+ await this.persistence.init();
+ const metas = await this.persistence.scan();
+ for (const meta of metas) {
+ const threadId = meta.info.threadId;
+ if (this.threads.has(threadId)) continue;
+ this.threads.set(threadId, rehydratedRecord(meta));
+ }
+ if (metas.length > 0) {
+ this.opts.log.info({ count: metas.length }, '[acp-threads] rehydrated archived threads');
+ }
+ }
+
+ listThreads(): ThreadInfo[] {
+ return [...this.threads.values()].map((t) => ({ ...t.info }));
+ }
+
+ private liveThreadCount(): number {
+ let count = 0;
+ for (const t of this.threads.values()) {
+ if (t.info.archived !== true) count += 1;
+ }
+ return count;
+ }
+
+ getInfo(threadId: string): ThreadInfo | undefined {
+ const t = this.threads.get(threadId);
+ return t === undefined ? undefined : { ...t.info };
+ }
+
+ async subscribe(threadId: string, sinceSeq: number, sink: Subscriber): Promise<ThreadInfo> {
+ const t = this.mustGet(threadId);
+ await this.ensureLogResolved(t);
+ const from = Math.max(sinceSeq, 0);
+ // Seqs below the in-memory window (an archived/rehydrated thread, or a
+ // live log that trimmed past 5k events) replay from disk first. Looped:
+ // `baseSeq` only ever grows, and a concurrent archive during the async
+ // read moves the memory window onto disk — without the re-check those
+ // events would fall between the disk pass and the memory pass.
+ let diskCursor = from;
+ while (diskCursor < t.baseSeq) {
+ const target = t.baseSeq;
+ await this.persistence.whenIdle(threadId);
+ await this.persistence.readEvents(threadId, diskCursor, target, (chunkFrom, events) => {
+ sink({ op: 'events', threadId, fromSeq: chunkFrom, events });
+ });
+ diskCursor = target;
+ }
+ // Flush the coalescing buffer, then replay the memory window and attach —
+ // all synchronous, so nothing lands between the replay and the live feed.
+ // Events appended DURING the disk pass are covered here (bounds are
+ // recomputed after the awaits).
+ this.flushBroadcast(t);
+ const memFrom = Math.max(from, t.baseSeq);
+ const end = t.baseSeq + t.events.length;
+ for (let chunkStart = memFrom; chunkStart < end; chunkStart += REPLAY_CHUNK_SIZE) {
+ const chunkEnd = Math.min(chunkStart + REPLAY_CHUNK_SIZE, end);
+ sink({
+ op: 'events',
+ threadId,
+ fromSeq: chunkStart,
+ events: t.events.slice(chunkStart - t.baseSeq, chunkEnd - t.baseSeq),
+ });
+ }
+ t.subscribers.add(sink);
+ t.unwatchedSince = null;
+ t.unwatchedCancelSent = false;
+ return { ...t.info };
+ }
+
+ /**
+ * Resolve the on-disk log's line count (== next seq) once per rehydrated
+ * record — the persisted meta's `lastSeq` can be stale after a crash (meta
+ * rewrites only on info changes, not per event). Memoized; live records are
+ * born resolved.
+ */
+ private ensureLogResolved(t: ThreadRecord): Promise<void> {
+ if (t.logResolved) return Promise.resolve();
+ t.logResolution ??= (async () => {
+ const resolved = await this.persistence.resolveEventLog(t.info.threadId);
+ t.baseSeq = resolved.count;
+ t.midTurnOnDisk = resolved.midTurn;
+ t.info.lastSeq = resolved.count - 1;
+ t.logResolved = true;
+ })();
+ return t.logResolution;
+ }
+
+ unsubscribe(threadId: string, sink: Subscriber): void {
+ const t = this.threads.get(threadId);
+ if (t === undefined) return;
+ t.subscribers.delete(sink);
+ if (t.subscribers.size === 0 && t.unwatchedSince === null) {
+ t.unwatchedSince = Date.now();
+ }
+ }
+
+ /**
+ * Create a thread: resolve the agent, spawn it, run the ACP handshake, and
+ * (optionally) send the launch prompt. Resolves as soon as the thread
+ * record exists — handshake progress streams as `status` events so the UI
+ * can render the spawning/installing states live.
+ */
+ async createThread(params: {
+ agent: { source: 'registry' | 'custom'; id: string };
+ prompt?: string;
+ docName?: string;
+ titleHint?: string;
+ }): Promise<ThreadInfo> {
+ if (this.destroyed) throw new ThreadOpError('capacity', 'server is shutting down');
+ if (this.liveThreadCount() >= this.maxThreads) {
+ throw new ThreadOpError('capacity', `maximum of ${this.maxThreads} concurrent agent threads`);
+ }
+
+ const { info: agentInfo, custom } = await this.resolveAgentInfo(params.agent);
+ // Re-check both gates after the await: resolveAgentInfo does file/registry
+ // I/O and the socket dispatches frames as independent async tasks, so a
+ // burst of creates can all pass the pre-await guard on the same count.
+ // No await sits between this check and the insert below, so it's atomic.
+ if (this.destroyed) throw new ThreadOpError('capacity', 'server is shutting down');
+ if (this.liveThreadCount() >= this.maxThreads) {
+ throw new ThreadOpError('capacity', `maximum of ${this.maxThreads} concurrent agent threads`);
+ }
+ const threadId = crypto.randomUUID();
+ const now = Date.now();
+ const record: ThreadRecord = {
+ info: {
+ threadId,
+ agent: agentInfo,
+ title: agentInfo.name,
+ status: 'installing',
+ createdAt: now,
+ lastActivityAt: now,
+ modes: null,
+ configOptions: null,
+ lastSeq: -1,
+ archived: false,
+ },
+ docName: params.docName,
+ agentRef: { source: params.agent.source, id: params.agent.id },
+ cwd: this.opts.contentDir,
+ child: null,
+ conn: null,
+ sessionId: null,
+ agentSessionId: `acp-${threadId}`,
+ events: [],
+ baseSeq: 0,
+ logResolved: true,
+ logResolution: null,
+ midTurnOnDisk: false,
+ resumeInFlight: false,
+ suppressUpdates: false,
+ lastSuppressedAt: 0,
+ subscribers: new Set(),
+ pendingPermissions: new Map(),
+ pendingRuntimeConsent: new Map(),
+ stderrTail: [],
+ terminals: null,
+ turnActive: false,
+ cancelRequested: false,
+ // Born unwatched — the creating socket subscribes right after `created`.
+ unwatchedSince: now,
+ unwatchedCancelSent: false,
+ pendingBroadcast: [],
+ pendingBroadcastFromSeq: 0,
+ flushTimer: null,
+ closed: false,
+ hadUserMessage: false,
+ titleHint: params.titleHint,
+ };
+ this.threads.set(threadId, record);
+ this.emitStatus(record, 'installing');
+
+ // Handshake runs async — errors land as status events, not throws.
+ void this.startThread(record, params, custom).catch((err) => {
+ this.opts.log.error({ err, threadId }, '[acp-threads] thread start failed');
+ this.emitStatus(record, 'error', err instanceof Error ? err.message : String(err));
+ });
+
+ return { ...record.info };
+ }
+
+ private async resolveAgentInfo(agent: {
+ source: 'registry' | 'custom';
+ id: string;
+ }): Promise<{ info: ThreadAgentInfo; custom: CustomAgentEntry | null }> {
+ if (agent.source === 'custom') {
+ const custom = (await loadCustomAgents(this.opts.localDir, this.opts.log)).find(
+ (c) => c.id === agent.id,
+ );
+ if (custom === undefined) {
+ throw new ThreadOpError('unknown-agent', `no custom agent '${agent.id}'`);
+ }
+ return { info: { id: custom.id, name: custom.name, source: 'custom' }, custom };
+ }
+ let manifest: Awaited<ReturnType<AcpRegistry['getAgent']>>;
+ try {
+ manifest = await this.opts.registry.getAgent(agent.id);
+ } catch (err) {
+ // A registry failure (network outage, cache parse error) is NOT
+ // "unknown agent" — that would misdirect the user toward a
+ // nonexistent-agent explanation when the real problem is transient.
+ throw new ThreadOpError(
+ 'install-failed',
+ `agent registry unavailable: ${err instanceof Error ? err.message : String(err)}`,
+ );
+ }
+ if (manifest === undefined) {
+ throw new ThreadOpError('unknown-agent', `agent '${agent.id}' is not in the registry`);
+ }
+ return {
+ info: { id: manifest.id, name: manifest.name, iconUrl: manifest.icon, source: 'registry' },
+ custom: null,
+ };
+ }
+
+ /**
+ * Resolve the launch, spawn the agent, wire its process/connection
+ * handlers, and run `initialize` — the half of the handshake shared by
+ * first start and resume. Returns null when the record closed mid-flight.
+ * Throws (AgentLaunchError / ThreadOpError) on failure; callers map to
+ * status events (create) or a rejected op (resume).
+ */
+ private async connectAgent(
+ record: ThreadRecord,
+ custom: CustomAgentEntry | null,
+ ): Promise<{ conn: ClientConnection; init: InitializeResponse; launch: ResolvedLaunch } | null> {
+ let launch: ResolvedLaunch;
+ if (custom !== null) {
+ launch = resolveCustomLaunch(custom);
+ } else {
+ const manifest = await this.opts.registry.getAgent(record.agentRef.id);
+ if (manifest === undefined) throw new ThreadOpError('unknown-agent', 'agent vanished');
+ launch = await resolveRegistryLaunch(manifest, registryPlatformKey(), this.opts.log);
+ }
+ if (record.closed) return null;
+
+ // Ensure the launch command exists. If the interpreter (npx/uvx) is
+ // missing, offer to download a managed runtime (consent-gated) and rewrite
+ // the launch to use it; otherwise this throws an actionable install hint
+ // rather than letting the missing command surface as an opaque async
+ // `spawn ENOENT`.
+ const launchable = await this.ensureLaunchable(record, launch);
+ if (launchable === null) return null;
+ launch = launchable;
+ if (record.closed) return null;
+
+ this.emitStatus(record, 'spawning');
+ const child = spawnAcpAgent(launch, record.cwd);
+ record.child = child;
+
+ child.stderr?.setEncoding('utf8');
+ child.stderr?.on('data', (chunk: string) => {
+ for (const line of chunk.split('\n')) {
+ if (line.trim() === '') continue;
+ record.stderrTail.push(line.slice(0, 500));
+ if (record.stderrTail.length > STDERR_TAIL_LINES) record.stderrTail.shift();
+ }
+ });
+ child.on('error', (err) => {
+ this.emitStatus(record, 'error', `agent failed to start: ${err.message}`);
+ });
+ child.on('exit', (code, signal) => {
+ record.child = null;
+ // Commands the agent asked OK to run die with the agent — nothing
+ // should keep executing for a conversation that can no longer see it.
+ record.terminals?.disposeAll().catch((err: unknown) => {
+ this.opts.log.warn(
+ { err, threadId: record.info.threadId },
+ '[acp-threads] terminal cleanup on agent exit failed',
+ );
+ });
+ if (record.closed || record.info.archived === true) return;
+ const tail = record.stderrTail.slice(-10).join('\n');
+ this.emitStatus(
+ record,
+ record.info.status === 'error' ? 'error' : 'exited',
+ `agent exited (${signal ?? code ?? 'unknown'})${tail ? `\n${tail}` : ''}`,
+ );
+ this.failPendingPermissions(record);
+ });
+
+ if (child.stdin === null || child.stdout === null) {
+ throw new ThreadOpError('spawn-failed', 'agent process has no stdio');
+ }
+ const stream = ndJsonStream(
+ Writable.toWeb(child.stdin),
+ Readable.toWeb(child.stdout) as unknown as ReadableStream<Uint8Array>,
+ );
+
+ // Fresh per spawn: a resume respawns the agent, and terminals from the
+ // previous process are dead by construction (disposed on its exit).
+ const terminals = new AcpTerminalSet({
+ defaultCwd: record.cwd,
+ emit: (event) => this.appendEvent(record, event),
+ log: this.opts.log,
+ });
+ record.terminals = terminals;
+
+ const conn = acpClient({ name: 'open-knowledge' })
+ .onRequest(acpMethods.client.session.requestPermission, (ctx) =>
+ this.handlePermissionRequest(record, ctx.params.toolCall, ctx.params.options),
+ )
+ .onRequest(acpMethods.client.fs.readTextFile, (ctx) =>
+ this.handleFsRead(ctx.params.path, ctx.params.line ?? null, ctx.params.limit ?? null),
+ )
+ .onRequest(acpMethods.client.fs.writeTextFile, async (ctx) => {
+ await this.handleFsWrite(record, ctx.params.path, ctx.params.content);
+ return {};
+ })
+ .onRequest(acpMethods.client.terminal.create, (ctx) => {
+ record.info.lastActivityAt = Date.now();
+ return terminals.create(ctx.params);
+ })
+ .onRequest(acpMethods.client.terminal.output, (ctx) =>
+ terminals.output(ctx.params.terminalId),
+ )
+ .onRequest(acpMethods.client.terminal.waitForExit, (ctx) =>
+ terminals.waitForExit(ctx.params.terminalId),
+ )
+ .onRequest(acpMethods.client.terminal.kill, async (ctx) => {
+ await terminals.kill(ctx.params.terminalId);
+ return {};
+ })
+ .onRequest(acpMethods.client.terminal.release, async (ctx) => {
+ await terminals.release(ctx.params.terminalId);
+ return {};
+ })
+ .onNotification(acpMethods.client.session.update, (ctx) =>
+ this.handleSessionUpdate(record, ctx.params),
+ )
+ .connect(stream);
+ record.conn = conn;
+ conn.closed.then(
+ () => {
+ if (
+ !record.closed &&
+ record.info.archived !== true &&
+ record.info.status !== 'exited' &&
+ record.info.status !== 'error'
+ ) {
+ this.emitStatus(record, 'exited', 'agent connection closed');
+ }
+ },
+ (err: unknown) => {
+ // A rejected `closed` (transport-level protocol error rather than a
+ // clean close) must not become an unhandled rejection — subscribers
+ // still need the terminal status event.
+ this.opts.log.warn(
+ { err, threadId: record.info.threadId },
+ '[acp-threads] agent connection closed with error',
+ );
+ if (
+ !record.closed &&
+ record.info.archived !== true &&
+ record.info.status !== 'exited' &&
+ record.info.status !== 'error'
+ ) {
+ this.emitStatus(
+ record,
+ 'error',
+ `agent connection failed: ${err instanceof Error ? err.message : String(err)}`,
+ );
+ }
+ },
+ );
+
+ let init: InitializeResponse;
+ try {
+ init = await conn.agent.request(acpMethods.agent.initialize, {
+ protocolVersion: PROTOCOL_VERSION,
+ clientCapabilities: {
+ fs: { readTextFile: true, writeTextFile: true },
+ terminal: true,
+ session: { configOptions: { boolean: {} } },
+ },
+ });
+ } catch (err) {
+ throw new ThreadOpError('spawn-failed', `initialize failed: ${describeAgentError(err)}`);
+ }
+ if (record.closed) return null;
+ return { conn, init, launch };
+ }
+
+ /**
+ * Preflight the launch; on a missing npx/uvx interpreter, resolve a managed
+ * runtime (already-installed → persisted-consent → interactive consent →
+ * download) and return the rewritten launch. Returns null only when the
+ * thread closed mid-flight; throws an actionable {@link AgentLaunchError} on
+ * decline / unsupported platform / failed install (callers map it to an
+ * error status).
+ */
+ private async ensureLaunchable(
+ record: ThreadRecord,
+ launch: ResolvedLaunch,
+ ): Promise<ResolvedLaunch | null> {
+ try {
+ await preflightLaunch(launch);
+ return launch;
+ } catch (err) {
+ if (!(err instanceof AgentLaunchError) || err.code !== 'command-not-found') throw err;
+ // Only npx/uvx have a managed fallback — a binary/custom command doesn't.
+ if (launch.kind !== 'npx' && launch.kind !== 'uvx') throw err;
+ const runtimeKind = runtimeForInterpreter(launch.kind);
+ // No download target for this platform → keep the original install hint.
+ if (!runtimeDownloadSupported(runtimeKind)) throw err;
+ const runtime = await this.provideManagedRuntime(record, runtimeKind);
+ if (runtime === null) return null; // closed mid-flight
+ const rewritten = rewriteLaunchToManagedRuntime(launch, runtime);
+ // The managed launcher must itself be executable before we spawn it.
+ await preflightLaunch(rewritten);
+ return rewritten;
+ }
+ }
+
+ /**
+ * Return a managed runtime for `runtimeKind`, downloading it if the user
+ * consents. Null means the thread closed while we waited; a throw means the
+ * user declined (or the install failed) and the launch can't proceed.
+ */
+ private async provideManagedRuntime(
+ record: ThreadRecord,
+ runtimeKind: ManagedRuntimeKind,
+ ): Promise<ManagedRuntime | null> {
+ const root = this.opts.runtimeInstall?.root;
+ const existing = await findManagedRuntime(runtimeKind, root).catch(() => null);
+ if (existing !== null) return existing;
+
+ const persisted = (await readRuntimeConsent(this.opts.runtimeInstall?.consentHome))[
+ runtimeKind
+ ];
+ const decision = persisted ?? (await this.requestRuntimeConsent(record, runtimeKind));
+ if (decision === 'closed' || record.closed) return null;
+ if (decision !== 'granted') {
+ throw new AgentLaunchError('command-not-found', declinedRuntimeHint(runtimeKind));
+ }
+
+ try {
+ const runtime = await this.downloadRuntime(record, runtimeKind);
+ return record.closed ? null : runtime;
+ } catch (err) {
+ const name = describeRuntime(runtimeKind).displayName;
+ throw new AgentLaunchError(
+ 'install-failed',
+ `couldn't install ${name}: ${err instanceof Error ? err.message : String(err)}`,
+ );
+ }
+ }
+
+ /**
+ * Emit a `runtime_consent_request` (retained + replayed like a permission
+ * prompt) and park until the user answers via a `runtime_consent_response`
+ * frame, the request times out, or the thread closes.
+ */
+ private requestRuntimeConsent(
+ record: ThreadRecord,
+ runtimeKind: ManagedRuntimeKind,
+ ): Promise<'granted' | 'declined' | 'timeout' | 'closed'> {
+ const requestId = crypto.randomUUID();
+ const d = describeRuntime(runtimeKind);
+ this.appendEvent(record, {
+ kind: 'runtime_consent_request',
+ requestId,
+ runtime: runtimeKind,
+ displayName: d.displayName,
+ provides: d.provides,
+ version: d.version,
+ approxSizeMB: d.approxSizeMB,
+ sourceHost: d.sourceHost,
+ agentName: record.info.agent.name,
+ ts: Date.now(),
+ });
+ return new Promise((resolvePromise) => {
+ const timer = setTimeout(() => {
+ record.pendingRuntimeConsent.delete(requestId);
+ this.appendEvent(record, {
+ kind: 'runtime_consent_resolved',
+ requestId,
+ decision: 'timeout',
+ ts: Date.now(),
+ });
+ resolvePromise('timeout');
+ }, RUNTIME_CONSENT_TIMEOUT_MS);
+ timer.unref?.();
+ record.pendingRuntimeConsent.set(requestId, {
+ runtime: runtimeKind,
+ resolve: resolvePromise,
+ timer,
+ });
+ });
+ }
+
+ /** Answer a parked runtime-consent prompt from the client. */
+ respondRuntimeConsent(
+ threadId: string,
+ requestId: string,
+ outcome: { kind: 'granted'; remember?: boolean } | { kind: 'declined'; remember?: boolean },
+ ): void {
+ const t = this.mustGet(threadId);
+ const pending = t.pendingRuntimeConsent.get(requestId);
+ if (pending === undefined) return;
+ t.pendingRuntimeConsent.delete(requestId);
+ clearTimeout(pending.timer);
+ const decision = outcome.kind === 'granted' ? 'granted' : 'declined';
+ if (outcome.remember === true) {
+ void writeRuntimeConsent(
+ pending.runtime,
+ decision,
+ this.opts.log,
+ this.opts.runtimeInstall?.consentHome,
+ );
+ }
+ this.appendEvent(t, {
+ kind: 'runtime_consent_resolved',
+ requestId,
+ decision,
+ ts: Date.now(),
+ });
+ pending.resolve(decision);
+ }
+
+ /** Download + install a consented runtime, streaming progress to subscribers. */
+ private async downloadRuntime(
+ record: ThreadRecord,
+ runtimeKind: ManagedRuntimeKind,
+ ): Promise<ManagedRuntime> {
+ this.emitStatus(record, 'installing');
+ let lastProgressAt = 0;
+ return ensureManagedRuntime(runtimeKind, this.opts.log, {
+ root: this.opts.runtimeInstall?.root,
+ fetchImpl: this.opts.runtimeInstall?.fetchImpl,
+ onProgress: (p) => {
+ const now = Date.now();
+ if (now - lastProgressAt < RUNTIME_PROGRESS_THROTTLE_MS) return;
+ lastProgressAt = now;
+ if (record.closed) return;
+ this.appendEvent(record, {
+ kind: 'runtime_install_progress',
+ runtime: runtimeKind,
+ phase: 'downloading',
+ receivedBytes: p.receivedBytes,
+ totalBytes: p.totalBytes ?? undefined,
+ ts: now,
+ });
+ },
+ });
+ }
+
+ private async buildMcpServers(
+ record: ThreadRecord,
+ init: InitializeResponse,
+ ): Promise<McpServer[]> {
+ if ((await this.harnessAlreadyHasOkMcp(record)) !== null) return [];
+ const mcpServers: McpServer[] = [];
+ const serverUrl = this.opts.getServerUrl?.();
+ if (serverUrl !== undefined && init.agentCapabilities?.mcpCapabilities?.http === true) {
+ // Preferred: a direct HTTP MCP connection to this running server.
+ mcpServers.push({
+ type: 'http',
+ name: 'open-knowledge',
+ url: `${serverUrl}/mcp`,
+ headers: [],
+ });
+ } else {
+ // Fallback for agents that don't advertise HTTP-MCP support (e.g. Claude
+ // Code's ACP adapter): a stdio MCP server. stdio needs no capability flag
+ // — every ACP agent accepts it — so this is what actually carries the OK
+ // tools to non-HTTP agents. Without it they connect with only their own
+ // personal MCP config and OK tools are silently absent (verified: Codex
+ // declares http and gets OK tools; Claude does not and got only its own).
+ const stdio = this.opts.getMcpStdioCommand?.();
+ if (stdio !== null && stdio !== undefined) {
+ mcpServers.push({
+ name: 'open-knowledge',
+ command: stdio.command,
+ args: [...stdio.args],
+ env: [],
+ });
+ }
+ }
+ return mcpServers;
+ }
+
+ /**
+ * Non-null when this agent's harness will already load OK's own managed
+ * MCP entry from the project/user editor config, so injecting our copy
+ * would only stage a same-name collision (see `probeHarnessManagedMcpEntry`
+ * on the options). Fail-open: no seam, unmapped/custom agent, probe miss,
+ * or probe throw all return null and injection proceeds.
+ */
+ private async harnessAlreadyHasOkMcp(
+ record: ThreadRecord,
+ ): Promise<HarnessManagedMcpEntryHit | null> {
+ const probe = this.opts.probeHarnessManagedMcpEntry;
+ if (probe === undefined || record.agentRef.source !== 'registry') return null;
+ const editorId = ACP_AGENT_EDITOR_IDS[record.agentRef.id];
+ if (editorId === undefined) return null;
+ let hit: HarnessManagedMcpEntryHit | null;
+ try {
+ hit = await probe(editorId, record.cwd);
+ } catch (err) {
+ this.opts.log.warn(
+ { err, threadId: record.info.threadId, editorId },
+ '[acp-threads] harness MCP-config probe failed — injecting OK MCP',
+ );
+ return null;
+ }
+ if (hit !== null) {
+ this.opts.log.info(
+ {
+ threadId: record.info.threadId,
+ agentId: record.agentRef.id,
+ editorId: hit.editorId,
+ scope: hit.scope,
+ configPath: hit.configPath,
+ },
+ "[acp-threads] skipping OK MCP injection — the agent's harness already loads OK's managed entry",
+ );
+ }
+ return hit;
+ }
+
+ private async startThread(
+ record: ThreadRecord,
+ params: { agent: { source: 'registry' | 'custom'; id: string }; prompt?: string },
+ custom: CustomAgentEntry | null,
+ ): Promise<void> {
+ let handshake: Awaited<ReturnType<AcpThreadManager['connectAgent']>>;
+ try {
+ handshake = await this.connectAgent(record, custom);
+ } catch (err) {
+ const detail =
+ err instanceof AgentLaunchError || err instanceof ThreadOpError ? err.message : String(err);
+ this.emitStatus(record, 'error', detail);
+ return;
+ }
+ if (handshake === null) return;
+ const { conn, init, launch } = handshake;
+
+ const mcpServers = await this.buildMcpServers(record, init);
+ try {
+ const session = await conn.agent.request(acpMethods.agent.session.new, {
+ cwd: record.cwd,
+ mcpServers,
+ });
+ record.sessionId = session.sessionId;
+ this.persistence.queueMetaWrite(record.info.threadId, this.buildMeta(record));
+ if (session.modes !== undefined && session.modes !== null) {
+ record.info.modes = session.modes;
+ this.emitInfo(record);
+ }
+ if (session.configOptions !== undefined && session.configOptions !== null) {
+ record.info.configOptions = session.configOptions;
+ this.emitInfo(record);
+ }
+ } catch (err) {
+ const authMethods = (init.authMethods ?? [])
+ .map((m) => (typeof m === 'object' && m !== null ? (m as { name?: string }).name : null))
+ .filter((n): n is string => typeof n === 'string');
+ if (authMethods.length > 0) {
+ this.emitStatus(
+ record,
+ 'auth_required',
+ `sign in first (${authMethods.join(' / ')}), then start a new thread — ${describeAgentError(err)}`,
+ );
+ } else {
+ this.emitStatus(record, 'error', `session setup failed: ${describeAgentError(err)}`);
+ }
+ return;
+ }
+ if (record.closed) return;
+
+ this.setPresence(record, 'idle');
+ this.emitStatus(record, 'ready');
+ // Startup latency is a known UX sore point (npx resolution + node boot +
+ // handshake, serialized) — keep it measurable per launch kind.
+ this.opts.log.info(
+ {
+ threadId: record.info.threadId,
+ agentId: record.info.agent.id,
+ launchKind: launch.kind,
+ msToReady: Date.now() - record.info.createdAt,
+ },
+ '[acp-threads] agent ready',
+ );
+
+ if (params.prompt !== undefined && params.prompt !== '') {
+ this.sendPrompt(record.info.threadId, params.prompt);
+ }
+ }
+
+ /**
+ * Resume an archived thread: respawn its agent and reconnect the stored
+ * ACP session. Preference order `session/resume` (no history replay — the
+ * retained transcript is already the source of truth) over `session/load`
+ * (protocol-mandated full replay, suppressed as duplicates), else fail
+ * with `resume-unsupported`. Unlike `createThread`, resolves only once the
+ * thread is ready (or rejects) — status events stream progress meanwhile.
+ */
+ async resumeThread(threadId: string, prompt?: string): Promise<ThreadInfo> {
+ if (this.destroyed) throw new ThreadOpError('capacity', 'server is shutting down');
+ const t = this.mustGet(threadId);
+ if (t.info.archived !== true) {
+ throw new ThreadOpError('not-ready', 'thread is not archived');
+ }
+ if (t.resumeInFlight) {
+ throw new ThreadOpError('not-ready', 'a resume is already in progress');
+ }
+ if (this.liveThreadCount() >= this.maxThreads) {
+ throw new ThreadOpError('capacity', `maximum of ${this.maxThreads} concurrent agent threads`);
+ }
+ t.resumeInFlight = true;
+ const startedAt = Date.now();
+ try {
+ await this.ensureLogResolved(t);
+ const sessionId = t.sessionId;
+ const { info: agentInfo, custom } = await this.resolveAgentInfo(t.agentRef);
+ // Re-check both gates after the awaits (same TOCTOU class as
+ // createThread): a concurrent create can pass its own guard while this
+ // resume is suspended, and un-archiving below is what raises the live
+ // count. No await sits between this check and the flip.
+ if (this.destroyed) throw new ThreadOpError('capacity', 'server is shutting down');
+ if (this.liveThreadCount() >= this.maxThreads) {
+ throw new ThreadOpError(
+ 'capacity',
+ `maximum of ${this.maxThreads} concurrent agent threads`,
+ );
+ }
+ t.info.agent = agentInfo;
+ t.info.archived = false;
+ t.stderrTail = [];
+ if (t.midTurnOnDisk) {
+ // The persisted log ended inside a turn (crash mid-stream) — close
+ // it so the folded transcript doesn't read as still-running.
+ t.midTurnOnDisk = false;
+ this.appendEvent(t, { kind: 'turn_ended', stopReason: 'cancelled', ts: Date.now() });
+ }
+ if (prompt !== undefined && prompt !== '') {
+ // Optimistic echo: the message lands in the transcript (and every
+ // subscriber's view) NOW, not after the multi-second respawn +
+ // handshake — otherwise the composer clears and nothing visibly
+ // happens until the agent is up. `dispatchPrompt` at the end of the
+ // handshake skips its own echo to match. Flushed synchronously so
+ // the echo frame always precedes the `resumed` response, not just
+ // usually (the coalescing timer could lose to a fast handshake).
+ this.echoUserMessage(t, prompt);
+ this.flushBroadcast(t);
+ }
+ this.emitStatus(t, 'installing');
+ try {
+ if (sessionId === null) {
+ throw new ThreadOpError(
+ 'resume-unsupported',
+ 'this thread never completed an agent session',
+ );
+ }
+ const handshake = await this.connectAgent(t, custom);
+ if (handshake === null) {
+ throw new ThreadOpError('not-ready', 'thread closed during resume');
+ }
+ const { conn, init } = handshake;
+ const mcpServers = await this.buildMcpServers(t, init);
+ const caps = init.agentCapabilities;
+ const viaResume = caps?.sessionCapabilities?.resume != null;
+ let response: { modes?: unknown; configOptions?: unknown };
+ if (viaResume) {
+ response = await conn.agent.request(acpMethods.agent.session.resume, {
+ sessionId,
+ cwd: t.cwd,
+ mcpServers,
+ });
+ } else if (caps?.loadSession === true) {
+ t.suppressUpdates = true;
+ t.lastSuppressedAt = Date.now();
+ try {
+ response = await conn.agent.request(acpMethods.agent.session.load, {
+ sessionId,
+ cwd: t.cwd,
+ mcpServers,
+ });
+ await this.awaitReplayQuiescence(t);
+ } finally {
+ t.suppressUpdates = false;
+ }
+ } else {
+ throw new ThreadOpError(
+ 'resume-unsupported',
+ `${t.info.agent.name} doesn't support resuming previous sessions`,
+ );
+ }
+ t.sessionId = sessionId;
+ const modes = response.modes as ThreadInfo['modes'] | undefined;
+ if (modes !== undefined && modes !== null) t.info.modes = modes;
+ const configOptions = response.configOptions as ThreadInfo['configOptions'] | undefined;
+ if (configOptions !== undefined && configOptions !== null) {
+ t.info.configOptions = configOptions;
+ }
+ this.setPresence(t, 'idle');
+ this.emitStatus(t, 'ready');
+ this.opts.log.info(
+ {
+ threadId,
+ agentId: t.info.agent.id,
+ method: viaResume ? 'session/resume' : 'session/load',
+ msToResumed: Date.now() - startedAt,
+ },
+ '[acp-threads] thread resumed',
+ );
+ if (prompt !== undefined && prompt !== '') {
+ this.dispatchPrompt(t, prompt, { echo: false });
+ }
+ return { ...t.info };
+ } catch (err) {
+ await this.abortResume(t);
+ if (err instanceof ThreadOpError) throw err;
+ if (err instanceof AgentLaunchError) {
+ throw new ThreadOpError(
+ err.code === 'install-failed' ? 'install-failed' : 'spawn-failed',
+ err.message,
+ );
+ }
+ // A rejected session/load|resume (unknown or expired sessionId, cwd
+ // mismatch) — expected at steady state: agents expire their own
+ // session stores (Claude defaults to 30 days).
+ throw new ThreadOpError(
+ 'resume-unsupported',
+ `couldn't resume the previous session: ${describeAgentError(err)}`,
+ );
+ }
+ } finally {
+ t.resumeInFlight = false;
+ }
+ }
+
+ /** Tear down a half-resumed agent and return the record to archived rest. */
+ private async abortResume(t: ThreadRecord): Promise<void> {
+ t.closed = true;
+ t.suppressUpdates = false;
+ this.failPendingPermissions(t);
+ this.failPendingRuntimeConsent(t);
+ try {
+ t.conn?.close();
+ } catch {
+ // Already closed.
+ }
+ const child = t.child;
+ if (child !== null) {
+ await terminateAgentTree(child, { graceMs: DESTROY_KILL_GRACE_MS });
+ }
+ t.child = null;
+ t.conn = null;
+ t.closed = false;
+ t.turnActive = false;
+ this.opts.agentPresenceBroadcaster?.clearPresence(toBroadcasterKey(t.agentSessionId));
+ t.info.archived = true;
+ this.emitStatus(t, 'exited', 'resume failed');
+ this.flushBroadcast(t);
+ this.persistence.queueMetaWrite(t.info.threadId, this.buildMeta(t));
+ await this.persistence.whenIdle(t.info.threadId);
+ t.baseSeq = t.info.lastSeq + 1;
+ t.events = [];
+ }
+
+ /**
+ * Wait for the `session/load` replay stream to go quiet (see
+ * RESUME_REPLAY_QUIESCENCE_MS) before the first post-resume turn opens.
+ */
+ private async awaitReplayQuiescence(t: ThreadRecord): Promise<void> {
+ const deadline = Date.now() + RESUME_REPLAY_MAX_WAIT_MS;
+ while (Date.now() - t.lastSuppressedAt < RESUME_REPLAY_QUIESCENCE_MS && Date.now() < deadline) {
+ await new Promise((r) => setTimeout(r, 50));
+ }
+ }
+
+ sendPrompt(threadId: string, content: string): void {
+ const t = this.mustGet(threadId);
+ if (t.info.archived === true) {
+ throw new ThreadOpError('not-ready', 'the thread is archived — resume it first');
+ }
+ if (t.resumeInFlight) {
+ // Mid-resume the connection exists before the session is reconnected —
+ // a prompt slipping in here would race the session/resume|load request.
+ throw new ThreadOpError('not-ready', 'the thread is still resuming');
+ }
+ if (t.sessionId === null || t.conn === null) {
+ throw new ThreadOpError('not-ready', 'thread has no live agent session');
+ }
+ if (t.turnActive) {
+ throw new ThreadOpError('not-ready', 'a turn is already running — cancel it first');
+ }
+ this.dispatchPrompt(t, content, { echo: true });
+ }
+
+ /** Adopt-title + append the `user_message` transcript event for a prompt. */
+ private echoUserMessage(t: ThreadRecord, content: string): void {
+ // The single choke point for every user message (launch prompt, interactive
+ // prompt, resume prompt) — mark the thread as touched so a later close
+ // archives it rather than discarding it as never-used.
+ t.hadUserMessage = true;
+ if (t.info.title === t.info.agent.name && content.trim() !== '') {
+ // Prefer the user's raw typed text (carried on the launch) over the
+ // composed prompt — its fixed handoff preamble would otherwise become
+ // the tab label. One-shot: cleared so later prompts derive from content.
+ const source = t.titleHint !== undefined && t.titleHint.trim() !== '' ? t.titleHint : content;
+ t.titleHint = undefined;
+ t.info.title = deriveThreadTitle(source);
+ this.appendEvent(t, { kind: 'title_changed', title: t.info.title, ts: Date.now() });
+ this.emitInfo(t);
+ }
+ this.appendEvent(t, { kind: 'user_message', content, ts: Date.now() });
+ }
+
+ /**
+ * Manually retitle a thread (tab double-click). Works on live and archived
+ * threads; a manual title differs from the agent name, so the first-prompt
+ * adoption in {@link echoUserMessage} will not overwrite it.
+ */
+ async renameThread(threadId: string, rawTitle: string): Promise<void> {
+ const t = this.mustGet(threadId);
+ if (t.closed) {
+ // Mid-teardown, closeThread is about to reset the memory window — an
+ // event appended here would be dropped after its seq was claimed.
+ throw new ThreadOpError('not-ready', 'the thread is closing');
+ }
+ const title = clampThreadTitle(rawTitle);
+ if (title === '' || title === t.info.title) return;
+ // Appending to a rehydrated record before its log is resolved would trust
+ // a possibly-stale `baseSeq` and break the line-index-IS-the-seq contract.
+ await this.ensureLogResolved(t);
+ t.info.title = title;
+ t.info.lastActivityAt = Date.now();
+ this.appendEvent(t, { kind: 'title_changed', title, ts: Date.now() });
+ this.flushBroadcast(t);
+ this.emitInfo(t);
+ // Durable on return: a rename is rare and tiny, and archived threads have
+ // no later flush point to ride.
+ await this.persistence.whenIdle(t.info.threadId);
+ }
+
+ /**
+ * Open a turn and send the prompt to the agent. `echo: false` is the
+ * resume path, whose optimistic echo already put the user message (and
+ * title adoption) in the transcript at resume start.
+ */
+ private dispatchPrompt(t: ThreadRecord, content: string, opts: { echo: boolean }): void {
+ if (t.sessionId === null || t.conn === null) {
+ throw new ThreadOpError('not-ready', 'thread has no live agent session');
+ }
+ if (opts.echo) {
+ this.echoUserMessage(t, content);
+ }
+ t.turnActive = true;
+ t.cancelRequested = false;
+ this.appendEvent(t, { kind: 'turn_started', ts: Date.now() });
+ this.emitStatus(t, 'running');
+ this.setPresence(t, 'writing');
+
+ const sessionId = t.sessionId;
+ t.conn.agent
+ .request(acpMethods.agent.session.prompt, {
+ sessionId,
+ prompt: [{ type: 'text', text: content }],
+ })
+ .then((response) => {
+ t.turnActive = false;
+ if (t.closed) return;
+ this.appendEvent(t, {
+ kind: 'turn_ended',
+ stopReason: response.stopReason,
+ ts: Date.now(),
+ });
+ this.emitStatus(t, 'ready');
+ this.setPresence(t, 'idle');
+ })
+ .catch((err) => {
+ t.turnActive = false;
+ if (t.closed) return;
+ this.appendEvent(t, { kind: 'turn_ended', stopReason: 'cancelled', ts: Date.now() });
+ if (t.cancelRequested) {
+ // The user asked for this — an aborted request is a completed
+ // cancel, not an agent failure.
+ this.emitStatus(t, 'ready');
+ } else {
+ this.emitStatus(t, 'error', `prompt failed: ${describeAgentError(err)}`);
+ }
+ this.setPresence(t, 'idle');
+ });
+ }
+
+ cancel(threadId: string): void {
+ const t = this.mustGet(threadId);
+ if (t.conn === null || t.sessionId === null) return;
+ if (t.turnActive) t.cancelRequested = true;
+ // Per ACP, a cancelled turn's pending permission requests resolve as
+ // 'cancelled' client-side — and a turn blocked ON a permission prompt
+ // only actually stops when we do (the agent is awaiting our response).
+ this.failPendingPermissions(t);
+ this.restoreRunningAfterPermission(t);
+ void t.conn.agent.notify(acpMethods.agent.session.cancel, { sessionId: t.sessionId });
+ }
+
+ setMode(threadId: string, modeId: string): void {
+ const t = this.mustGet(threadId);
+ if (t.conn === null || t.sessionId === null) {
+ throw new ThreadOpError('not-ready', 'thread has no live agent session');
+ }
+ void t.conn.agent
+ .request(acpMethods.agent.session.setMode, { sessionId: t.sessionId, modeId })
+ .then(() => {
+ if (t.info.modes) {
+ t.info.modes = { ...t.info.modes, currentModeId: modeId };
+ this.emitInfo(t);
+ }
+ })
+ .catch((err) => {
+ this.opts.log.warn({ err, threadId }, '[acp-threads] set_mode failed');
+ });
+ }
+
+ /**
+ * Set a session config option (model picker, thought level, …). The
+ * response's `configOptions` is the agent's authoritative post-change
+ * state — it replaces the cached array wholesale (option changes can
+ * cascade, e.g. picking a model can reshape the thought-level choices).
+ */
+ setConfigOption(threadId: string, configId: string, value: string | boolean): void {
+ const t = this.mustGet(threadId);
+ if (t.conn === null || t.sessionId === null) {
+ throw new ThreadOpError('not-ready', 'thread has no live agent session');
+ }
+ const request: SetSessionConfigOptionRequest =
+ typeof value === 'boolean'
+ ? { sessionId: t.sessionId, configId, type: 'boolean', value }
+ : { sessionId: t.sessionId, configId, value };
+ void t.conn.agent
+ .request(acpMethods.agent.session.setConfigOption, request)
+ .then((response: SetSessionConfigOptionResponse) => {
+ t.info.configOptions = response.configOptions;
+ this.emitInfo(t);
+ })
+ .catch((err) => {
+ this.opts.log.warn({ err, threadId, configId }, '[acp-threads] set_config_option failed');
+ });
+ }
+
+ respondPermission(
+ threadId: string,
+ requestId: string,
+ outcome: { kind: 'selected'; optionId: string } | { kind: 'cancelled' },
+ ): void {
+ const t = this.mustGet(threadId);
+ const pending = t.pendingPermissions.get(requestId);
+ if (pending === undefined) return;
+ t.pendingPermissions.delete(requestId);
+ clearTimeout(pending.timer);
+ if (outcome.kind === 'selected') {
+ pending.resolve({ outcome: { outcome: 'selected', optionId: outcome.optionId } });
+ this.appendEvent(t, {
+ kind: 'permission_resolved',
+ requestId,
+ optionId: outcome.optionId,
+ auto: false,
+ ts: Date.now(),
+ });
+ } else {
+ pending.resolve({ outcome: { outcome: 'cancelled' } });
+ this.appendEvent(t, {
+ kind: 'permission_resolved',
+ requestId,
+ optionId: null,
+ auto: false,
+ ts: Date.now(),
+ });
+ }
+ this.restoreRunningAfterPermission(t);
+ }
+
+ /**
+ * Un-park the status once no permission prompt remains. Guarded on the
+ * status still being `awaiting_permission` so a terminal transition
+ * (error/exited) that landed in between is never overwritten.
+ */
+ private restoreRunningAfterPermission(t: ThreadRecord): void {
+ if (
+ t.pendingPermissions.size === 0 &&
+ t.turnActive &&
+ t.info.status === 'awaiting_permission'
+ ) {
+ this.emitStatus(t, 'running');
+ }
+ }
+
+ /**
+ * Close a thread: kill its agent (resolving only once the process tree is
+ * actually dead — resolving earlier lets the server exit before the SIGKILL
+ * escalation can fire), then ARCHIVE it — unless it never received a user
+ * message, in which case it is DISCARDED (record + persisted log removed) so
+ * a spawned-but-untouched agent leaves no history. An archived record stays
+ * listed with `archived: true`; its transcript is already on disk and the
+ * stored sessionId keeps it resumable. `destroy()` passes a shorter grace so
+ * parallel closes fit inside boot's per-step destroy timeout.
+ */
+ async closeThread(threadId: string, opts?: { killGraceMs?: number }): Promise<void> {
+ const t = this.threads.get(threadId);
+ if (t === undefined || t.info.archived === true || t.closed) return;
+ t.closed = true; // Suppress exit/conn status handlers during teardown.
+ this.failPendingPermissions(t);
+ this.failPendingRuntimeConsent(t);
+ try {
+ t.conn?.close();
+ } catch {
+ // Already closed.
+ }
+ const child = t.child;
+ if (child !== null) {
+ const dead = await terminateAgentTree(child, {
+ graceMs: opts?.killGraceMs ?? KILL_GRACE_MS,
+ });
+ if (!dead) {
+ this.opts.log.error(
+ { threadId, pid: child.pid },
+ '[acp-threads] agent process survived SIGKILL escalation',
+ );
+ }
+ }
+ t.child = null;
+ t.conn = null;
+ await t.terminals?.disposeAll();
+ t.terminals = null;
+ this.opts.agentPresenceBroadcaster?.clearPresence(toBroadcasterKey(t.agentSessionId));
+ await this.opts.sessionManager.closeAllForAgent(t.agentSessionId).catch((err) => {
+ this.opts.log.warn({ err, threadId }, '[acp-threads] session cleanup failed');
+ });
+ // Never-used thread (no user message ever recorded): discard it rather than
+ // archive. The agent is dead above; drop the record and its (possibly
+ // partial) persisted log so a spawned-but-untouched agent leaves no history.
+ if (!t.hadUserMessage) {
+ this.threads.delete(threadId);
+ t.subscribers.clear();
+ if (t.flushTimer !== null) {
+ clearTimeout(t.flushTimer);
+ t.flushTimer = null;
+ }
+ await this.persistence.whenIdle(threadId);
+ await this.persistence.delete(threadId);
+ this.opts.log.info({ threadId }, '[acp-threads] empty thread discarded on close');
+ return;
+ }
+ if (t.turnActive) {
+ // Close the open turn so the persisted transcript doesn't fold as
+ // still-running when replayed later.
+ t.turnActive = false;
+ this.appendEvent(t, { kind: 'turn_ended', stopReason: 'cancelled', ts: Date.now() });
+ }
+ t.info.archived = true;
+ this.emitStatus(t, 'exited', 'thread closed');
+ this.flushBroadcast(t);
+ this.persistence.queueMetaWrite(threadId, this.buildMeta(t));
+ await this.persistence.whenIdle(threadId);
+ // Release the in-memory window — disk now holds the whole log. (The
+ // record was born resolved or resolved on first subscribe; either way
+ // `lastSeq` is accurate here.)
+ t.baseSeq = t.info.lastSeq + 1;
+ t.events = [];
+ t.pendingBroadcast = [];
+ t.closed = false; // Archived records stay addressable (subscribe/resume/delete).
+ this.opts.log.info({ threadId }, '[acp-threads] thread archived');
+ }
+
+ /** Permanently delete an ARCHIVED thread's transcript and metadata. */
+ async deleteThread(threadId: string): Promise<void> {
+ const t = this.mustGet(threadId);
+ if (t.info.archived !== true) {
+ throw new ThreadOpError('not-ready', 'close the thread before deleting it');
+ }
+ if (t.resumeInFlight) {
+ throw new ThreadOpError('not-ready', 'a resume is in progress');
+ }
+ this.threads.delete(threadId);
+ t.subscribers.clear();
+ if (t.flushTimer !== null) {
+ clearTimeout(t.flushTimer);
+ t.flushTimer = null;
+ }
+ await this.persistence.whenIdle(threadId);
+ await this.persistence.delete(threadId);
+ this.opts.log.info({ threadId }, '[acp-threads] thread deleted');
+ }
+
+ async destroy(): Promise<void> {
+ this.destroyed = true;
+ clearInterval(this.reapTimer);
+ await Promise.allSettled(
+ [...this.threads.keys()].map((id) =>
+ this.closeThread(id, { killGraceMs: DESTROY_KILL_GRACE_MS }),
+ ),
+ );
+ }
+
+ // ── ACP client-side handlers ────────────────────────────────────────────
+
+ private async handlePermissionRequest(
+ record: ThreadRecord,
+ toolCall: ToolCallUpdate,
+ options: PermissionOption[],
+ ): Promise<RequestPermissionResponse> {
+ record.info.lastActivityAt = Date.now();
+ const decision = this.opts.permissions.decide(record.info.agent.id, toolCall, options);
+ if (decision.auto !== null) {
+ const requestId = crypto.randomUUID();
+ this.appendEvent(record, {
+ kind: 'permission_resolved',
+ requestId,
+ optionId: decision.auto.optionId,
+ auto: true,
+ ts: Date.now(),
+ });
+ return { outcome: { outcome: 'selected', optionId: decision.auto.optionId } };
+ }
+
+ const requestId = crypto.randomUUID();
+ this.appendEvent(record, {
+ kind: 'permission_request',
+ requestId,
+ toolCall,
+ options,
+ ts: Date.now(),
+ });
+ // The turn is parked on the user now — say so in the tab strip instead of
+ // a generic "running" spinner. Only refine 'running': a terminal status
+ // (error/exited) always wins, so a dead turn's stale request never reads
+ // as still inviting approval.
+ if (record.turnActive && record.info.status === 'running') {
+ this.emitStatus(record, 'awaiting_permission');
+ }
+ return new Promise<RequestPermissionResponse>((resolvePromise) => {
+ const timer = setTimeout(() => {
+ record.pendingPermissions.delete(requestId);
+ this.appendEvent(record, {
+ kind: 'permission_resolved',
+ requestId,
+ optionId: null,
+ auto: true,
+ ts: Date.now(),
+ });
+ this.restoreRunningAfterPermission(record);
+ resolvePromise({ outcome: { outcome: 'cancelled' } });
+ }, PERMISSION_TIMEOUT_MS);
+ timer.unref?.();
+ record.pendingPermissions.set(requestId, {
+ timer,
+ resolve: (response) => {
+ if (response.outcome.outcome === 'selected') {
+ const chosen = options.find(
+ (o) =>
+ response.outcome.outcome === 'selected' && o.optionId === response.outcome.optionId,
+ );
+ if (chosen !== undefined) {
+ void this.opts.permissions.recordChoice(record.info.agent.id, toolCall, chosen);
+ }
+ }
+ resolvePromise(response);
+ },
+ });
+ });
+ }
+
+ private handleSessionUpdate(record: ThreadRecord, notification: SessionNotification): void {
+ record.info.lastActivityAt = Date.now();
+ const update: SessionUpdate = notification.update;
+ if (update.sessionUpdate === 'current_mode_update' && record.info.modes) {
+ record.info.modes = { ...record.info.modes, currentModeId: update.currentModeId };
+ this.emitInfo(record);
+ }
+ if (update.sessionUpdate === 'config_option_update') {
+ record.info.configOptions = update.configOptions;
+ this.emitInfo(record);
+ }
+ if (record.suppressUpdates) {
+ // A session/load replay — every update duplicates the retained log
+ // (which is richer: permission events, statuses). Live state above
+ // still applied; the transcript append is skipped.
+ record.lastSuppressedAt = Date.now();
+ return;
+ }
+ this.appendEvent(record, {
+ kind: 'session_update',
+ update: boundSessionUpdateForLog(update),
+ ts: Date.now(),
+ });
+ }
+
+ private async handleFsRead(
+ requestedPath: string,
+ line: number | null,
+ limit: number | null,
+ ): Promise<{ content: string }> {
+ const target = await this.confinePath(requestedPath);
+ let content: string;
+ if (target.docName !== null) {
+ // In-scope markdown: serve the live CRDT bytes when the doc is loaded
+ // (OK's equivalent of the protocol's "unsaved editor state"); otherwise
+ // read the persisted disk bytes. No tracked agent session is opened for
+ // a read — that would leak a DirectConnection per distinct doc.
+ content =
+ this.opts.getLoadedDocText?.(target.docName) ?? (await readFile(target.abs, 'utf8'));
+ } else {
+ content = await readFile(target.abs, 'utf8');
+ }
+ if (line !== null || limit !== null) {
+ const lines = content.split('\n');
+ const start = Math.max((line ?? 1) - 1, 0);
+ const end = limit !== null ? start + limit : lines.length;
+ content = lines.slice(start, end).join('\n');
+ }
+ return { content };
+ }
+
+ private async handleFsWrite(
+ record: ThreadRecord,
+ requestedPath: string,
+ content: string,
+ ): Promise<void> {
+ record.info.lastActivityAt = Date.now();
+ const target = await this.confinePath(requestedPath);
+ if (target.docName !== null) {
+ const session = await this.opts.sessionManager.getSession(
+ target.docName,
+ record.agentSessionId,
+ {
+ displayName: record.info.agent.name,
+ colorSeed: record.agentSessionId,
+ clientName: record.info.agent.id,
+ },
+ );
+ const embedResolver =
+ this.opts.resolveEmbed !== undefined
+ ? { resolveEmbed: this.opts.resolveEmbed, sourcePath: target.rel }
+ : undefined;
+ session.dc.document.transact(() => {
+ const beforeBlocks = snapshotBlocks(session.dc.document);
+ applyAgentMarkdownWrite(session.dc.document, content, 'replace', embedResolver);
+ // Same-transaction flash entry, mirroring the HTTP agent-write
+ // handlers — drives the editor's write-flash + follow-the-write
+ // animation for thread writes too (and rides the per-session
+ // UndoManager, which tracks the agent-flash map). `changedBlocks` lets
+ // an editor that follow-mode activates AFTER this write applied still
+ // scroll to + flash the changed section (no live transaction to diff).
+ const changedBlocks =
+ changedBlockRange(beforeBlocks, snapshotBlocks(session.dc.document)) ?? undefined;
+ const activityMap = session.dc.document.getMap('agent-flash');
+ activityMap.set(record.agentSessionId, {
+ agentId: record.agentSessionId,
+ timestamp: Date.now(),
+ type: 'insert',
+ description: `Added (${record.info.agent.name}): ${content.slice(0, 50)}`,
+ ...(changedBlocks !== undefined ? { changedBlocks } : {}),
+ });
+ }, session.origin);
+ this.setPresence(record, 'writing', target.docName);
+ } else {
+ // Non-markdown (and filter-excluded markdown) writes hit the disk
+ // directly — but never inside an ignored namespace. `.ok/` and `.git/`
+ // live INSIDE the confined root (content.dir defaults to `.`), so the
+ // `..`-escape check alone does not protect them.
+ if (this.opts.isIgnoredPath(target.rel)) {
+ throw new Error(`path is excluded from the project content scope: ${requestedPath}`);
+ }
+ const { tracedMkdir, tracedWriteFile } = await import('../fs-traced.ts');
+ await tracedMkdir(dirname(target.abs), { recursive: true });
+ await tracedWriteFile(target.abs, content);
+ }
+ }
+
+ private confinePath(
+ requestedPath: string,
+ ): Promise<{ abs: string; rel: string; docName: string | null }> {
+ return confineToContentDir(this.opts.contentDir, requestedPath, this.opts.isExcludedPath);
+ }
+
+ // ── internals ───────────────────────────────────────────────────────────
+
+ private mustGet(threadId: string): ThreadRecord {
+ const t = this.threads.get(threadId);
+ if (t === undefined) throw new ThreadOpError('unknown-thread', `no thread '${threadId}'`);
+ return t;
+ }
+
+ private appendEvent(t: ThreadRecord, event: ThreadEvent): void {
+ // Fold a streamed text chunk into the current unflushed tail event instead
+ // of giving each its own seq/line — collapses a per-word chunk burst into
+ // ~one event per flush window. Eligible only against the pending (not-yet-
+ // flushed) tail: a flushed event's seq is already on the wire and on disk,
+ // so `pendingBroadcast` non-empty means its last event === events[] tail and
+ // is still ours to grow. A fold consumes no seq, preserving line-index==seq.
+ // pendingBroadcast non-empty also implies a flush timer is already pending
+ // (set when it went non-empty below), so the fold needs no new timer.
+ const pending = t.pendingBroadcast;
+ if (pending.length > 0 && coalesceChunkInto(pending[pending.length - 1], event)) {
+ return;
+ }
+ const seq = t.baseSeq + t.events.length;
+ t.events.push(event);
+ t.info.lastSeq = seq;
+ if (t.events.length > EVENT_LOG_LIMIT) {
+ const drop = t.events.length - EVENT_LOG_LIMIT;
+ t.events.splice(0, drop);
+ t.baseSeq += drop;
+ }
+ if (t.pendingBroadcast.length === 0) t.pendingBroadcastFromSeq = seq;
+ t.pendingBroadcast.push(event);
+ if (t.flushTimer === null) {
+ t.flushTimer = setTimeout(() => this.flushBroadcast(t), EVENT_FLUSH_MS);
+ t.flushTimer.unref?.();
+ }
+ }
+
+ private flushBroadcast(t: ThreadRecord): void {
+ if (t.flushTimer !== null) {
+ clearTimeout(t.flushTimer);
+ t.flushTimer = null;
+ }
+ if (t.pendingBroadcast.length === 0) return;
+ const frame: ThreadServerFrame = {
+ op: 'events',
+ threadId: t.info.threadId,
+ fromSeq: t.pendingBroadcastFromSeq,
+ events: t.pendingBroadcast,
+ };
+ // Durability rides the same coalescing cadence: one serialized append
+ // per flushed batch, in seq order (the NDJSON line index IS the seq).
+ this.persistence.appendEvents(t.info.threadId, t.pendingBroadcast);
+ t.pendingBroadcast = [];
+ for (const sink of t.subscribers) {
+ try {
+ sink(frame);
+ } catch {
+ // A broken sink is dropped by its socket's close handler.
+ }
+ }
+ }
+
+ private emitStatus(t: ThreadRecord, status: ThreadStatus, detail?: string): void {
+ t.info.status = status;
+ t.info.lastActivityAt = Date.now();
+ this.appendEvent(t, { kind: 'status', status, detail, ts: Date.now() });
+ this.emitInfo(t);
+ }
+
+ private emitInfo(t: ThreadRecord): void {
+ // Info changes (status, title, modes, config) are the meta snapshot's
+ // refresh signal — bounded per turn, unlike per-event activity.
+ this.persistence.queueMetaWrite(t.info.threadId, this.buildMeta(t));
+ for (const sink of t.subscribers) {
+ try {
+ sink({ op: 'info', info: { ...t.info } });
+ } catch {
+ // Dropped with the socket.
+ }
+ }
+ }
+
+ private buildMeta(t: ThreadRecord): PersistedThreadMeta {
+ return {
+ version: 1,
+ info: { ...t.info },
+ sessionId: t.sessionId,
+ cwd: t.cwd,
+ agentRef: t.agentRef,
+ docName: t.docName,
+ };
+ }
+
+ private failPendingPermissions(t: ThreadRecord): void {
+ for (const [requestId, pending] of t.pendingPermissions) {
+ clearTimeout(pending.timer);
+ pending.resolve({ outcome: { outcome: 'cancelled' } });
+ this.appendEvent(t, {
+ kind: 'permission_resolved',
+ requestId,
+ optionId: null,
+ auto: true,
+ ts: Date.now(),
+ });
+ }
+ t.pendingPermissions.clear();
+ }
+
+ /** Resolve any parked runtime-consent prompts as `closed` during teardown. */
+ private failPendingRuntimeConsent(t: ThreadRecord): void {
+ for (const pending of t.pendingRuntimeConsent.values()) {
+ clearTimeout(pending.timer);
+ pending.resolve('closed');
+ }
+ t.pendingRuntimeConsent.clear();
+ }
+
+ private setPresence(t: ThreadRecord, mode: 'idle' | 'writing', currentDoc?: string): void {
+ const broadcaster = this.opts.agentPresenceBroadcaster;
+ if (broadcaster === undefined || broadcaster === null) return;
+ try {
+ const icon = iconFromClientName(t.info.agent.id);
+ const color = AGENT_ICON_COLORS[icon] ?? colorFromSeed(t.agentSessionId);
+ broadcaster.setPresence(toBroadcasterKey(t.agentSessionId), {
+ displayName: t.info.agent.name,
+ icon,
+ color,
+ currentDoc: currentDoc ?? t.docName ?? AGENT_THREAD_SENTINEL_DOC,
+ mode,
+ ts: Date.now(),
+ });
+ } catch (err) {
+ this.opts.log.warn({ err }, '[acp-threads] presence update failed');
+ }
+ }
+
+ private reapIdleThreads(): void {
+ const now = Date.now();
+ const cutoff = now - this.idleReapMs;
+ for (const t of this.threads.values()) {
+ // Archived threads hold no process and no memory window — nothing to reap.
+ if (t.info.archived === true) continue;
+ if (t.subscribers.size === 0 && !t.turnActive && t.info.lastActivityAt < cutoff) {
+ this.opts.log.info({ threadId: t.info.threadId }, '[acp-threads] reaping idle thread');
+ // A failed reap must not become an unhandled rejection from inside the
+ // interval callback — log it and let the next sweep retry.
+ this.closeThread(t.info.threadId).catch((err: unknown) => {
+ this.opts.log.error({ err, threadId: t.info.threadId }, '[acp-threads] reap failed');
+ });
+ continue;
+ }
+ // Unwatched-turn backstop (see DEFAULT_UNWATCHED_TURN_* above).
+ if (!t.turnActive || t.unwatchedSince === null) continue;
+ const unwatchedFor = now - t.unwatchedSince;
+ if (unwatchedFor >= this.unwatchedTurnKillMs) {
+ this.opts.log.warn(
+ { threadId: t.info.threadId, unwatchedFor },
+ '[acp-threads] force-closing unwatched turn that ignored cancel',
+ );
+ this.closeThread(t.info.threadId).catch((err: unknown) => {
+ this.opts.log.error(
+ { err, threadId: t.info.threadId },
+ '[acp-threads] force-close failed',
+ );
+ });
+ } else if (unwatchedFor >= this.unwatchedTurnCancelMs && !t.unwatchedCancelSent) {
+ t.unwatchedCancelSent = true;
+ this.opts.log.warn(
+ { threadId: t.info.threadId, unwatchedFor },
+ '[acp-threads] cancelling turn running with zero subscribers',
+ );
+ this.cancel(t.info.threadId);
+ }
+ }
+ }
+}
+
+/**
+ * Confine a requested path to the content directory. Resolves the deepest
+ * existing ancestor through `realpath` so a symlink inside the tree cannot
+ * point reads/writes outside it (mirrors the file-watcher's symlink-escape
+ * policy), and maps in-scope `.md`/`.mdx` paths to their extension-less
+ * docName — rejecting reserved namespaces and filter-excluded paths (those
+ * come back `docName: null` and take the plain-disk-IO path).
+ *
+ * Exported for unit testing; the thread manager is its only prod caller.
+ */
+export async function confineToContentDir(
+ contentDir: string,
+ requestedPath: string,
+ isExcludedPath: (relPosix: string) => boolean,
+): Promise<{ abs: string; rel: string; docName: string | null }> {
+ const contentRoot = await realpath(contentDir);
+ const abs = normalize(
+ isAbsolute(requestedPath) ? requestedPath : resolve(contentRoot, requestedPath),
+ );
+ let existing = abs;
+ let suffix = '';
+ // Walk up to the deepest existing ancestor; realpath that, re-append the
+ // (not-yet-existing) suffix.
+ for (;;) {
+ try {
+ const real = await realpath(existing);
+ const resolved = suffix === '' ? real : join(real, suffix);
+ const rel = relative(contentRoot, resolved);
+ if (rel === '' || rel.startsWith('..') || isAbsolute(rel)) {
+ throw new Error(`path escapes the content directory: ${requestedPath}`);
+ }
+ const mdMatch = /\.(md|mdx)$/.exec(rel);
+ let docName: string | null = null;
+ if (mdMatch !== null) {
+ const candidate = rel.slice(0, -mdMatch[0].length).split(sep).join('/');
+ const relPosix = rel.split(sep).join('/');
+ if (!isSystemDoc(candidate) && !isConfigDoc(candidate) && !isExcludedPath(relPosix)) {
+ docName = candidate;
+ }
+ }
+ return { abs: resolved, rel: rel.split(sep).join('/'), docName };
+ } catch (err) {
+ if ((err as NodeJS.ErrnoException).code !== 'ENOENT') throw err;
+ const parent = dirname(existing);
+ if (parent === existing) throw err;
+ suffix =
+ suffix === ''
+ ? abs.slice(parent.length + 1)
+ : join(existing.slice(parent.length + 1), suffix);
+ existing = parent;
+ }
+ }
+}
+
+/**
+ * Build the in-memory record for a persisted thread found at boot. Always
+ * archived (any live status in the meta means the server died mid-thread);
+ * the event log stays on disk until first subscribe/resume (`logResolved:
+ * false` defers the line count, since a crash can leave the meta's `lastSeq`
+ * stale).
+ */
+function rehydratedRecord(meta: PersistedThreadMeta): ThreadRecord {
+ const status = meta.info.status === 'error' ? 'error' : 'exited';
+ return {
+ info: { ...meta.info, status, archived: true },
+ docName: meta.docName,
+ agentRef: meta.agentRef,
+ cwd: meta.cwd,
+ child: null,
+ conn: null,
+ sessionId: meta.sessionId,
+ agentSessionId: `acp-${meta.info.threadId}`,
+ events: [],
+ baseSeq: meta.info.lastSeq + 1,
+ logResolved: false,
+ logResolution: null,
+ midTurnOnDisk: false,
+ resumeInFlight: false,
+ suppressUpdates: false,
+ lastSuppressedAt: 0,
+ subscribers: new Set(),
+ pendingPermissions: new Map(),
+ pendingRuntimeConsent: new Map(),
+ stderrTail: [],
+ terminals: null,
+ turnActive: false,
+ cancelRequested: false,
+ unwatchedSince: null,
+ unwatchedCancelSent: false,
+ pendingBroadcast: [],
+ pendingBroadcastFromSeq: 0,
+ flushTimer: null,
+ closed: false,
+ // An archived thread on disk carries a transcript, so a resume-then-close
+ // without a fresh prompt must archive again, never discard. Treat every
+ // rehydrated record as having received a message.
+ hadUserMessage: true,
+ };
+}
+
+/** Error detail shown when a runtime download is declined or times out. */
+function declinedRuntimeHint(runtimeKind: ManagedRuntimeKind): string {
+ const d = describeRuntime(runtimeKind);
+ const installUrl =
+ runtimeKind === 'node'
+ ? 'https://nodejs.org'
+ : 'https://docs.astral.sh/uv/getting-started/installation/';
+ return `This agent needs \`${d.provides}\`, which isn't installed. OK can download a private copy of ${d.displayName} for you, or install ${d.displayName} yourself (${installUrl}) and it'll be used automatically.`;
+}
+
+function describeAgentError(err: unknown): string {
+ if (err instanceof Error) {
+ const data = (err as { data?: unknown }).data;
+ if (data !== undefined && data !== null) {
+ try {
+ return `${err.message} (${JSON.stringify(data).slice(0, 300)})`;
+ } catch {
+ return err.message;
+ }
+ }
+ return err.message;
+ }
+ return String(err);
+}
diff --git a/packages/server/src/acp/thread-persistence.test.ts b/packages/server/src/acp/thread-persistence.test.ts
new file mode 100644
index 000000000..d335ed690
--- /dev/null
+++ b/packages/server/src/acp/thread-persistence.test.ts
@@ -0,0 +1,148 @@
+import { appendFileSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import type { ThreadEvent, ThreadInfo } from '@inkeep/open-knowledge-core/acp/thread-protocol';
+import { afterEach, describe, expect, test } from 'vitest';
+import { getLogger } from '../logger.ts';
+import { type PersistedThreadMeta, ThreadPersistenceStore } from './thread-persistence.ts';
+
+const log = getLogger('acp-persist-test');
+
+let dirs: string[] = [];
+function tmp(): string {
+ const d = mkdtempSync(join(tmpdir(), 'acp-persist-test-'));
+ dirs.push(d);
+ return d;
+}
+afterEach(() => {
+ for (const d of dirs) rmSync(d, { recursive: true, force: true });
+ dirs = [];
+});
+
+async function makeStore(): Promise<ThreadPersistenceStore> {
+ const store = new ThreadPersistenceStore(tmp(), log);
+ await store.init();
+ return store;
+}
+
+const info = (threadId: string): ThreadInfo => ({
+ threadId,
+ agent: { id: 'a', name: 'A', source: 'custom' },
+ title: 'T',
+ status: 'exited',
+ createdAt: 1,
+ lastActivityAt: 2,
+ modes: null,
+ configOptions: null,
+ lastSeq: -1,
+ archived: true,
+});
+
+const meta = (threadId: string): PersistedThreadMeta => ({
+ version: 1,
+ info: info(threadId),
+ sessionId: 'sess-1',
+ cwd: '/tmp/x',
+ agentRef: { source: 'custom', id: 'a' },
+});
+
+const ev = (i: number): ThreadEvent => ({ kind: 'user_message', content: `m${i}`, ts: i });
+
+async function readAll(
+ store: ThreadPersistenceStore,
+ threadId: string,
+ from: number,
+ to: number,
+): Promise<Array<{ seq: number; event: ThreadEvent }>> {
+ const out: Array<{ seq: number; event: ThreadEvent }> = [];
+ await store.readEvents(threadId, from, to, (chunkFrom, events) => {
+ for (const [i, event] of events.entries()) out.push({ seq: chunkFrom + i, event });
+ });
+ return out;
+}
+
+describe('ThreadPersistenceStore', () => {
+ test('append → read round-trips with line index == seq', async () => {
+ const store = await makeStore();
+ store.appendEvents('t1', [ev(0), ev(1)]);
+ store.appendEvents('t1', [ev(2)]);
+ await store.whenIdle('t1');
+ const all = await readAll(store, 't1', 0, 100);
+ expect(all.map((e) => e.seq)).toEqual([0, 1, 2]);
+ expect(all.map((e) => (e.event.kind === 'user_message' ? e.event.content : ''))).toEqual([
+ 'm0',
+ 'm1',
+ 'm2',
+ ]);
+ // Window reads slice by seq.
+ const window = await readAll(store, 't1', 1, 2);
+ expect(window).toHaveLength(1);
+ expect(window[0]?.seq).toBe(1);
+ });
+
+ test('a torn final line (crash mid-append) is dropped, not surfaced', async () => {
+ const store = await makeStore();
+ store.appendEvents('t1', [ev(0), ev(1)]);
+ await store.whenIdle('t1');
+ appendFileSync(store.eventsPath('t1'), '{"kind":"user_message","content":"tor');
+ const resolved = await store.resolveEventLog('t1');
+ expect(resolved.count).toBe(2);
+ const all = await readAll(store, 't1', 0, 100);
+ expect(all).toHaveLength(2);
+ });
+
+ test('resolveEventLog reports a log that ends mid-turn', async () => {
+ const store = await makeStore();
+ store.appendEvents('t1', [
+ ev(0),
+ { kind: 'turn_started', ts: 1 },
+ { kind: 'turn_ended', stopReason: 'end_turn', ts: 2 },
+ { kind: 'turn_started', ts: 3 },
+ ]);
+ await store.whenIdle('t1');
+ expect((await store.resolveEventLog('t1')).midTurn).toBe(true);
+ store.appendEvents('t1', [{ kind: 'turn_ended', stopReason: 'cancelled', ts: 4 }]);
+ await store.whenIdle('t1');
+ expect((await store.resolveEventLog('t1')).midTurn).toBe(false);
+ expect((await store.resolveEventLog('missing')).count).toBe(0);
+ });
+
+ test('meta round-trips through scan; junk and unknown versions are skipped', async () => {
+ const store = await makeStore();
+ store.queueMetaWrite('t1', meta('t1'));
+ await store.whenIdle('t1');
+ // Corrupt sibling + future-version sibling must not break the scan.
+ writeFileSync(store.metaPath('junk'), 'not json');
+ writeFileSync(store.metaPath('future'), JSON.stringify({ ...meta('future'), version: 99 }));
+ const metas = await store.scan();
+ expect(metas).toHaveLength(1);
+ expect(metas[0]?.info.threadId).toBe('t1');
+ expect(metas[0]?.sessionId).toBe('sess-1');
+ expect(metas[0]?.cwd).toBe('/tmp/x');
+ });
+
+ test('an unparseable middle line is substituted, preserving later seqs', async () => {
+ const store = await makeStore();
+ store.appendEvents('t1', [ev(0)]);
+ await store.whenIdle('t1');
+ appendFileSync(store.eventsPath('t1'), 'garbage line\n');
+ store.appendEvents('t1', [ev(2)]);
+ await store.whenIdle('t1');
+ const all = await readAll(store, 't1', 0, 100);
+ expect(all.map((e) => e.seq)).toEqual([0, 1, 2]);
+ expect(all[1]?.event.kind).toBe('agent_stderr');
+ expect(all[2]?.event.kind === 'user_message' && all[2].event.content).toBe('m2');
+ });
+
+ test('delete removes both files; scan and reads go empty', async () => {
+ const store = await makeStore();
+ store.appendEvents('t1', [ev(0)]);
+ store.queueMetaWrite('t1', meta('t1'));
+ await store.whenIdle('t1');
+ expect(readFileSync(store.eventsPath('t1'), 'utf8')).toContain('m0');
+ await store.delete('t1');
+ expect(await store.scan()).toHaveLength(0);
+ expect(await readAll(store, 't1', 0, 100)).toHaveLength(0);
+ expect((await store.resolveEventLog('t1')).count).toBe(0);
+ });
+});
diff --git a/packages/server/src/acp/thread-persistence.ts b/packages/server/src/acp/thread-persistence.ts
new file mode 100644
index 000000000..71133f04e
--- /dev/null
+++ b/packages/server/src/acp/thread-persistence.ts
@@ -0,0 +1,292 @@
+/**
+ * Durable transcript storage for ACP threads — `<localDir>/threads/`.
+ *
+ * Two files per thread, both machine-local and never committed (same trust
+ * envelope as `acp-permissions.json` — transcripts embed file diffs):
+ *
+ * <threadId>.ndjson one ThreadEvent per line; LINE INDEX IS THE SEQ.
+ * Every event a thread ever appends lands here (the
+ * in-memory log keeps only a bounded window), so a
+ * subscriber can replay from seq 0 after the memory
+ * window trimmed or the record was rehydrated.
+ * <threadId>.meta.json versioned ThreadInfo snapshot + the resume envelope
+ * (sessionId, cwd, agent ref) — everything needed to
+ * list a thread at boot and `session/resume` it later.
+ *
+ * Appends ride the thread manager's 25 ms broadcast flush and are serialized
+ * per thread through a promise chain, so line order == seq order without
+ * locking. No fsync: a torn final line (crash mid-append) is detected and
+ * dropped at read time; the line-index seq contract survives because tears
+ * can only hit the tail of an append-only file.
+ */
+
+import { createReadStream, existsSync } from 'node:fs';
+import { readdir, readFile } from 'node:fs/promises';
+import { join } from 'node:path';
+import { createInterface } from 'node:readline';
+import type { ThreadEvent, ThreadInfo } from '@inkeep/open-knowledge-core/acp/thread-protocol';
+import { tracedAppendFile, tracedMkdir, tracedRm, tracedWriteFile } from '../fs-traced.ts';
+import type { PinoLogger } from '../logger.ts';
+
+const THREADS_SUBDIR = 'threads';
+const META_VERSION = 1;
+/** Events per replay chunk delivered to `onChunk` (mirrors the WS replay chunking). */
+const READ_CHUNK_SIZE = 512;
+
+export interface PersistedThreadMeta {
+ version: typeof META_VERSION;
+ info: ThreadInfo;
+ /** ACP sessionId from `session/new` — the resume handle. Null until the handshake completed. */
+ sessionId: string | null;
+ /** cwd the session was created with. Agents key their session stores by it — resume MUST pass it back verbatim. */
+ cwd: string;
+ agentRef: { source: 'registry' | 'custom'; id: string };
+ docName?: string;
+}
+
+export interface ResolvedEventLog {
+ /** Complete (newline-terminated) event lines on disk == the next seq to assign. */
+ count: number;
+ /** The log ends inside a turn (crash while streaming) — the resume path appends a synthetic `turn_ended`. */
+ midTurn: boolean;
+}
+
+export class ThreadPersistenceStore {
+ private readonly dir: string;
+ private readonly log: PinoLogger;
+ /** Per-thread write chains (events + meta) — order within a thread is the seq contract. */
+ private readonly writeQueues = new Map<string, Promise<void>>();
+ /** Threads whose appends already failed once — log once, don't spam. */
+ private readonly appendBroken = new Set<string>();
+
+ constructor(localDir: string, log: PinoLogger) {
+ this.dir = join(localDir, THREADS_SUBDIR);
+ this.log = log;
+ }
+
+ private enqueue(threadId: string, task: () => Promise<void>): void {
+ const prev = this.writeQueues.get(threadId) ?? Promise.resolve();
+ this.writeQueues.set(threadId, prev.then(task));
+ }
+
+ async init(): Promise<void> {
+ await tracedMkdir(this.dir, { recursive: true });
+ }
+
+ eventsPath(threadId: string): string {
+ return join(this.dir, `${threadId}.ndjson`);
+ }
+
+ metaPath(threadId: string): string {
+ return join(this.dir, `${threadId}.meta.json`);
+ }
+
+ /**
+ * Queue an event batch for append. Fire-and-forget by design — persistence
+ * must never stall the live broadcast path; a failed append degrades to
+ * memory-only behavior for that thread (logged once).
+ */
+ appendEvents(threadId: string, events: readonly ThreadEvent[]): void {
+ if (events.length === 0 || this.appendBroken.has(threadId)) return;
+ const lines = `${events.map((e) => JSON.stringify(e)).join('\n')}\n`;
+ this.enqueue(threadId, async () => {
+ if (this.appendBroken.has(threadId)) return;
+ try {
+ await tracedAppendFile(this.eventsPath(threadId), lines);
+ } catch (err) {
+ this.appendBroken.add(threadId);
+ this.log.error(
+ { err, threadId },
+ '[acp-persist] event append failed; thread continues memory-only',
+ );
+ }
+ });
+ }
+
+ /** Queue a metadata snapshot write, serialized behind pending appends. */
+ queueMetaWrite(threadId: string, meta: PersistedThreadMeta): void {
+ const body = `${JSON.stringify(meta, null, 1)}\n`;
+ this.enqueue(threadId, async () => {
+ try {
+ await tracedWriteFile(this.metaPath(threadId), body);
+ } catch (err) {
+ this.log.warn({ err, threadId }, '[acp-persist] meta write failed');
+ }
+ });
+ }
+
+ /** Resolve once every queued write for the thread has hit disk. */
+ whenIdle(threadId: string): Promise<void> {
+ return this.writeQueues.get(threadId) ?? Promise.resolve();
+ }
+
+ /**
+ * List every persisted thread's metadata. Metadata only — event logs load
+ * lazily on first subscribe/resume, so boot cost is O(#threads) small-file
+ * reads. Unreadable or unknown-version files are skipped with a log line,
+ * never a boot failure.
+ */
+ async scan(): Promise<PersistedThreadMeta[]> {
+ let names: string[];
+ try {
+ names = await readdir(this.dir);
+ } catch {
+ return [];
+ }
+ const metas: PersistedThreadMeta[] = [];
+ for (const name of names) {
+ if (!name.endsWith('.meta.json')) continue;
+ const path = join(this.dir, name);
+ try {
+ const parsed = JSON.parse(await readFile(path, 'utf8')) as Partial<PersistedThreadMeta>;
+ if (
+ parsed.version !== META_VERSION ||
+ typeof parsed.info !== 'object' ||
+ parsed.info === null ||
+ typeof parsed.info.threadId !== 'string' ||
+ typeof parsed.cwd !== 'string' ||
+ typeof parsed.agentRef !== 'object' ||
+ parsed.agentRef === null
+ ) {
+ this.log.warn({ path }, '[acp-persist] skipping unreadable thread meta');
+ continue;
+ }
+ metas.push(parsed as PersistedThreadMeta);
+ } catch (err) {
+ this.log.warn({ err, path }, '[acp-persist] skipping unreadable thread meta');
+ }
+ }
+ return metas;
+ }
+
+ /**
+ * Count the complete event lines on disk (== next seq) and whether the log
+ * ends mid-turn. Streams without parsing: complete lines are exactly the
+ * newline-terminated ones, and turn markers are recognized by their stable
+ * serialized prefix (`kind` is always the first key we write).
+ */
+ async resolveEventLog(threadId: string): Promise<ResolvedEventLog> {
+ const path = this.eventsPath(threadId);
+ if (!existsSync(path)) return { count: 0, midTurn: false };
+ let count = 0;
+ let midTurn = false;
+ await this.forEachCompleteLine(path, (line) => {
+ count += 1;
+ if (line.startsWith('{"kind":"turn_started"')) midTurn = true;
+ else if (line.startsWith('{"kind":"turn_ended"')) midTurn = false;
+ return true;
+ });
+ return { count, midTurn };
+ }
+
+ /**
+ * Replay persisted events for seqs `[fromSeq, toSeqExclusive)` in chunks.
+ * Lines that fail to parse mid-file (should never happen in an append-only
+ * log) are substituted with a harmless placeholder rather than skipped —
+ * skipping would shift every later line off its seq.
+ */
+ async readEvents(
+ threadId: string,
+ fromSeq: number,
+ toSeqExclusive: number,
+ onChunk: (chunkFromSeq: number, events: ThreadEvent[]) => void,
+ ): Promise<void> {
+ const path = this.eventsPath(threadId);
+ if (fromSeq >= toSeqExclusive || !existsSync(path)) return;
+ let seq = 0;
+ let chunk: ThreadEvent[] = [];
+ let chunkFrom = fromSeq;
+ const flush = (): void => {
+ if (chunk.length === 0) return;
+ onChunk(chunkFrom, chunk);
+ chunkFrom += chunk.length;
+ chunk = [];
+ };
+ await this.forEachCompleteLine(path, (line) => {
+ if (seq >= toSeqExclusive) return false;
+ if (seq >= fromSeq) {
+ chunk.push(parseEventLine(line));
+ if (chunk.length >= READ_CHUNK_SIZE) flush();
+ }
+ seq += 1;
+ return true;
+ });
+ flush();
+ }
+
+ async delete(threadId: string): Promise<void> {
+ this.appendBroken.delete(threadId);
+ this.writeQueues.delete(threadId);
+ await tracedRm(this.eventsPath(threadId), { force: true });
+ await tracedRm(this.metaPath(threadId), { force: true });
+ }
+
+ /**
+ * Iterate newline-TERMINATED lines only: readline emits a trailing line
+ * without `\n` too, so the callback is buffered one line behind and the
+ * final unterminated fragment (a torn append) never reaches it.
+ */
+ private async forEachCompleteLine(
+ path: string,
+ onLine: (line: string) => boolean,
+ ): Promise<void> {
+ const stream = createReadStream(path, { encoding: 'utf8' });
+ // readline does not forward every input-stream error to its async
+ // iterator — one emitted between pulls (file deleted mid-read by a
+ // concurrent `delete()`, EIO) lands as an uncaught 'error' event on the
+ // stream and would crash the process. Capture it here and rethrow below
+ // so callers see a rejected op instead.
+ let streamError: Error | null = null;
+ stream.on('error', (err) => {
+ streamError = err;
+ });
+ const rl = createInterface({ input: stream, crlfDelay: Number.POSITIVE_INFINITY });
+ let endedWithNewline = false;
+ let pending: string | null = null;
+ let stopped = false;
+ try {
+ for await (const line of rl) {
+ if (pending !== null && !onLine(pending)) {
+ stopped = true;
+ break;
+ }
+ pending = line;
+ }
+ if (!stopped) {
+ // Whether the LAST line was complete needs the raw tail byte —
+ // readline can't tell. Cheap check: the stream already ended; peek
+ // via the stream's recorded bytes is gone, so re-read the final byte.
+ endedWithNewline = await fileEndsWithNewline(path);
+ if (pending !== null && endedWithNewline) onLine(pending);
+ }
+ } finally {
+ rl.close();
+ stream.destroy();
+ }
+ // Checked on BOTH exits (exhausted and early-stop) — a partial read that
+ // raced a stream error must read as failed, not as a clean prefix.
+ if (streamError !== null) throw streamError;
+ }
+}
+
+async function fileEndsWithNewline(path: string): Promise<boolean> {
+ const { open } = await import('node:fs/promises');
+ const handle = await open(path, 'r');
+ try {
+ const { size } = await handle.stat();
+ if (size === 0) return false;
+ const buf = Buffer.alloc(1);
+ await handle.read(buf, 0, 1, size - 1);
+ return buf[0] === 0x0a;
+ } finally {
+ await handle.close();
+ }
+}
+
+function parseEventLine(line: string): ThreadEvent {
+ try {
+ return JSON.parse(line) as ThreadEvent;
+ } catch {
+ return { kind: 'agent_stderr', line: '[unreadable log entry]', ts: 0 };
+ }
+}
diff --git a/packages/server/src/acp/thread-socket.test.ts b/packages/server/src/acp/thread-socket.test.ts
new file mode 100644
index 000000000..d65b8e140
--- /dev/null
+++ b/packages/server/src/acp/thread-socket.test.ts
@@ -0,0 +1,369 @@
+/**
+ * Frame-level coverage of the `/collab/thread` socket for the history ops:
+ * `resume` (success → `resumed` frame; failure → error frame carrying the
+ * reqId + `resume-unsupported`), `delete` (refused live / applied archived,
+ * followed by a refreshed `threads` list), `rename` (live + archived, manual
+ * title wins over first-prompt adoption), and archived `subscribe` replay
+ * through the socket's async path.
+ */
+
+import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import type { ThreadServerFrame } from '@inkeep/open-knowledge-core/acp/thread-protocol';
+import { afterEach, describe, expect, test } from 'vitest';
+import type { AgentSessionManager } from '../agent-sessions.ts';
+import { getLogger } from '../logger.ts';
+import { AcpPermissionStore } from './permissions.ts';
+import { AcpRegistry } from './registry.ts';
+import { AcpThreadManager } from './thread-manager.ts';
+import { attachAcpThreadSocket } from './thread-socket.ts';
+
+const log = getLogger('acp-thread-socket-test');
+
+const fakeSessionManager = {
+ getSession: async () => {
+ throw new Error('fixture agents never use client fs');
+ },
+ closeAllForAgent: async () => {},
+} as unknown as AgentSessionManager;
+
+let dirs: string[] = [];
+let managers: AcpThreadManager[] = [];
+function tmp(): string {
+ const d = mkdtempSync(join(tmpdir(), 'acp-socket-test-'));
+ dirs.push(d);
+ return d;
+}
+afterEach(async () => {
+ await Promise.allSettled(managers.map((m) => m.destroy()));
+ managers = [];
+ for (const d of dirs) rmSync(d, { recursive: true, force: true });
+ dirs = [];
+});
+
+/** Same minimal capability-matrix agent as the manager integration suite. */
+function writeFixtureAgent(localDir: string, caps: string): void {
+ const agentPath = join(localDir, 'fixture-agent.mjs');
+ writeFileSync(
+ agentPath,
+ `
+const caps = (process.env.FAKE_CAPS ?? '').split(',').filter(Boolean);
+const write = (msg) => process.stdout.write(JSON.stringify(msg) + '\\n');
+let buffer = '';
+process.stdin.setEncoding('utf8');
+process.stdin.on('data', (chunk) => {
+ buffer += chunk;
+ let idx = buffer.indexOf('\\n');
+ while (idx !== -1) {
+ const line = buffer.slice(0, idx);
+ buffer = buffer.slice(idx + 1);
+ idx = buffer.indexOf('\\n');
+ if (line.trim() === '') continue;
+ const msg = JSON.parse(line);
+ const reply = (result) => write({ jsonrpc: '2.0', id: msg.id, result });
+ if (msg.method === 'initialize') {
+ const agentCapabilities = {};
+ if (caps.includes('resume')) agentCapabilities.sessionCapabilities = { resume: {} };
+ reply({ protocolVersion: 1, agentCapabilities });
+ } else if (msg.method === 'session/new') {
+ reply({ sessionId: 'sess-fixed' });
+ } else if (msg.method === 'session/prompt') {
+ reply({ stopReason: 'end_turn' });
+ } else if (msg.method === 'session/resume') {
+ reply({});
+ } else if (msg.id !== undefined) {
+ reply({});
+ }
+ }
+});
+`,
+ );
+ writeFileSync(
+ join(localDir, 'acp-agents.json'),
+ JSON.stringify([
+ {
+ id: 'fixture',
+ name: 'Fixture',
+ command: 'node',
+ args: [agentPath],
+ env: { FAKE_CAPS: caps },
+ },
+ ]),
+ );
+}
+
+interface FakeSocket {
+ frames: ThreadServerFrame[];
+ emit(raw: string): void;
+ close(): void;
+ awaitFrame<T extends ThreadServerFrame['op']>(
+ op: T,
+ ms?: number,
+ ): Promise<Extract<ThreadServerFrame, { op: T }>>;
+}
+
+function attachFakeSocket(manager: AcpThreadManager): FakeSocket {
+ const frames: ThreadServerFrame[] = [];
+ const listeners = new Map<string, Array<(...args: unknown[]) => void>>();
+ const ws = {
+ send(data: string) {
+ frames.push(JSON.parse(data) as ThreadServerFrame);
+ },
+ close() {},
+ on(event: string, listener: (...args: unknown[]) => void) {
+ const list = listeners.get(event) ?? [];
+ list.push(listener);
+ listeners.set(event, list);
+ },
+ };
+ attachAcpThreadSocket(ws, manager, log);
+ return {
+ frames,
+ emit: (raw) => {
+ for (const l of listeners.get('message') ?? []) l(raw);
+ },
+ close: () => {
+ for (const l of listeners.get('close') ?? []) l();
+ },
+ awaitFrame: async (op, ms = 20_000) => {
+ const deadline = Date.now() + ms;
+ let cursor = 0;
+ for (;;) {
+ for (; cursor < frames.length; cursor++) {
+ const frame = frames[cursor];
+ if (frame.op === op) {
+ cursor++;
+ // biome-ignore lint/suspicious/noExplicitAny: op-narrowed by the guard above
+ return frame as any;
+ }
+ }
+ if (Date.now() > deadline) {
+ throw new Error(`no '${op}' frame; saw: ${frames.map((f) => f.op).join(',')}`);
+ }
+ await new Promise((r) => setTimeout(r, 25));
+ }
+ },
+ };
+}
+
+function makeManager(contentDir: string, localDir: string): AcpThreadManager {
+ const manager = new AcpThreadManager({
+ contentDir,
+ localDir,
+ registry: new AcpRegistry({
+ localDir,
+ log,
+ fetchImpl: (async () => {
+ throw new Error('offline test');
+ }) as typeof fetch,
+ }),
+ permissions: new AcpPermissionStore(localDir, log),
+ sessionManager: fakeSessionManager,
+ isExcludedPath: () => false,
+ isIgnoredPath: () => false,
+ log,
+ });
+ managers.push(manager);
+ return manager;
+}
+
+async function waitStatus(
+ manager: AcpThreadManager,
+ threadId: string,
+ status: string,
+ ms = 15_000,
+): Promise<void> {
+ const deadline = Date.now() + ms;
+ while (manager.getInfo(threadId)?.status !== status) {
+ if (Date.now() > deadline) {
+ throw new Error(`status never became ${status}: ${manager.getInfo(threadId)?.status}`);
+ }
+ await new Promise((r) => setTimeout(r, 25));
+ }
+}
+
+describe('/collab/thread socket — history ops', () => {
+ test('resume round-trips as a resumed frame; delete refuses live and applies archived', async () => {
+ const localDir = tmp();
+ writeFixtureAgent(localDir, 'resume');
+ const manager = makeManager(tmp(), localDir);
+ await manager.init();
+ const socket = attachFakeSocket(manager);
+
+ socket.emit(
+ JSON.stringify({ op: 'create', reqId: 'c1', agent: { source: 'custom', id: 'fixture' } }),
+ );
+ const created = await socket.awaitFrame('created');
+ const threadId = created.info.threadId;
+ await waitStatus(manager, threadId, 'ready');
+
+ // A real message makes it a conversation worth keeping — an untouched
+ // thread is discarded on close, never archived.
+ socket.emit(JSON.stringify({ op: 'prompt', threadId, reqId: 'p0', content: 'hello' }));
+ await waitStatus(manager, threadId, 'ready');
+
+ // Delete on a live thread → not-ready error, thread intact.
+ socket.emit(JSON.stringify({ op: 'delete', threadId }));
+ const err1 = await socket.awaitFrame('error');
+ expect(err1.code).toBe('not-ready');
+ expect(manager.getInfo(threadId)).toBeDefined();
+
+ socket.emit(JSON.stringify({ op: 'close', threadId }));
+ const threadsAfterClose = await socket.awaitFrame('threads');
+ expect(threadsAfterClose.threads[0]?.archived).toBe(true);
+
+ // Reopen the archived thread the way the client does (history open =
+ // subscribe), then resume through the socket: the resumed frame carries
+ // the reqId + live info.
+ socket.emit(JSON.stringify({ op: 'subscribe', threadId, sinceSeq: 0 }));
+ await socket.awaitFrame('subscribed');
+ socket.emit(JSON.stringify({ op: 'resume', threadId, reqId: 'r1', prompt: 'go' }));
+ const resumed = await socket.awaitFrame('resumed');
+ expect(resumed.reqId).toBe('r1');
+ expect(resumed.info.archived).toBe(false);
+ // Optimistic echo: the carried prompt reached subscribers as a
+ // user_message BEFORE the handshake finished (the resumed frame) — the
+ // transcript never sits empty while the agent respawns.
+ const resumedAt = socket.frames.indexOf(resumed);
+ const echoAt = socket.frames.findIndex(
+ (f) =>
+ f.op === 'events' && f.events.some((e) => e.kind === 'user_message' && e.content === 'go'),
+ );
+ expect(echoAt).toBeGreaterThanOrEqual(0);
+ expect(echoAt).toBeLessThan(resumedAt);
+ await waitStatus(manager, threadId, 'ready');
+
+ // Archive again, then delete for real: threads list refresh excludes it.
+ socket.emit(JSON.stringify({ op: 'close', threadId }));
+ await waitStatus(manager, threadId, 'exited');
+ socket.emit(JSON.stringify({ op: 'delete', threadId }));
+ const deadline = Date.now() + 10_000;
+ for (;;) {
+ const listFrames = socket.frames.filter(
+ (f): f is Extract<ThreadServerFrame, { op: 'threads' }> => f.op === 'threads',
+ );
+ const last = listFrames[listFrames.length - 1];
+ if (listFrames.length >= 2 && last?.threads.length === 0) break;
+ if (Date.now() > deadline) throw new Error('delete never refreshed the list');
+ await new Promise((r) => setTimeout(r, 25));
+ }
+ socket.close();
+ }, 45_000);
+
+ test('resume-unsupported surfaces as an error frame with the reqId', async () => {
+ const localDir = tmp();
+ writeFixtureAgent(localDir, '');
+ const manager = makeManager(tmp(), localDir);
+ await manager.init();
+ const socket = attachFakeSocket(manager);
+
+ socket.emit(
+ JSON.stringify({ op: 'create', reqId: 'c1', agent: { source: 'custom', id: 'fixture' } }),
+ );
+ const created = await socket.awaitFrame('created');
+ const threadId = created.info.threadId;
+ await waitStatus(manager, threadId, 'ready');
+ // A real message so close archives it (an untouched thread is discarded).
+ socket.emit(JSON.stringify({ op: 'prompt', threadId, reqId: 'p0', content: 'hello' }));
+ await waitStatus(manager, threadId, 'ready');
+ socket.emit(JSON.stringify({ op: 'close', threadId }));
+ await waitStatus(manager, threadId, 'exited');
+
+ socket.emit(JSON.stringify({ op: 'resume', threadId, reqId: 'r9' }));
+ const err = await socket.awaitFrame('error');
+ expect(err.code).toBe('resume-unsupported');
+ expect(err.reqId).toBe('r9');
+ expect(manager.getInfo(threadId)?.archived).toBe(true);
+ socket.close();
+ }, 45_000);
+
+ test('rename round-trips live and archived; a manual title survives first-prompt adoption', async () => {
+ const localDir = tmp();
+ writeFixtureAgent(localDir, '');
+ const manager = makeManager(tmp(), localDir);
+ await manager.init();
+ const socket = attachFakeSocket(manager);
+
+ socket.emit(
+ JSON.stringify({ op: 'create', reqId: 'c1', agent: { source: 'custom', id: 'fixture' } }),
+ );
+ const created = await socket.awaitFrame('created');
+ const threadId = created.info.threadId;
+ await waitStatus(manager, threadId, 'ready');
+
+ // Live rename → confirmed via an info frame carrying the new title.
+ socket.emit(JSON.stringify({ op: 'rename', threadId, title: 'Roadmap rewrite' }));
+ const deadline = Date.now() + 10_000;
+ while (manager.getInfo(threadId)?.title !== 'Roadmap rewrite') {
+ if (Date.now() > deadline) throw new Error('rename never applied');
+ await new Promise((r) => setTimeout(r, 25));
+ }
+ const infoFrames = socket.frames.filter(
+ (f): f is Extract<ThreadServerFrame, { op: 'info' }> => f.op === 'info',
+ );
+ expect(infoFrames.some((f) => f.info.title === 'Roadmap rewrite')).toBe(true);
+
+ // First-prompt title adoption must NOT clobber the manual title.
+ socket.emit(JSON.stringify({ op: 'prompt', threadId, reqId: 'p1', content: 'do the thing' }));
+ await waitStatus(manager, threadId, 'ready');
+ expect(manager.getInfo(threadId)?.title).toBe('Roadmap rewrite');
+
+ // Renames apply to archived threads too (the history menu keeps them).
+ socket.emit(JSON.stringify({ op: 'close', threadId }));
+ await waitStatus(manager, threadId, 'exited');
+ socket.emit(JSON.stringify({ op: 'rename', threadId, title: 'Archived and renamed' }));
+ const deadline2 = Date.now() + 10_000;
+ while (manager.getInfo(threadId)?.title !== 'Archived and renamed') {
+ if (Date.now() > deadline2) throw new Error('archived rename never applied');
+ await new Promise((r) => setTimeout(r, 25));
+ }
+ expect(manager.getInfo(threadId)?.archived).toBe(true);
+
+ // Unknown thread → error frame, no crash.
+ socket.emit(JSON.stringify({ op: 'rename', threadId: 'nope', title: 'x' }));
+ const err = await socket.awaitFrame('error');
+ expect(err.code).toBe('unknown-thread');
+ socket.close();
+ }, 45_000);
+
+ test('archived subscribe replays the transcript through the socket', async () => {
+ const localDir = tmp();
+ writeFixtureAgent(localDir, 'resume');
+ const manager = makeManager(tmp(), localDir);
+ await manager.init();
+ const socket = attachFakeSocket(manager);
+
+ socket.emit(
+ JSON.stringify({
+ op: 'create',
+ reqId: 'c1',
+ agent: { source: 'custom', id: 'fixture' },
+ prompt: 'hello world',
+ }),
+ );
+ const created = await socket.awaitFrame('created');
+ const threadId = created.info.threadId;
+ await waitStatus(manager, threadId, 'ready');
+ socket.emit(JSON.stringify({ op: 'close', threadId }));
+ await waitStatus(manager, threadId, 'exited');
+
+ // A SECOND socket (fresh client) subscribes to the archived thread.
+ const viewer = attachFakeSocket(manager);
+ viewer.emit(JSON.stringify({ op: 'subscribe', threadId, sinceSeq: 0 }));
+ await viewer.awaitFrame('subscribed');
+ const events = await viewer.awaitFrame('events');
+ expect(events.fromSeq).toBe(0);
+ const deadline = Date.now() + 10_000;
+ for (;;) {
+ const all = viewer.frames
+ .filter((f): f is Extract<ThreadServerFrame, { op: 'events' }> => f.op === 'events')
+ .flatMap((f) => f.events);
+ if (all.some((e) => e.kind === 'user_message' && e.content === 'hello world')) break;
+ if (Date.now() > deadline) throw new Error('replay never delivered the user message');
+ await new Promise((r) => setTimeout(r, 25));
+ }
+ socket.close();
+ viewer.close();
+ }, 45_000);
+});
diff --git a/packages/server/src/acp/thread-socket.ts b/packages/server/src/acp/thread-socket.ts
new file mode 100644
index 000000000..db2c16e1e
--- /dev/null
+++ b/packages/server/src/acp/thread-socket.ts
@@ -0,0 +1,215 @@
+/**
+ * `/collab/thread` WebSocket — frame routing between one connected client
+ * and the `AcpThreadManager`.
+ *
+ * The socket carries the wire protocol defined in core's
+ * `acp/thread-protocol.ts`: structured JSON frames both ways, with
+ * per-thread event replay driven by `subscribe { sinceSeq }`. Gating
+ * (loopback + workspace-host) happens at the upgrade site in
+ * `mcp-mount.ts` / the dev Vite plugin — by the time this module sees a
+ * socket it is trusted to the same level as the mutating HTTP surface.
+ */
+
+import type { ThreadServerFrame } from '@inkeep/open-knowledge-core/acp/thread-protocol';
+import { parseThreadClientFrame } from '@inkeep/open-knowledge-core/acp/thread-protocol';
+import type { PinoLogger } from '../logger.ts';
+import { type AcpThreadManager, ThreadOpError } from './thread-manager.ts';
+
+/** Minimal structural WS shape (matches `ws`'s WebSocket where we need it). */
+interface ThreadSocket {
+ send(data: string): void;
+ close(code?: number, reason?: string): void;
+ on(event: 'message', listener: (data: unknown) => void): void;
+ on(event: 'close', listener: () => void): void;
+ on(event: 'error', listener: (err: Error) => void): void;
+}
+
+export function attachAcpThreadSocket(
+ ws: ThreadSocket,
+ manager: AcpThreadManager,
+ log: PinoLogger,
+): void {
+ const subscriptions = new Map<string, (frame: ThreadServerFrame) => void>();
+
+ const send = (frame: ThreadServerFrame): void => {
+ try {
+ ws.send(JSON.stringify(frame));
+ } catch (err) {
+ log.warn({ err }, '[acp-thread-socket] send failed');
+ }
+ };
+
+ const sendError = (
+ code: Parameters<typeof errorFrame>[0],
+ message: string,
+ extra?: { reqId?: string; threadId?: string },
+ ): void => send(errorFrame(code, message, extra));
+
+ ws.on('message', (data) => {
+ const raw =
+ typeof data === 'string' ? data : Buffer.isBuffer(data) ? data.toString('utf8') : '';
+ const frame = parseThreadClientFrame(raw);
+ if (frame === null) {
+ sendError('bad-frame', 'unrecognized frame');
+ return;
+ }
+ void (async () => {
+ try {
+ switch (frame.op) {
+ case 'list': {
+ send({ op: 'threads', threads: manager.listThreads() });
+ return;
+ }
+ case 'create': {
+ const info = await manager.createThread({
+ agent: frame.agent,
+ prompt: frame.prompt,
+ docName: frame.docName,
+ titleHint: frame.titleHint,
+ });
+ send({ op: 'created', reqId: frame.reqId, info });
+ // Creating implies interest: auto-subscribe from the beginning
+ // so the creator renders the spawn/handshake status events.
+ await subscribeTo(info.threadId, 0);
+ return;
+ }
+ case 'subscribe': {
+ await subscribeTo(frame.threadId, frame.sinceSeq ?? 0);
+ return;
+ }
+ case 'resume': {
+ const info = await manager.resumeThread(frame.threadId, frame.prompt);
+ send({ op: 'resumed', reqId: frame.reqId, info });
+ // Resuming implies interest, same as create. Usually a no-op —
+ // the client opened (and subscribed to) the archived tab first.
+ await subscribeTo(frame.threadId, 0);
+ return;
+ }
+ case 'delete': {
+ const sink = subscriptions.get(frame.threadId);
+ if (sink !== undefined) {
+ manager.unsubscribe(frame.threadId, sink);
+ subscriptions.delete(frame.threadId);
+ }
+ await manager.deleteThread(frame.threadId);
+ send({ op: 'threads', threads: manager.listThreads() });
+ return;
+ }
+ case 'unsubscribe': {
+ const sink = subscriptions.get(frame.threadId);
+ if (sink !== undefined) {
+ manager.unsubscribe(frame.threadId, sink);
+ subscriptions.delete(frame.threadId);
+ }
+ return;
+ }
+ case 'prompt': {
+ manager.sendPrompt(frame.threadId, frame.content);
+ return;
+ }
+ case 'permission_response': {
+ manager.respondPermission(frame.threadId, frame.requestId, frame.outcome);
+ return;
+ }
+ case 'runtime_consent_response': {
+ manager.respondRuntimeConsent(frame.threadId, frame.requestId, frame.outcome);
+ return;
+ }
+ case 'cancel': {
+ manager.cancel(frame.threadId);
+ return;
+ }
+ case 'set_mode': {
+ manager.setMode(frame.threadId, frame.modeId);
+ return;
+ }
+ case 'rename': {
+ await manager.renameThread(frame.threadId, frame.title);
+ return;
+ }
+ case 'set_config_option': {
+ manager.setConfigOption(frame.threadId, frame.configId, frame.value);
+ return;
+ }
+ case 'close': {
+ const sink = subscriptions.get(frame.threadId);
+ if (sink !== undefined) {
+ manager.unsubscribe(frame.threadId, sink);
+ subscriptions.delete(frame.threadId);
+ }
+ await manager.closeThread(frame.threadId);
+ send({ op: 'threads', threads: manager.listThreads() });
+ return;
+ }
+ }
+ } catch (err) {
+ if (err instanceof ThreadOpError) {
+ sendError(err.code, err.message, {
+ reqId: 'reqId' in frame ? frame.reqId : undefined,
+ threadId: 'threadId' in frame ? frame.threadId : undefined,
+ });
+ } else {
+ log.error({ err, op: frame.op }, '[acp-thread-socket] frame handling failed');
+ sendError('internal', 'internal error', {
+ reqId: 'reqId' in frame ? (frame as { reqId?: string }).reqId : undefined,
+ });
+ }
+ }
+ })();
+ });
+
+ const subscribeTo = async (threadId: string, sinceSeq: number): Promise<void> => {
+ if (subscriptions.has(threadId)) return;
+ const sink = (frame: ThreadServerFrame): void => send(frame);
+ // Claim the slot BEFORE the async replay so a racing second subscribe
+ // for the same thread no-ops instead of double-attaching.
+ subscriptions.set(threadId, sink);
+ try {
+ // Replay happens inside subscribe() through the sink, AFTER the
+ // subscribed frame below has announced the replay window start.
+ const info = manager.getInfo(threadId);
+ if (info === undefined) {
+ subscriptions.delete(threadId);
+ sendError('unknown-thread', `no thread '${threadId}'`, { threadId });
+ return;
+ }
+ send({ op: 'subscribed', threadId, fromSeq: Math.max(sinceSeq, 0), info });
+ await manager.subscribe(threadId, sinceSeq, sink);
+ } catch (err) {
+ subscriptions.delete(threadId);
+ if (err instanceof ThreadOpError) {
+ sendError(err.code, err.message, { threadId });
+ } else {
+ throw err;
+ }
+ }
+ };
+
+ ws.on('close', () => {
+ for (const [threadId, sink] of subscriptions) {
+ manager.unsubscribe(threadId, sink);
+ }
+ subscriptions.clear();
+ });
+ ws.on('error', (err) => {
+ log.warn({ err }, '[acp-thread-socket] socket error');
+ });
+}
+
+function errorFrame(
+ code:
+ | 'bad-frame'
+ | 'unknown-thread'
+ | 'unknown-agent'
+ | 'capacity'
+ | 'spawn-failed'
+ | 'install-failed'
+ | 'agent-error'
+ | 'not-ready'
+ | 'resume-unsupported'
+ | 'internal',
+ message: string,
+ extra?: { reqId?: string; threadId?: string },
+): ThreadServerFrame {
+ return { op: 'error', code, message, ...extra };
+}
diff --git a/packages/server/src/acp/thread-title.test.ts b/packages/server/src/acp/thread-title.test.ts
new file mode 100644
index 000000000..6427cabfc
--- /dev/null
+++ b/packages/server/src/acp/thread-title.test.ts
@@ -0,0 +1,85 @@
+import { describe, expect, test } from 'vitest';
+import { clampThreadTitle, deriveThreadTitle, TITLE_MAX_CHARS } from './thread-title.ts';
+
+describe('deriveThreadTitle', () => {
+ test('passes a plain imperative line through unchanged', () => {
+ expect(deriveThreadTitle('Fix the login bug')).toBe('Fix the login bug');
+ });
+
+ test('strips a single filler prefix and recapitalizes', () => {
+ expect(deriveThreadTitle('please update the roadmap doc')).toBe('Update the roadmap doc');
+ expect(deriveThreadTitle('can you add tests for the parser')).toBe('Add tests for the parser');
+ });
+
+ test('strips stacked filler ("hey, can you please take a look at …")', () => {
+ expect(deriveThreadTitle('hey, can you please take a look at the pricing page copy')).toBe(
+ 'The pricing page copy',
+ );
+ });
+
+ test('keeps the raw line when stripping leaves a stub', () => {
+ // "there" alone is not a title — greeting-ish prompts degrade gracefully.
+ expect(deriveThreadTitle('hello there')).toBe('hello there');
+ expect(deriveThreadTitle('hey can you')).toBe('hey can you');
+ });
+
+ test('adopts a two-word remainder', () => {
+ expect(deriveThreadTitle('please fix bug')).toBe('Fix bug');
+ });
+
+ test('does not strip bare aux verbs that carry meaning', () => {
+ expect(deriveThreadTitle('Will this break the release build?')).toBe(
+ 'Will this break the release build?',
+ );
+ });
+
+ test('drops markdown lead-in', () => {
+ expect(deriveThreadTitle('## Update the changelog')).toBe('Update the changelog');
+ expect(deriveThreadTitle('- please rename the folder structure')).toBe(
+ 'Rename the folder structure',
+ );
+ });
+
+ test('uses only the first non-empty line', () => {
+ expect(deriveThreadTitle('\n\nplease review this diff\nwith lots of context below')).toBe(
+ 'Review this diff',
+ );
+ });
+
+ test('non-English prompts pass through untouched', () => {
+ expect(deriveThreadTitle('actualiza la hoja de ruta por favor')).toBe(
+ 'actualiza la hoja de ruta por favor',
+ );
+ });
+
+ test('clamps long results at a word boundary with an ellipsis', () => {
+ const derived = deriveThreadTitle(
+ 'please update the roadmap document with the newly agreed quarterly milestones',
+ );
+ expect(derived.length).toBeLessThanOrEqual(TITLE_MAX_CHARS);
+ expect(derived.endsWith('…')).toBe(true);
+ expect(derived).toBe('Update the roadmap document with the newly…');
+ });
+});
+
+describe('clampThreadTitle', () => {
+ test('returns blank input as empty string', () => {
+ expect(clampThreadTitle('')).toBe('');
+ expect(clampThreadTitle(' \n ')).toBe('');
+ });
+
+ test('keeps short titles verbatim — no stripping, no recapitalization', () => {
+ expect(clampThreadTitle('please my weird title')).toBe('please my weird title');
+ });
+
+ test('takes the first line of multi-line input', () => {
+ expect(clampThreadTitle('first line\nsecond line')).toBe('first line');
+ });
+
+ test('hard-cuts a single long word when no word boundary is usable', () => {
+ const word = 'x'.repeat(80);
+ const clamped = clampThreadTitle(word);
+ expect(clamped.length).toBe(TITLE_MAX_CHARS);
+ expect(clamped.endsWith('…')).toBe(true);
+ });
+});
diff --git a/packages/server/src/acp/thread-title.ts b/packages/server/src/acp/thread-title.ts
new file mode 100644
index 000000000..90d489080
--- /dev/null
+++ b/packages/server/src/acp/thread-title.ts
@@ -0,0 +1,125 @@
+/**
+ * Thread-title derivation for the ACP dock.
+ *
+ * Tab labels get ~160px, so the first words of a prompt ARE the title in
+ * practice — and real prompts overwhelmingly open with the same filler
+ * ("please", "can you", "hey, could you take a look at…"), which made every
+ * tab read identically. `deriveThreadTitle` strips that shared lead-in so the
+ * distinguishing words surface first, and falls back to the raw line whenever
+ * stripping would leave a stub too short to stand as a title.
+ *
+ * Heuristics are English-only by design: a non-matching prompt passes through
+ * unchanged, so other languages simply keep today's behavior. The manual
+ * escape hatch is the `rename` op (tab double-click), which routes through
+ * `clampThreadTitle` without any stripping.
+ */
+
+export const TITLE_MAX_CHARS = 48;
+
+/**
+ * Leading filler a prompt's first line may open with, longest-first so
+ * multi-word frames win over their single-word prefixes ("can you" before
+ * "can" — bare aux verbs are deliberately absent so questions like "Will this
+ * break X?" keep their meaning).
+ */
+const FILLER_PREFIXES = [
+ 'do you mind',
+ 'i would like you to',
+ "i'd like you to",
+ 'i want you to',
+ 'i need you to',
+ 'i would like to',
+ "i'd like to",
+ 'i want to',
+ 'i need to',
+ 'we need to',
+ 'we want to',
+ 'we should',
+ 'go ahead and',
+ 'take a look at',
+ 'have a look at',
+ 'look into',
+ 'look at',
+ 'help me with',
+ 'help me to',
+ 'help me',
+ 'can you',
+ 'could you',
+ 'would you',
+ 'will you',
+ 'can we',
+ 'could we',
+ 'should we',
+ "let's",
+ 'lets',
+ 'try to',
+ 'please',
+ 'kindly',
+ 'hello',
+ 'alright',
+ 'actually',
+ 'anyway',
+ 'also',
+ 'okay',
+ 'hey',
+ 'hi',
+ 'yo',
+ 'ok',
+ 'so',
+ 'pls',
+ 'plz',
+ 'just',
+ 'maybe',
+];
+
+const FILLER_RE = new RegExp(
+ `^(?:${FILLER_PREFIXES.map((p) => p.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')).join('|')})\\b(?:[\\s,:;!.\\-–—]+|$)`,
+ 'i',
+);
+
+/** Markdown lead-in on a prompt's first line: headings, quotes, list markers. */
+const MARKDOWN_LEAD_RE = /^(?:[#>]+\s*|[-*]\s+|\d+[.)]\s+)+/;
+
+/** Guard against a pathological prefix chain; real prompts stack 2-3 deep. */
+const MAX_STRIP_PASSES = 6;
+
+function firstLine(raw: string): string {
+ return (raw.trim().split('\n')[0] ?? '').trim();
+}
+
+/**
+ * Clamp arbitrary text to a single ≤48-char title line, ellipsizing at a word
+ * boundary when one falls in the back half. Returns `''` for blank input.
+ * This is the whole pipeline for MANUAL titles (the `rename` op) — user text
+ * is never stripped or re-capitalized.
+ */
+export function clampThreadTitle(raw: string): string {
+ const line = firstLine(raw);
+ if (line.length <= TITLE_MAX_CHARS) return line;
+ const hard = line.slice(0, TITLE_MAX_CHARS - 1);
+ const lastSpace = hard.lastIndexOf(' ');
+ const cut = lastSpace >= TITLE_MAX_CHARS / 2 ? hard.slice(0, lastSpace) : hard;
+ return `${cut.trimEnd()}…`;
+}
+
+/**
+ * Derive a tab title from a thread's first prompt: drop the markdown/filler
+ * lead-in, keep the words that distinguish this thread. Stripping is only
+ * adopted when the remainder still reads as a title (two-plus words, or one
+ * long one) — otherwise the raw first line passes through untouched, so
+ * greeting-only prompts and non-English prompts degrade to today's behavior.
+ */
+export function deriveThreadTitle(prompt: string): string {
+ const line = firstLine(prompt);
+ let stripped = line.replace(MARKDOWN_LEAD_RE, '');
+ for (let pass = 0; pass < MAX_STRIP_PASSES; pass++) {
+ const next = stripped.replace(FILLER_RE, '');
+ if (next === stripped) break;
+ stripped = next;
+ }
+ stripped = stripped.trim();
+ const words = stripped.split(/\s+/).filter((w) => w !== '').length;
+ const viable = stripped !== '' && (words >= 2 || stripped.length >= 12);
+ if (!viable || stripped === line) return clampThreadTitle(line);
+ return clampThreadTitle(stripped.charAt(0).toUpperCase() + stripped.slice(1));
+}
diff --git a/packages/server/src/agent-sessions.ts b/packages/server/src/agent-sessions.ts
index 28bdfdb3f..7d3079030 100644
--- a/packages/server/src/agent-sessions.ts
+++ b/packages/server/src/agent-sessions.ts
@@ -190,6 +190,23 @@ export function applyAgentMarkdownWrite(
);
}
+/**
+ * Serialize the doc's top-level blocks — one string per XmlFragment child, in
+ * order. Follow mode diffs a before/after pair of these (via
+ * `changedBlockRange`) around an agent write to record which blocks changed, so
+ * an editor that becomes active only AFTER the write applied can still flash +
+ * scroll to the changed section instead of missing the moment. XmlFragment
+ * children map 1:1 to PM top-level nodes, so a block index is a PM node index.
+ * Call inside the write's transact (after `applyAgentMarkdownWrite` the
+ * fragment is already updated — the paired-write primitives run synchronously).
+ */
+export function snapshotBlocks(document: Document): string[] {
+ return document
+ .getXmlFragment('default')
+ .toArray()
+ .map((child) => child.toString());
+}
+
function applyAgentMarkdownWriteInner(
document: Document,
markdown: string,
diff --git a/packages/server/src/api-extension.ts b/packages/server/src/api-extension.ts
index 80cc1b8e0..203bf9bb1 100644
--- a/packages/server/src/api-extension.ts
+++ b/packages/server/src/api-extension.ts
@@ -59,6 +59,7 @@ import {
CreateFolderSuccessSchema,
CreatePageRequestSchema,
CreatePageSuccessSchema,
+ changedBlockRange,
colorFromSeed,
createCodeFenceTracker,
createWorkspaceSearchCorpus,
@@ -254,6 +255,18 @@ import busboy from 'busboy';
import { fileTypeFromBuffer } from 'file-type';
import { parse as parseYaml, stringify as stringifyYaml } from 'yaml';
import { z } from 'zod';
+import {
+ ACP_AGENT_HARNESS_CLIS,
+ type AcpHarnessAvailability,
+ createAcpHarnessAvailabilityProbe,
+} from './acp/harness-availability.ts';
+import {
+ type AcpRegistry,
+ type CustomAgentEntry,
+ FEATURED_AGENT_IDS,
+ registryPlatformKey,
+} from './acp/registry.ts';
+import { MAX_ACP_THREADS } from './acp/thread-manager.ts';
import { captureEffect, type EffectValue } from './activity-log.ts';
import { listAgentActivity, synthesizeVersionDiff } from './agent-activity.ts';
import type { AgentFocusBroadcaster } from './agent-focus.ts';
@@ -265,6 +278,7 @@ import {
applyAgentMarkdownWrite,
applyAgentUndo,
iconFromClientName,
+ snapshotBlocks,
} from './agent-sessions.ts';
import { type NormalizedSummary, normalizeSummary } from './agent-write-summary.ts';
import { isAllowedApiOrigin } from './api-origin.ts';
@@ -2745,6 +2759,17 @@ export interface ApiExtensionOptions {
* so global-scope writes don't touch the real user home.
*/
homeDirOverride?: string;
+ /**
+ * ACP agent catalog (registry-driven). When present, `GET /api/acp/catalog`
+ * serves the featured + full agent lists the thread-launch UI renders.
+ * Omitted in harnesses that don't exercise agent threads — the route then
+ * answers 404.
+ */
+ acpRegistry?: AcpRegistry;
+ /** Custom-agent source for the catalog (machine-local `.ok/local` file). */
+ loadAcpCustomAgents?: () => Promise<CustomAgentEntry[]>;
+ /** Test seam for server-host CLI detection surfaced in the ACP catalog. */
+ acpHarnessAvailability?: () => Promise<AcpHarnessAvailability>;
/**
* Active ContentFilter (the same instance threaded into the file watcher).
* When present, `POST /api/rename-path` rejects destinations excluded by
@@ -2944,6 +2969,9 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {
projectDir,
getPrincipal,
homeDirOverride,
+ acpRegistry,
+ loadAcpCustomAgents,
+ acpHarnessAvailability = createAcpHarnessAvailabilityProbe(),
contentFilter,
installedAgentsProbe,
forceUnloadDocument,
@@ -5116,6 +5144,7 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {
captureEffect(session.dc.document.getText('source'), agentId, colorSeed, clientName);
// Use per-session origin, not shared AGENT_WRITE_ORIGIN (STOP rule)
session.dc.document.transact(() => {
+ const beforeBlocks = snapshotBlocks(session.dc.document);
applyAgentMarkdownWrite(
session.dc.document,
`${content}\n`,
@@ -5125,12 +5154,15 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {
: undefined,
);
+ const changedBlocks =
+ changedBlockRange(beforeBlocks, snapshotBlocks(session.dc.document)) ?? undefined;
const activityMap = session.dc.document.getMap('agent-flash');
activityMap.set(agentId, {
agentId,
timestamp: Date.now(),
type: 'insert',
description: `Added (${agentName}): ${content.slice(0, 50)}`,
+ ...(changedBlocks !== undefined ? { changedBlocks } : {}),
});
}, session.origin);
recordContributor(
@@ -5307,6 +5339,7 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {
captureEffect(session.dc.document.getText('source'), agentId, colorSeed, clientName);
// Use per-session origin, not shared AGENT_WRITE_ORIGIN (STOP rule)
session.dc.document.transact(() => {
+ const beforeBlocks = snapshotBlocks(session.dc.document);
writeDivergence = applyAgentMarkdownWrite(
session.dc.document,
body.markdown,
@@ -5316,12 +5349,15 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {
: undefined,
);
+ const changedBlocks =
+ changedBlockRange(beforeBlocks, snapshotBlocks(session.dc.document)) ?? undefined;
const activityMap = session.dc.document.getMap('agent-flash');
activityMap.set(agentId, {
agentId,
timestamp: Date.now(),
type: 'insert',
description: `Added (${agentName}): ${body.markdown.trim().slice(0, 50)}`,
+ ...(changedBlocks !== undefined ? { changedBlocks } : {}),
});
}, session.origin);
if (writeDivergence !== undefined) {
@@ -7092,6 +7128,7 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {
const newFull =
currentFull.slice(0, pos) + replace + currentFull.slice(pos + find.length);
const { body: newBody } = stripFrontmatter(newFull);
+ const beforeBlocks = snapshotBlocks(session.dc.document);
patchDivergence = applyAgentMarkdownWrite(
session.dc.document,
newBody,
@@ -7101,12 +7138,15 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {
: undefined,
);
+ const changedBlocks =
+ changedBlockRange(beforeBlocks, snapshotBlocks(session.dc.document)) ?? undefined;
const activityMap = session.dc.document.getMap('agent-flash');
activityMap.set(agentId, {
agentId,
timestamp: Date.now(),
type: 'insert',
description: `Patched (${agentName}): ${find.slice(0, 50)}`,
+ ...(changedBlocks !== undefined ? { changedBlocks } : {}),
});
}, session.origin);
if (patchDivergence !== undefined) {
@@ -8737,6 +8777,105 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {
{ handler: 'server-info', method: 'GET', skipBodyParse: true },
);
+ const AcpCatalogAgentSchema = z.object({
+ id: z.string(),
+ name: z.string(),
+ version: z.string(),
+ description: z.string().optional(),
+ license: z.string().optional(),
+ iconUrl: z.string().optional(),
+ website: z.string().optional(),
+ source: z.enum(['registry', 'custom']),
+ /** A launchable distribution exists for this host platform. */
+ supported: z.boolean(),
+ featured: z.boolean(),
+ harness: z
+ .object({
+ cli: z.enum(['claude', 'codex', 'cursor', 'opencode', 'pi']),
+ availability: z.enum(['present', 'not-found', 'unknown']),
+ })
+ .optional(),
+ });
+ const AcpCatalogSuccessSchema = z.object({
+ agents: z.array(AcpCatalogAgentSchema),
+ /** True when served from the offline fallback cache. */
+ stale: z.boolean(),
+ maxThreads: z.number(),
+ });
+
+ const handleAcpCatalog = withValidation(
+ EmptyRequestSchema,
+ async (_req, res) => {
+ if (acpRegistry === undefined) {
+ errorResponse(res, 404, 'urn:ok:error:not-found', 'ACP catalog unavailable.', {
+ handler: 'acp-catalog',
+ });
+ return;
+ }
+ try {
+ const platform = registryPlatformKey();
+ const { agents, stale } = await acpRegistry.getCatalog();
+ const custom = (await loadAcpCustomAgents?.()) ?? [];
+ const harnessAvailability = await acpHarnessAvailability();
+ const rows = [
+ ...agents.map((a) => {
+ const harnessCli = ACP_AGENT_HARNESS_CLIS[a.id];
+ return {
+ id: a.id,
+ name: a.name,
+ version: a.version,
+ ...(a.description !== undefined ? { description: a.description } : {}),
+ ...(a.license !== undefined ? { license: a.license } : {}),
+ ...(a.icon !== undefined ? { iconUrl: a.icon } : {}),
+ ...(a.website !== undefined ? { website: a.website } : {}),
+ source: 'registry' as const,
+ supported:
+ a.distribution.npx !== undefined ||
+ a.distribution.uvx !== undefined ||
+ (platform !== null && a.distribution.binary?.[platform] !== undefined),
+ featured: FEATURED_AGENT_IDS.includes(a.id),
+ ...(harnessCli !== undefined
+ ? {
+ harness: {
+ cli: harnessCli,
+ availability: harnessAvailability[harnessCli] ?? 'unknown',
+ },
+ }
+ : {}),
+ };
+ }),
+ ...custom.map((c: CustomAgentEntry) => ({
+ id: c.id,
+ name: c.name,
+ version: 'custom',
+ source: 'custom' as const,
+ supported: true,
+ featured: false,
+ })),
+ ];
+ successResponse(
+ res,
+ 200,
+ AcpCatalogSuccessSchema,
+ { agents: rows, stale, maxThreads: MAX_ACP_THREADS },
+ { handler: 'acp-catalog', extraHeaders: { 'Cache-Control': 'no-store' } },
+ );
+ } catch (e) {
+ errorResponse(
+ res,
+ 502,
+ 'urn:ok:error:registry-unreachable',
+ 'Agent registry unreachable.',
+ {
+ handler: 'acp-catalog',
+ cause: e,
+ },
+ );
+ }
+ },
+ { handler: 'acp-catalog', method: 'GET', skipBodyParse: true },
+ );
+
async function handlePrincipal(req: IncomingMessage, res: ServerResponse): Promise<void> {
// Loopback + Host-header gate. The principal record discloses operator
// PII — `display_name` (real name) and `display_email` — sourced from
@@ -18805,6 +18944,7 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {
'/api/metrics/agent-effects': handleMetricsAgentEffects,
'/api/__embed-detect': handleEmbedDetect,
'/api/server-info': handleServerInfo,
+ '/api/acp/catalog': handleAcpCatalog,
'/api/share/construct-url': handleShareConstructUrl,
'/api/share/target-status': handleShareTargetStatus,
'/api/git/branch-info': handleBranchInfo,
diff --git a/packages/server/src/api-origin.test.ts b/packages/server/src/api-origin.test.ts
index ce78fb551..3ad5f8a2e 100644
--- a/packages/server/src/api-origin.test.ts
+++ b/packages/server/src/api-origin.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, test } from 'vitest';
import { isAllowedApiOrigin } from './api-origin.ts';
describe('API origin guards', () => {
@@ -11,4 +11,14 @@ describe('API origin guards', () => {
expect(isAllowedApiOrigin('https://example.com')).toBe(false);
expect(isAllowedApiOrigin('not a url')).toBe(false);
});
+
+ test('allows the file: origin serialization Chromium WebSockets send from loadFile pages', () => {
+ // fetch/XHR from a file: page send `Origin: null`; the WS handshake from
+ // the same page sends `Origin: file://`. Both must pass or the packaged
+ // desktop renderer's `/collab/thread` upgrade is destroyed while all its
+ // HTTP calls succeed.
+ expect(isAllowedApiOrigin('file://')).toBe(true);
+ // Only the bare serialization — a file URL with a host is not a page origin.
+ expect(isAllowedApiOrigin('file://evil.example')).toBe(false);
+ });
});
diff --git a/packages/server/src/api-origin.ts b/packages/server/src/api-origin.ts
index 248031325..39816dd29 100644
--- a/packages/server/src/api-origin.ts
+++ b/packages/server/src/api-origin.ts
@@ -1,8 +1,15 @@
/**
* Shared loopback-origin guard for unauthenticated local HTTP surfaces.
+ *
+ * `null` and `file://` are the two serializations of a local-file page's
+ * origin (the packaged Electron renderer loads via `loadFile`): fetch/XHR
+ * send `Origin: null`, but Chromium's WebSocket handshake sends
+ * `Origin: file://`. They carry the same trust level — rejecting one while
+ * allowing the other only breaks the desktop renderer's WS surfaces
+ * (`/collab/thread`) while its HTTP calls sail through.
*/
export function isAllowedApiOrigin(origin: string): boolean {
- if (origin === 'null') return true;
+ if (origin === 'null' || origin === 'file://') return true;
try {
const { hostname } = new URL(origin);
return (
diff --git a/packages/server/src/boot.ts b/packages/server/src/boot.ts
index ba69bac2f..5a5e19326 100644
--- a/packages/server/src/boot.ts
+++ b/packages/server/src/boot.ts
@@ -37,6 +37,11 @@ import {
import { context, propagation } from '@opentelemetry/api';
import { simpleGit } from 'simple-git';
import sirv from 'sirv';
+import {
+ AcpThreadManager,
+ type AcpThreadManagerOptions,
+ buildOkMcpStdioCommand,
+} from './acp/thread-manager.ts';
import { createAssetServeMiddleware } from './asset-serve-middleware.ts';
import { bootElapsedMs, recordBootPhase, startBootTimings } from './boot-timings.ts';
import type { Config } from './config/schema.ts';
@@ -221,6 +226,13 @@ export interface BootServerOptions
* invoke UI-sibling spawn logic. Default false.
*/
skipAutoInit?: boolean;
+ /**
+ * Forwarded to the ACP thread manager — see
+ * `AcpThreadManagerOptions.probeHarnessManagedMcpEntry`. `ok start` and the
+ * Electron utility wire the CLI's `probeOwnManagedEditorMcpEntry`; unset
+ * keeps unconditional OK-MCP injection for ACP threads.
+ */
+ probeHarnessManagedMcpEntry?: AcpThreadManagerOptions['probeHarnessManagedMcpEntry'];
/**
* If false, UI-sibling callbacks (`spawnUiSiblingFn` / `onSkipUiSpawn`) are
* NOT invoked regardless of `spawnUiSiblingFn` presence. Default true —
@@ -356,6 +368,8 @@ export interface BootedServer {
didAutoInit: boolean;
/** Full ServerInstance from createServer — exposed for advanced consumers (e.g., desktop utility's drain sequencing). */
serverInstance: ServerInstance;
+ /** ACP thread host, or null in ephemeral single-file mode. */
+ acpThreadManager: AcpThreadManager | null;
}
/**
@@ -809,6 +823,33 @@ async function bootServerInner(opts: BootServerOptions): Promise<BootedServer> {
})
: undefined;
+ // ACP thread host — server-hosted external-agent threads. Ephemeral
+ // single-file mode has no agent capabilities (mirrors the `/mcp` off-switch
+ // above), so the manager is simply never constructed there and the
+ // `/collab/thread` upgrade branch fail-closes on the missing handle.
+ const acpThreadManager = opts.ephemeral
+ ? null
+ : new AcpThreadManager({
+ contentDir: opts.contentDir,
+ localDir: lockDir,
+ registry: serverInstance.acpRegistry,
+ permissions: serverInstance.acpPermissions,
+ sessionManager,
+ agentPresenceBroadcaster,
+ resolveEmbed: serverInstance.resolveEmbed,
+ isExcludedPath: (rel) => serverInstance.contentFilter.isExcluded(rel),
+ isIgnoredPath: (rel) => serverInstance.contentFilter.isPathIgnored(rel),
+ getLoadedDocText: (docName) =>
+ hocuspocus.documents.get(docName)?.getText('source').toString() ?? null,
+ getServerUrl: () => `http://${mcpHost}:${boundPort}`,
+ getMcpStdioCommand: () => buildOkMcpStdioCommand(opts.localOpCliArgs, boundPort),
+ probeHarnessManagedMcpEntry: opts.probeHarnessManagedMcpEntry,
+ log,
+ });
+ // Rehydrate archived threads (metadata-only scan) before the WS surface
+ // mounts, so the first `list` already includes them.
+ if (acpThreadManager !== null) await acpThreadManager.init();
+
const mount = mountMcpAndApi({
httpServer,
hocuspocus,
@@ -822,6 +863,7 @@ async function bootServerInner(opts: BootServerOptions): Promise<BootedServer> {
contentAssetMiddleware,
reactShellMiddleware,
ephemeral: opts.ephemeral,
+ acpThreadManager,
});
// Forward-declare destroy so idle-shutdown's onShutdown can reach the full
@@ -985,6 +1027,12 @@ async function bootServerInner(opts: BootServerOptions): Promise<BootedServer> {
log.warn({ err, step: 'idleHandle.detach' }, 'bootServer destroy step failed');
}
+ // Kill agent subprocesses FIRST — their threads hold `/collab/thread`
+ // sockets open, and a live agent outliving the server would orphan a
+ // process no UI can reach anymore.
+ if (acpThreadManager !== null) {
+ await runStep('acpThreads.destroy', () => acpThreadManager.destroy());
+ }
await runStep('mount.shutdown', () => mount.shutdown());
if (mcpHttpHandler !== undefined) {
await runStep('mcpHttpHandler.close', () => mcpHttpHandler.close());
@@ -1086,6 +1134,7 @@ async function bootServerInner(opts: BootServerOptions): Promise<BootedServer> {
degraded,
didAutoInit,
serverInstance,
+ acpThreadManager,
};
}
diff --git a/packages/server/src/fs-traced.ts b/packages/server/src/fs-traced.ts
index d2aae51c9..031d60c8a 100644
--- a/packages/server/src/fs-traced.ts
+++ b/packages/server/src/fs-traced.ts
@@ -28,7 +28,7 @@ import {
unlinkSync,
writeFileSync,
} from 'node:fs';
-import { mkdir, rename, writeFile } from 'node:fs/promises';
+import { appendFile, mkdir, rename, rm, writeFile } from 'node:fs/promises';
import { basename, sep } from 'node:path';
import type { AtomicWriteFsAdapter } from '@inkeep/open-knowledge-core/server';
import type { Attributes } from '@opentelemetry/api';
@@ -101,6 +101,26 @@ export async function tracedWriteFile(
);
}
+export async function tracedAppendFile(
+ path: string,
+ data: string | Uint8Array,
+ options?: WriteFileOptions,
+): Promise<void> {
+ return withSpan(
+ 'fs.appendFile',
+ { attributes: buildAttrs('appendFile', path, { 'fs.bytes': byteLength(data) }) },
+ async () => {
+ await appendFile(path, data, options);
+ },
+ );
+}
+
+export async function tracedRm(path: string, options?: RmOptions): Promise<void> {
+ return withSpan('fs.rm', { attributes: buildAttrs('rm', path) }, async () => {
+ await rm(path, options);
+ });
+}
+
export async function tracedRename(from: string, to: string): Promise<void> {
return withSpan(
'fs.rename',
diff --git a/packages/server/src/index.ts b/packages/server/src/index.ts
index 3b4aebc61..54d95e4d4 100644
--- a/packages/server/src/index.ts
+++ b/packages/server/src/index.ts
@@ -3,6 +3,15 @@ export {
GitDirAccessError,
MalformedGitPointerError,
} from '@inkeep/open-knowledge-core/shadow-repo-layout';
+export { AcpPermissionStore } from './acp/permissions.ts';
+export { AcpRegistry, FEATURED_AGENT_IDS, loadCustomAgents } from './acp/registry.ts';
+export {
+ AcpThreadManager,
+ buildOkMcpStdioCommand,
+ type HarnessManagedMcpEntryHit,
+ MAX_ACP_THREADS,
+} from './acp/thread-manager.ts';
+export { attachAcpThreadSocket } from './acp/thread-socket.ts';
export { AgentFocusBroadcaster } from './agent-focus.ts';
export { AGENT_ID_MAX_LEN, AGENT_ID_RE, toBroadcasterKey, validateAgentId } from './agent-id.ts';
export { AgentPresenceBroadcaster } from './agent-presence.ts';
diff --git a/packages/server/src/mcp-mount.ts b/packages/server/src/mcp-mount.ts
index d46fc019a..671d8910b 100644
--- a/packages/server/src/mcp-mount.ts
+++ b/packages/server/src/mcp-mount.ts
@@ -33,6 +33,8 @@ import type { Duplex } from 'node:stream';
import type { Hocuspocus } from '@hocuspocus/server';
import { AGENT_ICON_COLORS, colorFromSeed, iconFromClientName } from '@inkeep/open-knowledge-core';
import { WebSocketServer } from 'ws';
+import type { AcpThreadManager } from './acp/thread-manager.ts';
+import { attachAcpThreadSocket } from './acp/thread-socket.ts';
import type { AgentFocusBroadcaster } from './agent-focus.ts';
import { toBroadcasterKey, validateAgentId } from './agent-id.ts';
import type { AgentPresenceBroadcaster } from './agent-presence.ts';
@@ -116,6 +118,12 @@ export interface MountMcpAndApiOptions {
* the shell on its own port.
*/
reactShellMiddleware?: (req: IncomingMessage, res: ServerResponse, next: () => void) => void;
+ /**
+ * ACP thread host answering the `/collab/thread` upgrade. When omitted or
+ * null (ephemeral mode, restartable test harness), the branch fail-closes
+ * by destroying the socket — no thread surface exists to reach.
+ */
+ acpThreadManager?: AcpThreadManager | null;
/**
* No-project ephemeral single-file mode (`ok <file>`). When `true`, the
* content-asset surface is gated by the same loopback + workspace-host
@@ -391,6 +399,34 @@ export function mountMcpAndApi(opts: MountMcpAndApiOptions): MountMcpAndApiHandl
};
const onUpgrade = (req: IncomingMessage, socket: Duplex, head: Buffer): void => {
+ if (req.url?.startsWith('/collab/thread')) {
+ // Same gate family as the mutating HTTP surface: loopback peer +
+ // workspace Host header, plus browser-Origin allowlist when an Origin
+ // is present (WS upgrades from pages always carry one; a DNS-rebound
+ // page fails the Host check, a foreign page fails the Origin check).
+ const acp = opts.acpThreadManager;
+ if (
+ acp === undefined ||
+ acp === null ||
+ !isLoopbackAddress(req.socket.remoteAddress) ||
+ !isAllowedWorkspaceHostHeader(req.headers.host) ||
+ (req.headers.origin !== undefined && !isAllowedApiOrigin(req.headers.origin))
+ ) {
+ socket.destroy();
+ return;
+ }
+ socket.on('error', (err: NodeJS.ErrnoException) => {
+ if (handleCollabSocketError(err)) return;
+ log.error({ err }, 'ACP thread socket error');
+ });
+ liveUpgradeSockets.add(socket);
+ socket.once('close', () => liveUpgradeSockets.delete(socket));
+ wss.handleUpgrade(req, socket, head, (ws) => {
+ attachAcpThreadSocket(ws, acp, log);
+ });
+ return;
+ }
+
if (req.url?.startsWith('/collab/keepalive')) {
if (
!isLoopbackAddress(req.socket.remoteAddress) ||
diff --git a/packages/server/src/mcp/tools/registry.test.ts b/packages/server/src/mcp/tools/registry.test.ts
index 564c70b47..f23b50064 100644
--- a/packages/server/src/mcp/tools/registry.test.ts
+++ b/packages/server/src/mcp/tools/registry.test.ts
@@ -20,11 +20,11 @@
* names in RETIRED_TOOL_NAMES are.
*/
-import { describe, expect, test } from 'bun:test';
import { mkdtempSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { OK_GATED_TOOL_NAMES } from '@inkeep/open-knowledge-core';
+import { describe, expect, test } from 'vitest';
import { type Config, ConfigSchema } from '../../config/schema.ts';
import { registerAllTools } from './index.ts';
import type { ServerInstance } from './shared.ts';
@@ -60,6 +60,9 @@ const EXPECTED_TOOLS = [
] as const;
const RETIRED_TOOL_NAMES = [
+ // View choreography → client-side derived views (the docked graph panel):
+ // no tool call to remember, and it works for every agent.
+ 'graph_view',
// Link-graph getters → links
'get_backlinks',
'get_forward_links',
@@ -137,7 +140,7 @@ describe('registerAllTools — full tool surface (SPEC.md §9.1 / AC8 + install
}
});
- test('none of the 17 pre-consolidation tool names are registered', () => {
+ test('none of the retired tool names are registered', () => {
const names = new Set(captureRegistered());
for (const retired of RETIRED_TOOL_NAMES) {
expect(names.has(retired)).toBe(false);
diff --git a/packages/server/src/server-factory.ts b/packages/server/src/server-factory.ts
index 17fcf4e82..7c9c16370 100644
--- a/packages/server/src/server-factory.ts
+++ b/packages/server/src/server-factory.ts
@@ -44,6 +44,8 @@ import {
resolveShadowDir,
} from '@inkeep/open-knowledge-core/shadow-repo-layout';
import simpleGit from 'simple-git';
+import { AcpPermissionStore } from './acp/permissions.ts';
+import { AcpRegistry, loadCustomAgents } from './acp/registry.ts';
import { AgentFocusBroadcaster } from './agent-focus.ts';
import { AgentPresenceBroadcaster } from './agent-presence.ts';
import { AgentSessionManager } from './agent-sessions.ts';
@@ -393,6 +395,16 @@ export interface ServerInstance {
readonly lockDir: string;
/** Active sync engine instance, or null if dormant / no remote detected. */
readonly syncEngine: SyncEngine | null;
+ /**
+ * Wiki-embed resolver (basename → contentDir-relative path). Exposed so
+ * consumers that apply agent markdown writes outside the HTTP handlers
+ * (the ACP thread host) resolve `![[file.ext]]` refs identically.
+ */
+ readonly resolveEmbed: (basename: string, sourcePath: string) => string | null;
+ /** ACP agent catalog shared by the catalog route and the thread host. */
+ readonly acpRegistry: AcpRegistry;
+ /** ACP permission-policy store shared with the thread host. */
+ readonly acpPermissions: AcpPermissionStore;
}
/**
@@ -772,6 +784,13 @@ export function createServer(options: ServerOptions): ServerInstance {
// different `content.dir` settings still collide on the same lock — desired,
// because one server services one project.
const lockDir = getLocalDir(projectDir);
+
+ // ACP catalog + permission store — cheap lazy objects (network/disk only on
+ // first use), constructed unconditionally so the catalog route and the boot
+ // paths (CLI, desktop utility, dev plugin) share one instance per server.
+ const acpRegistry = new AcpRegistry({ localDir: lockDir, log: getLogger('acp-registry') });
+ const acpPermissions = new AcpPermissionStore(lockDir, getLogger('acp-permissions'));
+
acquireServerLock(lockDir, {
port: options.port ?? 0,
worktreeRoot: projectDir,
@@ -1723,6 +1742,8 @@ export function createServer(options: ServerOptions): ServerInstance {
projectDir,
resolveEmbed,
getPrincipal: () => loadedPrincipal,
+ acpRegistry,
+ loadAcpCustomAgents: () => loadCustomAgents(lockDir, getLogger('acp-registry')),
// Reuse the single user-home override that also resolves `~/.ok/global.yml`
// so global-scope skills (`<home>/.ok/skills`) resolve under the same
// home (tests pass a tempdir; production leaves it undefined → homedir()).
@@ -4227,5 +4248,8 @@ export function createServer(options: ServerOptions): ServerInstance {
get syncEngine() {
return syncEngine;
},
+ resolveEmbed,
+ acpRegistry,
+ acpPermissions,
};
}
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 4fc14b4b1..ac2b75da3 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -584,6 +584,9 @@ importers:
sonner:
specifier: ^2.0.7
+ streamdown:
+ specifier: ^2.5.0
tailwind-merge:
specifier: ^3.5.0
version: 3.6.0
@@ -830,6 +833,9 @@ importers:
packages/core:
dependencies:
+ '@agentclientprotocol/sdk':
+ specifier: ^1.1.0
+ version: 1.2.1([email protected])
'@handlewithcare/remark-prosemirror':
specifier: 0.1.5
version: 0.1.5(patch_hash=a6b60cc8640e04973be2c8123e0dbd73156b54388a57cd2b76191c2fd8ac2865)([email protected])
@@ -1141,6 +1147,9 @@ importers:
packages/server:
dependencies:
+ '@agentclientprotocol/sdk':
+ specifier: ^1.1.0
+ version: 1.2.1([email protected])
'@hocuspocus/server':
specifier: 4.0.0-rc.1
@@ -1293,6 +1302,11 @@ packages:
resolution: {integrity: sha512-6OzddxPio9UiWTCemp4N8cYLV2ZN1ncRnV1cVGtve7dhPOtRkleRyx32GQCYSwDYgaHU3USMm84tNsvKzRCa1Q==}
+ '@agentclientprotocol/[email protected]':
+ resolution: {integrity: sha512-jwYUdOQR7tc+Zfch53VL4JJyUNK/46q03uUTYb+PjECsmnNl94XFXOfYLJ8RBpMNidXd1rpOAVgb0vqD98xImA==}
+ peerDependencies:
+ zod: ^3.25.0 || ^4.0.0
+
resolution: {integrity: sha512-UrcABB+4bUrFABwbluTIBErXwvbsU/V7TZWfmbgJfbkwiBuziS9gxdODUyuiecfdGQ85jglMW6juS3+z5TsKLw==}
engines: {node: '>=10'}
@@ -8035,6 +8049,9 @@ packages:
resolution: {integrity: sha512-Y8/SBAHkZGoNkpzqqfCldijcuUKh7/su31kEBp67cFY09Wy0mTRgtsLYsiIxMJxlu0f6AA5SUTbDR8K0rxnbUw==}
+ resolution: {integrity: sha512-3yTWghByc50aGS7JlGhk61SPenfE/p1oaFeNwkOOyrscaOkMGrcW9+Cy/QAIOBpZxP1yqDIzFMR0+Np0i0+usg==}
+
resolution: {integrity: sha512-48+B/rJWAp0jamNbAAf9M7Uf//UVqAoMmgXhBdxTDJLGKY+LRnZ99qcG+Qjl5HfMpYNzS5v4EAwVEF34LeAj7w==}
@@ -8805,6 +8822,11 @@ packages:
engines: {node: '>= 20'}
hasBin: true
+ resolution: {integrity: sha512-gB0gkNafnonOw0obSTEGZTT86IuhILt2Wfx0mWH/1Au83kybTayroZ/V6nS25mN7u8ASy+5fMhgB3XPNrOZdmA==}
+ engines: {node: '>= 20'}
+ hasBin: true
+
resolution: {integrity: sha512-OkeDaAZ/bQCxeFAozM55PKcKU0yJMPGifLwV4Qgjitu+5MoAfSQN4lsLJeXZ1b8w0x+/Emda6MZgXS1jvsapng==}
engines: {node: '>=10'}
@@ -10051,6 +10073,9 @@ packages:
resolution: {integrity: sha512-dYqgNSZbDwkaJ2ceRd9ojCGjBq+mOm9LmtXnAnEGyHhN/5R7iDW2TRw3h+o/jCFxus3P2LfWIIiwowAjANm7IA==}
engines: {node: '>= 0.4'}
+ resolution: {integrity: sha512-Qn7vR1xrf6fZCrkm9TDWi/AB4ylrHy+jqsNm1EHOAmbARYA6gsnVJBq/sdBh6kmT4NEZxH5vgIjrscefJAOXcw==}
+
resolution: {integrity: sha512-Zk0pyQ06A3Lyxhe9vGtOtzz3Z0+qZ5+7icZ/PL/2x1SHPbKao5oB/g/rlc6BCTajqBb33JcOe71Ye1oFsuYbnw==}
@@ -10066,6 +10091,9 @@ packages:
resolution: {integrity: sha512-EmDndlb5NVwXGfUa4c9GPK+lXeItTilLhE6ADSaQuHr4JUlKw9MidzGzx4HpqZrNCt6vnHmEifXQiiA+CEnjYQ==}
+ resolution: {integrity: sha512-CsnhKNsyI8Tub6L4sm5ZFsme4puGfc6pYylvXo1AeqaGbjOYyzNv3qZPwvs0oMJ39eryyeOdmxwUIo94IpEhqg==}
+
resolution: {integrity: sha512-k9ecfXHmIPuFVI61B9DeLPN0qFHfawM6RsuX48hoqlaKSF61RskNjSm1lI8PhBEM0MRdLxVVm4WmTqJQccH9mA==}
@@ -10103,6 +10131,9 @@ packages:
resolution: {integrity: sha512-Eht5w30ruCXgFmxVUSlNWQ9iiimq07URKeFS3hNc8cUWy1llX4KDWfyEDZRycMc+znsN9Ux5/tJ/BFdgdOwA3A==}
+ resolution: {integrity: sha512-iIhggPkhW3hFImKtB10w0dz4EZbs28mV/dmbcYVonWEJ6UGHHpP+bFZnTh6GNWJONg5m+U56JrL+8IxZRdgWjw==}
+
resolution: {integrity: sha512-fGxEI7+wsG9xrvdjsrlmL22OMTTiHRwAMroiEeMgq8gzoLC/PQr7RsRDSTLUg/bZAZtF+TVIkHc6/4RIKrui+Q==}
engines: {node: '>=0.10.0'}
@@ -10521,6 +10552,12 @@ packages:
resolution: {integrity: sha512-eLoXW/DHyl62zxY4SCaIgnRhuMr6ri4juEYARS8E6sCEqzKpOiE521Ucofdx+KnDZl5xmvGYaaKCk5FEOxJCoQ==}
engines: {node: '>= 0.4'}
+ resolution: {integrity: sha512-/tTnURfIOxZK/pqJAxsfCvETG/XCJHoWnk3jq9xLcuz6CSpnjjuxSRBTTL4PKGhxiZQf0lqPxGhImdpwcZ2XwA==}
+ peerDependencies:
+ react: 19.2.5
+ react-dom: 19.2.5
+
resolution: {integrity: sha512-Mcc5wHehp9aXz1ax6bZUyY5afg9u2rv5cqQI3mRrYkGC8rW2hM02jWuwjtL++LS5qinSyhj2QfLyNsuc+VsExg==}
engines: {node: '>=10.0.0'}
@@ -11419,6 +11456,10 @@ snapshots:
'@adobe/[email protected]': {}
+ '@agentclientprotocol/[email protected]([email protected])':
+ dependencies:
+ zod: 4.4.3
+
'@alloc/[email protected]': {}
@@ -18491,6 +18532,12 @@ snapshots:
web-namespaces: 2.0.1
zwitch: 2.0.4
+ dependencies:
+ '@types/hast': 3.0.5
+ '@ungap/structured-clone': 1.3.3
+ unist-util-position: 5.0.0
+
dependencies:
'@types/estree': 1.0.9
@@ -19274,6 +19321,8 @@ snapshots:
+
dependencies:
escape-string-regexp: 4.0.0
@@ -21150,6 +21199,10 @@ snapshots:
gopd: 1.2.0
set-function-name: 2.0.2
+ dependencies:
+ unist-util-visit: 5.1.0
+
dependencies:
'@types/hast': 3.0.5
@@ -21183,6 +21236,11 @@ snapshots:
unified: 11.0.5
vfile: 6.0.3
+ dependencies:
+ '@types/hast': 3.0.5
+ hast-util-sanitize: 5.0.2
+
dependencies:
'@types/hast': 3.0.5
@@ -21274,6 +21332,8 @@ snapshots:
transitivePeerDependencies:
- supports-color
+
@@ -21829,6 +21889,29 @@ snapshots:
es-errors: 1.3.0
internal-slot: 1.1.0
+ dependencies:
+ clsx: 2.1.1
+ hast-util-to-jsx-runtime: 2.3.6
+ html-url-attributes: 3.0.1
+ marked: 17.0.6
+ mermaid: 11.16.0
+ react: 19.2.5
+ react-dom: 19.2.5([email protected])
+ rehype-harden: 1.1.8
+ rehype-raw: 7.0.0
+ rehype-sanitize: 6.0.0
+ remark-gfm: 4.0.1
+ remark-parse: 11.0.0
+ remark-rehype: 11.1.2
+ remend: 1.3.0
+ tailwind-merge: 3.6.0
+ unified: 11.0.5
+ unist-util-visit: 5.1.0
+ unist-util-visit-parents: 6.0.2
+ transitivePeerDependencies:
+ - supports-color
+