Beautiful, AI-native markdown IDE and LLM wiki
TypeScript 2nd-brainagent-skillsclaudecodexcompany-braindocsknowledge-knowledge-baseknowledge-managementllmllm-wikillm-wiki-karpathymarkdownmarkdown-editormdmdxnotespkmsecond-brainskills
feat(open-knowledge): ACP thread improvements — list overflow, per-agent settings, global storage, message queue, permissive-mode flag, launch PATH (#2871)
mike-inkeep863a0a783f69
diff --git a/.changeset/acp-agent-path-augment.md b/.changeset/acp-agent-path-augment.mdnew file mode 100644index 000000000..e4ac189f3--- /dev/null+++ b/.changeset/acp-agent-path-augment.md@@ -0,0 +1,5 @@+---+"@inkeep/open-knowledge": patch+---++Agents started from the desktop app now launch even when their CLI was installed through a JavaScript package manager's global bin (pnpm, bun, Volta, Yarn, or npm's user prefix). A desktop app opened from the Dock or Finder inherits a minimal `PATH` that omits locations like `~/Library/pnpm` and `~/.bun/bin`, so an agent such as Pi that ran fine in a terminal would fail to start with a "command not found" error. Agent and terminal launches now append the well-known tool directories and package-manager global bins to `PATH` — the same approach already used for git — so these agents start correctly. When a command still can't be found, the error now explains that Dock/Finder-launched apps don't see your shell's `PATH`.diff --git a/.changeset/acp-message-queue.md b/.changeset/acp-message-queue.mdnew file mode 100644index 000000000..660e7c791--- /dev/null+++ b/.changeset/acp-message-queue.md@@ -0,0 +1,5 @@+---+"@inkeep/open-knowledge": patch+---++You can now queue messages to an in-app agent while it's still working. Sending mid-turn no longer fails with "a turn is already running" — the message joins a queue and is sent automatically as soon as the current turn ends, in the order you wrote them. Queued messages appear between the transcript and the composer, where each one can be edited in place or removed before it runs. Stopping the agent clears the queue, and it's never saved to disk, so a crash mid-turn can't resurrect messages you never sent. Up to 20 messages can be queued at once.diff --git a/.changeset/acp-thread-improvements.md b/.changeset/acp-thread-improvements.mdnew file mode 100644index 000000000..b245353a1--- /dev/null+++ b/.changeset/acp-thread-improvements.md@@ -0,0 +1,10 @@+---+"@inkeep/open-knowledge": patch+---++In-app agent (ACP) threads: four improvements.++- **Numbered lists in agent replies no longer render off-screen.** Ordered- and unordered-list markers were being clipped off the left edge of the narrow thread panel; lists now get inline-start padding so their markers stay on screen.+- **Agent settings persist per agent type.** Picking a model, reasoning effort, or agent mode in a thread is remembered for that agent, and the next thread you start with the same agent opens on those settings — applied before the first turn (model first, so dependent options like thought level re-validate).+- **A mode that lets the agent act without asking is marked.** Because modes carry across threads, a permissive one — Claude's Bypass Permissions and Accept Edits, Codex's Agent (full access), Gemini's YOLO and Auto Edit, goose's Auto — puts a small amber dot on the settings button, with a hover tooltip spelling out what it allows. (Cursor exposes no permissive mode over ACP, and goose's Smart Approve still prompts for risky steps, so neither is flagged.) The marking follows whichever mode is actually in force, whether you just picked it or it carried over from your last thread. It's a recognition heuristic over the mode's name, so it's a hint, not a guarantee — it never blocks or changes a mode.+- **Thread transcripts are stored globally in `~/.ok/threads/`** (alongside the existing `~/.ok/acp-agents` and `~/.ok/runtimes`) instead of per-project, so they survive project-folder moves. Each project still sees only its own threads (matched by working directory). Threads created before this change are read back from their old per-project location — nothing to migrate. Per-project tool-permission grants are unchanged.diff --git a/packages/app/src/components/acp/AgentMarkdown.tsx b/packages/app/src/components/acp/AgentMarkdown.tsxindex 19d74c7d9..aec62e900 100644--- a/packages/app/src/components/acp/AgentMarkdown.tsx+++ b/packages/app/src/components/acp/AgentMarkdown.tsx@@ -26,13 +26,21 @@ export function AgentMarkdown({ text }: { text: string }): ReactNode {// so `lineNumbers={false}` alone collapses multi-line code onto one// visual line.//+ // Lists force `list-outside` + inline-start padding for a deterministic+ // hanging indent: the marker sits in the padding and wrapped lines align+ // under the text. Without this, lists inherit Tailwind's preflight+ // (ol/ul padding:0) and Streamdown's list-style-position varies by build+ // — top-level markers then hang into zero padding and clip off the+ // transcript's narrow, scroll-free left edge. Padding matches+ // Streamdown's own nested-list `[li_&]:pl-6`.+ //// Code drops a notch to 13px (Streamdown hard-codes `text-sm` on both// inline and block code) so the mono face, which reads larger than the// UI face at a matched point size, sits optically level with the prose// around it. Deliberately not `!`: the descendant selector already// outranks Streamdown's own class, which leaves an `!` override on a// wrapper — the thought bubble's flattening — free to win.- className="[&>*:first-child]:mt-0 [&>*:last-child]:mb-0 [&_pre_code>span]:block [&_code]:text-1sm [&_pre]:text-1sm"+ className="[&>*:first-child]:mt-0 [&>*:last-child]:mb-0 [&_pre_code>span]:block [&_ol]:list-outside [&_ul]:list-outside [&_ol]:ps-6 [&_ul]:ps-6 [&_code]:text-1sm [&_pre]:text-1sm"lineNumbers={false}controls={{ code: { copy: true, download: false }, table: false, mermaid: false }}// Plain hardened anchors instead of Streamdown's confirm-modal flow:diff --git a/packages/app/src/components/acp/ThreadView.dom.test.tsx b/packages/app/src/components/acp/ThreadView.dom.test.tsxindex e45404295..6ac08c8e6 100644--- a/packages/app/src/components/acp/ThreadView.dom.test.tsx+++ b/packages/app/src/components/acp/ThreadView.dom.test.tsx@@ -37,13 +37,18 @@ const setConfigOption = vi.fn((_threadId: string, _configId: string, _value: string | boolean) => {},);const setMode = vi.fn((_threadId: string, _modeId: string) => {});+const prompt = vi.fn((_threadId: string, _content: string) => {});+const editQueued = vi.fn((_threadId: string, _id: string, _content: string) => {});+const removeQueued = vi.fn((_threadId: string, _id: string) => {});vi.doMock('@/lib/acp/thread-client', () => ({getAgentThreadClient: () => ({respondPermission,respondRuntimeConsent: () => {},cancel: () => {},- prompt: () => {},+ prompt,+ editQueued,+ removeQueued,setMode,setConfigOption,closeThread: () => {},@@ -80,6 +85,10 @@ vi.doMock('@/components/acp/AgentMarkdown', () => ({}));const { ThreadView } = await import('./ThreadView');+// Not mocked — the settings popover writes real remembered picks through it.+const { agentSettingsKey, getRememberedAgentConfig, getRememberedAgentMode } = await import(+ '@/lib/acp/agent-settings-store'+);function makeInfo(overrides?: Partial<ThreadInfo>): ThreadInfo {return {@@ -147,12 +156,16 @@ async function openToolCall(): Promise<void> {afterEach(() => {cleanup();+ localStorage.clear();// No-op when timers are already real; makes cleanup unconditional even if a// test using fake timers fails before its own teardown would run.vi.useRealTimers();respondPermission.mockClear();setConfigOption.mockClear();setMode.mockClear();+ prompt.mockClear();+ editQueued.mockClear();+ removeQueued.mockClear();model = null;});@@ -231,6 +244,127 @@ describe('ThreadView agent settings', () => {expect(setConfigOption).toHaveBeenCalledWith('thread-1', 'model', 'opus');});+ test('remembers every pick for this agent, modes included', async () => {+ const key = agentSettingsKey({ source: 'registry', id: 'claude' });+ 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: 'permission',+ name: 'Permission mode',+ category: 'mode',+ type: 'select',+ currentValue: 'default',+ options: [+ { value: 'default', name: 'Default' },+ { value: 'bypass', name: 'Bypass permissions' },+ ],+ },+ ],+ })}+ />,+ );++ await userEvent.click(screen.getByRole('button', { name: 'Agent settings' }));++ // A model pick is remembered, so the next thread with this agent opens on it.+ await userEvent.click(screen.getByTestId('agent-thread-config-model'));+ fireEvent.click(await screen.findByTestId('agent-thread-config-option-opus'));+ expect(setConfigOption).toHaveBeenCalledWith('thread-1', 'model', 'opus');+ expect(getRememberedAgentConfig(key)).toEqual({ model: 'opus' });++ // A mode advertised as a config option is remembered through that same+ // path — no special case. Its permissiveness is surfaced by the accent, not+ // by declining to remember it. (Picking a select value closes the menu, so+ // reopen it.)+ await userEvent.click(screen.getByRole('button', { name: 'Agent settings' }));+ await userEvent.click(screen.getByTestId('agent-thread-config-permission'));+ fireEvent.click(await screen.findByTestId('agent-thread-config-option-bypass'));+ expect(setConfigOption).toHaveBeenCalledWith('thread-1', 'permission', 'bypass');+ expect(getRememberedAgentConfig(key)).toEqual({ model: 'opus', permission: 'bypass' });+ });+});++describe('ThreadView permissive-mode accent', () => {+ /** A ready thread sitting on `currentValue`. */+ const modeInfo = (currentValue: string) =>+ makeInfo({+ status: 'ready',+ configOptions: [+ {+ id: 'permission',+ name: 'Permission mode',+ category: 'mode',+ type: 'select',+ currentValue,+ options: [+ { value: 'default', name: 'Default' },+ { value: 'bypassPermissions', name: 'Bypass permissions' },+ ],+ },+ ],+ });++ test('an ordinary mode carries no accent', () => {+ render(<ThreadView info={modeInfo('default')} />);+ expect(screen.queryByTestId('agent-thread-mode-accent')).toBeNull();+ });++ test('a mode that lets the agent act unprompted is marked, and says so', () => {+ render(<ThreadView info={modeInfo('bypassPermissions')} />);+ expect(screen.queryByTestId('agent-thread-mode-accent')).not.toBeNull();+ // The warning must name what it is warning about, not just glow.+ expect(+ screen.getByRole('button', {+ name: /Bypass permissions lets Claude Agent act without asking/,+ }),+ ).toBeDefined();+ });++ test('marks a permissive mode on the legacy modes surface too', () => {+ render(+ <ThreadView+ info={makeInfo({+ status: 'ready',+ modes: {+ currentModeId: 'yolo',+ availableModes: [+ { id: 'default', name: 'Default' },+ { id: 'yolo', name: 'YOLO' },+ ],+ },+ })}+ />,+ );+ expect(screen.queryByTestId('agent-thread-mode-accent')).not.toBeNull();+ });++ test('the accent tracks the live mode, restored or hand-picked alike', async () => {+ const { rerender } = render(<ThreadView info={modeInfo('default')} />);+ expect(screen.queryByTestId('agent-thread-mode-accent')).toBeNull();+ // Whatever moved the thread into a permissive mode — a pick, or a restore+ // applied before turn 1 — the accent follows the mode the agent reports.+ rerender(<ThreadView info={modeInfo('bypassPermissions')} />);+ expect(screen.queryByTestId('agent-thread-mode-accent')).not.toBeNull();+ rerender(<ThreadView info={modeInfo('default')} />);+ expect(screen.queryByTestId('agent-thread-mode-accent')).toBeNull();+ });+});++describe('ThreadView agent settings (modes)', () => {test('includes the legacy ACP mode selector when no mode config option is advertised', async () => {render(<ThreadView@@ -254,6 +388,38 @@ describe('ThreadView agent settings', () => {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');+ // The legacy surface has no config option to ride, so it persists under its+ // own key — but it persists just the same.+ expect(getRememberedAgentMode(agentSettingsKey({ source: 'registry', id: 'claude' }))).toBe(+ 'ask',+ );+ });++ test('a permissive legacy mode persists like any other — it is flagged, not withheld', async () => {+ render(+ <ThreadView+ info={makeInfo({+ status: 'ready',+ modes: {+ currentModeId: 'default',+ availableModes: [+ { id: 'default', name: 'Default' },+ { id: 'yolo', name: 'YOLO' },+ ],+ },+ })}+ />,+ );++ await userEvent.click(screen.getByRole('button', { name: 'Agent settings' }));+ await userEvent.click(screen.getByTestId('agent-thread-config-legacy-mode'));+ fireEvent.click(await screen.findByTestId('agent-thread-config-option-yolo'));+ expect(setMode).toHaveBeenCalledWith('thread-1', 'yolo');+ // Guards against a relapse into gating persistence on permissiveness: the+ // accent is what makes a permissive mode legible, not refusing to keep it.+ expect(getRememberedAgentMode(agentSettingsKey({ source: 'registry', id: 'claude' }))).toBe(+ 'yolo',+ );});});@@ -833,3 +999,90 @@ describe('ThreadView raw input', () => {expect(screen.queryByTestId('agent-thread-tool-raw-input')).toBeNull();});});++describe('ThreadView message queue', () => {+ test('mid-turn the composer offers Stop AND a live Send that queues the draft', () => {+ model = makeModel({ turnActive: true });+ render(<ThreadView info={makeInfo({ status: 'running' })} />);++ expect(screen.getByTestId('agent-thread-cancel')).toBeTruthy();+ const send = screen.getByTestId('agent-thread-send');+ expect(send.getAttribute('aria-label')).toBe('Queue message');+ expect((send as HTMLButtonElement).disabled).toBe(true); // empty draft++ fireEvent.change(screen.getByTestId('agent-thread-composer'), {+ target: { value: 'queued while running' },+ });+ fireEvent.click(screen.getByTestId('agent-thread-send'));+ expect(prompt).toHaveBeenCalledWith('thread-1', 'queued while running');+ });++ test('queued messages render between transcript and composer with a remove control', () => {+ model = makeModel({ turnActive: true });+ render(+ <ThreadView+ info={makeInfo({+ status: 'running',+ queue: [+ { id: 'q1', content: 'first queued', ts: 1 },+ { id: 'q2', content: 'second queued', ts: 2 },+ ],+ })}+ />,+ );++ const rows = screen.getAllByTestId('agent-thread-queued');+ expect(rows).toHaveLength(2);+ expect(rows[0]?.textContent).toContain('first queued');+ expect(rows[1]?.textContent).toContain('second queued');++ const firstRow = rows[0];+ if (firstRow === undefined) throw new Error('missing queue row');+ fireEvent.click(within(firstRow).getByTestId('agent-thread-queued-remove'));+ expect(removeQueued).toHaveBeenCalledWith('thread-1', 'q1');+ });++ test('in-place edit opens with the current content and saves on Enter', () => {+ model = makeModel({ turnActive: true });+ render(+ <ThreadView+ info={makeInfo({+ status: 'running',+ queue: [{ id: 'q1', content: 'original text', ts: 1 }],+ })}+ />,+ );++ fireEvent.click(screen.getByTestId('agent-thread-queued-edit'));+ const input = screen.getByTestId('agent-thread-queued-input') as HTMLTextAreaElement;+ expect(input.value).toBe('original text');++ fireEvent.change(input, { target: { value: 'sharper text' } });+ fireEvent.keyDown(input, { key: 'Enter' });+ expect(editQueued).toHaveBeenCalledWith('thread-1', 'q1', 'sharper text');+ // The row returned to display mode.+ expect(screen.queryByTestId('agent-thread-queued-input')).toBeNull();+ expect(screen.getByTestId('agent-thread-queued')).toBeTruthy();+ });++ test('Escape abandons the edit without sending anything', () => {+ model = makeModel({ turnActive: true });+ render(+ <ThreadView+ info={makeInfo({+ status: 'running',+ queue: [{ id: 'q1', content: 'keep me', ts: 1 }],+ })}+ />,+ );++ fireEvent.click(screen.getByTestId('agent-thread-queued-edit'));+ const input = screen.getByTestId('agent-thread-queued-input') as HTMLTextAreaElement;+ fireEvent.change(input, { target: { value: 'discarded' } });+ fireEvent.keyDown(input, { key: 'Escape' });++ expect(editQueued).not.toHaveBeenCalled();+ expect(screen.queryByTestId('agent-thread-queued-input')).toBeNull();+ expect(screen.getByTestId('agent-thread-queued').textContent).toContain('keep me');+ });+});diff --git a/packages/app/src/components/acp/ThreadView.tsx b/packages/app/src/components/acp/ThreadView.tsxindex 2dc4af0f7..5d201844e 100644--- a/packages/app/src/components/acp/ThreadView.tsx+++ b/packages/app/src/components/acp/ThreadView.tsx@@ -9,6 +9,7 @@*/import type {+ QueuedMessage,SessionConfigOption,ThreadInfo,} from '@inkeep/open-knowledge-core/acp/thread-protocol';@@ -29,6 +30,7 @@ import {Terminal as TerminalIcon,Trash2,Wrench,+ X,} from 'lucide-react';import {Fragment,@@ -64,7 +66,13 @@ 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 {+ agentSettingsKey,+ rememberAgentConfigOption,+ rememberAgentMode,+} from '@/lib/acp/agent-settings-store';import { computeDiffRows } from '@/lib/acp/inline-diff';+import { isPermissiveMode } from '@/lib/acp/permissive-mode';import { renderTerminalText } from '@/lib/acp/terminal-text';import {getAgentThreadClient,@@ -157,6 +165,9 @@ export function ThreadView({ info }: { info: ThreadInfo }): ReactNode {const [resumePending, setResumePending] = useState(false);const [resumeError, setResumeError] = useState<ThreadResumeError | null>(null);const canPrompt = archived ? !resumePending : status === 'ready' && !turnActive;+ // Mid-turn sends don't reject anymore — the server queues them behind the+ // active turn and drains FIFO (`ThreadInfo.queue`).+ const canQueue = !archived && 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).@@ -283,7 +294,7 @@ export function ThreadView({ info }: { info: ThreadInfo }): ReactNode {const submit = (): void => {const text = draft.trim();- if (text === '' || !canPrompt) return;+ if (text === '' || !(canPrompt || canQueue)) 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@@ -445,6 +456,7 @@ export function ThreadView({ info }: { info: ThreadInfo }): ReactNode {onDraftChange={setDraft}onSubmit={submit}canPrompt={canPrompt}+ canQueue={canQueue}turnActive={turnActive}cancelPending={cancelPending}onCancel={requestCancel}@@ -525,47 +537,130 @@ function hasSelectValues(option: SelectConfigOption): boolean {return option.options.some((entry) => ('value' in entry ? true : entry.options.length > 0));}+/** Every selectable value, flattened across groups. */+function flattenSelectValues(option: SelectConfigOption): Array<{ id: string; name: string }> {+ const flat: Array<{ id: string; name: string }> = [];+ for (const entry of option.options) {+ if ('value' in entry) flat.push({ id: entry.value, name: entry.name });+ else for (const grouped of entry.options) flat.push({ id: grouped.value, name: grouped.name });+ }+ return flat;+}++/**+ * The one mode surface this agent exposes, normalized. Agents advertise modes+ * either as a mode-category config option (current) or as `SessionModeState`+ * (legacy `session/set_mode`) — `configId` says which, so callers apply a mode+ * without re-deriving the branch. Single source of truth for the settings menu+ * and the mode offer, which must agree on what "the current mode" is.+ */+interface ModeSurface {+ /** Config-option id, or null when the agent uses legacy `session/set_mode`. */+ configId: string | null;+ currentId: string;+ currentName: string;+ values: ReadonlyArray<{ id: string; name: string }>;+}++function deriveModeSurface(info: ThreadInfo): ModeSurface | null {+ const modeOption = (info.configOptions ?? []).find(+ (option): option is SelectConfigOption =>+ option.type === 'select' && option.category === 'mode' && hasSelectValues(option),+ );+ if (modeOption !== undefined) {+ return {+ configId: modeOption.id,+ currentId: modeOption.currentValue,+ currentName: selectOptionName(modeOption),+ values: flattenSelectValues(modeOption),+ };+ }+ // `modes` predates generalized config options. Keep it as a fallback, but+ // never duplicate a mode the agent already exposes in `configOptions`.+ const modes = info.modes;+ if (modes != null && modes.availableModes.length > 1) {+ return {+ configId: null,+ currentId: modes.currentModeId,+ currentName:+ modes.availableModes.find((mode) => mode.id === modes.currentModeId)?.name ??+ modes.currentModeId,+ values: modes.availableModes.map((mode) => ({ id: mode.id, name: mode.name })),+ };+ }+ return null;+}+/** One stable trigger for every setting an ACP agent advertises. */function AgentSettingsPopover({ info }: { info: ThreadInfo }): ReactNode {const { t } = useLingui();const client = getAgentThreadClient();+ const settingsKey = agentSettingsKey(info.agent);+ const applyConfig = (option: SessionConfigOption, value: string | boolean): void => {+ client.setConfigOption(info.threadId, option.id, value);+ // Every pick carries to the next thread of this agent, modes included — a+ // mode advertised as a config option needs no special case. What keeps a+ // restored permissive mode honest is the accent below, not withholding it.+ rememberAgentConfigOption(settingsKey, option.id, value);+ };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');+ const modeSurface = deriveModeSurface(info);+ const showLegacyModes = modeSurface !== null && modeSurface.configId === null;if (configOptions.length === 0 && !showLegacyModes) return null;+ const legacyModeName = showLegacyModes ? modeSurface.currentName : undefined;+ // Modes carry across threads like everything else, so the thing worth+ // marking is not "this was restored" but "this mode lets the agent act+ // without asking" — true whether it was restored or just picked. Best-effort+ // name matching; see `permissive-mode.ts` for why a hint is the right bar.+ const permissiveMode =+ modeSurface !== null &&+ isPermissiveMode({ id: modeSurface.currentId, name: modeSurface.currentName });+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`);+ const accentTooltip =+ permissiveMode && modeSurface !== null+ ? t`${modeSurface.currentName} lets ${info.agent.name} act without asking`+ : t`Agent 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>+ <Tooltip>+ <TooltipTrigger asChild>+ <DropdownMenuTrigger asChild>+ <Button+ type="button"+ variant="ghost"+ className="h-6 max-w-48 gap-1 rounded-md px-2 text-xs"+ aria-label={accentTooltip}+ data-testid="agent-thread-settings"+ >+ {/* A mode that lets the agent act unprompted should never be in+ force unnoticed — least of all one carried over from an+ earlier thread. Kept small and low-contrast: present, not+ alarming. */}+ {permissiveMode ? (+ <span+ className="size-1.5 shrink-0 rounded-full bg-amber-500 ring-[3px] ring-amber-500/15 dark:bg-amber-400 dark:ring-amber-400/15"+ data-testid="agent-thread-mode-accent"+ aria-hidden="true"+ />+ ) : null}+ <span className="truncate">{triggerText}</span>+ <ChevronDown className="size-3.5" data-icon="inline-end" aria-hidden="true" />+ </Button>+ </DropdownMenuTrigger>+ </TooltipTrigger>+ <TooltipContent side="bottom">{accentTooltip}</TooltipContent>+ </Tooltip>{/* Hybrid menu: each multi-value select is a submenu row summarizing itscurrent value; a lone boolean stays inline. The compact top level scalesas agents expose more (and longer-described) options — the sprawl lives@@ -576,27 +671,30 @@ function AgentSettingsPopover({ info }: { info: ThreadInfo }): ReactNode {<ConfigSelectSubkey={option.id}option={option}- onSelect={(value) => client.setConfigOption(info.threadId, option.id, value)}+ onSelect={(value) => applyConfig(option, value)}/>) : (<ConfigBooleanItemkey={option.id}option={option}- onCheckedChange={(value) => client.setConfigOption(info.threadId, option.id, value)}+ onCheckedChange={(value) => applyConfig(option, value)}/>),)}- {showLegacyModes && modes != null ? (+ {showLegacyModes ? (<ConfigSelectSuboption={{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 })),+ currentValue: modeSurface.currentId,+ options: modeSurface.values.map((mode) => ({ value: mode.id, name: mode.name })),+ }}+ onSelect={(modeId) => {+ client.setMode(info.threadId, modeId);+ rememberAgentMode(settingsKey, modeId);}}- onSelect={(modeId) => client.setMode(info.threadId, modeId)}/>) : null}</DropdownMenuContent>@@ -1841,6 +1939,7 @@ function ThreadComposer({onDraftChange,onSubmit,canPrompt,+ canQueue,turnActive,cancelPending,onCancel,@@ -1854,6 +1953,8 @@ function ThreadComposer({onDraftChange: (value: string) => void;onSubmit: () => void;canPrompt: boolean;+ /** A turn is running — sends queue behind it instead of dispatching. */+ canQueue: boolean;turnActive: boolean;/** Stop was pressed and the turn hasn't ended yet. */cancelPending: boolean;@@ -1887,8 +1988,13 @@ function ThreadComposer({? Math.min(100, Math.round((usage.used / usage.size) * 100)): null;+ const queue = info.queue ?? [];+return (<div className="p-2">+ {queue.length > 0 && !archived ? (+ <QueuedMessageList threadId={info.threadId} queue={queue} />+ ) : null}{/* Two-row field: the textarea fills the full width on top; a bottom barholds the model/agent settings (left) and the context ring + send/stop(right). The wrapper owns the border + focus ring so the whole box lights@@ -1962,22 +2068,162 @@ function ThreadComposer({<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>- )}+ ) : null}+ <Button+ type="button"+ size="icon-sm"+ className="rounded-lg"+ disabled={!(canPrompt || canQueue) || draft.trim() === ''}+ onClick={onSubmit}+ aria-label={canQueue ? t`Queue message` : t`Send`}+ data-testid="agent-thread-send"+ >+ <ArrowUp className="size-4" aria-hidden="true" />+ </Button></div></div></div></div>);}++/** Messages waiting behind the active turn, shown between the transcript and+ * the composer. Server-authoritative (`ThreadInfo.queue`): rows appear for+ * every subscriber of the thread and vanish as each entry dispatches. */+function QueuedMessageList({+ threadId,+ queue,+}: {+ threadId: string;+ queue: readonly QueuedMessage[];+}): ReactNode {+ const { t } = useLingui();+ return (+ <div className="mb-1.5 flex flex-col gap-1" data-testid="agent-thread-queue">+ <span className="px-1 font-medium text-[10px] text-muted-foreground/70 uppercase tracking-wide">+ {t`Queued`}+ </span>+ {queue.map((message) => (+ <QueuedMessageRow key={message.id} threadId={threadId} message={message} />+ ))}+ </div>+ );+}++function QueuedMessageRow({+ threadId,+ message,+}: {+ threadId: string;+ message: QueuedMessage;+}): ReactNode {+ const { t } = useLingui();+ const client = getAgentThreadClient();+ const [editing, setEditing] = useState(false);+ const [value, setValue] = useState('');++ const startEdit = (): void => {+ setValue(message.content);+ setEditing(true);+ };+ const save = (): void => {+ const trimmed = value.trim();+ if (trimmed === '') {+ // Empty isn't a valid queued prompt. Treat Enter-on-empty as cancel —+ // exit editing and keep the original — rather than trapping the user in+ // edit mode with a silent no-op. Removing is its own explicit action.+ setEditing(false);+ return;+ }+ // The server confirms via an `info` frame; if the entry dispatched while+ // the edit was open, the row unmounts and the transcript shows what ran.+ if (trimmed !== message.content) client.editQueued(threadId, message.id, trimmed);+ setEditing(false);+ };++ if (editing) {+ return (+ <div+ className="rounded-md border border-input bg-muted/30 p-1"+ data-testid="agent-thread-queued-editing"+ >+ <Textarea+ value={value}+ onChange={(event) => setValue(event.target.value)}+ onKeyDown={(event) => {+ if (event.key === 'Enter' && !event.shiftKey) {+ event.preventDefault();+ save();+ } else if (event.key === 'Escape') {+ event.preventDefault();+ setEditing(false);+ }+ }}+ autoFocus+ rows={1}+ aria-label={t`Edit queued message`}+ className="min-h-8 resize-none border-0 bg-transparent px-1.5 py-1 shadow-none focus-visible:border-0 focus-visible:ring-0 dark:bg-transparent"+ data-testid="agent-thread-queued-input"+ />+ <div className="flex items-center justify-end gap-1">+ <Button+ type="button"+ size="icon-sm"+ variant="ghost"+ className="size-6"+ onClick={() => setEditing(false)}+ aria-label={t`Cancel editing`}+ data-testid="agent-thread-queued-cancel-edit"+ >+ <X className="size-3.5" aria-hidden="true" />+ </Button>+ <Button+ type="button"+ size="icon-sm"+ variant="ghost"+ className="size-6"+ disabled={value.trim() === ''}+ onClick={save}+ aria-label={t`Save queued message`}+ data-testid="agent-thread-queued-save"+ >+ <Check className="size-3.5" aria-hidden="true" />+ </Button>+ </div>+ </div>+ );+ }++ return (+ <div+ className="flex items-center gap-1 rounded-md border border-input/60 bg-muted/30 py-0.5 pl-2 pr-1"+ data-testid="agent-thread-queued"+ >+ <span className="min-w-0 flex-1 truncate text-muted-foreground text-sm">+ {message.content}+ </span>+ <Button+ type="button"+ size="icon-sm"+ variant="ghost"+ className="size-6 shrink-0 text-muted-foreground"+ onClick={startEdit}+ aria-label={t`Edit queued message`}+ data-testid="agent-thread-queued-edit"+ >+ <SquarePen className="size-3.5" aria-hidden="true" />+ </Button>+ <Button+ type="button"+ size="icon-sm"+ variant="ghost"+ className="size-6 shrink-0 text-muted-foreground"+ onClick={() => client.removeQueued(threadId, message.id)}+ aria-label={t`Remove queued message`}+ data-testid="agent-thread-queued-remove"+ >+ <X className="size-3.5" aria-hidden="true" />+ </Button>+ </div>+ );+}diff --git a/packages/app/src/lib/acp/agent-settings-store.test.ts b/packages/app/src/lib/acp/agent-settings-store.test.tsnew file mode 100644index 000000000..e41f50c59--- /dev/null+++ b/packages/app/src/lib/acp/agent-settings-store.test.ts@@ -0,0 +1,121 @@+import { beforeEach, describe, expect, test } from 'vitest';++// Plain test runner has no localStorage — install a minimal stub BEFORE the+// module under test first touches it.+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 {+ agentSettingsKey,+ getRememberedAgentConfig,+ getRememberedAgentMode,+ rememberAgentConfigOption,+ rememberAgentMode,+} from './agent-settings-store';++const STORAGE_KEY = 'ok-acp-agent-settings-v1';++beforeEach(() => localStorage.clear());++describe('agent-settings-store', () => {+ test('agentSettingsKey matches the registered-agents <source>:<id> shape', () => {+ expect(agentSettingsKey({ source: 'registry', id: 'claude-acp' })).toBe('registry:claude-acp');+ expect(agentSettingsKey({ source: 'custom', id: 'x' })).toBe('custom:x');+ });++ test('nothing stored → undefined', () => {+ expect(getRememberedAgentConfig('registry:claude-acp')).toBeUndefined();+ });++ test('remembers config options per agent type', () => {+ const key = agentSettingsKey({ source: 'registry', id: 'claude-acp' });+ rememberAgentConfigOption(key, 'model', 'opus');+ rememberAgentConfigOption(key, 'thought_level', 'xhigh');+ rememberAgentConfigOption(key, 'verbose', true);+ expect(getRememberedAgentConfig(key)).toEqual({+ model: 'opus',+ thought_level: 'xhigh',+ verbose: true,+ });+ });++ test('a later pick overwrites the same option, keeps the others', () => {+ const key = agentSettingsKey({ source: 'custom', id: 'a' });+ rememberAgentConfigOption(key, 'model', 'sonnet');+ rememberAgentConfigOption(key, 'model', 'opus');+ rememberAgentConfigOption(key, 'thought_level', 'high');+ expect(getRememberedAgentConfig(key)).toEqual({ model: 'opus', thought_level: 'high' });+ });++ test('keeps agent types isolated', () => {+ const a = agentSettingsKey({ source: 'registry', id: 'claude-acp' });+ const b = agentSettingsKey({ source: 'registry', id: 'codex' });+ rememberAgentConfigOption(a, 'model', 'opus');+ rememberAgentConfigOption(b, 'model', 'gpt-5');+ expect(getRememberedAgentConfig(a)).toEqual({ model: 'opus' });+ expect(getRememberedAgentConfig(b)).toEqual({ model: 'gpt-5' });+ });++ test('a corrupt payload reads as empty and does not throw', () => {+ localStorage.setItem(STORAGE_KEY, '{not json');+ expect(getRememberedAgentConfig('registry:x')).toBeUndefined();+ // …and the store is still writable afterward.+ rememberAgentConfigOption('registry:x', 'model', 'opus');+ expect(getRememberedAgentConfig('registry:x')).toEqual({ model: 'opus' });+ });++ test('drops non-primitive values from a tampered payload', () => {+ localStorage.setItem(+ STORAGE_KEY,+ JSON.stringify({ 'registry:x': { config: { model: 'opus', bad: { nested: 1 } } } }),+ );+ expect(getRememberedAgentConfig('registry:x')).toEqual({ model: 'opus' });+ });++ test('a legacy-surface mode is remembered alongside config, not instead of it', () => {+ const key = agentSettingsKey({ source: 'registry', id: 'claude-acp' });+ expect(getRememberedAgentMode(key)).toBeUndefined();+ rememberAgentConfigOption(key, 'model', 'opus');+ rememberAgentMode(key, 'bypass');+ expect(getRememberedAgentConfig(key)).toEqual({ model: 'opus' });+ expect(getRememberedAgentMode(key)).toBe('bypass');+ });++ test('a later mode pick overwrites the earlier one', () => {+ const key = agentSettingsKey({ source: 'custom', id: 'b' });+ rememberAgentMode(key, 'plan');+ rememberAgentMode(key, 'bypass');+ expect(getRememberedAgentMode(key)).toBe('bypass');+ });++ // The storage key is unversioned across the mode-persistence redesign, so a+ // payload written by the previous shape is what real users upgrade with.+ test('a mode saved by the previous release is still honoured', () => {+ localStorage.setItem(+ STORAGE_KEY,+ JSON.stringify({ 'registry:x': { config: { model: 'opus' }, modeId: 'bypass' } }),+ );+ expect(getRememberedAgentMode('registry:x')).toBe('bypass');+ expect(getRememberedAgentConfig('registry:x')).toEqual({ model: 'opus' });+ });++ test('a retired field from the previous shape is ignored, not fatal', () => {+ // `lastModeId` backed the old offer flow; nothing reads it now.+ localStorage.setItem(+ STORAGE_KEY,+ JSON.stringify({ 'registry:x': { lastModeId: 'bypass', config: { model: 'opus' } } }),+ );+ expect(getRememberedAgentMode('registry:x')).toBeUndefined();+ expect(getRememberedAgentConfig('registry:x')).toEqual({ model: 'opus' });+ // …and the entry stays writable afterward.+ rememberAgentMode('registry:x', 'plan');+ expect(getRememberedAgentMode('registry:x')).toBe('plan');+ });+});diff --git a/packages/app/src/lib/acp/agent-settings-store.ts b/packages/app/src/lib/acp/agent-settings-store.tsnew file mode 100644index 000000000..015197505--- /dev/null+++ b/packages/app/src/lib/acp/agent-settings-store.ts@@ -0,0 +1,103 @@+/**+ * Per-agent-type remembered ACP thread settings (model, thought level, and+ * other config options). Picking a model / effort in one thread makes the next+ * thread of the SAME agent open on that choice — the choice rides the `create`+ * frame and the server applies it between `session/new` and the first prompt.+ *+ * localStorage-only, like the other launcher preferences. Write-mostly /+ * read-once-per-launch, so — unlike `registered-agents.ts` — it keeps no+ * module-scope cache and does no cross-tab `storage` plumbing: each call reads+ * or writes fresh.+ *+ * Every pick is remembered, modes included. A mode can be permission-affecting+ * (Claude's `bypassPermissions`, Gemini's YOLO), so a restored one must stay+ * legible rather than silent: the settings trigger flags a mode that reads as+ * permissive with an amber accent, whether it was restored or just chosen. See+ * `permissive-mode.ts`.+ */++const STORAGE_KEY = 'ok-acp-agent-settings-v1';++type ConfigValue = string | boolean;+// `modeId` matches the wire naming end-to-end (`settings.modeId`,+// `modes.currentModeId`, `session/set_mode`) so the value keeps one name from+// localStorage through the server. It carries the legacy `SessionModeState`+// surface only — an agent that exposes its mode as a config option stores it+// in `config` like any other option, with no special case anywhere.+type StoredAgentSettings = { config?: Record<string, ConfigValue>; modeId?: string };+type Store = Record<string, StoredAgentSettings>;++/** Stable per-agent identity — the same `<source>:<id>` key `registered-agents.ts` uses. */+export function agentSettingsKey(agent: { source: 'registry' | 'custom'; id: string }): string {+ return `${agent.source}:${agent.id}`;+}++function read(): Store {+ try {+ const raw = localStorage.getItem(STORAGE_KEY);+ if (raw === null) return {};+ const parsed = JSON.parse(raw) as unknown;+ return typeof parsed === 'object' && parsed !== null ? (parsed as Store) : {};+ } catch {+ // No localStorage (non-browser) or corrupt payload — behave as empty.+ return {};+ }+}++function write(store: Store): void {+ try {+ localStorage.setItem(STORAGE_KEY, JSON.stringify(store));+ } catch (err) {+ // Quota / privacy mode — the choice simply won't carry to the next thread.+ // Log (no toast) so "my picks don't stick" leaves evidence in DevTools while+ // keeping the graceful-degradation contract: never throw, never interrupt.+ console.warn('[acp-settings] could not persist agent settings', err);+ }+}++/** Remember a config-option choice for this agent type. */+export function rememberAgentConfigOption(+ agentKey: string,+ configId: string,+ value: ConfigValue,+): void {+ const store = read();+ const entry = store[agentKey] ?? {};+ store[agentKey] = { ...entry, config: { ...entry.config, [configId]: value } };+ write(store);+}++/**+ * The remembered config-option map for this agent type, or undefined when+ * nothing is stored. Non-primitive values from a corrupt payload are dropped.+ */+export function getRememberedAgentConfig(+ agentKey: string,+): Record<string, ConfigValue> | undefined {+ const config = read()[agentKey]?.config;+ if (typeof config !== 'object' || config === null) return undefined;+ const clean: Record<string, ConfigValue> = {};+ for (const [k, v] of Object.entries(config)) {+ if (typeof v === 'string' || typeof v === 'boolean') clean[k] = v;+ }+ return Object.keys(clean).length > 0 ? clean : undefined;+}++/**+ * Remember a legacy-surface mode pick, so the next thread of this agent opens+ * on it. Modes that expose themselves as config options go through+ * {@link rememberAgentConfigOption} instead.+ */+export function rememberAgentMode(agentKey: string, modeId: string): void {+ if (modeId === '') return;+ const store = read();+ const entry = store[agentKey] ?? {};+ store[agentKey] = { ...entry, modeId };+ write(store);+}++/** The remembered legacy-surface mode for this agent type, or undefined. */+export function getRememberedAgentMode(agentKey: string): string | undefined {+ const modeId = read()[agentKey]?.modeId;+ return typeof modeId === 'string' && modeId !== '' ? modeId : undefined;+}diff --git a/packages/app/src/lib/acp/permissive-mode.test.ts b/packages/app/src/lib/acp/permissive-mode.test.tsnew file mode 100644index 000000000..50be539a0--- /dev/null+++ b/packages/app/src/lib/acp/permissive-mode.test.ts@@ -0,0 +1,81 @@+import { describe, expect, test } from 'vitest';++import { isPermissiveMode } from './permissive-mode';++describe('isPermissiveMode', () => {+ // The id/name pairs below are the real `session/new` modes read out of the+ // shipped adapters (claude-agent-acp 0.63.0, codex-acp 1.1.7, gemini-cli+ // 0.52.0, cursor-agent 2026.07.23) — not their CLI flags, which differ.+ test.each([+ ['claude-agent-acp', 'bypassPermissions', 'Bypass Permissions'],+ ['claude-agent-acp', 'acceptEdits', 'Accept Edits'],+ // Codex's mode id is `agent-full-access`; `danger-full-access` is the+ // sandbox policy behind it and never reaches us as a mode.+ ['codex-acp', 'agent-full-access', 'Agent (full access)'],+ ['gemini-cli', 'yolo', 'YOLO'],+ ['gemini-cli', 'auto_edit', 'Auto Edit'],+ // goose names full autonomy exactly `auto` — matched as a whole word, so+ // an unrelated mode merely containing "auto" isn't dragged in with it.+ ['goose', 'auto', 'Auto'],+ ])('flags the real %s mode %s', (_adapter, id, name) => {+ expect(isPermissiveMode({ id, name })).toBe(true);+ });++ test.each([+ ['claude-agent-acp', 'default', 'Default'],+ ['claude-agent-acp', 'plan', 'Plan Mode'],+ ['codex-acp', 'read-only', 'Read-only'],+ // `agent` is Codex's AND Cursor's ordinary default — flagging it would put+ // a warning on the mode almost everyone runs.+ ['codex-acp', 'agent', 'Agent'],+ ['cursor-agent', 'agent', 'Agent'],+ ['cursor-agent', 'ask', 'Ask'],+ ['cursor-agent', 'plan', 'Plan'],+ ['gemini-cli', 'default', 'Default'],+ // Still prompts for the risky operations — flagging it would warn on+ // goose's recommended everyday mode.+ ['goose', 'smart_approve', 'Smart Approve'],+ ['goose', 'approve', 'Approve'],+ ['goose', 'chat', 'Chat'],+ // pi-acp puts reasoning effort on the modes surface, not permissions.+ ['pi-acp', 'xhigh', 'Thinking: xhigh'],+ ])('leaves the real %s mode %s alone', (_adapter, id, name) => {+ expect(isPermissiveMode({ id, name })).toBe(false);+ });++ // Not observed as mode ids, but this vocabulary is present in the shipped+ // binaries (opencode carries `unrestricted` / `autoApprove` / `dangerously`,+ // amp carries `dangerously`), so an agent surfacing one stays covered.+ test.each([+ ['dangerously-skip-permissions', 'Skip all permission checks'],+ ['full-auto', 'Full Auto'],+ ['auto_approve', 'Auto-approve tools'],+ ['no-confirm', 'Run without confirmation'],+ ['unrestricted', 'Unrestricted'],+ ])('flags %s on naming alone', (id, name) => {+ expect(isPermissiveMode({ id, name })).toBe(true);+ });++ test.each([+ ['code', 'Code'],+ ['architect', 'Architect'],+ ['edit', 'Edit'],+ ['workspace-write', 'Workspace write'],+ // "auto" flags only as a whole mode (goose), never as a substring.+ ['autocomplete', 'Autocomplete'],+ ['automation', 'Automation'],+ ])('leaves %s alone', (id, name) => {+ expect(isPermissiveMode({ id, name })).toBe(false);+ });++ test('matches on either the id or the name alone', () => {+ // Harnesses disagree about which half carries the meaning.+ expect(isPermissiveMode({ id: 'mode-3', name: 'Bypass permissions' })).toBe(true);+ expect(isPermissiveMode({ id: 'bypassPermissions', name: 'Fast' })).toBe(true);+ });++ test('name is optional', () => {+ expect(isPermissiveMode({ id: 'yolo' })).toBe(true);+ expect(isPermissiveMode({ id: 'plan' })).toBe(false);+ });+});diff --git a/packages/app/src/lib/acp/permissive-mode.ts b/packages/app/src/lib/acp/permissive-mode.tsnew file mode 100644index 000000000..bfc488328--- /dev/null+++ b/packages/app/src/lib/acp/permissive-mode.ts@@ -0,0 +1,94 @@+/**+ * Best-effort detection of agent modes that let the agent act without asking.+ *+ * ACP hands the client an opaque `{id, name}` mode list with no "affects+ * permissions" flag, so OK cannot know what a mode does. What it CAN do is+ * recognise the vocabulary the common harnesses use for their permissive modes+ * — Claude Code's `bypassPermissions` / `acceptEdits`, Gemini's YOLO, Codex's+ * full-auto and danger-full-access, and the auto-approve / skip-permissions+ * naming everyone converges on.+ *+ * This drives a visual warning only (the amber accent on the settings trigger).+ * It never gates, blocks, or rewrites a mode, so the failure modes are mild in+ * both directions: a miss loses a hint, a false positive shows one too many.+ * Deliberately biased toward matching — an unflagged bypass mode is the worse+ * error — but not so loose that ordinary modes (`plan`, `ask`, `architect`,+ * `code`, `default`) trip it.+ */++/**+ * Matched against the id and name with everything but letters removed, so+ * `accept-edits`, `acceptEdits`, and "Accept Edits" all reduce to+ * `acceptedits`. Keep the alternatives letters-only for the same reason.+ *+ * The first group is what the adapters in the ACP registry actually advertise+ * over `session/new` — read out of the shipped adapters, not from their CLI+ * flags, which differ (Codex's mode id is `agent-full-access`; the+ * `danger-full-access` you see in its docs is the sandbox policy behind it):+ *+ * claude-agent-acp default · plan · acceptEdits · bypassPermissions+ * codex-acp read-only · agent · agent-full-access+ * gemini-cli default · plan · auto_edit · yolo+ * cursor-agent agent · plan · ask (none permissive)+ * goose auto · approve · smart_approve · chat+ * pi-acp off · minimal · … · xhigh (see note below)+ *+ * The second group is naming seen in these tools' flags and elsewhere in their+ * binaries (opencode carries `unrestricted` / `autoApprove` / `dangerously`,+ * amp carries `dangerously`) but not yet observed as a mode id. Cheap to+ * carry: matching one costs a dot the user can ignore.+ *+ * `agent` must never be added — Codex and Cursor both call their ordinary+ * mode that, so it would flag what almost everyone runs. `smart_approve` is+ * likewise left alone: it still prompts for the risky operations.+ *+ * Not every agent uses modes for permissions at all — pi-acp exposes reasoning+ * effort through the same surface. Matching on permission vocabulary rather+ * than on "is a non-default mode" is what keeps those quiet.+ */+const PERMISSIVE = new RegExp(+ [+ // Observed in shipped adapters.+ 'bypass', // claude-agent-acp `bypassPermissions`+ 'acceptedits', // claude-agent-acp `acceptEdits`+ 'fullaccess', // codex-acp `agent-full-access`+ 'autoedit', // gemini-cli `auto_edit`+ 'yolo', // gemini-cli `yolo`+ // Speculative: seen in these tools' flags/docs, not (yet) as mode ids.+ 'danger', // `--dangerously-skip-permissions`, codex `danger-full-access`+ 'fullauto', // codex `--full-auto`+ 'autoaccept',+ 'autoapprove',+ 'autorun',+ 'skippermission',+ 'noconfirm',+ 'noprompt',+ 'unrestricted',+ 'allowall',+ ].join('|'),+);++/**+ * Words that mean "no approval" as a WHOLE mode, but are too common to match+ * as a substring: goose names its full-autonomy mode exactly `auto`, while+ * `auto` inside a longer word says nothing on its own (an "Autocomplete" mode+ * is not a permission grant). The specific `auto*` compounds that DO carry the+ * meaning — `auto_edit`, `autoApprove` — are in `PERMISSIVE` above.+ */+const PERMISSIVE_EXACT = new Set(['auto']);++/** Letters only, lowercased — separators and casing vary per harness. */+function normalize(value: string): string {+ return value.toLowerCase().replace(/[^a-z]/g, '');+}++/**+ * True when a mode's id or name reads as "act without asking". See the module+ * header for why this is a hint rather than a guarantee.+ */+export function isPermissiveMode(mode: { id: string; name?: string }): boolean {+ const id = normalize(mode.id);+ const name = normalize(mode.name ?? '');+ if (PERMISSIVE_EXACT.has(id) || PERMISSIVE_EXACT.has(name)) return true;+ return PERMISSIVE.test(id) || PERMISSIVE.test(name);+}diff --git a/packages/app/src/lib/acp/thread-client.ts b/packages/app/src/lib/acp/thread-client.tsindex 218ae0019..286e0912a 100644--- a/packages/app/src/lib/acp/thread-client.ts+++ b/packages/app/src/lib/acp/thread-client.ts@@ -23,6 +23,11 @@ import type {import { t } from '@lingui/core/macro';import { useSyncExternalStore } from 'react';import { toast } from 'sonner';+import {+ agentSettingsKey,+ getRememberedAgentConfig,+ getRememberedAgentMode,+} from './agent-settings-store';import { type ThreadRenderModel, ThreadRenderModelBuilder } from './thread-event-model';export interface ThreadState {@@ -194,7 +199,26 @@ export class AgentThreadClient {}, CREATE_TIMEOUT_MS);this.pendingCreates.set(reqId, { resolve, reject, timer });});- this.send({ op: 'create', reqId, ...params });+ // Carry this agent type's remembered settings so the server applies them+ // before turn 1 (a new thread of the same agent opens on the last-chosen+ // options). `modeId` covers the legacy mode surface; a mode advertised as a+ // config option already rides `config`. Absent → the agent's defaults stand.+ const settingsKey = agentSettingsKey(params.agent);+ const config = getRememberedAgentConfig(settingsKey);+ const modeId = getRememberedAgentMode(settingsKey);+ const settings =+ config !== undefined || modeId !== undefined+ ? {+ ...(config !== undefined ? { config } : {}),+ ...(modeId !== undefined ? { modeId } : {}),+ }+ : undefined;+ this.send({+ op: 'create',+ reqId,+ ...params,+ ...(settings !== undefined ? { settings } : {}),+ });return promise;}@@ -203,6 +227,20 @@ export class AgentThreadClient {this.send({ op: 'prompt', threadId, reqId: `prompt-${this.reqCounter}`, content });}+ /** Edit a message waiting in the thread's queue (`ThreadInfo.queue`) in+ * place. The server confirms via an `info` frame; an entry that already+ * dispatched is silently left alone. */+ editQueued(threadId: string, id: string, content: string): void {+ const trimmed = content.trim();+ if (trimmed === '') return;+ this.send({ op: 'queue_edit', threadId, id, content: trimmed });+ }++ /** Remove a message from the thread's queue before it dispatches. */+ removeQueued(threadId: string, id: string): void {+ this.send({ op: 'queue_remove', threadId, id });+ }+respondPermission(threadId: string,requestId: string,@@ -516,9 +554,9 @@ export class AgentThreadClient {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.+ // A rejected prompt (thread archived/not ready, or the queue is+ // full) 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;}diff --git a/packages/app/src/locales/en/messages.json b/packages/app/src/locales/en/messages.jsonindex aaa9468e4..11d8d8335 100644--- a/packages/app/src/locales/en/messages.json+++ b/packages/app/src/locales/en/messages.json@@ -18,6 +18,7 @@"-QCLWk": ["Templates available"],"-Qw-1t": ["GitHub authentication failed. Try signing in again."],"-WFFG2": ["Default properties"],+ "-WeuHF": ["Remove queued message"],"-YV1Uo": ["Pattern ", ["patternNumber"]],"-bFGPF": ["Next change"],"-dNlfM": ["Undid the last edit on ", ["docName"]],@@ -345,6 +346,7 @@],"5qQr1u": ["Allowed values for ", ["field"]],"5rnB76": ["Your edits stay on this computer"],+ "5soCUZ": ["Edit queued message"],"5tcmwY": ["Add value"],"5vAI6Z": ["It didn't fit into my workflow"],"5vYdh9": ["New thread with ", ["0"]],@@ -495,6 +497,7 @@],"8vCZcs": ["Failed to open file."],"8vETh9": ["Show"],+ "8wu9lr": ["Queued"],"92rbk2": ["Mirror loading <0>", ["mirrorRef"], "</0>"],"96G6Re": ["New folder"],"96w9hU": ["Something went wrong opening this file (HTTP ", ["status"], ")."],@@ -650,6 +653,7 @@"C62P6b": ["Editor selection"],"C7XjNB": ["Global Skill"],"C9TBvF": ["No Outgoing"],+ "CB7c0Z": ["Save queued message"],"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."],@@ -1226,6 +1230,7 @@"MqQoV-": ["Describe what you want to build, start a blank file, or scaffold from a template."],"MqsbfN": ["Turn on external link previews?"],"MrwYIK": ["Toggle a source comment through CodeMirror."],+ "MuxcRB": [["0"], " lets ", ["1"], " act without asking"],"My0wYT": ["When you hover an external link, its URL is sent to the destination site to fetch the page's preview metadata — one request per previewed link."],@@ -1462,6 +1467,7 @@"We'll build <0>openknowledge.skill</0>, save it to <1>~/Downloads</1>, and open the Claude Desktop App for you."],"RO-yts": ["Failed to disable link previews — ", ["detail"]],+ "RQWuCs": ["Queue message"],"RSqaSd": ["Project root"],"RVZJWQ": ["Search projects..."],"RXEbZy": ["In app"],@@ -2642,6 +2648,7 @@"n8DwqQ": ["Connects automatically the next time you open this project in a trusted Codex session."],+ "nBHvPL": ["Cancel editing"],"nCzR-G": ["Copy code ", ["userCode"]],"nD7Fx9": ["This replaces the current skill content with the bundled version ",diff --git a/packages/app/src/locales/en/messages.po b/packages/app/src/locales/en/messages.poindex aa32f8ea5..46aeefc6f 100644--- a/packages/app/src/locales/en/messages.po+++ b/packages/app/src/locales/en/messages.po@@ -224,6 +224,12 @@ msgstr "{0} hex value"msgid "{0} isn't installed yet — opening its download page."msgstr "{0} isn't installed yet — opening its download page."+#. placeholder {0}: modeSurface.currentName+#. placeholder {1}: info.agent.name+#: src/components/acp/ThreadView.tsx+msgid "{0} lets {1} act without asking"+msgstr "{0} lets {1} act without asking"+#. placeholder {0}: item.agentName#. placeholder {1}: item.displayName#: src/components/acp/ThreadView.tsx@@ -1610,6 +1616,10 @@ msgstr "Can't safely edit this tool's config"msgid "Cancel"msgstr "Cancel"+#: src/components/acp/ThreadView.tsx+msgid "Cancel editing"+msgstr "Cancel editing"+#: src/components/DocumentErrorBoundary.tsxmsgid "Cancelled"msgstr "Cancelled"@@ -3458,6 +3468,10 @@ msgstr "Edit in config file"msgid "Edit markdown link"msgstr "Edit markdown link"+#: src/components/acp/ThreadView.tsx+msgid "Edit queued message"+msgstr "Edit queued message"+#: src/components/settings/LintingSection.tsxmsgid "Edit schema {file}"msgstr "Edit schema {file}"@@ -7291,6 +7305,14 @@ msgstr "Push failed — check the server logs for details."msgid "Pushing"msgstr "Pushing"+#: src/components/acp/ThreadView.tsx+msgid "Queue message"+msgstr "Queue message"++#: src/components/acp/ThreadView.tsx+msgid "Queued"+msgstr "Queued"+#: src/editor/slash-command/items.tsxmsgid "Quote"msgstr "Quote"@@ -7516,6 +7538,10 @@ msgstr "Remove OpenKnowledge from {0}"msgid "Remove property"msgstr "Remove property"+#: src/components/acp/ThreadView.tsx+msgid "Remove queued message"+msgstr "Remove queued message"+#: src/components/BottomComposer.tsxmsgid "Remove selection"msgstr "Remove selection"@@ -7964,6 +7990,10 @@ msgstr "Save changes"msgid "Save failed: {error}"msgstr "Save failed: {error}"+#: src/components/acp/ThreadView.tsx+msgid "Save queued message"+msgstr "Save queued message"+#: src/components/DiffView.tsxmsgid "Save resolution"msgstr "Save resolution"diff --git a/packages/app/src/locales/pseudo/messages.json b/packages/app/src/locales/pseudo/messages.jsonindex b76e70f6e..c37a7a0e9 100644--- a/packages/app/src/locales/pseudo/messages.json+++ b/packages/app/src/locales/pseudo/messages.json@@ -18,6 +18,7 @@"-QCLWk": ["Ţēḿƥĺàţēś àvàĩĺàƀĺē"],"-Qw-1t": ["ĜĩţĤũƀ àũţĥēńţĩćàţĩōń ƒàĩĺēď. Ţŕŷ śĩĝńĩńĝ ĩń àĝàĩń."],"-WFFG2": ["Ďēƒàũĺţ ƥŕōƥēŕţĩēś"],+ "-WeuHF": ["Ŕēḿōvē ǫũēũēď ḿēśśàĝē"],"-YV1Uo": ["Ƥàţţēŕń ", ["patternNumber"]],"-bFGPF": ["Ńēxţ ćĥàńĝē"],"-dNlfM": ["Ũńďĩď ţĥē ĺàśţ ēďĩţ ōń ", ["docName"]],@@ -345,6 +346,7 @@],"5qQr1u": ["Àĺĺōŵēď vàĺũēś ƒōŕ ", ["field"]],"5rnB76": ["Ŷōũŕ ēďĩţś śţàŷ ōń ţĥĩś ćōḿƥũţēŕ"],+ "5soCUZ": ["Ēďĩţ ǫũēũēď ḿēśśàĝē"],"5tcmwY": ["Àďď vàĺũē"],"5vAI6Z": ["Ĩţ ďĩďń'ţ ƒĩţ ĩńţō ḿŷ ŵōŕķƒĺōŵ"],"5vYdh9": ["Ńēŵ ţĥŕēàď ŵĩţĥ ", ["0"]],@@ -495,6 +497,7 @@],"8vCZcs": ["Ƒàĩĺēď ţō ōƥēń ƒĩĺē."],"8vETh9": ["Śĥōŵ"],+ "8wu9lr": ["Ǫũēũēď"],"92rbk2": ["Ḿĩŕŕōŕ ĺōàďĩńĝ <0>", ["mirrorRef"], "</0>"],"96G6Re": ["Ńēŵ ƒōĺďēŕ"],"96w9hU": ["Śōḿēţĥĩńĝ ŵēńţ ŵŕōńĝ ōƥēńĩńĝ ţĥĩś ƒĩĺē (ĤŢŢƤ ", ["status"], ")."],@@ -650,6 +653,7 @@"C62P6b": ["Ēďĩţōŕ śēĺēćţĩōń"],"C7XjNB": ["Ĝĺōƀàĺ Śķĩĺĺ"],"C9TBvF": ["Ńō Ōũţĝōĩńĝ"],+ "CB7c0Z": ["Śàvē ǫũēũēď ḿēśśàĝē"],"CBsdhe": ["Ţĥē àĝēńţ ĩśń'ţ śţōƥƥĩńĝ. Ƒōŕćē śţōƥ ćĺōśēś ţĥĩś ţĥŕēàď àńď ǫũĩţś ţĥē àĝēńţ."],"CCTop_": ["Ŕēćēńţ"],"CFnavk": ["Ţĥĩś ƥŕōĴēćţ ĩśń'ţ à ĝĩţ ŕēƥōśĩţōŕŷ, śō ŵōŕķţŕēēś àŕēń'ţ àvàĩĺàƀĺē."],@@ -1226,6 +1230,7 @@"MqQoV-": ["Ďēśćŕĩƀē ŵĥàţ ŷōũ ŵàńţ ţō ƀũĩĺď, śţàŕţ à ƀĺàńķ ƒĩĺē, ōŕ śćàƒƒōĺď ƒŕōḿ à ţēḿƥĺàţē."],"MqsbfN": ["Ţũŕń ōń ēxţēŕńàĺ ĺĩńķ ƥŕēvĩēŵś?"],"MrwYIK": ["Ţōĝĝĺē à śōũŕćē ćōḿḿēńţ ţĥŕōũĝĥ ĆōďēḾĩŕŕōŕ."],+ "MuxcRB": [["0"], " ĺēţś ", ["1"], " àćţ ŵĩţĥōũţ àśķĩńĝ"],"My0wYT": ["Ŵĥēń ŷōũ ĥōvēŕ àń ēxţēŕńàĺ ĺĩńķ, ĩţś ŨŔĹ ĩś śēńţ ţō ţĥē ďēśţĩńàţĩōń śĩţē ţō ƒēţćĥ ţĥē ƥàĝē'ś ƥŕēvĩēŵ ḿēţàďàţà — ōńē ŕēǫũēśţ ƥēŕ ƥŕēvĩēŵēď ĺĩńķ."],@@ -1462,6 +1467,7 @@"Ŵē'ĺĺ ƀũĩĺď <0>ōƥēńķńōŵĺēďĝē.śķĩĺĺ</0>, śàvē ĩţ ţō <1>~/Ďōŵńĺōàďś</1>, àńď ōƥēń ţĥē Ćĺàũďē Ďēśķţōƥ Àƥƥ ƒōŕ ŷōũ."],"RO-yts": ["Ƒàĩĺēď ţō ďĩśàƀĺē ĺĩńķ ƥŕēvĩēŵś — ", ["detail"]],+ "RQWuCs": ["Ǫũēũē ḿēśśàĝē"],"RSqaSd": ["ƤŕōĴēćţ ŕōōţ"],"RVZJWQ": ["Śēàŕćĥ ƥŕōĴēćţś..."],"RXEbZy": ["Ĩń àƥƥ"],@@ -2642,6 +2648,7 @@"n8DwqQ": ["Ćōńńēćţś àũţōḿàţĩćàĺĺŷ ţĥē ńēxţ ţĩḿē ŷōũ ōƥēń ţĥĩś ƥŕōĴēćţ ĩń à ţŕũśţēď Ćōďēx śēśśĩōń."],+ "nBHvPL": ["Ćàńćēĺ ēďĩţĩńĝ"],"nCzR-G": ["Ćōƥŷ ćōďē ", ["userCode"]],"nD7Fx9": ["Ţĥĩś ŕēƥĺàćēś ţĥē ćũŕŕēńţ śķĩĺĺ ćōńţēńţ ŵĩţĥ ţĥē ƀũńďĺēď vēŕśĩōń ",diff --git a/packages/app/src/locales/pseudo/messages.po b/packages/app/src/locales/pseudo/messages.poindex b4c6adda2..0cbb209ff 100644--- a/packages/app/src/locales/pseudo/messages.po+++ b/packages/app/src/locales/pseudo/messages.po@@ -224,6 +224,12 @@ msgstr ""msgid "{0} isn't installed yet — opening its download page."msgstr ""+#. placeholder {0}: modeSurface.currentName+#. placeholder {1}: info.agent.name+#: src/components/acp/ThreadView.tsx+msgid "{0} lets {1} act without asking"+msgstr ""+#. placeholder {0}: item.agentName#. placeholder {1}: item.displayName#: src/components/acp/ThreadView.tsx@@ -1606,6 +1612,10 @@ msgstr ""msgid "Cancel"msgstr ""+#: src/components/acp/ThreadView.tsx+msgid "Cancel editing"+msgstr ""+#: src/components/DocumentErrorBoundary.tsxmsgid "Cancelled"msgstr ""@@ -3454,6 +3464,10 @@ msgstr ""msgid "Edit markdown link"msgstr ""+#: src/components/acp/ThreadView.tsx+msgid "Edit queued message"+msgstr ""+#: src/components/settings/LintingSection.tsxmsgid "Edit schema {file}"msgstr ""@@ -7287,6 +7301,14 @@ msgstr ""msgid "Pushing"msgstr ""+#: src/components/acp/ThreadView.tsx+msgid "Queue message"+msgstr ""++#: src/components/acp/ThreadView.tsx+msgid "Queued"+msgstr ""+#: src/editor/slash-command/items.tsxmsgid "Quote"msgstr ""@@ -7512,6 +7534,10 @@ msgstr ""msgid "Remove property"msgstr ""+#: src/components/acp/ThreadView.tsx+msgid "Remove queued message"+msgstr ""+#: src/components/BottomComposer.tsxmsgid "Remove selection"msgstr ""@@ -7960,6 +7986,10 @@ msgstr ""msgid "Save failed: {error}"msgstr ""+#: src/components/acp/ThreadView.tsx+msgid "Save queued message"+msgstr ""+#: src/components/DiffView.tsxmsgid "Save resolution"msgstr ""diff --git a/packages/app/src/server/hocuspocus-plugin.ts b/packages/app/src/server/hocuspocus-plugin.tsindex f935d0530..99a08896c 100644--- a/packages/app/src/server/hocuspocus-plugin.ts+++ b/packages/app/src/server/hocuspocus-plugin.ts@@ -13,11 +13,13 @@* wired to a soon-to-be-destroyed srv.*/import { existsSync, mkdirSync, readFileSync, realpathSync } from 'node:fs';+import { homedir } from 'node:os';import { relative, resolve } from 'node:path';import {ASSET_EXTENSIONS,EXECUTABLE_BLOCKLIST_EXTENSIONS,INLINE_RENDERABLE_EXTENSIONS,+ OK_DIR,} from '@inkeep/open-knowledge-core';import {AcpThreadManager,@@ -191,6 +193,9 @@ export function hocuspocusPlugin(): Plugin {: new AcpThreadManager({contentDir: CONTENT_DIR,localDir: currentSrv.lockDir,+ // Match boot.ts: transcripts under `~/.ok/threads`, cwd-scoped, with+ // the per-project dir read back for pre-move threads.+ globalDir: resolve(homedir(), OK_DIR),registry: currentSrv.acpRegistry,permissions: currentSrv.acpPermissions,sessionManager,diff --git a/packages/app/tests/dom/jsdom-preload.ts b/packages/app/tests/dom/jsdom-preload.tsindex 417b99616..adb8a2be7 100644--- a/packages/app/tests/dom/jsdom-preload.ts+++ b/packages/app/tests/dom/jsdom-preload.ts@@ -65,6 +65,27 @@ if (domWindow?.HTMLElement) {domWindow.HTMLElement.prototype.scrollIntoView ||= () => {};}+// jsdom doesn't implement layout, so `Range` has no `getClientRects` /+// `getBoundingClientRect`. ProseMirror measures a text Range on every+// selection scroll (`coordsAtPos` → `singleRect`), and TipTap dispatches that+// scroll ASYNCHRONOUSLY — so the resulting TypeError lands after the test that+// triggered it has finished, where vitest can only report it as an unhandled+// error and fail the whole run. Backfilling the two methods removes the throw+// at its source; empty rects are the honest answer in a layout-free DOM, and+// PM already treats a zero rect as "unmeasurable".+if (domWindow?.Range && typeof domWindow.Range.prototype.getClientRects !== 'function') {+ Object.defineProperty(domWindow.Range.prototype, 'getClientRects', {+ configurable: true,+ value: () => [],+ });+}+if (domWindow?.Range && typeof domWindow.Range.prototype.getBoundingClientRect !== 'function') {+ Object.defineProperty(domWindow.Range.prototype, 'getBoundingClientRect', {+ configurable: true,+ value: () => ({ bottom: 0, height: 0, left: 0, right: 0, top: 0, width: 0 }),+ });+}+// jsdom doesn't ship MessageChannel; React 19's scheduler uses it for postTask// scheduling. Node 24 provides it globally, but guard for jsdom builds that// shadow it as undefined.diff --git a/packages/core/src/acp/thread-protocol.test.ts b/packages/core/src/acp/thread-protocol.test.tsindex 94aa249a0..307367879 100644--- a/packages/core/src/acp/thread-protocol.test.ts+++ b/packages/core/src/acp/thread-protocol.test.ts@@ -43,6 +43,35 @@ describe('parseThreadClientFrame', () => {).toBeNull();});+ test('queue_edit requires threadId, id, and non-empty content', () => {+ expect(+ parseThreadClientFrame(+ JSON.stringify({ op: 'queue_edit', threadId: 't', id: 'q1', content: 'new text' }),+ ),+ ).toMatchObject({ op: 'queue_edit', threadId: 't', id: 'q1', content: 'new text' });+ expect(+ parseThreadClientFrame(+ JSON.stringify({ op: 'queue_edit', threadId: 't', id: 'q1', content: '' }),+ ),+ ).toBeNull();+ expect(+ parseThreadClientFrame(JSON.stringify({ op: 'queue_edit', threadId: 't', content: 'x' })),+ ).toBeNull();+ expect(+ parseThreadClientFrame(JSON.stringify({ op: 'queue_edit', id: 'q1', content: 'x' })),+ ).toBeNull();+ });++ test('queue_remove requires threadId and id', () => {+ expect(+ parseThreadClientFrame(JSON.stringify({ op: 'queue_remove', threadId: 't', id: 'q1' })),+ ).toMatchObject({ op: 'queue_remove', threadId: 't', id: 'q1' });+ expect(+ parseThreadClientFrame(JSON.stringify({ op: 'queue_remove', threadId: 't' })),+ ).toBeNull();+ expect(parseThreadClientFrame(JSON.stringify({ op: 'queue_remove', id: 'q1' }))).toBeNull();+ });+test('permission_response validates the outcome union', () => {expect(parseThreadClientFrame(@@ -210,3 +239,57 @@ describe('parseThreadClientFrame', () => {).toBeNull();});});++describe('parseThreadClientFrame create settings', () => {+ const base = { op: 'create', reqId: 'r', agent: { source: 'registry', id: 'x' } };++ test('accepts a create with a config settings map', () => {+ expect(+ parseThreadClientFrame(+ JSON.stringify({ ...base, settings: { config: { model: 'opus', verbose: true } } }),+ ),+ ).toMatchObject({ op: 'create', settings: { config: { model: 'opus', verbose: true } } });+ });++ test('accepts a create with no settings (settings is optional)', () => {+ expect(parseThreadClientFrame(JSON.stringify(base))).toMatchObject({ op: 'create' });+ });++ test('rejects non-object settings', () => {+ expect(parseThreadClientFrame(JSON.stringify({ ...base, settings: 'x' }))).toBeNull();+ });++ test('rejects a config that is not a plain object', () => {+ expect(+ parseThreadClientFrame(JSON.stringify({ ...base, settings: { config: [] } })),+ ).toBeNull();+ });++ test('rejects non-primitive config values', () => {+ expect(+ parseThreadClientFrame(+ JSON.stringify({ ...base, settings: { config: { model: { nested: 1 } } } }),+ ),+ ).toBeNull();+ });++ test('accepts a string modeId in settings', () => {+ expect(+ parseThreadClientFrame(JSON.stringify({ ...base, settings: { modeId: 'bypass' } })),+ ).toMatchObject({ op: 'create', settings: { modeId: 'bypass' } });+ });++ test('accepts config and modeId together', () => {+ expect(+ parseThreadClientFrame(+ JSON.stringify({ ...base, settings: { config: { model: 'opus' }, modeId: 'plan' } }),+ ),+ ).toMatchObject({ op: 'create', settings: { config: { model: 'opus' }, modeId: 'plan' } });+ });++ test('rejects a non-string modeId', () => {+ expect(+ parseThreadClientFrame(JSON.stringify({ ...base, settings: { modeId: 42 } })),+ ).toBeNull();+ });+});diff --git a/packages/core/src/acp/thread-protocol.ts b/packages/core/src/acp/thread-protocol.tsindex 7fb6f19fb..bfec64391 100644--- a/packages/core/src/acp/thread-protocol.ts+++ b/packages/core/src/acp/thread-protocol.ts@@ -58,6 +58,19 @@ export interface ThreadAgentInfo {source: 'registry' | 'custom';}+/**+ * A prompt waiting behind the active turn. Queue state is ephemeral —+ * in-memory only, dropped on cancel/error/exit and never persisted — so it+ * rides the `ThreadInfo` snapshot (meta channel), NOT the event log: a+ * replayed transcript must not resurrect ghost queue entries.+ */+export interface QueuedMessage {+ /** Server-assigned id — the handle `queue_edit` / `queue_remove` target. */+ id: string;+ content: string;+ ts: number;+}+/** Snapshot metadata for one thread (tab strip + thread header). */export interface ThreadInfo {threadId: string;@@ -79,12 +92,19 @@ export interface ThreadInfo {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+ * disk (`~/.ok/threads/`, or the pre-move per-project `.ok/local/threads/`+ * for threads created before that move). 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;+ /**+ * Prompts queued behind the active turn, FIFO. Absent (or empty) when+ * nothing is waiting. Live-thread-only and never persisted: the server+ * drops the queue on cancel, agent error/exit, and archive.+ */+ queue?: QueuedMessage[];}/** One entry in a thread's event log. */@@ -203,10 +223,40 @@ export type ThreadClientFrame =* deriving from `prompt`.*/titleHint?: string;+ /**+ * Remembered per-agent-type settings to apply between `session/new` and+ * the first prompt, so a new thread of the same agent opens on the+ * model / options the user last chose. `config` maps configId → value;+ * the server applies them (model-category first) so option cascades+ * re-validate before turn 1. `modeId` restores a mode on the legacy+ * `SessionModeState` surface (a mode advertised as a config option rides+ * `config` like any other option). The server validates it against the+ * live session's advertised modes; a mode that reads as permissive stays+ * visibly marked in the client while it is in force.+ */+ settings?: { config?: Record<string, string | boolean>; modeId?: string };}| { op: 'subscribe'; threadId: string; sinceSeq?: number }| { op: 'unsubscribe'; threadId: string }| { op: 'prompt'; threadId: string; reqId: string; content: string }+ | {+ /**+ * Replace a queued message's content in place. Targets an entry of+ * `ThreadInfo.queue` by its server-assigned id; an unknown id is a+ * silent no-op (the entry raced its own dispatch — the transcript+ * already shows the original was sent).+ */+ op: 'queue_edit';+ threadId: string;+ id: string;+ content: string;+ }+ | {+ /** Remove a queued message before it dispatches. Unknown id: no-op. */+ op: 'queue_remove';+ threadId: string;+ id: string;+ }| {op: 'permission_response';threadId: string;@@ -313,6 +363,8 @@ const CLIENT_OPS = new Set(['subscribe','unsubscribe','prompt',+ 'queue_edit',+ 'queue_remove','permission_response','runtime_consent_response','cancel',@@ -356,6 +408,18 @@ export function parseThreadClientFrame(raw: string): ThreadClientFrame | null {}if (frame.prompt !== undefined && typeof frame.prompt !== 'string') return null;if (frame.docName !== undefined && typeof frame.docName !== 'string') return null;+ if (frame.settings !== undefined) {+ const settings = frame.settings as Record<string, unknown> | null;+ if (typeof settings !== 'object' || settings === null) return null;+ if (settings.config !== undefined) {+ const config = settings.config as Record<string, unknown> | null;+ if (typeof config !== 'object' || config === null || Array.isArray(config)) return null;+ for (const v of Object.values(config)) {+ if (typeof v !== 'string' && typeof v !== 'boolean') return null;+ }+ }+ if (settings.modeId !== undefined && typeof settings.modeId !== 'string') return null;+ }return frame as unknown as ThreadClientFrame;}case 'subscribe':@@ -365,6 +429,12 @@ export function parseThreadClientFrame(raw: string): ThreadClientFrame | null {case 'prompt':if (!str('threadId') || !str('reqId') || typeof frame.content !== 'string') return null;return frame as unknown as ThreadClientFrame;+ case 'queue_edit':+ if (!str('threadId') || !str('id') || !str('content')) return null;+ return frame as unknown as ThreadClientFrame;+ case 'queue_remove':+ if (!str('threadId') || !str('id')) 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;diff --git a/packages/core/src/git/git-spawn-path.test.ts b/packages/core/src/git/git-spawn-path.test.tsindex 1dcbbeb36..e91bf8b2c 100644--- a/packages/core/src/git/git-spawn-path.test.ts+++ b/packages/core/src/git/git-spawn-path.test.ts@@ -1,5 +1,10 @@import { describe, expect, test } from 'vitest';-import { augmentGitSpawnPath, wellKnownToolDirs } from './git-spawn-path.ts';+import {+ agentToolDirs,+ augmentAgentSpawnPath,+ augmentGitSpawnPath,+ wellKnownToolDirs,+} from './git-spawn-path.ts';const HOME = '/Users/tester';@@ -81,3 +86,59 @@ describe('augmentGitSpawnPath', () => {expect(dirs).not.toContain('/opt/local/bin');});});++describe('augmentAgentSpawnPath', () => {+ test('appends package-manager global bins on top of the well-known dirs', () => {+ const out = augmentAgentSpawnPath(+ '/usr/bin:/bin',+ darwinOpts([`${HOME}/Library/pnpm`, '/opt/homebrew/bin']),+ );+ // Well-known dirs come first, then the PM-global dirs — both append-only.+ expect(out).toBe(`/usr/bin:/bin:/opt/homebrew/bin:${HOME}/Library/pnpm`);+ });++ test('resolves an agent CLI dir (~/Library/pnpm) that the git variant omits', () => {+ const opts = darwinOpts([`${HOME}/Library/pnpm`]);+ expect(augmentAgentSpawnPath('/usr/bin', opts).split(':')).toContain(`${HOME}/Library/pnpm`);+ // Pure superset: the git variant must NOT pick up the agent-only dir.+ expect(augmentGitSpawnPath('/usr/bin', opts).split(':')).not.toContain(`${HOME}/Library/pnpm`);+ });++ test('never prepends and is idempotent', () => {+ const opts = darwinOpts(['/opt/homebrew/bin', `${HOME}/.bun/bin`]);+ const once = augmentAgentSpawnPath('/usr/bin', opts);+ expect(once.startsWith('/usr/bin')).toBe(true);+ expect(augmentAgentSpawnPath(once, opts)).toBe(once);+ });++ test('skips dirs that do not exist on disk', () => {+ expect(augmentAgentSpawnPath('/usr/bin', darwinOpts([]))).toBe('/usr/bin');+ });+});++describe('agentToolDirs', () => {+ test('darwin lists every JS package-manager global bin', () => {+ expect(agentToolDirs('darwin', HOME)).toEqual([+ `${HOME}/Library/pnpm`,+ `${HOME}/.bun/bin`,+ `${HOME}/.volta/bin`,+ `${HOME}/.yarn/bin`,+ `${HOME}/.npm-global/bin`,+ ]);+ });++ test('linux uses the XDG pnpm dir, not the macOS Library path', () => {+ expect(agentToolDirs('linux', HOME)).toEqual([+ `${HOME}/.local/share/pnpm`,+ `${HOME}/.bun/bin`,+ `${HOME}/.volta/bin`,+ `${HOME}/.yarn/bin`,+ `${HOME}/.npm-global/bin`,+ ]);+ expect(agentToolDirs('linux', HOME)).not.toContain(`${HOME}/Library/pnpm`);+ });++ test('win32 adds nothing (Explorer inherits the registry user PATH)', () => {+ expect(agentToolDirs('win32', 'C:\\Users\\tester')).toEqual([]);+ });+});diff --git a/packages/core/src/git/git-spawn-path.ts b/packages/core/src/git/git-spawn-path.tsindex d72c72992..916900d26 100644--- a/packages/core/src/git/git-spawn-path.ts+++ b/packages/core/src/git/git-spawn-path.ts@@ -77,21 +77,88 @@ export function wellKnownToolDirs(platform: NodeJS.Platform, homeDir: string): r}/**- * Return `currentPath` with well-known tool directories APPENDED: only- * directories that exist on disk and aren't already present (exact string- * match against current entries). `undefined`/empty input yields just the- * existing well-known dirs, so a spawn env never ends up with an empty PATH.- * Idempotent — augmenting an already-augmented PATH is a no-op.+ * Append `dirs` to `currentPath`: only those that exist on disk and aren't+ * already present (exact string match against current entries, and against+ * dirs already appended this call). `undefined`/empty input yields just the+ * appended dirs, so a spawn env never ends up with an empty PATH. Appending+ * (never prepending) keeps existing entries authoritative. Idempotent.*/-export function augmentGitSpawnPath(+function appendDirs(currentPath: string | undefined,+ dirs: readonly string[],options: GitSpawnPathOptions,): string {const delim = options.delimiter;const existing = (currentPath ?? '').split(delim).filter((entry) => entry.length > 0);const present = new Set(existing);- const additions = wellKnownToolDirs(options.platform, options.homeDir).filter(- (dir) => !present.has(dir) && options.isDir(dir),- );+ const additions: string[] = [];+ for (const dir of dirs) {+ if (!present.has(dir) && options.isDir(dir)) {+ present.add(dir);+ additions.push(dir);+ }+ }return [...existing, ...additions].join(delim);}++/**+ * Return `currentPath` with well-known tool directories APPENDED. See+ * `appendDirs` for the append/dedup/existence semantics.+ */+export function augmentGitSpawnPath(+ currentPath: string | undefined,+ options: GitSpawnPathOptions,+): string {+ return appendDirs(currentPath, wellKnownToolDirs(options.platform, options.homeDir), options);+}++/**+ * JavaScript package-manager global bin directories where coding-agent CLIs+ * (the ACP harnesses — pi, claude, codex, …) land on a global install. These+ * are put on PATH only by a shell profile, so an agent installed with e.g.+ * `pnpm add -g` is unreachable from a Dock/Finder-launched app that inherits+ * launchd's minimal PATH. Static home-relative literals, NOT `$PNPM_HOME` /+ * `$BUN_INSTALL` reads: those vars are shell-profile-set too, so they are+ * equally absent in exactly the launchd-minimal case this targets.+ */+export function agentToolDirs(platform: NodeJS.Platform, homeDir: string): readonly string[] {+ switch (platform) {+ case 'darwin':+ return [+ `${homeDir}/Library/pnpm`, // pnpm global (PNPM_HOME default on macOS)+ `${homeDir}/.bun/bin`, // bun global+ `${homeDir}/.volta/bin`, // Volta shims+ `${homeDir}/.yarn/bin`, // Yarn classic global+ `${homeDir}/.npm-global/bin`, // npm's documented non-sudo prefix+ ];+ case 'win32':+ // Explorer-launched apps inherit the registry-backed user PATH, so the+ // minimal-PATH class barely exists here — nothing safe to statically add.+ return [];+ default:+ return [+ `${homeDir}/.local/share/pnpm`, // pnpm global (XDG default on Linux)+ `${homeDir}/.bun/bin`,+ `${homeDir}/.volta/bin`,+ `${homeDir}/.yarn/bin`,+ `${homeDir}/.npm-global/bin`,+ ];+ }+}++/**+ * Like `augmentGitSpawnPath`, but for ACP agent + terminal spawns: appends the+ * well-known tool dirs (npx/uvx/node are commonly Homebrew installs) AND the+ * package-manager global bins where agent CLIs install. Same append-only,+ * existence-gated, idempotent semantics; never yields an empty PATH.+ */+export function augmentAgentSpawnPath(+ currentPath: string | undefined,+ options: GitSpawnPathOptions,+): string {+ const dirs = [+ ...wellKnownToolDirs(options.platform, options.homeDir),+ ...agentToolDirs(options.platform, options.homeDir),+ ];+ return appendDirs(currentPath, dirs, options);+}diff --git a/packages/core/src/index.ts b/packages/core/src/index.tsindex 4b24755d2..52bd003b7 100644--- a/packages/core/src/index.ts+++ b/packages/core/src/index.ts@@ -410,6 +410,8 @@ export {} from './extensions/wiki-link-embed.ts';export { parseBranchList } from './git/branch-list-parser.ts';export {+ agentToolDirs,+ augmentAgentSpawnPath,augmentGitSpawnPath,type GitSpawnPathOptions,wellKnownToolDirs,diff --git a/packages/server/src/acp/launch.test.ts b/packages/server/src/acp/launch.test.tsindex 3c8ea0fbe..4a37fd989 100644--- a/packages/server/src/acp/launch.test.ts+++ b/packages/server/src/acp/launch.test.ts@@ -10,10 +10,11 @@import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';import { tmpdir } from 'node:os';-import { join } from 'node:path';+import { delimiter, join } from 'node:path';import { afterEach, describe, expect, test } from 'vitest';import {AgentLaunchError,+ mergedEnv,preflightLaunch,type ResolvedLaunch,resolveWindowsCommand,@@ -22,6 +23,27 @@ import {windowsCmdWrap,} from './launch.ts';+describe('mergedEnv PATH augmentation', () => {+ test('an explicit overlay PATH is used verbatim — augmentation repairs only the inherited base', () => {+ const key = 'PATH' in process.env ? 'PATH' : 'Path';+ const out = mergedEnv({ [key]: '/sentinel/only' });+ // An overlay PATH is a spawn-env contract: it wins verbatim, never appended-to.+ expect(out[key]).toBe('/sentinel/only');+ });++ test('appends without dropping any existing PATH entry', () => {+ const key = 'PATH' in process.env ? 'PATH' : 'Path';+ const after = new Set((mergedEnv()[key] ?? '').split(delimiter));+ for (const dir of (process.env[key] ?? '').split(delimiter).filter(Boolean)) {+ expect(after.has(dir)).toBe(true);+ }+ });++ test('preserves non-PATH process.env entries', () => {+ expect(mergedEnv().HOME).toBe(process.env.HOME);+ });+});+const isAlive = (pid: number): boolean => {try {process.kill(pid, 0);diff --git a/packages/server/src/acp/launch.ts b/packages/server/src/acp/launch.tsindex f2e905b84..f538dc5e6 100644--- a/packages/server/src/acp/launch.ts+++ b/packages/server/src/acp/launch.ts@@ -19,7 +19,7 @@ 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 { augmentAgentSpawnPath, 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';@@ -51,12 +51,40 @@ function defaultBinaryCacheDir(): string {return join(homedir(), OK_DIR, 'acp-agents');}+/** True iff `dir` exists and is a directory (symlinks followed). */+function isDir(dir: string): boolean {+ try {+ return statSync(dir).isDirectory();+ } catch {+ return false;+ }+}++/**+ * Build the spawn env for an ACP agent / terminal: `process.env` with its PATH+ * repaired, then `overlay` applied on top.+ *+ * The PATH repair targets the INHERITED base only — a Dock/Finder-launched+ * Desktop inherits launchd's minimal PATH, so an agent CLI installed under a+ * package-manager global bin (`~/Library/pnpm`, `~/.bun/bin`, …) isn't found+ * even when it runs fine from a terminal. We append the well-known tool ++ * PM-global dirs, the same augmentation git spawns use. An overlay that sets+ * PATH is a spawn-env contract and wins verbatim (applied after): augmentation+ * repairs the base env, it does not transform caller intent — matching+ * `child_process` / Docker / systemd semantics.+ */export function mergedEnv(overlay?: Record<string, string>): Record<string, string> {- const env: Record<string, string> = {};+ const base: Record<string, string> = {};for (const [k, v] of Object.entries(process.env)) {- if (v !== undefined) env[k] = v;+ if (v !== undefined) base[k] = v;}- return { ...env, ...overlay };+ base[pathKey(base)] = augmentAgentSpawnPath(envPath(base), {+ platform: process.platform,+ homeDir: homedir(),+ isDir,+ delimiter,+ });+ return { ...base, ...overlay };}/**@@ -254,7 +282,7 @@ function missingCommandHint(launch: ResolvedLaunch): string {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.`;+ return `\`${launch.cmd}\` was not found on your PATH. A desktop app launched from the Dock or Finder doesn't inherit your shell's PATH, so an agent installed only in a shell-configured location won't be visible here — use an absolute path to the command, or install it to a standard location.`;}}diff --git a/packages/server/src/acp/managed-runtime-flow.integration.test.ts b/packages/server/src/acp/managed-runtime-flow.integration.test.tsindex 77335324e..ebc64cf63 100644--- a/packages/server/src/acp/managed-runtime-flow.integration.test.ts+++ b/packages/server/src/acp/managed-runtime-flow.integration.test.ts@@ -55,7 +55,9 @@ const NPX_AGENT = {id: 'npxagent',name: 'NPX Agent',version: '1.0.0',- // Empty PATH forces the system `npx` to be unresolvable → download flow.+ // Empty overlay PATH forces the system `npx` to be unresolvable → download+ // flow. Also pins the contract that an explicit overlay PATH is used verbatim:+ // `mergedEnv`'s base-PATH augmentation must not re-populate it.distribution: { npx: { package: '@fake/agent', env: { PATH: '' } } },};@@ -101,6 +103,7 @@ function makeManager(opts: {const manager = new AcpThreadManager({contentDir: opts.contentDir,localDir: opts.localDir,+ globalDir: null,registry: new AcpRegistry({ localDir: opts.localDir, log, fetchImpl: opts.fetchImpl }),permissions: new AcpPermissionStore(opts.localDir, log),sessionManager: fakeSessionManager,diff --git a/packages/server/src/acp/mcp-injection-skip.test.ts b/packages/server/src/acp/mcp-injection-skip.test.tsindex 79b2c4ed1..7ef4f96cc 100644--- a/packages/server/src/acp/mcp-injection-skip.test.ts+++ b/packages/server/src/acp/mcp-injection-skip.test.ts@@ -61,6 +61,7 @@ function makeManager(const manager = new AcpThreadManager({contentDir: tmp(),localDir,+ globalDir: null,registry: new AcpRegistry({localDir,log,diff --git a/packages/server/src/acp/thread-manager.integration.test.ts b/packages/server/src/acp/thread-manager.integration.test.tsindex f7b4cdd85..142e9af23 100644--- a/packages/server/src/acp/thread-manager.integration.test.ts+++ b/packages/server/src/acp/thread-manager.integration.test.ts@@ -23,7 +23,7 @@ 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 { AcpThreadManager, MAX_QUEUED_PROMPTS } from './thread-manager.ts';const log = getLogger('acp-thread-test');@@ -68,6 +68,7 @@ function makeManager(const manager = new AcpThreadManager({contentDir,localDir,+ globalDir: null,registry: new AcpRegistry({localDir,log,@@ -1226,3 +1227,524 @@ describe('AcpThreadManager terminals + permission effects', () => {await manager.closeThread(info.threadId);}, 45_000);});++/**+ * A stdio ACP agent whose thought-level options depend on the model — picking+ * `opus` unlocks `xhigh`, which `sonnet` doesn't offer. Exercises the initial-+ * config apply's model-first ordering + per-step re-validation.+ */+function writeCascadingConfigAgent(localDir: string): void {+ const agentPath = join(localDir, 'cascade-agent.mjs');+ writeFileSync(+ agentPath,+ `+let model = 'sonnet';+let thought = 'med';+const thoughtOptions = () =>+ model === 'opus'+ ? [{ value: 'low', name: 'Low' }, { value: 'med', name: 'Med' }, { value: 'high', name: 'High' }, { value: 'xhigh', name: 'XHigh' }]+ : [{ value: 'low', name: 'Low' }, { value: 'med', name: 'Med' }];+const configOptions = () => [+ { id: 'model', name: 'Model', category: 'model', type: 'select', currentValue: model,+ options: [{ value: 'sonnet', name: 'Sonnet' }, { value: 'opus', name: 'Opus' }] },+ { id: 'thought_level', name: 'Thinking', category: 'thought_level', type: 'select', currentValue: thought,+ options: thoughtOptions() },+];+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') {+ const { configId, value } = msg.params;+ if (configId === 'model') model = value;+ else if (configId === 'thought_level' && thoughtOptions().some((o) => o.value === value)) thought = 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: 'cascade-agent', name: 'Cascade Agent', command: 'node', args: [agentPath] },+ ]),+ );+}++/**+ * A stdio ACP agent that advertises legacy `SessionModeState` modes (Claude's+ * permission-mode surface) and accepts `session/set_mode`. Exercises the+ * opt-in mode restore via `session/set_mode`.+ */+function writeLegacyModeAgent(localDir: string): void {+ const agentPath = join(localDir, 'mode-agent.mjs');+ writeFileSync(+ agentPath,+ `+let current = 'default';+const modes = () => ({ currentModeId: current, availableModes: [+ { id: 'default', name: 'Default' },+ { id: 'plan', name: 'Plan' },+ { id: 'bypass', name: 'Bypass permissions' },+] });+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', modes: modes() });+ } else if (msg.method === 'session/set_mode') {+ current = msg.params.modeId;+ reply({});+ } 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: 'mode-agent', name: 'Mode Agent', command: 'node', args: [agentPath] }]),+ );+}++/**+ * A stdio ACP agent that exposes mode through a generalized mode-category+ * config option (the newer surface) rather than legacy `modes`. Exercises the+ * opt-in mode restore falling through to `session/set_config_option`.+ */+function writeConfigModeAgent(localDir: string): void {+ const agentPath = join(localDir, 'config-mode-agent.mjs');+ writeFileSync(+ agentPath,+ `+let mode = 'default';+const configOptions = () => [+ { id: 'permission', name: 'Permission mode', category: 'mode', type: 'select', currentValue: mode,+ options: [{ value: 'default', name: 'Default' }, { value: 'bypass', name: 'Bypass permissions' }] },+];+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') {+ if (msg.params.configId === 'permission') mode = 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-mode-agent', name: 'Config Mode Agent', command: 'node', args: [agentPath] },+ ]),+ );+}++/**+ * A legacy-modes agent that *rejects* every `session/set_mode` with a JSON-RPC+ * error. Proves the opt-in mode restore is best-effort: a rejected set is+ * caught and the thread still reaches `ready` on the agent's default mode.+ */+function writeRejectingModeAgent(localDir: string): void {+ const agentPath = join(localDir, 'reject-mode-agent.mjs');+ writeFileSync(+ agentPath,+ `+const modes = { currentModeId: 'default', availableModes: [+ { id: 'default', name: 'Default' },+ { id: 'bypass', name: 'Bypass permissions' },+] };+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', modes });+ } else if (msg.method === 'session/set_mode') {+ process.stdout.write(JSON.stringify({ jsonrpc: '2.0', id: msg.id,+ error: { code: -32000, message: 'mode change refused' } }) + '\\n');+ } 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: 'reject-mode-agent', name: 'Reject Mode Agent', command: 'node', args: [agentPath] },+ ]),+ );+}++describe('AcpThreadManager initial mode apply', () => {+ test('restores an opted-in mode via session/set_mode before ready', async () => {+ const contentDir = tmp();+ const localDir = tmp();+ writeLegacyModeAgent(localDir);+ const manager = makeManager(contentDir, localDir);++ const info = await manager.createThread({+ agent: { source: 'custom', id: 'mode-agent' },+ settings: { modeId: 'bypass' },+ });+ await waitUntil(() => manager.getInfo(info.threadId)?.status === 'ready', 15_000, 'ready');++ expect(manager.getInfo(info.threadId)?.modes?.currentModeId).toBe('bypass');++ await manager.closeThread(info.threadId);+ }, 30_000);++ test('skips a remembered mode the session no longer advertises', async () => {+ const contentDir = tmp();+ const localDir = tmp();+ writeLegacyModeAgent(localDir);+ const manager = makeManager(contentDir, localDir);++ const info = await manager.createThread({+ agent: { source: 'custom', id: 'mode-agent' },+ // `ghost` isn't in availableModes → no set_mode is sent; the session+ // stays on its own default rather than arming a retired mode.+ settings: { modeId: 'ghost' },+ });+ await waitUntil(() => manager.getInfo(info.threadId)?.status === 'ready', 15_000, 'ready');++ expect(manager.getInfo(info.threadId)?.modes?.currentModeId).toBe('default');++ await manager.closeThread(info.threadId);+ }, 30_000);++ test('restores an opted-in mode exposed as a config option via set_config_option', async () => {+ const contentDir = tmp();+ const localDir = tmp();+ writeConfigModeAgent(localDir);+ const manager = makeManager(contentDir, localDir);++ const info = await manager.createThread({+ agent: { source: 'custom', id: 'config-mode-agent' },+ settings: { modeId: 'bypass' },+ });+ await waitUntil(() => manager.getInfo(info.threadId)?.status === 'ready', 15_000, 'ready');++ const opts = manager.getInfo(info.threadId)?.configOptions ?? [];+ expect(opts.find((o) => o.id === 'permission')?.currentValue).toBe('bypass');++ await manager.closeThread(info.threadId);+ }, 30_000);++ test('a rejected set_mode still reaches ready on the agent default', async () => {+ const contentDir = tmp();+ const localDir = tmp();+ writeRejectingModeAgent(localDir);+ const manager = makeManager(contentDir, localDir);++ const info = await manager.createThread({+ agent: { source: 'custom', id: 'reject-mode-agent' },+ settings: { modeId: 'bypass' },+ });+ // The set_mode rejection is caught (best-effort) — startup must not hang.+ await waitUntil(() => manager.getInfo(info.threadId)?.status === 'ready', 15_000, 'ready');++ // The refused mode did not stick; the session stays on its own default.+ expect(manager.getInfo(info.threadId)?.modes?.currentModeId).toBe('default');++ await manager.closeThread(info.threadId);+ }, 30_000);+});++describe('AcpThreadManager initial config apply', () => {+ test('applies remembered config before ready — model first, dependent option re-validated', async () => {+ const contentDir = tmp();+ const localDir = tmp();+ writeCascadingConfigAgent(localDir);+ const manager = makeManager(contentDir, localDir);++ const info = await manager.createThread({+ agent: { source: 'custom', id: 'cascade-agent' },+ // thought_level listed first on purpose: it's only valid AFTER the model+ // switches to opus, so a correct apply must order model → thought_level.+ // `retired_option` pins the skip contract: a remembered key this agent+ // version no longer advertises must be ignored, not fail the launch.+ settings: { config: { thought_level: 'xhigh', model: 'opus', retired_option: 'gone' } },+ });+ await waitUntil(() => manager.getInfo(info.threadId)?.status === 'ready', 15_000, 'ready');++ const opts = manager.getInfo(info.threadId)?.configOptions ?? [];+ expect(opts.find((o) => o.id === 'model')?.currentValue).toBe('opus');+ expect(opts.find((o) => o.id === 'thought_level')?.currentValue).toBe('xhigh');++ await manager.closeThread(info.threadId);+ }, 30_000);++ test('skips a remembered value the resolved options no longer offer', async () => {+ const contentDir = tmp();+ const localDir = tmp();+ writeCascadingConfigAgent(localDir);+ const manager = makeManager(contentDir, localDir);++ const info = await manager.createThread({+ agent: { source: 'custom', id: 'cascade-agent' },+ // No model change → the model stays sonnet, whose options lack `xhigh`,+ // so the stored thought_level is dropped rather than sent-and-rejected.+ settings: { config: { thought_level: 'xhigh' } },+ });+ await waitUntil(() => manager.getInfo(info.threadId)?.status === 'ready', 15_000, 'ready');++ const opts = manager.getInfo(info.threadId)?.configOptions ?? [];+ expect(opts.find((o) => o.id === 'model')?.currentValue).toBe('sonnet');+ expect(opts.find((o) => o.id === 'thought_level')?.currentValue).toBe('med');++ await manager.closeThread(info.threadId);+ }, 30_000);+});++describe('AcpThreadManager prompt queueing', () => {+ 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('');+ const userMessages = (events: Collected): string[] =>+ events+ .map((e) => e.event)+ .filter((e): e is Extract<ThreadEvent, { kind: 'user_message' }> => e.kind === 'user_message')+ .map((e) => e.content);++ /** Agent that echoes each prompt and holds a WAIT-marked turn open until+ * `releasePath` exists — the deterministic gate the queue forms behind. */+ function writeGateAgent(localDir: string, releasePath: string): void {+ writeRequestingAgentEntry(+ localDir,+ 'gate-agent',+ `+ const text = (msg.params.prompt ?? []).map((b) => b.text ?? '').join('');+ notify({ sessionUpdate: 'agent_message_chunk', content: { type: 'text', text: 'ran:' + text + ';' } });+ if (text.includes('WAIT')) {+ const fs = await import('node:fs');+ while (!fs.existsSync(${JSON.stringify(releasePath)})) {+ await new Promise((r) => setTimeout(r, 20));+ }+ }+ finish();+`,+ );+ }++ test('mid-turn prompts queue, edit/remove target entries by id, and drain FIFO', async () => {+ const contentDir = tmp();+ const localDir = tmp();+ const releasePath = join(localDir, 'release-turn');+ writeGateAgent(localDir, releasePath);+ const manager = makeManager(contentDir, localDir);+ const info = await manager.createThread({ agent: { source: 'custom', id: 'gate-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, 'WAIT at the gate');+ await waitUntil(() => internals(manager).turnActive(info.threadId), 5_000, 'turn active');++ manager.sendPrompt(info.threadId, 'second draft');+ manager.sendPrompt(info.threadId, 'third');+ manager.sendPrompt(info.threadId, 'fourth');+ const queued = manager.getInfo(info.threadId)?.queue ?? [];+ expect(queued.map((m) => m.content)).toEqual(['second draft', 'third', 'fourth']);++ // Edit the head in place, drop the middle; unknown ids are silent no-ops.+ const head = queued[0];+ const middle = queued[1];+ if (head === undefined || middle === undefined) throw new Error('queue entries missing');+ manager.editQueued(info.threadId, head.id, 'second final');+ manager.removeQueued(info.threadId, middle.id);+ manager.editQueued(info.threadId, 'no-such-id', 'ignored');+ manager.removeQueued(info.threadId, 'no-such-id');+ expect((manager.getInfo(info.threadId)?.queue ?? []).map((m) => m.content)).toEqual([+ 'second final',+ 'fourth',+ ]);++ writeFileSync(releasePath, 'go');+ await waitUntil(+ () => events.filter((e) => e.event.kind === 'turn_ended').length === 3,+ 20_000,+ `three turn ends; got ${JSON.stringify(events.map((e) => e.event.kind))}`,+ );+ expect(manager.getInfo(info.threadId)?.queue).toBeUndefined();+ expect(manager.getInfo(info.threadId)?.status).toBe('ready');++ // FIFO order with the edit applied; the removed entry never ran.+ const text = agentText(events);+ expect(text).toContain('ran:second final;');+ expect(text).toContain('ran:fourth;');+ expect(text).not.toContain('second draft');+ expect(text).not.toContain('ran:third;');+ expect(text.indexOf('ran:second final;')).toBeLessThan(text.indexOf('ran:fourth;'));++ // Each drained prompt landed as a normal user turn in the transcript.+ expect(userMessages(events)).toEqual(['WAIT at the gate', 'second final', 'fourth']);++ await manager.closeThread(info.threadId);+ }, 40_000);++ test('cancel drops the whole queue; the cap rejects the overflow prompt', async () => {+ const contentDir = tmp();+ const localDir = tmp();+ const releasePath = join(localDir, 'release-turn');+ writeGateAgent(localDir, releasePath);+ const manager = makeManager(contentDir, localDir);+ const info = await manager.createThread({ agent: { source: 'custom', id: 'gate-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, 'WAIT for cancel');+ await waitUntil(() => internals(manager).turnActive(info.threadId), 5_000, 'turn active');++ for (let i = 0; i < MAX_QUEUED_PROMPTS; i += 1) {+ manager.sendPrompt(info.threadId, `queued ${i}`);+ }+ expect(manager.getInfo(info.threadId)?.queue?.length).toBe(MAX_QUEUED_PROMPTS);+ expect(() => manager.sendPrompt(info.threadId, 'one too many')).toThrow(/already waiting/);++ manager.cancel(info.threadId);+ expect(manager.getInfo(info.threadId)?.queue).toBeUndefined();++ // The gate agent ignores session/cancel — release it and confirm the+ // cleared queue never drains.+ writeFileSync(releasePath, 'go');+ await waitUntil(() => !internals(manager).turnActive(info.threadId), 10_000, 'turn ended');+ expect(manager.getInfo(info.threadId)?.queue).toBeUndefined();+ expect(userMessages(events)).toEqual(['WAIT for cancel']);++ await manager.closeThread(info.threadId);+ }, 40_000);++ test('a terminal status drops the queue — a dead agent keeps no phantom entries', async () => {+ const contentDir = tmp();+ const localDir = tmp();+ writeGateAgent(localDir, join(localDir, 'release-turn'));+ const manager = makeManager(contentDir, localDir);+ const info = await manager.createThread({ agent: { source: 'custom', id: 'gate-agent' } });+ await manager.subscribe(info.threadId, 0, () => {});+ await waitUntil(() => manager.getInfo(info.threadId)?.status === 'ready', 15_000, 'ready');++ manager.sendPrompt(info.threadId, 'WAIT at the gate');+ await waitUntil(() => internals(manager).turnActive(info.threadId), 5_000, 'turn active');+ manager.sendPrompt(info.threadId, 'never runs');+ expect(manager.getInfo(info.threadId)?.queue?.length).toBe(1);++ // Killing the agent mid-turn takes the thread terminal. The queue has to go+ // with it: entries that outlive the agent render as messages the user can+ // see but can never dispatch.+ await manager.closeThread(info.threadId);+ expect(manager.getInfo(info.threadId)?.queue).toBeUndefined();+ }, 40_000);++ test('the queue is never persisted — a rehydrated thread comes back empty', async () => {+ const contentDir = tmp();+ const localDir = tmp();+ writeGateAgent(localDir, join(localDir, 'release-turn'));+ const manager = makeManager(contentDir, localDir);+ // init() creates the threads dir — without it the archive's meta write has+ // nowhere to land and there is nothing for manager2 to rehydrate.+ await manager.init();+ const info = await manager.createThread({ agent: { source: 'custom', id: 'gate-agent' } });+ await manager.subscribe(info.threadId, 0, () => {});+ await waitUntil(() => manager.getInfo(info.threadId)?.status === 'ready', 15_000, 'ready');++ manager.sendPrompt(info.threadId, 'WAIT at the gate');+ await waitUntil(() => internals(manager).turnActive(info.threadId), 5_000, 'turn active');+ manager.sendPrompt(info.threadId, 'queued while busy');+ expect(manager.getInfo(info.threadId)?.queue?.length).toBe(1);++ await manager.closeThread(info.threadId);++ // A fresh manager over the same persistence dir rehydrates the archived+ // thread from its meta. `buildMeta` strips the queue on the way out, so it+ // must not come back — otherwise a restart resurrects undispatchable rows.+ const manager2 = makeManager(contentDir, localDir);+ await manager2.init();+ expect(manager2.getInfo(info.threadId)).toBeDefined();+ expect(manager2.getInfo(info.threadId)?.queue).toBeUndefined();+ }, 40_000);+});diff --git a/packages/server/src/acp/thread-manager.ts b/packages/server/src/acp/thread-manager.tsindex 4e6d0904a..14a8edb71 100644--- a/packages/server/src/acp/thread-manager.ts+++ b/packages/server/src/acp/thread-manager.ts@@ -34,6 +34,7 @@ import {type PermissionOption,PROTOCOL_VERSION,type RequestPermissionResponse,+ type SessionConfigOption,type SessionNotification,type SessionUpdate,type SetSessionConfigOptionRequest,@@ -49,6 +50,7 @@ import {iconFromClientName,} from '@inkeep/open-knowledge-core';import type {+ QueuedMessage,ThreadAgentInfo,ThreadEvent,ThreadInfo,@@ -99,6 +101,8 @@ import { type PersistedThreadMeta, ThreadPersistenceStore } from './thread-persiimport { clampThreadTitle, deriveThreadTitle } from './thread-title.ts';export const MAX_ACP_THREADS = 8;+/** Prompts allowed to wait behind the active turn before `prompt` rejects. */+export const MAX_QUEUED_PROMPTS = 20;const EVENT_LOG_LIMIT = 5_000;const DEFAULT_IDLE_REAP_MS = 60 * 60 * 1000;const REAP_SWEEP_MS = 5 * 60 * 1000;@@ -243,6 +247,14 @@ export interface AcpThreadManagerOptions {contentDir: string;/** `<projectDir>/.ok/local` — custom agents, permission grants, registry cache. */localDir: string;+ /**+ * Machine-global OK dir (`~/.ok`) where thread transcripts persist under+ * `threads/`, shared across projects and cwd-scoped by `contentDir`. `null`+ * keeps transcripts in the per-project `localDir/threads` (tests). Required+ * so a new construction site can't silently forget where threads live —+ * `null` is the explicit opt-out.+ */+ globalDir: string | null;registry: AcpRegistry;permissions: AcpPermissionStore;sessionManager: AgentSessionManager;@@ -347,7 +359,15 @@ export class AcpThreadManager {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.persistence = new ThreadPersistenceStore({+ // Global dir → transcripts under `~/.ok/threads`, cwd-scoped, with the+ // per-project `localDir/threads` as a read-only legacy fallback. No+ // global dir → single per-project dir (unchanged behavior).+ primaryDir: opts.globalDir ?? opts.localDir,+ legacyDir: opts.globalDir !== null ? opts.localDir : null,+ cwd: opts.globalDir !== null ? opts.contentDir : null,+ log: opts.log,+ });this.reapTimer = setInterval(() => this.reapIdleThreads(), REAP_SWEEP_MS);this.reapTimer.unref?.();}@@ -468,6 +488,12 @@ export class AcpThreadManager {prompt?: string;docName?: string;titleHint?: string;+ /**+ * Remembered settings to apply before turn 1: `config` (model, thought+ * level, and any mode advertised as a config option) and `modeId` (the+ * legacy mode surface). Validated against the live session before applying.+ */+ settings?: { config?: Record<string, string | boolean>; modeId?: string };}): Promise<ThreadInfo> {if (this.destroyed) throw new ThreadOpError('capacity', 'server is shutting down');if (this.liveThreadCount() >= this.maxThreads) {@@ -984,7 +1010,11 @@ export class AcpThreadManager {private async startThread(record: ThreadRecord,- params: { agent: { source: 'registry' | 'custom'; id: string }; prompt?: string },+ params: {+ agent: { source: 'registry' | 'custom'; id: string };+ prompt?: string;+ settings?: { config?: Record<string, string | boolean>; modeId?: string };+ },custom: CustomAgentEntry | null,): Promise<void> {let handshake: Awaited<ReturnType<AcpThreadManager['connectAgent']>>;@@ -1032,6 +1062,17 @@ export class AcpThreadManager {}if (record.closed) return;+ if (params.settings?.config !== undefined) {+ await this.applyInitialConfig(record, conn, params.settings.config);+ if (record.closed) return;+ }+ if (params.settings?.modeId !== undefined) {+ // After config: a model→option cascade may reshape the mode surface, so+ // validate the remembered mode against the settled session state.+ await this.applyInitialMode(record, conn, params.settings.modeId);+ if (record.closed) return;+ }+this.setPresence(record, 'idle');this.emitStatus(record, 'ready');// Startup latency is a known UX sore point (npx resolution + node boot +@@ -1248,11 +1289,55 @@ export class AcpThreadManager {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');+ // Queue behind the active turn instead of rejecting; the turn-end+ // handler in dispatchPrompt drains FIFO. Queue state is ephemeral+ // (memory-only): cancel, agent error/exit, and archive all drop it.+ const queue = t.info.queue ?? [];+ if (queue.length >= MAX_QUEUED_PROMPTS) {+ throw new ThreadOpError(+ 'not-ready',+ `${MAX_QUEUED_PROMPTS} messages are already waiting — let the agent catch up`,+ );+ }+ t.info.queue = [...queue, { id: crypto.randomUUID(), content, ts: Date.now() }];+ t.info.lastActivityAt = Date.now();+ this.emitInfo(t);+ return;}this.dispatchPrompt(t, content, { echo: true });}+ /** Replace a queued message's content in place. Unknown id: the entry+ * raced its own dispatch (or a cancel) — silent no-op; the transcript+ * already shows what actually ran. */+ editQueued(threadId: string, id: string, content: string): void {+ const t = this.mustGet(threadId);+ const queue = t.info.queue ?? [];+ if (!queue.some((m) => m.id === id)) return;+ t.info.queue = queue.map((m) => (m.id === id ? { ...m, content } : m));+ this.emitInfo(t);+ }++ /** Remove a queued message before it dispatches. Unknown id: no-op. */+ removeQueued(threadId: string, id: string): void {+ const t = this.mustGet(threadId);+ const queue = t.info.queue ?? [];+ const next = queue.filter((m) => m.id !== id);+ if (next.length === queue.length) return;+ t.info.queue = next.length > 0 ? next : undefined;+ this.emitInfo(t);+ }++ /** Pop the next queued prompt, or null. Broadcast rides the dispatch that+ * follows (its status flip emits the refreshed info snapshot). */+ private takeNextQueued(t: ThreadRecord): QueuedMessage | null {+ const queue = t.info.queue;+ if (queue === undefined || queue.length === 0) return null;+ const [next, ...rest] = queue;+ t.info.queue = rest.length > 0 ? rest : undefined;+ return next ?? null;+ }+/** 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@@ -1331,6 +1416,17 @@ export class AcpThreadManager {stopReason: response.stopReason,ts: Date.now(),});+ // Drain the queue FIFO — skip the 'ready' blip so the status history+ // reads running → running, matching what the user sees. Guarded on a+ // live connection: an agent that died as the turn settled already+ // dropped the queue via its terminal status.+ if (t.sessionId !== null && t.conn !== null) {+ const next = this.takeNextQueued(t);+ if (next !== null) {+ this.dispatchPrompt(t, next.content, { echo: true });+ return;+ }+ }this.emitStatus(t, 'ready');this.setPresence(t, 'idle');})@@ -1351,6 +1447,13 @@ export class AcpThreadManager {cancel(threadId: string): void {const t = this.mustGet(threadId);+ // Stop means "stop the plan", not just the current turn — queued+ // messages go with it (before the conn guard, so a cancel racing agent+ // death still clears).+ if (t.info.queue !== undefined) {+ t.info.queue = undefined;+ this.emitInfo(t);+ }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@@ -1405,6 +1508,121 @@ export class AcpThreadManager {});}+ /**+ * Apply the user's remembered per-agent config options to a fresh session+ * BEFORE the first prompt, so turn 1 runs on their chosen model. Applied+ * model-category first and awaited one at a time: a `set_config_option`+ * response is the agent's authoritative post-change state (picking a model+ * can reshape the thought-level choices), so each step re-validates against+ * the reshaped options. Unknown / deprecated / already-current values are+ * skipped; a rejected set is logged and does not block the rest. Best-effort+ * by design — the turn proceeds on the agent's defaults for anything that+ * couldn't be applied.+ */+ private async applyInitialConfig(+ record: ThreadRecord,+ conn: NonNullable<ThreadRecord['conn']>,+ config: Record<string, string | boolean>,+ ): Promise<void> {+ const sessionId = record.sessionId;+ if (sessionId === null) return;+ const isModel = (id: string): boolean =>+ (record.info.configOptions ?? []).find((o) => o.id === id)?.category === 'model';+ const ids = Object.keys(config).sort((a, b) => Number(isModel(b)) - Number(isModel(a)));+ let applied = false;+ const rejected: string[] = [];+ for (const configId of ids) {+ const value = config[configId];+ if (value === undefined) continue;+ const option = (record.info.configOptions ?? []).find((o) => o.id === configId);+ if (option === undefined) continue; // agent no longer offers this option+ if (option.currentValue === value) continue; // already the agent's default+ if (!initialConfigValueValid(option, value)) continue; // stored value gone (e.g. retired model)+ const request: SetSessionConfigOptionRequest =+ typeof value === 'boolean'+ ? { sessionId, configId, type: 'boolean', value }+ : { sessionId, configId, value };+ try {+ const response: SetSessionConfigOptionResponse = await conn.agent.request(+ acpMethods.agent.session.setConfigOption,+ request,+ );+ record.info.configOptions = response.configOptions;+ applied = true;+ } catch (err) {+ rejected.push(configId);+ this.opts.log.warn(+ { err, threadId: record.info.threadId, configId },+ '[acp-threads] initial config apply failed',+ );+ }+ if (record.closed) return;+ }+ // The thread still opens on the agent's defaults for anything that couldn't+ // be applied (best-effort). One rolled-up warn makes "my remembered settings+ // didn't stick" diagnosable from a bundle without correlating per-id lines.+ if (rejected.length > 0) {+ this.opts.log.warn(+ { threadId: record.info.threadId, rejectedConfigIds: rejected },+ '[acp-threads] some remembered config options could not be applied to the new session',+ );+ }+ if (applied) this.emitInfo(record);+ }++ /**+ * Apply the user's remembered mode to a fresh session BEFORE the first+ * prompt. Best-effort: the mode must still be advertised+ * by the settled session; an unknown or already-current mode is skipped, and+ * a rejected set is logged and does not block the turn. Handles both mode+ * surfaces — the legacy `SessionModeState` (`session/set_mode`) and the+ * generalized mode-category config option (`session/set_config_option`).+ */+ private async applyInitialMode(+ record: ThreadRecord,+ conn: NonNullable<ThreadRecord['conn']>,+ modeId: string,+ ): Promise<void> {+ const sessionId = record.sessionId;+ if (sessionId === null) return;+ const modes = record.info.modes;+ if (modes != null) {+ // Legacy SessionModeState path (Claude's permission modes).+ if (modes.availableModes.some((m) => m.id === modeId)) {+ if (modes.currentModeId === modeId) return; // already the session default+ try {+ await conn.agent.request(acpMethods.agent.session.setMode, { sessionId, modeId });+ record.info.modes = { ...modes, currentModeId: modeId };+ this.emitInfo(record);+ } catch (err) {+ this.opts.log.warn(+ { err, threadId: record.info.threadId, modeId, method: 'set_mode' },+ '[acp-threads] initial mode apply failed',+ );+ }+ return;+ }+ }+ // Generalized mode-category config option (agents that expose mode there).+ const option = (record.info.configOptions ?? []).find(+ (o) => o.category === 'mode' && initialConfigValueValid(o, modeId),+ );+ if (option === undefined || option.currentValue === modeId) return;+ try {+ const response: SetSessionConfigOptionResponse = await conn.agent.request(+ acpMethods.agent.session.setConfigOption,+ { sessionId, configId: option.id, value: modeId },+ );+ record.info.configOptions = response.configOptions;+ this.emitInfo(record);+ } catch (err) {+ this.opts.log.warn(+ { err, threadId: record.info.threadId, modeId, method: 'set_config_option' },+ '[acp-threads] initial mode apply failed',+ );+ }+ }+respondPermission(threadId: string,requestId: string,@@ -1803,6 +2021,10 @@ export class AcpThreadManager {}private emitStatus(t: ThreadRecord, status: ThreadStatus, detail?: string): void {+ // A terminal status is the single choke point where queued prompts die —+ // whatever path got here (agent exit, connection loss, prompt failure,+ // archive), messages must not fire into a dead agent.+ if (status === 'exited' || status === 'error') t.info.queue = undefined;t.info.status = status;t.info.lastActivityAt = Date.now();this.appendEvent(t, { kind: 'status', status, detail, ts: Date.now() });@@ -1823,9 +2045,12 @@ export class AcpThreadManager {}private buildMeta(t: ThreadRecord): PersistedThreadMeta {+ // The queue is ephemeral by contract — persisting it would resurrect+ // ghost entries into an archived thread after a mid-turn crash.+ const { queue: _ephemeral, ...info } = t.info;return {version: 1,- info: { ...t.info },+ info,sessionId: t.sessionId,cwd: t.cwd,agentRef: t.agentRef,@@ -1981,7 +2206,9 @@ export async function confineToContentDir(function rehydratedRecord(meta: PersistedThreadMeta): ThreadRecord {const status = meta.info.status === 'error' ? 'error' : 'exited';return {- info: { ...meta.info, status, archived: true },+ // `queue: undefined` belt-and-suspenders: buildMeta never persists one,+ // but a meta written by a different build must not resurrect entries.+ info: { ...meta.info, status, archived: true, queue: undefined },docName: meta.docName,agentRef: meta.agentRef,cwd: meta.cwd,@@ -2017,6 +2244,20 @@ function rehydratedRecord(meta: PersistedThreadMeta): ThreadRecord {};}+/** True when `value` is still a selectable value of `option` (booleans always). */+function initialConfigValueValid(option: SessionConfigOption, value: string | boolean): boolean {+ if (typeof value === 'boolean') return option.type === 'boolean';+ if (option.type !== 'select') return false;+ for (const entry of option.options) {+ if ('value' in entry) {+ if (entry.value === value) return true;+ } else if (entry.options.some((o) => o.value === value)) {+ return true;+ }+ }+ return false;+}+/** Error detail shown when a runtime download is declined or times out. */function declinedRuntimeHint(runtimeKind: ManagedRuntimeKind): string {const d = describeRuntime(runtimeKind);diff --git a/packages/server/src/acp/thread-persistence.test.ts b/packages/server/src/acp/thread-persistence.test.tsindex d335ed690..87bce8466 100644--- a/packages/server/src/acp/thread-persistence.test.ts+++ b/packages/server/src/acp/thread-persistence.test.ts@@ -1,4 +1,12 @@-import { appendFileSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';+import {+ appendFileSync,+ existsSync,+ mkdtempSync,+ readFileSync,+ realpathSync,+ 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';@@ -20,7 +28,7 @@ afterEach(() => {});async function makeStore(): Promise<ThreadPersistenceStore> {- const store = new ThreadPersistenceStore(tmp(), log);+ const store = new ThreadPersistenceStore({ primaryDir: tmp(), log });await store.init();return store;}@@ -146,3 +154,113 @@ describe('ThreadPersistenceStore', () => {expect((await store.resolveEventLog('t1')).count).toBe(0);});});++const metaCwd = (threadId: string, cwd: string): PersistedThreadMeta => ({+ version: 1,+ info: info(threadId),+ sessionId: 'sess-1',+ cwd,+ agentRef: { source: 'custom', id: 'a' },+});++describe('ThreadPersistenceStore global dir + legacy fallback', () => {+ test('scan cwd-filters the shared global dir (by realpath) but never the legacy dir', async () => {+ const global = tmp();+ const legacy = tmp();+ const rawCwd = tmp(); // on macOS a /var symlink; canonicalizes to /private/var+ const canonCwd = realpathSync(rawCwd);+ const otherCwd = realpathSync(tmp());++ // Global-dir threads for this project (cwd matches) and another (does not).+ const globalWriter = new ThreadPersistenceStore({+ primaryDir: global,+ legacyDir: legacy,+ cwd: canonCwd,+ log,+ });+ await globalWriter.init();+ globalWriter.queueMetaWrite('mine', metaCwd('mine', rawCwd)); // un-canonicalized, as the manager stores it+ globalWriter.queueMetaWrite('other', metaCwd('other', otherCwd));+ await globalWriter.whenIdle('mine');+ await globalWriter.whenIdle('other');++ // A pre-move thread living in the per-project legacy dir, with a cwd that+ // would FAIL a cwd filter — proving the legacy dir is admitted unfiltered.+ const legacyWriter = new ThreadPersistenceStore({ primaryDir: legacy, log });+ await legacyWriter.init();+ legacyWriter.queueMetaWrite('legacy', metaCwd('legacy', otherCwd));+ await legacyWriter.whenIdle('legacy');++ const reader = new ThreadPersistenceStore({+ primaryDir: global,+ legacyDir: legacy,+ cwd: canonCwd,+ log,+ });+ const ids = (await reader.scan()).map((m) => m.info.threadId).sort();+ expect(ids).toEqual(['legacy', 'mine']); // 'other' filtered out; realpath let 'mine' match+ });++ test('a legacy-homed thread stays in legacy for append and delete (never split)', async () => {+ const global = tmp();+ const legacy = tmp();+ const cwd = realpathSync(tmp());++ const seed = new ThreadPersistenceStore({ primaryDir: legacy, log });+ await seed.init();+ seed.queueMetaWrite('tl', metaCwd('tl', cwd));+ seed.appendEvents('tl', [ev(0), ev(1)]);+ await seed.whenIdle('tl');++ const store = new ThreadPersistenceStore({+ primaryDir: global,+ legacyDir: legacy,+ cwd,+ log,+ });+ await store.init();+ expect((await store.scan()).map((m) => m.info.threadId)).toContain('tl');++ // Appends ride the legacy file — the seq contract needs one file, not a split.+ store.appendEvents('tl', [ev(2)]);+ await store.whenIdle('tl');+ expect(store.eventsPath('tl')).toContain(legacy);+ expect(existsSync(join(global, 'threads', 'tl.ndjson'))).toBe(false);+ expect((await store.resolveEventLog('tl')).count).toBe(3);++ await store.delete('tl');+ expect(existsSync(join(legacy, 'threads', 'tl.ndjson'))).toBe(false);+ expect((await store.resolveEventLog('tl')).count).toBe(0);+ });++ test('new threads write to the global primary dir', async () => {+ const global = tmp();+ const legacy = tmp();+ const cwd = realpathSync(tmp());+ const store = new ThreadPersistenceStore({ primaryDir: global, legacyDir: legacy, cwd, log });+ await store.init();+ store.queueMetaWrite('tn', metaCwd('tn', cwd));+ store.appendEvents('tn', [ev(0)]);+ await store.whenIdle('tn');+ expect(store.eventsPath('tn')).toContain(global);+ expect(existsSync(join(global, 'threads', 'tn.ndjson'))).toBe(true);+ });++ test('an unwritable primary dir degrades to legacy without failing init', async () => {+ const fileAsDir = join(tmp(), 'not-a-dir');+ writeFileSync(fileAsDir, 'x'); // primaryDir is a file → mkdir(<file>/threads) fails+ const legacy = tmp();+ const store = new ThreadPersistenceStore({+ primaryDir: fileAsDir,+ legacyDir: legacy,+ cwd: null,+ log,+ });+ await store.init(); // must NOT throw — boot survives a bad HOME+ store.queueMetaWrite('td', metaCwd('td', '/x'));+ store.appendEvents('td', [ev(0)]);+ await store.whenIdle('td');+ expect(store.eventsPath('td')).toContain(legacy);+ expect(existsSync(join(legacy, 'threads', 'td.ndjson'))).toBe(true);+ });+});diff --git a/packages/server/src/acp/thread-persistence.ts b/packages/server/src/acp/thread-persistence.tsindex 71133f04e..fc6b4b0f9 100644--- a/packages/server/src/acp/thread-persistence.ts+++ b/packages/server/src/acp/thread-persistence.ts@@ -1,8 +1,8 @@/**- * Durable transcript storage for ACP threads — `<localDir>/threads/`.+ * Durable transcript storage for ACP threads — `<dir>/threads/`.*- * Two files per thread, both machine-local and never committed (same trust- * envelope as `acp-permissions.json` — transcripts embed file diffs):+ * Two files per thread, both machine-local and never committed (transcripts+ * embed file diffs):** <threadId>.ndjson one ThreadEvent per line; LINE INDEX IS THE SEQ.* Every event a thread ever appends lands here (the@@ -13,6 +13,23 @@* (sessionId, cwd, agent ref) — everything needed to* list a thread at boot and `session/resume` it later.*+ * Location: threads live under a machine-global `~/.ok/threads/` so they+ * survive project-folder churn and are shared like `~/.ok/acp-agents` and+ * `~/.ok/runtimes`. Because that dir is shared across a machine's projects,+ * `scan()` returns only threads whose `meta.cwd` canonically matches this+ * server's contentDir (realpath-compared, so `/var`↔`/private/var` and+ * symlinks agree). A read-only LEGACY dir — the pre-move per-project+ * `<projectDir>/.ok/local/threads/` — is also scanned, UNFILTERED (it was+ * already project-scoped by its location); threads found there stay there for+ * every op (read, append, delete), never split across dirs, and no migration+ * runs. New threads always write to the global dir. With no global dir+ * configured (tests) the store is single-dir and behaves exactly as before.+ *+ * Trade-offs of the global dir: deleting a project folder no longer deletes+ * its transcripts (they orphan under the cwd filter), and transcripts leave+ * the project's own volume — accepted, matching how CLI agents keep sessions+ * globally; the per-project permission grants deliberately did NOT move.+ ** 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@@ -21,11 +38,17 @@*/import { createReadStream, existsSync } from 'node:fs';-import { readdir, readFile } from 'node:fs/promises';-import { join } from 'node:path';+import { readdir, readFile, realpath } from 'node:fs/promises';+import { join, resolve } 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 {+ tracedAppendFile,+ tracedMkdir,+ tracedRename,+ tracedRm,+ tracedWriteFile,+} from '../fs-traced.ts';import type { PinoLogger } from '../logger.ts';const THREADS_SUBDIR = 'threads';@@ -51,17 +74,53 @@ export interface ResolvedEventLog {midTurn: boolean;}+export interface ThreadPersistenceStoreOptions {+ /** Parent of the primary `threads/` dir — where new threads write and reads look first. */+ primaryDir: string;+ /** Parent of a read-only fallback `threads/` dir (pre-move per-project state), or null. */+ legacyDir?: string | null;+ /**+ * Canonical contentDir for cwd-scoping the shared primary dir: `scan()`+ * returns a primary-dir thread only when `realpath(meta.cwd)` matches+ * `realpath(cwd)`. Null disables filtering (single-dir / test mode); the+ * legacy dir is never cwd-filtered.+ */+ cwd?: string | null;+ log: PinoLogger;+}+export class ThreadPersistenceStore {- private readonly dir: string;+ /** `<primaryDir>/threads` — reads look here first; new threads write here. */+ private readonly primaryThreadsDir: string;+ /** `<legacyDir>/threads` read-only fallback, or null. */+ private readonly legacyThreadsDir: string | null;+ private readonly cwd: string | null;private readonly log: PinoLogger;+ /** Where NEW threads write. Normally the primary dir; falls back to legacy if the primary mkdir fails. */+ private writeThreadsDir: string;+ /** threadId → the `threads/` dir owning its files. Pinned at scan (rehydrated) or on first write (new). */+ private readonly homeByThread = new Map<string, string>();/** 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;+ constructor(opts: ThreadPersistenceStoreOptions) {+ this.primaryThreadsDir = join(opts.primaryDir, THREADS_SUBDIR);+ this.legacyThreadsDir = opts.legacyDir != null ? join(opts.legacyDir, THREADS_SUBDIR) : null;+ this.cwd = opts.cwd ?? null;+ this.log = opts.log;+ this.writeThreadsDir = this.primaryThreadsDir;+ }++ /** The `threads/` dir that owns this thread's files (its home, else the write dir). */+ private threadsDirFor(threadId: string): string {+ return this.homeByThread.get(threadId) ?? this.writeThreadsDir;+ }++ /** Pin a not-yet-seen thread to the current write dir (called on first write). */+ private pinHome(threadId: string): void {+ if (!this.homeByThread.has(threadId)) this.homeByThread.set(threadId, this.writeThreadsDir);}private enqueue(threadId: string, task: () => Promise<void>): void {@@ -70,15 +129,36 @@ export class ThreadPersistenceStore {}async init(): Promise<void> {- await tracedMkdir(this.dir, { recursive: true });+ try {+ await tracedMkdir(this.primaryThreadsDir, { recursive: true });+ } catch (err) {+ // A bad / read-only HOME must not fail server boot. Degrade to the legacy+ // per-project dir when there is one (still writable — it's inside the+ // project); otherwise per-thread writes fail and degrade to memory-only.+ this.log.warn(+ { err, dir: this.primaryThreadsDir },+ '[acp-persist] primary threads dir unavailable',+ );+ if (this.legacyThreadsDir !== null) {+ this.writeThreadsDir = this.legacyThreadsDir;+ try {+ await tracedMkdir(this.legacyThreadsDir, { recursive: true });+ } catch (legacyErr) {+ this.log.error(+ { err: legacyErr, dir: this.legacyThreadsDir },+ '[acp-persist] legacy threads dir also unavailable; threads are memory-only',+ );+ }+ }+ }}eventsPath(threadId: string): string {- return join(this.dir, `${threadId}.ndjson`);+ return join(this.threadsDirFor(threadId), `${threadId}.ndjson`);}metaPath(threadId: string): string {- return join(this.dir, `${threadId}.meta.json`);+ return join(this.threadsDirFor(threadId), `${threadId}.meta.json`);}/**@@ -88,6 +168,7 @@ export class ThreadPersistenceStore {*/appendEvents(threadId: string, events: readonly ThreadEvent[]): void {if (events.length === 0 || this.appendBroken.has(threadId)) return;+ this.pinHome(threadId);const lines = `${events.map((e) => JSON.stringify(e)).join('\n')}\n`;this.enqueue(threadId, async () => {if (this.appendBroken.has(threadId)) return;@@ -105,12 +186,24 @@ export class ThreadPersistenceStore {/** Queue a metadata snapshot write, serialized behind pending appends. */queueMetaWrite(threadId: string, meta: PersistedThreadMeta): void {+ this.pinHome(threadId);const body = `${JSON.stringify(meta, null, 1)}\n`;this.enqueue(threadId, async () => {+ const path = this.metaPath(threadId);+ const tmp = `${path}.tmp`;try {- await tracedWriteFile(this.metaPath(threadId), body);+ // tmp + rename so a concurrent scan (a sibling project's boot shares+ // the global dir) never reads a half-written meta.+ await tracedWriteFile(tmp, body);+ await tracedRename(tmp, path);} catch (err) {this.log.warn({ err, threadId }, '[acp-persist] meta write failed');+ try {+ // Don't leave a half-written `.tmp` behind to accumulate.+ await tracedRm(tmp, { force: true });+ } catch {+ // Best-effort cleanup — the failed write is already logged.+ }}});}@@ -127,36 +220,73 @@ export class ThreadPersistenceStore {* never a boot failure.*/async scan(): Promise<PersistedThreadMeta[]> {+ const metas: PersistedThreadMeta[] = [];+ const seen = new Set<string>();+ const canonCwd = this.cwd !== null ? await canonicalPath(this.cwd) : null;+ // Primary dir first so it wins any threadId collision with legacy.+ await this.scanDir(this.primaryThreadsDir, canonCwd, metas, seen);+ if (this.legacyThreadsDir !== null && this.legacyThreadsDir !== this.primaryThreadsDir) {+ await this.scanDir(this.legacyThreadsDir, null, metas, seen);+ }+ return metas;+ }++ /**+ * Read one dir's metas into `out`, recording each thread's home dir so later+ * ops resolve to the right files. A non-null `canonCwd` cwd-filters this dir+ * (realpath-compared); null admits all. `seen` is the per-scan dedup set —+ * a threadId an earlier dir already returned is skipped (primary wins).+ */+ private async scanDir(+ dir: string,+ canonCwd: string | null,+ out: PersistedThreadMeta[],+ seen: Set<string>,+ ): Promise<void> {let names: string[];try {- names = await readdir(this.dir);- } catch {- return [];+ names = await readdir(dir);+ } catch (err) {+ // A missing dir is the normal case (no legacy threads yet, or a fresh+ // global dir). Anything else — EACCES on a locked-down HOME, EIO —+ // silently hides EVERY thread in it, so it has to be said out loud.+ if ((err as NodeJS.ErrnoException).code !== 'ENOENT') {+ this.log.warn({ err, dir }, '[acp-persist] could not read a threads dir');+ }+ return;}- const metas: PersistedThreadMeta[] = [];for (const name of names) {if (!name.endsWith('.meta.json')) continue;- const path = join(this.dir, name);+ const path = join(dir, name);+ let parsed: Partial<PersistedThreadMeta>;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);+ parsed = JSON.parse(await readFile(path, 'utf8')) as Partial<PersistedThreadMeta>;} catch (err) {this.log.warn({ err, path }, '[acp-persist] skipping unreadable thread meta');+ continue;+ }+ 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;}+ const meta = parsed as PersistedThreadMeta;+ const threadId = meta.info.threadId;+ if (seen.has(threadId)) continue; // an earlier dir already claimed it this scan+ if (canonCwd !== null && (await canonicalPath(meta.cwd)) !== canonCwd) continue;+ seen.add(threadId);+ // Record the home only if not already pinned (a live thread written this+ // session keeps its write-dir home).+ if (!this.homeByThread.has(threadId)) this.homeByThread.set(threadId, dir);+ out.push(meta);}- return metas;}/**@@ -217,8 +347,21 @@ export class ThreadPersistenceStore {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 });+ // Resolve paths (via the home map) BEFORE forgetting the home. The two+ // removals are independent: `force` only swallows ENOENT, so a failing+ // events rm (EACCES/EIO) must not strand the meta on disk — the next+ // boot's scan would rehydrate the "deleted" thread as a phantom.+ const paths = [this.eventsPath(threadId), this.metaPath(threadId)];+ const results = await Promise.allSettled(paths.map((p) => tracedRm(p, { force: true })));+ this.homeByThread.delete(threadId);+ for (const [i, result] of results.entries()) {+ if (result.status === 'rejected') {+ this.log.warn(+ { err: result.reason, threadId, path: paths[i] },+ '[acp-persist] thread file removal failed',+ );+ }+ }}/**@@ -290,3 +433,12 @@ function parseEventLine(line: string): ThreadEvent {return { kind: 'agent_stderr', line: '[unreadable log entry]', ts: 0 };}}++/** realpath, falling back to a lexical resolve when the path doesn't exist yet. */+async function canonicalPath(p: string): Promise<string> {+ try {+ return await realpath(p);+ } catch {+ return resolve(p);+ }+}diff --git a/packages/server/src/acp/thread-socket.test.ts b/packages/server/src/acp/thread-socket.test.tsindex d65b8e140..0f447b89a 100644--- a/packages/server/src/acp/thread-socket.test.ts+++ b/packages/server/src/acp/thread-socket.test.ts@@ -151,6 +151,7 @@ function makeManager(contentDir: string, localDir: string): AcpThreadManager {const manager = new AcpThreadManager({contentDir,localDir,+ globalDir: null,registry: new AcpRegistry({localDir,log,@@ -367,3 +368,36 @@ describe('/collab/thread socket — history ops', () => {viewer.close();}, 45_000);});++describe('/collab/thread socket — queue ops', () => {+ test('queue_edit / queue_remove route to the manager; unknown thread → error frame', async () => {+ const manager = makeManager(tmp(), tmp());+ await manager.init();+ const socket = attachFakeSocket(manager);++ const errors = () =>+ socket.frames.filter((f): f is Extract<ThreadServerFrame, { op: 'error' }> => {+ return f.op === 'error';+ });+ const awaitErrors = async (count: number): Promise<void> => {+ const deadline = Date.now() + 10_000;+ while (errors().length < count) {+ if (Date.now() > deadline) {+ throw new Error(`saw ${errors().length}/${count} errors`);+ }+ await new Promise((r) => setTimeout(r, 10));+ }+ };++ socket.emit(+ JSON.stringify({ op: 'queue_edit', threadId: 'missing', id: 'q1', content: 'new text' }),+ );+ socket.emit(JSON.stringify({ op: 'queue_remove', threadId: 'missing', id: 'q1' }));+ // Empty content fails structural parse and never reaches the manager.+ socket.emit(JSON.stringify({ op: 'queue_edit', threadId: 'missing', id: 'q1', content: '' }));+ await awaitErrors(3);++ expect(errors().map((f) => f.code)).toEqual(['unknown-thread', 'unknown-thread', 'bad-frame']);+ expect(errors()[0]?.threadId).toBe('missing');+ });+});diff --git a/packages/server/src/acp/thread-socket.ts b/packages/server/src/acp/thread-socket.tsindex db2c16e1e..e69406771 100644--- a/packages/server/src/acp/thread-socket.ts+++ b/packages/server/src/acp/thread-socket.ts@@ -66,6 +66,7 @@ export function attachAcpThreadSocket(prompt: frame.prompt,docName: frame.docName,titleHint: frame.titleHint,+ settings: frame.settings,});send({ op: 'created', reqId: frame.reqId, info });// Creating implies interest: auto-subscribe from the beginning@@ -107,6 +108,14 @@ export function attachAcpThreadSocket(manager.sendPrompt(frame.threadId, frame.content);return;}+ case 'queue_edit': {+ manager.editQueued(frame.threadId, frame.id, frame.content);+ return;+ }+ case 'queue_remove': {+ manager.removeQueued(frame.threadId, frame.id);+ return;+ }case 'permission_response': {manager.respondPermission(frame.threadId, frame.requestId, frame.outcome);return;diff --git a/packages/server/src/boot.ts b/packages/server/src/boot.tsindex e57e5b534..fa13b9ac4 100644--- a/packages/server/src/boot.ts+++ b/packages/server/src/boot.ts@@ -22,6 +22,7 @@*/import { existsSync, readdirSync, statSync } from 'node:fs';import type { Server as HttpServer } from 'node:http';+import { homedir } from 'node:os';import { join, resolve } from 'node:path';import {ASSET_EXTENSIONS,@@ -835,6 +836,11 @@ async function bootServerInner(opts: BootServerOptions): Promise<BootedServer> {: new AcpThreadManager({contentDir: opts.contentDir,localDir: lockDir,+ // Transcripts persist under `~/.ok/threads`, shared across projects and+ // cwd-scoped — surviving project-folder churn (like the agent binary and+ // runtime caches already at `~/.ok`). The legacy per-project dir is read+ // back for pre-move threads.+ globalDir: resolve(homedir(), OK_DIR),registry: serverInstance.acpRegistry,permissions: serverInstance.acpPermissions,sessionManager,