Beautiful, AI-native markdown IDE and LLM wiki
TypeScript 2nd-brainagent-skillsclaudecodexcompany-braindocsknowledge-knowledge-baseknowledge-managementllmllm-wikillm-wiki-karpathymarkdownmarkdown-editormdmdxnotespkmsecond-brainskills
fix(open-knowledge): ACP bug-bash reliability overhaul (PRD-7824) (#3258)
mike-inkeepe88f67c397f0
diff --git a/.changeset/acp-bug-bash-blockers.md b/.changeset/acp-bug-bash-blockers.mdnew file mode 100644index 000000000..318dacb08--- /dev/null+++ b/.changeset/acp-bug-bash-blockers.md@@ -0,0 +1,5 @@+---+"@inkeep/open-knowledge": patch+---++In-app agent (ACP) reliability overhaul from the July 31 bug bash. Startup failures now tell the truth: "sign in first" only appears for real authentication failures (classified by the protocol's auth-required code), other errors show the agent's own message with wire-level details behind a Show details disclosure, and failed threads keep their transcript instead of erasing it when the tab closes. Sign-in works in place — auth failures render a button per advertised sign-in method, and completing one reopens the session on the same agent process with your drafted message intact. Agents and their terminals now inherit your login shell's PATH on every launch (not just when the top-level command is missing), so tools installed via nvm and friends resolve; a Retry button on failure notices re-probes the PATH and respawns. Queued messages survive Stop (they fold back into the composer), editing a queued message holds it until you resubmit, the queue says when it delivers, and a new Steer now button interrupts the current run and sends your correction as the next turn — falling back to the front of the queue if the agent won't stop.diff --git a/packages/app/src/components/acp/ThreadView.dom.test.tsx b/packages/app/src/components/acp/ThreadView.dom.test.tsxindex 7fdafaf69..b694b8727 100644--- a/packages/app/src/components/acp/ThreadView.dom.test.tsx+++ b/packages/app/src/components/acp/ThreadView.dom.test.tsx@@ -38,9 +38,20 @@ const setConfigOption = vi.fn();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 steer = vi.fn((_threadId: string, _content: string) => {});+/** What the mocked `editQueued` hands back — a rejection stands in for the+ * server refusing an entry that already dispatched. */+let editQueuedResult: Promise<void> = Promise.resolve();+const editQueued = vi.fn((_threadId: string, _id: string, _content: string) => editQueuedResult);+const holdQueued = vi.fn((_threadId: string, _id: string, _held: boolean) => {});const removeQueued = vi.fn((_threadId: string, _id: string) => {});+const toastError = vi.fn((_message: string) => {});const cancel = vi.fn((_threadId: string) => {});+const retryThread = vi.fn(async (_threadId: string) => {});+/** What the mocked `authenticateThread` hands back — a rejection stands in for+ * the agent refusing the sign-in. */+let authenticateResult: Promise<void> = Promise.resolve();+const authenticateThread = vi.fn((_threadId: string, _methodId: string) => authenticateResult);vi.doMock('@/lib/acp/thread-client', () => ({getAgentThreadClient: () => ({@@ -48,7 +59,9 @@ vi.doMock('@/lib/acp/thread-client', () => ({respondRuntimeConsent: () => {},cancel,prompt,+ steer,editQueued,+ holdQueued,removeQueued,setMode,setConfigOption,@@ -59,6 +72,8 @@ vi.doMock('@/lib/acp/thread-client', () => ({resumeThread: async () => {throw new Error('unused');},+ retryThread,+ authenticateThread,}),ThreadResumeError: class ThreadResumeError extends Error {readonly code: string;@@ -71,6 +86,10 @@ vi.doMock('@/lib/acp/thread-client', () => ({useAgentThreadModel: () => model,}));+vi.doMock('sonner', () => ({+ toast: { error: toastError, success: vi.fn(), info: vi.fn() },+}));+vi.doMock('@/editor/DocumentContext', () => ({useDocumentContext: () => ({ systemProvider: null }),}));@@ -165,9 +184,16 @@ afterEach(() => {setConfigOption.mockClear();setMode.mockClear();prompt.mockClear();+ steer.mockClear();editQueued.mockClear();+ editQueuedResult = Promise.resolve();+ holdQueued.mockClear();removeQueued.mockClear();+ toastError.mockClear();cancel.mockClear();+ retryThread.mockClear();+ authenticateThread.mockClear();+ authenticateResult = Promise.resolve();model = null;});@@ -1260,3 +1286,561 @@ describe('ThreadView message queue', () => {expect(screen.getByTestId('agent-thread-queued').textContent).toContain('keep me');});});++describe('ThreadView queue rescue on Stop', () => {+ test('Stop folds every queued message back into the composer', () => {+ model = makeModel({ turnActive: true });+ render(+ <ThreadView+ info={makeInfo({+ status: 'running',+ queue: [+ { id: 'q1', content: 'first correction', ts: 1 },+ { id: 'q2', content: 'second correction', ts: 2 },+ ],+ })}+ />,+ );++ fireEvent.click(screen.getByTestId('agent-thread-cancel'));++ expect(cancel).toHaveBeenCalledWith('thread-1');+ // The server drops the queue on cancel, so the words only survive here.+ const composer = screen.getByTestId('agent-thread-composer') as HTMLTextAreaElement;+ expect(composer.value).toBe('first correction\n\nsecond correction');+ });++ test('the Escape cancel path rescues the queue too, appended to the draft', () => {+ model = makeModel({ turnActive: true });+ render(+ <ThreadView+ info={makeInfo({+ status: 'running',+ queue: [{ id: 'q1', content: 'queued fix', ts: 1 }],+ })}+ />,+ );++ const composer = screen.getByTestId('agent-thread-composer') as HTMLTextAreaElement;+ fireEvent.change(composer, { target: { value: 'already typing' } });+ fireEvent.keyDown(composer, { key: 'Escape' });++ expect(cancel).toHaveBeenCalledWith('thread-1');+ expect(composer.value).toBe('already typing\n\nqueued fix');+ });++ test('an empty queue leaves the draft exactly as typed', () => {+ model = makeModel({ turnActive: true });+ render(<ThreadView info={makeInfo({ status: 'running' })} />);++ const composer = screen.getByTestId('agent-thread-composer') as HTMLTextAreaElement;+ fireEvent.change(composer, { target: { value: 'just this' } });+ fireEvent.keyDown(composer, { key: 'Escape' });++ expect(composer.value).toBe('just this');+ });+});++describe('ThreadView steer now', () => {+ test('mid-turn with a draft, Steer now sends the correction and clears the composer', () => {+ model = makeModel({ turnActive: true });+ render(<ThreadView info={makeInfo({ status: 'running' })} />);++ // Nothing typed: no steer affordance to mis-click, only Stop.+ expect(screen.queryByTestId('agent-thread-steer')).toBeNull();++ const composer = screen.getByTestId('agent-thread-composer') as HTMLTextAreaElement;+ fireEvent.change(composer, { target: { value: ' actually, do this instead ' } });++ // Both outcomes are offered side by side: wait your turn, or interrupt.+ expect(screen.getByTestId('agent-thread-send').getAttribute('aria-label')).toBe(+ 'Queue message',+ );+ const steerButton = screen.getByTestId('agent-thread-steer');+ expect(steerButton.getAttribute('aria-label')).toBe('Steer now');++ fireEvent.click(steerButton);+ expect(steer).toHaveBeenCalledWith('thread-1', 'actually, do this instead');+ expect(prompt).not.toHaveBeenCalled();+ expect(composer.value).toBe('');+ });++ test('Enter still queues — steering is only ever an explicit click', () => {+ model = makeModel({ turnActive: true });+ render(<ThreadView info={makeInfo({ status: 'running' })} />);++ const composer = screen.getByTestId('agent-thread-composer');+ fireEvent.change(composer, { target: { value: 'queue me' } });+ fireEvent.keyDown(composer, { key: 'Enter' });++ expect(prompt).toHaveBeenCalledWith('thread-1', 'queue me');+ expect(steer).not.toHaveBeenCalled();+ });++ test('outside a turn there is nothing to steer away from', () => {+ model = makeModel({ turnActive: false });+ render(<ThreadView info={makeInfo({ status: 'ready' })} />);++ fireEvent.change(screen.getByTestId('agent-thread-composer'), {+ target: { value: 'plain send' },+ });+ expect(screen.queryByTestId('agent-thread-steer')).toBeNull();+ });++ test('a parked steer shows the waiting strip with the correction previewed', () => {+ model = makeModel({ turnActive: true });+ render(+ <ThreadView+ info={makeInfo({ status: 'running', steer: { content: 'use the other API', ts: 1 } })}+ />,+ );++ const strip = screen.getByTestId('agent-thread-steer-pending');+ expect(strip.textContent).toContain('waiting for the current run to stop');+ expect(strip.textContent).toContain('use the other API');+ });++ test('Stop rescues the parked steer ahead of the queue', () => {+ model = makeModel({ turnActive: true });+ render(+ <ThreadView+ info={makeInfo({+ status: 'running',+ steer: { content: 'the correction', ts: 3 },+ queue: [{ id: 'q1', content: 'queued after', ts: 4 }],+ })}+ />,+ );++ fireEvent.click(screen.getByTestId('agent-thread-cancel'));++ expect(cancel).toHaveBeenCalledWith('thread-1');+ // Server-side both are dropped, so the composer is the only place the+ // words survive — steer first, because that is the order it would have run.+ const composer = screen.getByTestId('agent-thread-composer') as HTMLTextAreaElement;+ expect(composer.value).toBe('the correction\n\nqueued after');+ });+});++describe('ThreadView queued-message holds', () => {+ const oneQueued = (content = 'original text', held?: boolean) =>+ makeInfo({+ status: 'running',+ queue: [{ id: 'q1', content, ts: 1, ...(held === undefined ? {} : { held }) }],+ });++ test('opening the editor holds the row so the drain cannot take it', () => {+ model = makeModel({ turnActive: true });+ render(<ThreadView info={oneQueued()} />);++ fireEvent.click(screen.getByTestId('agent-thread-queued-edit'));+ expect(holdQueued).toHaveBeenCalledWith('thread-1', 'q1', true);+ });++ test('cancelling the edit releases the hold', () => {+ model = makeModel({ turnActive: true });+ render(<ThreadView info={oneQueued()} />);++ fireEvent.click(screen.getByTestId('agent-thread-queued-edit'));+ fireEvent.click(screen.getByTestId('agent-thread-queued-cancel-edit'));++ expect(holdQueued).toHaveBeenLastCalledWith('thread-1', 'q1', false);+ expect(editQueued).not.toHaveBeenCalled();+ });++ test('Escape releases the hold as well', () => {+ model = makeModel({ turnActive: true });+ render(<ThreadView info={oneQueued()} />);++ fireEvent.click(screen.getByTestId('agent-thread-queued-edit'));+ fireEvent.keyDown(screen.getByTestId('agent-thread-queued-input'), { key: 'Escape' });++ expect(holdQueued).toHaveBeenLastCalledWith('thread-1', 'q1', false);+ });++ test('saving changed text resubmits through the edit; the server clears the hold', () => {+ model = makeModel({ turnActive: true });+ render(<ThreadView info={oneQueued()} />);++ fireEvent.click(screen.getByTestId('agent-thread-queued-edit'));+ fireEvent.change(screen.getByTestId('agent-thread-queued-input'), {+ target: { value: 'sharper text' },+ });+ fireEvent.keyDown(screen.getByTestId('agent-thread-queued-input'), { key: 'Enter' });++ expect(editQueued).toHaveBeenCalledWith('thread-1', 'q1', 'sharper text');+ // A second release frame would race the edit's own clear.+ expect(holdQueued).toHaveBeenCalledTimes(1);+ expect(holdQueued).toHaveBeenCalledWith('thread-1', 'q1', true);+ });++ test('saving unchanged text just releases the hold — nothing to edit', () => {+ model = makeModel({ turnActive: true });+ render(<ThreadView info={oneQueued()} />);++ fireEvent.click(screen.getByTestId('agent-thread-queued-edit'));+ fireEvent.keyDown(screen.getByTestId('agent-thread-queued-input'), { key: 'Enter' });++ expect(editQueued).not.toHaveBeenCalled();+ expect(holdQueued).toHaveBeenLastCalledWith('thread-1', 'q1', false);+ });++ test('a held row is marked as held and offers to send it', () => {+ model = makeModel({ turnActive: true });+ render(<ThreadView info={oneQueued('parked text', true)} />);++ const row = screen.getByTestId('agent-thread-queued');+ expect(row.textContent).toContain('Held');+ expect(row.getAttribute('data-held')).toBe('true');++ fireEvent.click(within(row).getByTestId('agent-thread-queued-release'));+ expect(holdQueued).toHaveBeenCalledWith('thread-1', 'q1', false);+ });++ test('an ordinary queued row carries no held marking', () => {+ model = makeModel({ turnActive: true });+ render(<ThreadView info={oneQueued()} />);++ const row = screen.getByTestId('agent-thread-queued');+ expect(row.getAttribute('data-held')).toBeNull();+ expect(screen.queryByTestId('agent-thread-queued-release')).toBeNull();+ });++ test('an edit that lost its race says so instead of vanishing', async () => {+ editQueuedResult = Promise.reject(new Error('queued message already dispatched'));+ model = makeModel({ turnActive: true });+ render(<ThreadView info={oneQueued()} />);++ fireEvent.click(screen.getByTestId('agent-thread-queued-edit'));+ fireEvent.change(screen.getByTestId('agent-thread-queued-input'), {+ target: { value: 'too late' },+ });+ fireEvent.keyDown(screen.getByTestId('agent-thread-queued-input'), { key: 'Enter' });++ await vi.waitFor(() => expect(toastError).toHaveBeenCalledTimes(1));+ expect(String(toastError.mock.calls[0]?.[0])).toContain("wasn't applied");+ });+});++describe('ThreadView send-vs-queue labelling', () => {+ test('the queue header says when the messages actually go out', () => {+ model = makeModel({ turnActive: true });+ render(+ <ThreadView+ info={makeInfo({+ status: 'running',+ queue: [{ id: 'q1', content: 'waiting', ts: 1 }],+ })}+ />,+ );++ expect(screen.getByTestId('agent-thread-queue').textContent).toContain(+ 'sends when this run finishes',+ );+ });++ test('mid-turn the action button wears the queue icon and explains itself', async () => {+ const user = userEvent.setup();+ model = makeModel({ turnActive: true });+ render(<ThreadView info={makeInfo({ status: 'running' })} />);++ fireEvent.change(screen.getByTestId('agent-thread-composer'), {+ target: { value: 'queued while running' },+ });++ const send = screen.getByTestId('agent-thread-send');+ // The aria-label alone was the only send-vs-queue tell; sighted users read+ // the glyph.+ expect(send.querySelector('svg')?.getAttribute('class')).toContain('list-plus');++ await user.hover(send);+ const tooltip = await screen.findByRole('tooltip');+ expect(tooltip.textContent).toContain('Queues behind the running turn');+ });++ test('outside a turn it is a plain send arrow with no queue tooltip', async () => {+ const user = userEvent.setup();+ model = makeModel({ turnActive: false });+ render(<ThreadView info={makeInfo({ status: 'ready' })} />);++ fireEvent.change(screen.getByTestId('agent-thread-composer'), {+ target: { value: 'idle send' },+ });++ const send = screen.getByTestId('agent-thread-send');+ expect(send.querySelector('svg')?.getAttribute('class')).toContain('arrow-up');++ await user.hover(send);+ expect(screen.queryByRole('tooltip')).toBeNull();+ });+});++describe('ThreadView retry', () => {+ function failureNotice(+ reason: 'auth-required' | 'connect' | 'session-setup' | 'prompt',+ ): Extract<RenderedItem, { kind: 'notice' }> {+ return {+ kind: 'notice',+ text: '',+ tone: 'error',+ failure: { reason, agentMessage: 'harness not installed' },+ };+ }++ test('a startup failure offers Retry and re-runs the launch', async () => {+ model = makeModel({ turnActive: false, items: [failureNotice('session-setup')] });+ render(<ThreadView info={makeInfo({ status: 'error' })} />);++ await userEvent.click(screen.getByTestId('agent-thread-retry'));+ expect(retryThread).toHaveBeenCalledWith('thread-1');+ });++ // The session is live and the message is what failed — sending it again IS+ // the retry, so a second control here would only be a worse way to do it.+ test('a prompt failure offers no Retry', () => {+ model = makeModel({ turnActive: false, items: [failureNotice('prompt')] });+ render(<ThreadView info={makeInfo({ status: 'error' })} />);++ expect(screen.getByTestId('agent-thread-notice')).toBeDefined();+ expect(screen.queryByTestId('agent-thread-retry')).toBeNull();+ });++ // A transcript accumulates a notice per failed attempt; Retry belongs to the+ // one the user is looking at, not to every one they have ever seen.+ test('only the last startup failure carries the button', () => {+ model = makeModel({+ turnActive: false,+ items: [failureNotice('connect'), failureNotice('session-setup')],+ });+ render(<ThreadView info={makeInfo({ status: 'auth_required' })} />);++ expect(screen.getAllByTestId('agent-thread-notice')).toHaveLength(2);+ const buttons = screen.getAllByTestId('agent-thread-retry');+ expect(buttons).toHaveLength(1);+ const notices = screen.getAllByTestId('agent-thread-notice');+ expect(notices[1]?.contains(buttons[0] ?? null)).toBe(true);+ });++ test('an archived thread offers no Retry — that one resumes', () => {+ model = makeModel({ turnActive: false, items: [failureNotice('session-setup')] });+ render(<ThreadView info={makeInfo({ status: 'error', archived: true })} />);++ expect(screen.queryByTestId('agent-thread-retry')).toBeNull();+ });++ test('an auth failure offers a sign-in button that authenticates in place', async () => {+ model = makeModel({+ turnActive: false,+ items: [+ {+ kind: 'notice',+ text: '',+ tone: 'info',+ failure: {+ reason: 'auth-required',+ authMethods: [{ id: 'test_login', name: 'Test Login' }],+ },+ },+ ],+ });+ render(<ThreadView info={makeInfo({ status: 'auth_required' })} />);++ const button = screen.getByTestId('agent-thread-auth-method');+ expect(button.getAttribute('data-auth-method-id')).toBe('test_login');+ expect(button.textContent).toContain('Sign in with Test Login');+ await userEvent.click(button);+ expect(authenticateThread).toHaveBeenCalledWith('thread-1', 'test_login');+ // Retry stays: "I signed in elsewhere, try again" is still a valid answer.+ expect(screen.getByTestId('agent-thread-retry')).toBeDefined();+ });++ test('a refused sign-in surfaces the reason and leaves the button usable', async () => {+ authenticateResult = Promise.reject(new Error('wrong account'));+ model = makeModel({+ turnActive: false,+ items: [+ {+ kind: 'notice',+ text: '',+ tone: 'info',+ failure: {+ reason: 'auth-required',+ authMethods: [{ id: 'test_login', name: 'Test Login' }],+ },+ },+ ],+ });+ render(<ThreadView info={makeInfo({ status: 'auth_required' })} />);++ // Synchronous click: the pre-armed rejection has to meet its handler in+ // this same tick, or Node reports it as unhandled before the click lands.+ fireEvent.click(screen.getByTestId('agent-thread-auth-method'));++ await vi.waitFor(() => expect(toastError).toHaveBeenCalledTimes(1));+ expect(String(toastError.mock.calls[0]?.[0])).toContain('wrong account');+ expect(screen.getByTestId('agent-thread-auth-method').hasAttribute('disabled')).toBe(false);+ });++ // A terminal/env_var sign-in happens in the user's own shell — a button OK+ // can't complete would be a promise it has no way to keep.+ test('a terminal-kind method is named, not offered as a button', () => {+ model = makeModel({+ turnActive: false,+ items: [+ {+ kind: 'notice',+ text: '',+ tone: 'info',+ failure: {+ reason: 'auth-required',+ authMethods: [+ {+ id: 'cli_login',+ name: 'CLI Login',+ description: 'Run `agent login`',+ kind: 'terminal',+ },+ ],+ },+ },+ ],+ });+ render(<ThreadView info={makeInfo({ status: 'auth_required' })} />);++ expect(screen.queryByTestId('agent-thread-auth-method')).toBeNull();+ expect(screen.getByTestId('agent-thread-auth-manual').textContent).toContain('CLI Login');+ expect(screen.getByTestId('agent-thread-auth-manual').textContent).toContain('agent login');+ expect(screen.getByTestId('agent-thread-retry')).toBeDefined();+ });++ // Signing in takes a detour through a browser; a draft written before it has+ // to survive, so the field stays typable even though sending is still gated.+ test('the composer stays typable while the thread waits on sign-in', () => {+ model = makeModel({ turnActive: false, items: [] });+ render(<ThreadView info={makeInfo({ status: 'auth_required' })} />);++ const composer = screen.getByTestId('agent-thread-composer');+ expect(composer.hasAttribute('disabled')).toBe(false);+ fireEvent.change(composer, { target: { value: 'draft while signing in' } });+ expect((composer as HTMLTextAreaElement).value).toBe('draft while signing in');+ expect(screen.getByTestId('agent-thread-send').hasAttribute('disabled')).toBe(true);+ });++ // Clicking Sign in flips the status to `installing` — the same field the+ // draft was written in must not go read-only underneath it.+ test('the composer stays typable once the sign-in is under way', () => {+ model = makeModel({ turnActive: false, items: [] });+ render(<ThreadView info={makeInfo({ status: 'installing' })} />);++ const composer = screen.getByTestId('agent-thread-composer');+ expect(composer.hasAttribute('disabled')).toBe(false);+ fireEvent.change(composer, { target: { value: 'kept across the sign-in' } });+ expect((composer as HTMLTextAreaElement).value).toBe('kept across the sign-in');+ expect(screen.getByTestId('agent-thread-send').hasAttribute('disabled')).toBe(true);+ });++ test('a thread whose agent is gone for good has nothing left to type into', () => {+ model = makeModel({ turnActive: false, items: [] });+ render(<ThreadView info={makeInfo({ status: 'exited' })} />);++ expect(screen.getByTestId('agent-thread-composer').hasAttribute('disabled')).toBe(true);+ });++ test('the header names the build OK launched', () => {+ model = makeModel({ turnActive: false, items: [] });+ render(+ <ThreadView+ info={makeInfo({+ status: 'ready',+ agent: { id: 'claude', name: 'Claude Agent', source: 'registry', version: '0.53.0' },+ })}+ />,+ );++ expect(screen.getByTestId('agent-thread-agent-version').textContent).toBe('0.53.0');+ });+});+describe('ThreadView failure notices', () => {+ function notice(+ overrides?: Partial<Extract<RenderedItem, { kind: 'notice' }>>,+ ): Extract<RenderedItem, { kind: 'notice' }> {+ return {+ kind: 'notice',+ text: '',+ tone: 'error',+ failure: null,+ ...overrides,+ };+ }++ test('an auth failure reads as sign-in copy, quotes the agent, and hides the wire payload', async () => {+ model = makeModel({+ turnActive: false,+ items: [+ notice({+ tone: 'info',+ failure: {+ reason: 'auth-required',+ agentMessage: 'Authentication required',+ machineDetail: '{"detail":"run /login first"}',+ authMethods: [{ id: 'test_login', name: 'Test Login' }],+ },+ }),+ ],+ });+ render(<ThreadView info={makeInfo({ status: 'auth_required' })} />);++ const card = screen.getByTestId('agent-thread-notice');+ // "Claude Agent" reads as the brand in copy — the display name drops the suffix.+ expect(card.textContent).toContain('Sign in to Claude to continue');+ expect(card.textContent).toContain('Authentication required');+ // The JSON payload is diagnostic, not headline copy: it stays behind the+ // disclosure until the user asks for it.+ expect(card.textContent).not.toContain('run /login first');+ expect(screen.queryByTestId('agent-thread-notice-details')).toBeNull();++ const toggle = screen.getByTestId('agent-thread-notice-details-toggle');+ expect(toggle.getAttribute('aria-expanded')).toBe('false');+ await userEvent.click(toggle);++ expect(screen.getByTestId('agent-thread-notice-details').textContent).toContain(+ 'run /login first',+ );+ expect(+ screen.getByTestId('agent-thread-notice-details-toggle').getAttribute('aria-expanded'),+ ).toBe('true');+ });++ test('a session-setup failure names the step that broke', () => {+ model = makeModel({+ turnActive: false,+ items: [+ notice({+ failure: {+ reason: 'session-setup',+ agentMessage: 'Failed to initialize session services',+ },+ }),+ ],+ });+ render(<ThreadView info={makeInfo({ status: 'error' })} />);++ const card = screen.getByTestId('agent-thread-notice');+ expect(card.textContent).toContain("Claude couldn't start a conversation");+ expect(card.textContent).toContain('Failed to initialize session services');+ // Nothing machine-readable was attached, so no disclosure is offered.+ expect(screen.queryByTestId('agent-thread-notice-details-toggle')).toBeNull();+ });++ test('a legacy detail-only error still renders its raw text', () => {+ model = makeModel({+ turnActive: false,+ items: [notice({ text: 'session setup failed: boom' })],+ });+ render(<ThreadView info={makeInfo({ status: 'error' })} />);++ const card = screen.getByTestId('agent-thread-notice');+ expect(card.textContent).toBe('session setup failed: boom');+ expect(screen.queryByTestId('agent-thread-notice-details-toggle')).toBeNull();+ });+});diff --git a/packages/app/src/components/acp/ThreadView.tsx b/packages/app/src/components/acp/ThreadView.tsxindex af2d9aa92..e3b4dafc5 100644--- a/packages/app/src/components/acp/ThreadView.tsx+++ b/packages/app/src/components/acp/ThreadView.tsx@@ -11,6 +11,7 @@import type {QueuedMessage,SessionConfigOption,+ ThreadFailureDetail,ThreadInfo,} from '@inkeep/open-knowledge-core/acp/thread-protocol';import { useLingui } from '@lingui/react/macro';@@ -21,6 +22,7 @@ import {ChevronRight,Download,FileText,+ ListPlus,Loader2,MousePointer2,Search,@@ -31,6 +33,7 @@ import {Trash2,Wrench,X,+ Zap,} from 'lucide-react';import {Fragment,@@ -144,12 +147,31 @@ const TOOL_ICONS: Record<string, typeof Wrench> = {think: Sparkles,};+function errorText(err: unknown): string {+ return err instanceof Error ? err.message : String(err);+}+/** Display name for an agent — drops a trailing "Agent" so it reads as the brand* ("Claude Agent" → "Claude"). */function agentDisplayName(name: string): string {return name.replace(/\s+Agent$/i, '');}+/**+ * Failures a fresh launch can plausibly clear — mirrors the server's+ * `retryThread` guards (a thread that never opened a session). Everything+ * else, including a prompt failure on a live session, gets no Retry.+ */+const RETRYABLE_FAILURE_REASONS: ReadonlySet<ThreadFailureDetail['reason']> = new Set([+ 'connect',+ 'session-setup',+ 'auth-required',+]);++function isRetryableFailure(failure: ThreadFailureDetail): boolean {+ return RETRYABLE_FAILURE_REASONS.has(failure.reason);+}+export function ThreadView({ info }: { info: ThreadInfo }): ReactNode {const { t } = useLingui();const state = useAgentThread(info.threadId);@@ -191,6 +213,10 @@ 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;+ // A live thread sitting in a failure status never opened a session, so the+ // launch can simply be run again — see the server's `retryThread` guards.+ const canRetry = !archived && (status === 'error' || status === 'auth_required');+ const [retryPending, setRetryPending] = useState(false);// Mid-turn sends don't reject anymore — the server queues them behind the// active turn and drains FIFO (`ThreadInfo.queue`).const canQueue = !archived && turnActive;@@ -262,14 +288,47 @@ export function ThreadView({ info }: { info: ThreadInfo }): ReactNode {}, [cancelPending, turnActive]);const requestCancel = (): void => {+ // Stop clears the queue and any parked steer server-side, and has to: a+ // compliant agent answers the cancel through the same continuation that+ // dispatches them, so anything retained would fire at the agent the user+ // just stopped. Folding the words back into the composer is the rescue —+ // they survive, nothing sends. The steer leads, because that is the order+ // it was going to run in.+ const rescued = [+ ...(info.steer !== undefined ? [info.steer.content] : []),+ ...(info.queue ?? []).map((message) => message.content),+ ];+ if (rescued.length > 0) {+ const text = rescued.join('\n\n');+ setDraft((prev) => (prev.trim() === '' ? text : `${prev.replace(/\s+$/, '')}\n\n${text}`));+ }client.cancel(info.threadId);setCancelPending(true);};+ /**+ * Stop the running turn and send the draft as the next one. Always an+ * explicit click — Enter stays the queue-behind-the-turn default, because+ * interrupting a run is not something a habit keystroke should do.+ */+ const requestSteer = (): void => {+ const text = draft.trim();+ if (text === '') return;+ client.steer(info.threadId, text);+ setDraft('');+ scrollApiRef.current?.scrollToEnd();+ };+useEffect(() => {if (lastSeq !== null && initialSeqRef.current === null) initialSeqRef.current = lastSeq;}, [lastSeq]);+ // A retry that succeeded leaves the failure status behind; the button it was+ // spinning on is gone with it.+ useEffect(() => {+ if (!canRetry) setRetryPending(false);+ }, [canRetry]);+// Follow the agent's file: navigate the editor to the doc the agent is// working on, as it works. Live events only (see initialSeqRef above), and// only while a turn is streaming — an idle thread never steals navigation.@@ -433,6 +492,23 @@ export function ThreadView({ info }: { info: ThreadInfo }): ReactNode {setCommentsExpanded(false);};+ const retryThread = (): void => {+ setRetryPending(true);+ void client+ .retryThread(info.threadId)+ .catch((err: unknown) => {+ toast.error(t`Couldn't start ${info.agent.name}: ${errorText(err)}`);+ })+ .finally(() => setRetryPending(false));+ };++ // Sign-in runs on the agent's live connection — on success the server's+ // `info` frame flips the thread to ready and the notice's action row goes+ // with it, so there is nothing to navigate to here.+ const authenticateThread = async (methodId: string): Promise<void> => {+ await client.authenticateThread(info.threadId, methodId);+ };+const startFreshThread = (): void => {const prompt = failedPrompt ?? (draft.trim() === '' ? undefined : draft.trim());setResumeError(null);@@ -455,6 +531,21 @@ export function ThreadView({ info }: { info: ThreadInfo }): ReactNode {});};+ // Retry belongs to the failure the user is looking at — the LAST startup+ // failure, once. An allowlist rather than "not a prompt failure": a reason+ // added later is only retryable once someone decides it is, and a prompt+ // failure never is (that session is live, and re-sending IS the retry).+ let retryNoticeIndex = -1;+ if (canRetry && model !== null) {+ for (let index = model.items.length - 1; index >= 0; index -= 1) {+ const item = model.items[index];+ if (item?.kind === 'notice' && item.failure !== null && isRetryableFailure(item.failure)) {+ retryNoticeIndex = index;+ break;+ }+ }+ }+return (<divclassName="flex min-h-0 flex-1 flex-col text-gray-800 dark:text-gray-200"@@ -505,6 +596,7 @@ export function ThreadView({ info }: { info: ThreadInfo }): ReactNode {<ThreadItemitem={item}threadId={info.threadId}+ agent={info.agent}// Thread liveness, not turn liveness: the server keeps an// unanswered request answerable until its timeout even after// the prompt settles (and some agents ask outside a turn) —@@ -512,6 +604,13 @@ export function ThreadView({ info }: { info: ThreadInfo }): ReactNode {actionable={!archived && status !== 'exited' && status !== 'error'}terminals={model.terminals}permissionsByToolCall={model.permissionsByToolCall}+ showRetry={index === retryNoticeIndex}+ retryPending={retryPending}+ onRetry={retryThread}+ // Sign-in belongs to the same notice Retry does, and+ // only while the thread is still waiting on it.+ showAuth={index === retryNoticeIndex && status === 'auth_required'}+ onAuthenticate={authenticateThread}/></MessageScrollerItem>);@@ -549,6 +648,16 @@ export function ThreadView({ info }: { info: ThreadInfo }): ReactNode {</MessageScroller></MessageScrollerProvider>)}+ {info.steer !== undefined && !archived ? (+ <div+ className="flex items-center gap-2 border-t bg-muted/40 px-3 py-1.5 text-muted-foreground text-xs"+ data-testid="agent-thread-steer-pending"+ >+ <Loader2 className="size-3.5 shrink-0 animate-spin" aria-hidden="true" />+ <span className="shrink-0">{t`Steering — waiting for the current run to stop…`}</span>+ <span className="min-w-0 flex-1 truncate text-foreground/80">{info.steer.content}</span>+ </div>+ ) : null}{cancelStalled && turnActive ? (<divclassName="flex items-center gap-2 border-amber-500/30 border-t bg-amber-500/5 px-3 py-1.5 text-amber-700 text-xs dark:text-amber-400"@@ -601,6 +710,7 @@ export function ThreadView({ info }: { info: ThreadInfo }): ReactNode {turnActive={turnActive}cancelPending={cancelPending}onCancel={requestCancel}+ onSteer={requestSteer}status={status}archived={archived}resumePending={resumePending}@@ -644,6 +754,18 @@ function ThreadHeader({{t`Archived`}</Badge>) : null}+ {info.agent.version !== undefined && info.agent.version !== '' ? (+ // Which build answered. OK launches the registry-pinned version, which+ // is routinely not the one the user's own terminal runs — without this+ // a version-specific bug has no visible attribution.+ <span+ className="shrink-0 text-[10px] text-muted-foreground tabular-nums"+ title={t`${info.agent.name} version ${info.agent.version}`}+ data-testid="agent-thread-agent-version"+ >+ {info.agent.version}+ </span>+ ) : null}<div className="ml-auto flex shrink-0 items-center gap-1.5"><Tooltip><TooltipTrigger asChild>@@ -1142,16 +1264,30 @@ function ScrollToEndBridge({function ThreadItem({item,threadId,+ agent,actionable,terminals,permissionsByToolCall,+ showRetry,+ retryPending,+ onRetry,+ showAuth,+ onAuthenticate,}: {item: RenderedItem;threadId: string;+ agent: ThreadInfo['agent'];/** The thread can still take answers (live agent, not archived/dead). */actionable: boolean;terminals: Record<string, RenderedTerminal>;permissionsByToolCall: Record<string, RenderedPermission>;+ /** This notice is the one that offers Retry (at most one per transcript). */+ showRetry: boolean;+ retryPending: boolean;+ onRetry: () => void;+ /** …and the one that offers sign-in, while the thread still needs it. */+ showAuth: boolean;+ onAuthenticate: (methodId: string) => Promise<void>;}): ReactNode {switch (item.kind) {case 'message':@@ -1175,21 +1311,186 @@ function ThreadItem({return <RuntimeConsentPrompt item={item} threadId={threadId} />;case 'notice':return (- <div- className={cn(- 'rounded-md border px-2 py-1.5 text-xs',- item.tone === 'error'- ? 'border-red-500/30 bg-red-500/5 text-red-600 dark:text-red-400'- : 'border-amber-500/30 bg-amber-500/5 text-amber-700 dark:text-amber-400',- )}- data-testid="agent-thread-notice"- >- {item.text}- </div>+ <ThreadNotice+ item={item}+ agentName={agentDisplayName(agent.name)}+ showRetry={showRetry}+ retryPending={retryPending}+ onRetry={onRetry}+ showAuth={showAuth}+ onAuthenticate={onAuthenticate}+ />);}}+/**+ * A failure the user has to read: what broke, in OK's own words, with the+ * agent's message quoted underneath and the wire payload behind a disclosure+ * so a JSON blob never becomes the headline.+ */+function ThreadNotice({+ item,+ agentName,+ showRetry,+ retryPending,+ onRetry,+ showAuth,+ onAuthenticate,+}: {+ item: Extract<RenderedItem, { kind: 'notice' }>;+ agentName: string;+ showRetry: boolean;+ retryPending: boolean;+ onRetry: () => void;+ showAuth: boolean;+ onAuthenticate: (methodId: string) => Promise<void>;+}): ReactNode {+ const { t } = useLingui();+ const [showDetail, setShowDetail] = useState(false);+ const [authPending, setAuthPending] = useState<string | null>(null);+ const failure = item.failure;+ const authMethods =+ showAuth && failure !== null && failure.reason === 'auth-required'+ ? (failure.authMethods ?? [])+ : [];+ // `env_var` / `terminal` methods are completed in the user's own shell or+ // environment — OK can name them, but the protocol gives it no way to carry+ // out the sign-in, so they get no button. Retry below is how the user says+ // they did it. Everything else (including the default agent-driven kind) is+ // an `authenticate` call OK can make itself.+ const signInMethods = authMethods.filter((m) => m.kind !== 'terminal' && m.kind !== 'env_var');+ const manualMethods = authMethods.filter((m) => m.kind === 'terminal' || m.kind === 'env_var');+ const signIn = (methodId: string): void => {+ setAuthPending(methodId);+ void onAuthenticate(methodId)+ .catch((err: unknown) => {+ toast.error(t`Sign-in failed: ${errorText(err)}`);+ })+ .finally(() => setAuthPending(null));+ };+ // Exhaustive by construction: a new `reason` on the wire fails the build+ // here instead of silently rendering the prompt-failure copy.+ const failureHeadline = (reason: ThreadFailureDetail['reason']): string => {+ switch (reason) {+ case 'auth-required':+ return t`Sign in to ${agentName} to continue.`;+ case 'connect':+ return t`${agentName} couldn't start.`;+ case 'session-setup':+ return t`${agentName} couldn't start a conversation.`;+ case 'prompt':+ return t`Your message didn't reach ${agentName}.`;+ default: {+ const exhaustive: never = reason;+ return String(exhaustive);+ }+ }+ };+ const headline = failure === null ? null : failureHeadline(failure.reason);+ return (+ <div+ className={cn(+ 'rounded-md border px-2 py-1.5 text-xs',+ item.tone === 'error'+ ? 'border-red-500/30 bg-red-500/5 text-red-600 dark:text-red-400'+ : 'border-amber-500/30 bg-amber-500/5 text-amber-700 dark:text-amber-400',+ )}+ data-testid="agent-thread-notice"+ >+ {failure === null ? (+ item.text+ ) : (+ <>+ <p>{headline}</p>+ {failure.agentMessage !== undefined && failure.agentMessage !== '' ? (+ <p className="mt-1 opacity-80">{failure.agentMessage}</p>+ ) : null}+ {failure.machineDetail !== undefined && failure.machineDetail !== '' ? (+ <>+ <Button+ type="button"+ variant="ghost"+ size="sm"+ className="mt-1 h-auto p-0 text-[11px] underline hover:bg-transparent"+ onClick={() => setShowDetail((open) => !open)}+ aria-expanded={showDetail}+ data-testid="agent-thread-notice-details-toggle"+ >+ {showDetail ? t`Hide details` : t`Show details`}+ </Button>+ {showDetail ? (+ <pre+ className="mt-1 overflow-x-auto whitespace-pre-wrap font-mono text-[10px] opacity-70"+ data-testid="agent-thread-notice-details"+ >+ {failure.machineDetail}+ </pre>+ ) : null}+ </>+ ) : null}+ {manualMethods.length > 0 ? (+ <ul className="mt-1.5 flex flex-col gap-0.5 opacity-80">+ {manualMethods.map((method) => (+ <li key={method.id} data-testid="agent-thread-auth-manual">+ {method.description !== undefined && method.description !== ''+ ? `${method.name} — ${method.description}`+ : method.name}+ </li>+ ))}+ </ul>+ ) : null}+ {signInMethods.length > 0 ? (+ <div className="mt-1.5 flex flex-wrap items-center gap-1.5">+ {signInMethods.map((method) => (+ <Button+ key={method.id}+ type="button"+ size="sm"+ className="h-6 text-xs"+ disabled={authPending !== null}+ onClick={() => signIn(method.id)}+ data-testid="agent-thread-auth-method"+ data-auth-method-id={method.id}+ >+ {authPending === method.id ? (+ <Loader2 className="size-3 animate-spin" aria-hidden="true" />+ ) : null}+ {/* One method is the whole choice, so the button says what it+ does; several are a menu, and the names are the choice. */}+ {signInMethods.length === 1 ? t`Sign in with ${method.name}` : method.name}+ </Button>+ ))}+ </div>+ ) : null}+ {showRetry ? (+ <div className="mt-1.5">+ <Button+ type="button"+ variant="outline"+ size="sm"+ className="h-6 text-xs"+ disabled={retryPending}+ onClick={onRetry}+ data-testid="agent-thread-retry"+ >+ {retryPending ? (+ <>+ <Loader2 className="size-3 animate-spin" aria-hidden="true" />+ {t`Retrying…`}+ </>+ ) : (+ t`Retry`+ )}+ </Button>+ </div>+ ) : null}+ </>+ )}+ </div>+ );+}+function MessageBubble({ item }: { item: Extract<RenderedItem, { kind: 'message' }> }): ReactNode {if (item.role === 'thought') {// Thoughts carry markdown like any other agent output, so they parse —@@ -2118,6 +2419,7 @@ function ThreadComposer({turnActive,cancelPending,onCancel,+ onSteer,status,archived,resumePending,@@ -2141,6 +2443,8 @@ function ThreadComposer({/** Stop was pressed and the turn hasn't ended yet. */cancelPending: boolean;onCancel: () => void;+ /** Stop the running turn and send the draft as the next one. */+ onSteer: () => void;status: ThreadInfo['status'];archived: boolean;/** A resume op is in flight (archived thread, message queued on it). */@@ -2195,6 +2499,27 @@ function ThreadComposer({// the comments are the ask, so a send with nothing typed is a real send.const hasSendableContent = draft.trim() !== '' || hasQueuedComments;+ // Mid-turn the same control queues rather than sends, so it stops wearing the+ // send arrow — an aria-label the sighted user never reads was the only thing+ // distinguishing the two outcomes.+ const sendButton = (+ <Button+ type="button"+ size="icon-sm"+ className="rounded-lg"+ disabled={!(canPrompt || canQueue) || !hasSendableContent}+ onClick={onSubmit}+ aria-label={canQueue ? t`Queue message` : t`Send`}+ data-testid="agent-thread-send"+ >+ {canQueue ? (+ <ListPlus className="size-4" aria-hidden="true" />+ ) : (+ <ArrowUp className="size-4" aria-hidden="true" />+ )}+ </Button>+ );+return (<div className="p-2">{queue.length > 0 && !archived ? (@@ -2273,7 +2598,14 @@ function ThreadComposer({disabled={archived? resumePending- : status !== 'ready' && status !== 'running' && status !== 'awaiting_permission'+ : // Typable in every live state, including the ones that are only+ // waiting on something: signing in takes a detour through a+ // browser (and flips the status to `installing` while it does),+ // a failed start is a Retry away from running, and a draft+ // written across any of that must survive. Only a thread whose+ // agent is gone for good has nothing left to say. Sending is+ // still gated by canPrompt / canQueue.+ status === 'exited'}// Borderless + transparent so the wrapper alone renders the field chrome// and focus ring (no doubled border/ring). Full width — the action bar@@ -2322,18 +2654,39 @@ function ThreadComposer({already known in the draft-present state where it's hidden. */}<TooltipContent side="top">{t`Stop (Esc)`}</TooltipContent></Tooltip>+ ) : canQueue ? (+ <>+ {/* Steering sends the typed words, so it appears only when there+ are some — an attached comment batch has its own delivery+ rules (it stays queued until a turn actually runs it) and+ must not be interrupted onto a run being cancelled. */}+ {draft.trim() !== '' ? (+ <Tooltip>+ <TooltipTrigger asChild>+ <Button+ type="button"+ size="icon-sm"+ variant="outline"+ className="rounded-lg"+ onClick={onSteer}+ aria-label={t`Steer now`}+ data-testid="agent-thread-steer"+ >+ <Zap className="size-4" aria-hidden="true" />+ </Button>+ </TooltipTrigger>+ <TooltipContent side="top">{t`Stops the current run and sends this instead`}</TooltipContent>+ </Tooltip>+ ) : null}+ <Tooltip>+ <TooltipTrigger asChild>{sendButton}</TooltipTrigger>+ {/* The icon change alone says "not a plain send"; this says what+ actually happens to the message. */}+ <TooltipContent side="top">{t`Queues behind the running turn`}</TooltipContent>+ </Tooltip>+ </>) : (- <Button- type="button"- size="icon-sm"- className="rounded-lg"- disabled={!(canPrompt || canQueue) || !hasSendableContent}- onClick={onSubmit}- aria-label={canQueue ? t`Queue message` : t`Send`}- data-testid="agent-thread-send"- >- <ArrowUp className="size-4" aria-hidden="true" />- </Button>+ sendButton)}</div></div>@@ -2356,7 +2709,7 @@ function QueuedMessageList({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`}+ {t`Queued — sends when this run finishes`}</span>{queue.map((message) => (<QueuedMessageRow key={message.id} threadId={threadId} message={message} />@@ -2377,23 +2730,40 @@ function QueuedMessageRow({const [editing, setEditing] = useState(false);const [value, setValue] = useState('');+ const held = message.held === true;++ const release = (): void => client.holdQueued(threadId, message.id, false);+const startEdit = (): void => {+ // Hold before the editor opens: a turn ending mid-edit would otherwise+ // dispatch the very text being replaced, and the edit would die with the+ // row. Every exit from editing releases the hold or saves over it.+ client.holdQueued(threadId, message.id, true);setValue(message.content);setEditing(true);};+ const cancelEdit = (): void => {+ setEditing(false);+ release();+ };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);+ cancelEdit();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 (trimmed === message.content) {+ release();+ return;+ }+ // Saving is the resubmit — the server clears the hold with the content.+ void client.editQueued(threadId, message.id, trimmed).catch(() => {+ toast.error(t`That message already went out — your edit wasn't applied.`);+ });};if (editing) {@@ -2411,7 +2781,7 @@ function QueuedMessageRow({save();} else if (event.key === 'Escape') {event.preventDefault();- setEditing(false);+ cancelEdit();}}}autoFocus@@ -2426,7 +2796,7 @@ function QueuedMessageRow({size="icon-sm"variant="ghost"className="size-6"- onClick={() => setEditing(false)}+ onClick={cancelEdit}aria-label={t`Cancel editing`}data-testid="agent-thread-queued-cancel-edit">@@ -2451,12 +2821,41 @@ function QueuedMessageRow({return (<div- className="flex items-center gap-1 rounded-md border border-input/60 bg-muted/30 py-0.5 pl-2 pr-1"+ className={cn(+ 'flex items-center gap-1 rounded-md border py-0.5 pl-2 pr-1',+ held ? 'border-input/40 border-dashed bg-muted/20' : 'border-input/60 bg-muted/30',+ )}data-testid="agent-thread-queued"+ data-held={held ? 'true' : undefined}>- <span className="min-w-0 flex-1 truncate text-muted-foreground text-sm">+ <span+ className={cn(+ 'min-w-0 flex-1 truncate text-sm',+ held ? 'text-muted-foreground/60' : 'text-muted-foreground',+ )}+ >{message.content}</span>+ {held ? (+ <>+ {/* A row the drain skips has to say so, or it reads as queued and the+ user waits for a message that is never going anywhere. */}+ <span className="shrink-0 font-medium text-[10px] text-muted-foreground/70 uppercase tracking-wide">+ {t`Held`}+ </span>+ <Button+ type="button"+ size="icon-sm"+ variant="ghost"+ className="size-6 shrink-0 text-muted-foreground"+ onClick={release}+ aria-label={t`Send when the agent is free`}+ data-testid="agent-thread-queued-release"+ >+ <Check className="size-3.5" aria-hidden="true" />+ </Button>+ </>+ ) : null}<Buttontype="button"size="icon-sm"diff --git a/packages/app/src/lib/acp/catalog.ts b/packages/app/src/lib/acp/catalog.tsindex 75318b89a..c710ef5d4 100644--- a/packages/app/src/lib/acp/catalog.ts+++ b/packages/app/src/lib/acp/catalog.ts@@ -21,7 +21,7 @@ export interface CatalogAgent {supported: boolean;featured: boolean;harness?: {- cli: 'claude' | 'codex' | 'cursor' | 'opencode' | 'pi';+ cli: 'claude' | 'codex' | 'cursor' | 'gemini' | 'opencode' | 'pi';availability: 'present' | 'not-found' | 'unknown';};}diff --git a/packages/app/src/lib/acp/thread-client.test.ts b/packages/app/src/lib/acp/thread-client.test.tsindex 24a731915..4b6f8b854 100644--- a/packages/app/src/lib/acp/thread-client.test.ts+++ b/packages/app/src/lib/acp/thread-client.test.ts@@ -99,6 +99,199 @@ describe('batched event delivery', () => {});});+describe('queue edit settlement', () => {+ const info: ThreadInfo = {+ threadId: 't1',+ agent: { id: 'a', name: 'A', source: 'custom' },+ title: 'A',+ status: 'running',+ createdAt: 1,+ lastActivityAt: 1,+ lastSeq: -1,+ };++ /** Client with a stub socket, so sent frames are observable. */+ function makeWiredClient(): {+ client: AgentThreadClient;+ sent: Array<Record<string, unknown>>;+ frame: (f: ThreadServerFrame) => void;+ } {+ const client = new AgentThreadClient();+ const sent: Array<Record<string, unknown>> = [];+ const internals = client as unknown as {+ ws: unknown;+ handleFrame: (f: ThreadServerFrame) => void;+ };+ internals.ws = {+ readyState: 1,+ send: (raw: string) => sent.push(JSON.parse(raw) as Record<string, unknown>),+ };+ const frame = (f: ThreadServerFrame) => internals.handleFrame.call(client, f);+ frame({ op: 'subscribed', threadId: 't1', fromSeq: 0, info });+ return { client, sent, frame };+ }++ test('the ack carrying the reqId settles the edit as applied', async () => {+ const { client, sent, frame } = makeWiredClient();+ const pending = client.editQueued('t1', 'q1', ' sharper text ');+ const edit = sent.find((f) => f.op === 'queue_edit');+ // The reqId is what makes both the ack and a refusal answerable at all.+ expect(edit).toMatchObject({ threadId: 't1', id: 'q1', content: 'sharper text' });+ expect(typeof edit?.reqId).toBe('string');++ frame({ op: 'queue_edited', reqId: edit?.reqId as string, threadId: 't1' });+ await expect(pending).resolves.toBeUndefined();+ });++ test('a refusal rejects even when an unrelated info frame for the thread arrived first', async () => {+ const { client, sent, frame } = makeWiredClient();+ const pending = client.editQueued('t1', 'q1', 'too late');+ const reqId = sent.find((f) => f.op === 'queue_edit')?.reqId;+ expect(typeof reqId).toBe('string');++ // The regression: a batched `info` (a turn ending, a status flip) reaches+ // the client before the server's refusal. Settling on it would report the+ // edit as applied and leave the error with nowhere to go.+ frame({ op: 'info', info: { ...info, lastActivityAt: 2 } });+ frame({+ op: 'error',+ code: 'not-ready',+ message: 'queued message already dispatched',+ reqId: reqId as string,+ threadId: 't1',+ });+ await expect(pending).rejects.toThrow(/already dispatched/);+ });++ test('info frames — this thread or another — never settle the edit; the ack does', async () => {+ const { client, sent, frame } = makeWiredClient();+ let settled = false;+ const pending = client.editQueued('t1', 'q1', 'sharper text');+ void pending.then(() => {+ settled = true;+ });+ frame({ op: 'info', info: { ...info, threadId: 'other' } });+ frame({ op: 'info', info });+ // An ack for a different edit is just as inert.+ frame({ op: 'queue_edited', reqId: 'queue-edit-not-mine', threadId: 't1' });+ await Promise.resolve();+ expect(settled).toBe(false);++ frame({+ op: 'queue_edited',+ reqId: sent.find((f) => f.op === 'queue_edit')?.reqId as string,+ threadId: 't1',+ });+ await expect(pending).resolves.toBeUndefined();+ });++ test('an empty edit never reaches the wire', async () => {+ const { client, sent } = makeWiredClient();+ await expect(client.editQueued('t1', 'q1', ' ')).resolves.toBeUndefined();+ expect(sent.some((f) => f.op === 'queue_edit')).toBe(false);+ });++ test('holdQueued sends the park/release frame verbatim', () => {+ const { client, sent } = makeWiredClient();+ client.holdQueued('t1', 'q1', true);+ client.holdQueued('t1', 'q1', false);+ expect(sent.filter((f) => f.op === 'queue_hold')).toEqual([+ { op: 'queue_hold', threadId: 't1', id: 'q1', held: true },+ { op: 'queue_hold', threadId: 't1', id: 'q1', held: false },+ ]);+ });+});++describe('retry and sign-in lifecycle', () => {+ const info: ThreadInfo = {+ threadId: 't1',+ agent: { id: 'a', name: 'A', source: 'custom' },+ title: 'A',+ status: 'error',+ createdAt: 1,+ lastActivityAt: 1,+ lastSeq: -1,+ };++ /** Client with a stub socket, so sent frames are observable. */+ function makeWiredClient(): {+ client: AgentThreadClient;+ sent: Array<Record<string, unknown>>;+ frame: (f: ThreadServerFrame) => void;+ } {+ const client = new AgentThreadClient();+ const sent: Array<Record<string, unknown>> = [];+ const internals = client as unknown as {+ ws: unknown;+ handleFrame: (f: ThreadServerFrame) => void;+ };+ internals.ws = {+ readyState: 1,+ send: (raw: string) => sent.push(JSON.parse(raw) as Record<string, unknown>),+ };+ const frame = (f: ThreadServerFrame) => internals.handleFrame.call(client, f);+ frame({ op: 'subscribed', threadId: 't1', fromSeq: 0, info });+ return { client, sent, frame };+ }++ /** Both ops await `waitForOpen` before sending, so the frame lands a tick later. */+ const flush = (): Promise<void> => new Promise((resolve) => setTimeout(resolve, 0));++ test('retryThread sends the op and resolves with the retried thread info', async () => {+ const { client, sent, frame } = makeWiredClient();+ const pending = client.retryThread('t1');+ await flush();+ const retry = sent.find((f) => f.op === 'retry');+ expect(retry).toMatchObject({ op: 'retry', threadId: 't1' });+ expect(typeof retry?.reqId).toBe('string');++ const ready: ThreadInfo = { ...info, status: 'ready' };+ frame({ op: 'retried', reqId: retry?.reqId as string, info: ready });+ await expect(pending).resolves.toMatchObject({ status: 'ready' });+ });++ test('a retry the server refuses rejects with its message', async () => {+ const { client, sent, frame } = makeWiredClient();+ const pending = client.retryThread('t1');+ await flush();+ const reqId = sent.find((f) => f.op === 'retry')?.reqId as string;++ frame({+ op: 'error',+ code: 'spawn-failed',+ message: 'harness not installed',+ reqId,+ threadId: 't1',+ });+ await expect(pending).rejects.toThrow(/harness not installed/);+ });++ test('authenticateThread sends the method id and resolves with the signed-in info', async () => {+ const { client, sent, frame } = makeWiredClient();+ const pending = client.authenticateThread('t1', 'test_login');+ await flush();+ const auth = sent.find((f) => f.op === 'authenticate');+ expect(auth).toMatchObject({ op: 'authenticate', threadId: 't1', methodId: 'test_login' });+ // The prefix is what an error frame is correlated by — it must not collide+ // with another op's namespace.+ expect(String(auth?.reqId)).toMatch(/^authenticate-/);++ const ready: ThreadInfo = { ...info, status: 'ready' };+ frame({ op: 'authenticated', reqId: auth?.reqId as string, info: ready });+ await expect(pending).resolves.toMatchObject({ status: 'ready' });+ });++ test('a refused sign-in rejects with what the agent said', async () => {+ const { client, sent, frame } = makeWiredClient();+ const pending = client.authenticateThread('t1', 'test_login');+ await flush();+ const reqId = sent.find((f) => f.op === 'authenticate')?.reqId as string;++ frame({ op: 'error', code: 'not-ready', message: 'wrong account', reqId, threadId: 't1' });+ await expect(pending).rejects.toThrow(/wrong account/);+ });+});+describe('createThread channel wait', () => {test('rejects with ThreadChannelUnavailableError when no URL is ever bound', async () => {const client = new AgentThreadClient();diff --git a/packages/app/src/lib/acp/thread-client.ts b/packages/app/src/lib/acp/thread-client.tsindex 286e0912a..a3911c4cd 100644--- a/packages/app/src/lib/acp/thread-client.ts+++ b/packages/app/src/lib/acp/thread-client.ts@@ -45,12 +45,24 @@ interface PendingCreate {timer: ReturnType<typeof setTimeout>;}+interface PendingQueueEdit {+ resolve: () => void;+ reject: (err: Error) => void;+ timer: ReturnType<typeof setTimeout>;+}+const RECONNECT_MIN_MS = 500;const RECONNECT_MAX_MS = 15_000;const CREATE_TIMEOUT_MS = 30_000;/** Resume resolves only after the full agent respawn + session handshake (npx cold boots take a while). */const RESUME_TIMEOUT_MS = 90_000;+/** Retry re-runs the same launch, plus a fresh login-shell PATH probe. */+const RETRY_TIMEOUT_MS = 90_000;+/** Sign-in can park on a browser round trip before the session re-opens. */+const AUTHENTICATE_TIMEOUT_MS = 180_000;const CHANNEL_WAIT_MS = 8_000;+/** How long a queue edit waits for a refusal before it counts as applied. */+const QUEUE_EDIT_TIMEOUT_MS = 10_000;/** A `resume` op the server rejected; `code` distinguishes "this agent can't* resume old sessions" (offer a fresh thread) from transient failures. */@@ -84,6 +96,9 @@ export class AgentThreadClient {private listeners = new Set<() => void>();private pendingCreates = new Map<string, PendingCreate>();private pendingResumes = new Map<string, PendingCreate>();+ private pendingRetries = new Map<string, PendingCreate>();+ private pendingAuths = new Map<string, PendingCreate>();+ private pendingQueueEdits = new Map<string, PendingQueueEdit>();/** Archived threads the user explicitly opened as tabs this session. */private openedArchived = new Set<string>();private reqCounter = 0;@@ -227,13 +242,48 @@ 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 {+ /**+ * Stop the running turn and send `content` as the next one. Fire-and-forget+ * like `prompt`: the refreshed `info` (carrying the parked `steer`) is the+ * confirmation, and a refusal comes back as an `error` frame on the reqId.+ */+ steer(threadId: string, content: string): void {const trimmed = content.trim();if (trimmed === '') return;- this.send({ op: 'queue_edit', threadId, id, content: trimmed });+ this.reqCounter += 1;+ this.send({ op: 'steer', threadId, reqId: `steer-${this.reqCounter}`, content: trimmed });+ }++ /**+ * Edit a message waiting in the thread's queue (`ThreadInfo.queue`) in+ * place, releasing any hold on it — saving is the resubmit. Resolves on the+ * server's `queue_edited` ack; REJECTS on the refusal carrying this reqId,+ * so the caller can tell the user the edit never landed instead of letting+ * it vanish.+ */+ editQueued(threadId: string, id: string, content: string): Promise<void> {+ const trimmed = content.trim();+ if (trimmed === '') return Promise.resolve();+ this.reqCounter += 1;+ const reqId = `queue-edit-${this.reqCounter}`;+ const promise = new Promise<void>((resolve, reject) => {+ // Backstop for a server too old to ack (or a frame lost with the+ // socket): silence for this long is read as applied, which is what the+ // pre-ack protocol assumed anyway.+ const timer = setTimeout(() => {+ this.pendingQueueEdits.delete(reqId);+ resolve();+ }, QUEUE_EDIT_TIMEOUT_MS);+ this.pendingQueueEdits.set(reqId, { resolve, reject, timer });+ });+ this.send({ op: 'queue_edit', threadId, id, content: trimmed, reqId });+ return promise;+ }++ /** Park a queued message so the drain skips it (an open edit holds its+ * row), or release it back into line. */+ holdQueued(threadId: string, id: string, held: boolean): void {+ this.send({ op: 'queue_hold', threadId, id, held });}/** Remove a message from the thread's queue before it dispatches. */@@ -341,6 +391,51 @@ export class AgentThreadClient {return promise;}+ /**+ * Retry a thread whose startup failed — same thread, same transcript, a+ * fresh launch (the server re-probes the environment first, so a binary+ * installed since the failure is picked up). Resolves once the agent is+ * ready; rejects with the failure the retry landed on.+ */+ async retryThread(threadId: string): Promise<ThreadInfo> {+ this.connectNow();+ await this.waitForOpen(CHANNEL_WAIT_MS);+ this.reqCounter += 1;+ const reqId = `retry-${this.reqCounter}`;+ const promise = new Promise<ThreadInfo>((resolve, reject) => {+ const timer = setTimeout(() => {+ this.pendingRetries.delete(reqId);+ reject(new Error('retry timed out'));+ }, RETRY_TIMEOUT_MS);+ this.pendingRetries.set(reqId, { resolve, reject, timer });+ });+ this.send({ op: 'retry', threadId, reqId });+ return promise;+ }++ /**+ * Complete an advertised sign-in on a thread parked in `auth_required`. The+ * server authenticates on the agent's live connection and re-opens the+ * session there, so nothing respawns and the transcript is untouched.+ * Resolves once the thread is ready; rejects with what the sign-in failed+ * on (the caller surfaces it — the thread stays on its notice).+ */+ async authenticateThread(threadId: string, methodId: string): Promise<ThreadInfo> {+ this.connectNow();+ await this.waitForOpen(CHANNEL_WAIT_MS);+ this.reqCounter += 1;+ const reqId = `authenticate-${this.reqCounter}`;+ const promise = new Promise<ThreadInfo>((resolve, reject) => {+ const timer = setTimeout(() => {+ this.pendingAuths.delete(reqId);+ reject(new Error('sign-in timed out'));+ }, AUTHENTICATE_TIMEOUT_MS);+ this.pendingAuths.set(reqId, { resolve, reject, timer });+ });+ this.send({ op: 'authenticate', threadId, reqId, methodId });+ return promise;+ }+// ── internals ─────────────────────────────────────────────────────────/**@@ -441,6 +536,24 @@ export class AgentThreadClient {pending.reject(new ThreadChannelUnavailableError());}this.pendingResumes.clear();+ for (const pending of this.pendingRetries.values()) {+ clearTimeout(pending.timer);+ pending.reject(new ThreadChannelUnavailableError());+ }+ this.pendingRetries.clear();+ for (const pending of this.pendingAuths.values()) {+ clearTimeout(pending.timer);+ pending.reject(new ThreadChannelUnavailableError());+ }+ this.pendingAuths.clear();+ // A dropped socket says nothing about whether the edit applied — settling+ // these as refusals would tell the user their words were lost on no+ // evidence at all.+ for (const pending of this.pendingQueueEdits.values()) {+ clearTimeout(pending.timer);+ pending.resolve();+ }+ this.pendingQueueEdits.clear();const ws = this.ws;this.ws = null;if (ws !== null) {@@ -521,10 +634,39 @@ export class AgentThreadClient {this.upsertInfo(frame.info);return;}+ case 'retried': {+ const pending = this.pendingRetries.get(frame.reqId);+ if (pending !== undefined) {+ this.pendingRetries.delete(frame.reqId);+ clearTimeout(pending.timer);+ pending.resolve(frame.info);+ }+ this.upsertInfo(frame.info);+ return;+ }+ case 'authenticated': {+ const pending = this.pendingAuths.get(frame.reqId);+ if (pending !== undefined) {+ this.pendingAuths.delete(frame.reqId);+ clearTimeout(pending.timer);+ pending.resolve(frame.info);+ }+ this.upsertInfo(frame.info);+ return;+ }case 'subscribed': {this.upsertInfo(frame.info);return;}+ case 'queue_edited': {+ const pending = this.pendingQueueEdits.get(frame.reqId);+ if (pending !== undefined) {+ this.pendingQueueEdits.delete(frame.reqId);+ clearTimeout(pending.timer);+ pending.resolve();+ }+ return;+ }case 'info': {this.upsertInfo(frame.info);return;@@ -553,10 +695,31 @@ export class AgentThreadClient {pendingResume.reject(new ThreadResumeError(frame.code, frame.message));return;}- if (frame.reqId.startsWith('prompt-')) {- // 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.+ const pendingRetry = this.pendingRetries.get(frame.reqId);+ if (pendingRetry !== undefined) {+ this.pendingRetries.delete(frame.reqId);+ clearTimeout(pendingRetry.timer);+ pendingRetry.reject(new Error(frame.message));+ return;+ }+ const pendingAuth = this.pendingAuths.get(frame.reqId);+ if (pendingAuth !== undefined) {+ this.pendingAuths.delete(frame.reqId);+ clearTimeout(pendingAuth.timer);+ pendingAuth.reject(new Error(frame.message));+ return;+ }+ const pendingQueueEdit = this.pendingQueueEdits.get(frame.reqId);+ if (pendingQueueEdit !== undefined) {+ this.pendingQueueEdits.delete(frame.reqId);+ clearTimeout(pendingQueueEdit.timer);+ pendingQueueEdit.reject(new Error(frame.message));+ return;+ }+ if (frame.reqId.startsWith('prompt-') || frame.reqId.startsWith('steer-')) {+ // A rejected prompt or steer (thread archived/not ready, or the+ // queue is full) never reaches the transcript — the composer+ // already cleared, so without feedback the message just vanishes.toast.error(t`Message not sent: ${frame.message}`);return;}diff --git a/packages/app/src/lib/acp/thread-event-model.test.ts b/packages/app/src/lib/acp/thread-event-model.test.tsindex 5026a8da6..20ccc0e69 100644--- a/packages/app/src/lib/acp/thread-event-model.test.ts+++ b/packages/app/src/lib/acp/thread-event-model.test.ts@@ -221,12 +221,46 @@ describe('buildThreadRenderModel', () => {];const model = buildThreadRenderModel(events);const notices = model.items.filter((i) => i.kind === 'notice');+ // A transcript recorded before the server classified failures carries only+ // the headline string — it still renders, with nothing structured to show.expect(notices).toEqual([- { kind: 'notice', text: 'boom', tone: 'error' },- { kind: 'notice', text: 'sign in', tone: 'info' },+ { kind: 'notice', text: 'boom', tone: 'error', failure: null },+ { kind: 'notice', text: 'sign in', tone: 'info', failure: null },]);});+ test('carries a structured failure onto the notice it produces', () => {+ const failure = {+ reason: 'auth-required' as const,+ agentMessage: 'Authentication required',+ machineDetail: '{"detail":"x"}',+ authMethods: [{ id: 'test_login', name: 'Test Login', description: 'Sign in via test' }],+ };+ const model = buildThreadRenderModel([+ ev({ kind: 'status', status: 'auth_required', detail: 'sign in required', failure, ts: 1 }),+ ]);+ const notice = model.items.find((i) => i.kind === 'notice');+ if (notice?.kind !== 'notice') throw new Error('unreachable');+ expect(notice.tone).toBe('info');+ expect(notice.failure).toEqual(failure);+ });++ test('a failure with no detail string still produces a notice', () => {+ const model = buildThreadRenderModel([+ ev({+ kind: 'status',+ status: 'error',+ failure: { reason: 'session-setup', agentMessage: 'no session for you' },+ ts: 1,+ }),+ ]);+ const notice = model.items.find((i) => i.kind === 'notice');+ if (notice?.kind !== 'notice') throw new Error('unreachable');+ expect(notice.text).toBe('');+ expect(notice.tone).toBe('error');+ expect(notice.failure).toMatchObject({ reason: 'session-setup' });+ });+test('a terminal exit ends a dangling turn (crash-mid-stream transcript)', () => {// The agent process exited after the turn opened but before the prompt// settled, so the persisted log has `turn_started` and no `turn_ended`.diff --git a/packages/app/src/lib/acp/thread-event-model.ts b/packages/app/src/lib/acp/thread-event-model.tsindex 943e65320..b9aa333df 100644--- a/packages/app/src/lib/acp/thread-event-model.ts+++ b/packages/app/src/lib/acp/thread-event-model.ts@@ -20,6 +20,7 @@ import type {PermissionOption,SessionUpdate,ThreadEvent,+ ThreadFailureDetail,} from '@inkeep/open-knowledge-core/acp/thread-protocol';interface RenderedMessage {@@ -67,8 +68,15 @@ export interface RenderedPermission {interface RenderedNotice {kind: 'notice';+ /** The server's legacy headline string — empty for structured failures. */text: string;tone: 'info' | 'error';+ /**+ * Structured failure the view renders as translated copy plus a disclosure.+ * Null for notices that carry only a server-composed string (older+ * transcripts, and any failure site that hasn't been classified yet).+ */+ failure: ThreadFailureDetail | null;}/**@@ -266,10 +274,17 @@ export class ThreadRenderModelBuilder {}}}- if (event.status === 'error' && event.detail) {- this.items.push({ kind: 'notice', text: event.detail, tone: 'error' });- } else if (event.status === 'auth_required' && event.detail) {- this.items.push({ kind: 'notice', text: event.detail, tone: 'info' });+ if (event.status === 'error' || event.status === 'auth_required') {+ // A structured failure alone is enough: the view composes its own+ // copy from `reason`, so the server no longer has to ship a string.+ if (event.failure !== undefined || (event.detail ?? '') !== '') {+ this.items.push({+ kind: 'notice',+ text: event.detail ?? '',+ tone: event.status === 'error' ? 'error' : 'info',+ failure: event.failure ?? null,+ });+ }}break;case 'permission_request': {diff --git a/packages/app/src/locales/en/messages.json b/packages/app/src/locales/en/messages.jsonindex 98f207c1a..3a8b51748 100644--- a/packages/app/src/locales/en/messages.json+++ b/packages/app/src/locales/en/messages.json@@ -347,6 +347,7 @@"5GBQ-F": ["Select this text in the property"],"5GKMSz": ["Indent or outdent the current list item."],"5GRxoA": ["Search files, folders, and commands for the current workspace."],+ "5HJpFY": ["Queues behind the running turn"],"5LXwX8": ["This permanently removes ",["path"],@@ -515,6 +516,7 @@"7jIIFX": ["You're all set up!"],"7kb4LU": ["Approved"],"7l15X4": ["failed"],+ "7lFX_h": ["Steer now"],"7m3Ade": ["installs:"],"7qRHf0": ["Install for Claude Chat & Cowork"],"7uBlRT": ["Copy the focused file-tree item so Paste can duplicate it."],@@ -586,7 +588,6 @@],"8vCZcs": ["Failed to open file."],"8vETh9": ["Show"],- "8wu9lr": ["Queued"],"92rbk2": ["Mirror loading <0>", ["mirrorRef"], "</0>"],"93LBnX": ["Hide Agents"],"96G6Re": ["New folder"],@@ -763,6 +764,7 @@],"BlLxpG": ["Search skills"],"Bn9-El": ["default"],+ "BowKyI": ["Show details"],"Bv5a9_": ["Selection statistics"],"Bx4EXG": ["Actions for ", ["label"]],"By-7Pn": ["Toggle a bullet list."],@@ -905,6 +907,7 @@"EDl9kS": ["Subscribe"],"EDm3wJ": ["Loading diff renderer"],"EEYbdt": ["Publish"],+ "EFfGAv": ["That message already went out — your edit wasn't applied."],"EHu0x2": ["Syncing"],"EJuO7B": ["Connect a GitHub account to browse and sync your repositories."],"EKwNEe": [@@ -1068,6 +1071,7 @@"GK-IRZ": ["Undo buttons are disabled — per-session state has been garbage-collected."],"GLxIKR": ["How to push manually"],"GN6L5F": ["Filename"],+ "GNkUvW": ["Queued — sends when this run finishes"],"GQDSBN": ["Layout options"],"GSYWCm": ["Hide document panel"],"GUYwCr": ["Dismiss notice"],@@ -1409,6 +1413,7 @@"MJqRO6": ["Your report is being sent."],"MJuO1q": ["Context window:"],"MKEPCY": ["Follow"],+ "MLVPcm": [["0"], " version ", ["1"]],"MQ5LOx": ["Turn ",["display"],@@ -1602,6 +1607,7 @@"PRnH8G": ["of ", ["0"]],"PTUuoc": ["Couldn't unmark that comment — it's still waiting to send."],"PTb1Nx": ["Sync is paused. Turn it back on to resume."],+ "PVSwOe": ["Steering — waiting for the current run to stop…"],"PVUn_c": ["Open folder"],"PVggyD": ["Frontmatter schemas"],"PYmp-0": ["Import as template"],@@ -1858,9 +1864,11 @@["boldLevel"]," level."],+ "UJEFJY": ["Couldn't start ", ["0"], ": ", ["1"]],"UL8A9w": ["Tag"],"UNwKSz": ["Auto-update on for \"", ["name"], "\""],"UPWItY": ["A folder containing SKILL.md."],+ "UPi_yZ": ["Held"],"UPjaXD": ["Couldn't duplicate \"", ["0"], "\": ", ["1"]],"UQAp48": ["Search templates"],"URN-cv": ["Cancelled moving ", ["0"], "."],@@ -1944,6 +1952,7 @@"VIwCaD": ["Entry"],"VJaBca": ["Choose a skill folder"],"VM7H66": ["This file is binary and can't be shown as text."],+ "VMlRqi": ["Hide details"],"VNNRfN": ["make source"],"VNgKZz": ["Advanced settings"],"VTulZj": ["Open in worktree"],@@ -2471,6 +2480,7 @@"dOHMA0": ["Failed to move"],"dOxPd4": ["Footnote"],"dQHSCs": ["Convert (delete original)"],+ "dSORvE": ["Stops the current run and sends this instead"],"dTaauv": ["Reason: ", ["reason"]],"dUQ7_J": ["Add meaning-based ranking to search so conceptually-related pages surface even when they share no keywords. This setting applies only to this computer."@@ -2541,6 +2551,7 @@"eUFXS1": ["Sort skills"],"eVPynQ": ["Open <0><1>", ["verificationUri"], "</1><2/></0> and enter this code:"],"eXPP7Z": ["Contemplating…"],+ "e_ToF5": ["Sign in with ", ["0"]],"eaHUxx": ["Files toolbar"],"eazHgv": ["Git can't track this folder — it's empty or contains only ignored files. The link won't work until you add a tracked document."@@ -2569,6 +2580,7 @@"f9lQNJ": ["Adds a managed block to"],"fBHvBn": ["There's no project folder for this window, so a terminal can't start here."],"fBoO7w": ["This is a preview of ", ["boldName"], ". Install it into your agents."],+ "fCSBwN": [["agentName"], " couldn't start."],"fDjZxw": ["Copies the skill to ", ["0"]],"fG0X0e": ["Install ", ["brand"], " →"],"fGqEFq": ["Install ", ["0"]],@@ -2917,6 +2929,7 @@" will appear once the branch syncs."],"kMKqP_": ["Hide these comments"],+ "kNGLX6": ["Retrying…"],"kNqMMd": ["Folder"],"kRTXGw": ["Point semantic search at any OpenAI-compatible embeddings endpoint — a self-hosted server or another provider. The API key above is for whichever endpoint you set here."@@ -2992,6 +3005,7 @@") that won't touch the rest of your system."],"l7X_SM": ["Send to AI"],+ "l9s3IX": [["agentName"], " couldn't start a conversation."],"lAiyU_": ["Only the current document uses <0>#", ["tag"], "</0>."],"lCC_D5": ["Subscribing..."],"lGs_bQ": ["Page <0>*</0>"],@@ -3177,6 +3191,7 @@["errorDetail"],". Try <0>ok status</0> or check <1>.ok/local/last-spawn-error.log</1>."],+ "np2zZM": ["Sign in to ", ["agentName"], " to continue."],"np9pbC": ["Show ", ["inAppHiddenCount"], " more"],"npcziF": ["Install on"],"nqV0Kk": ["This folder hasn't synced to GitHub yet. The link will work after the next sync."],@@ -3213,6 +3228,7 @@"oCZkaG": ["Copy path"],"oJl7eO": ["Unknown component: ", ["componentName"], " — source editable below"],"oKBnk5": ["More requests were blocked."],+ "oPU_4D": ["Send when the agent is free"],"oQA-cA": ["Full path"],"oS1YpJ": ["Open the Project Navigator."],"oWsZk8": ["Create missing page ", ["target"]],@@ -3422,6 +3438,7 @@"s0IDhW": ["This file could not be found."],"s0Iold": ["Edited locally since it was installed"],"s0J_k9": [["0", "plural", { "one": ["#", " key"], "other": ["#", " keys"] }]],+ "s0QzlI": ["Sign-in failed: ", ["0"]],"s0_GnA": ["Opening ", ["openingLabel"], "…"],"s1c0ja": ["Bullet List"],"s3caR3": ["Deleting"],@@ -3482,6 +3499,7 @@"stlgky": ["On — your search queries and the text of matching pages are sent to your embeddings provider (OpenAI by default) to compute embeddings."],+ "str6n9": ["Your message didn't reach ", ["agentName"], "."],"sweBEk": ["Model: <0>", ["0"], "</0>"],"sxTdZI": ["Loading paths…"],"sxjyRq": ["Worktrees"],diff --git a/packages/app/src/locales/en/messages.po b/packages/app/src/locales/en/messages.poindex 65902ca59..420f9b0cf 100644--- a/packages/app/src/locales/en/messages.po+++ b/packages/app/src/locales/en/messages.po@@ -318,6 +318,12 @@ msgstr "{0} templates available"msgid "{0} total"msgstr "{0} total"+#. placeholder {0}: info.agent.name+#. placeholder {1}: info.agent.version+#: src/components/acp/ThreadView.tsx+msgid "{0} version {1}"+msgstr "{0} version {1}"+#. placeholder {0}: activeData.label#: src/components/EditorWorkspace.tsxmsgid "{0} was not moved."@@ -377,6 +383,14 @@ msgstr "{0}y ago"msgid "{accessibleLabel} (conflict)"msgstr "{accessibleLabel} (conflict)"+#: src/components/acp/ThreadView.tsx+msgid "{agentName} couldn't start a conversation."+msgstr "{agentName} couldn't start a conversation."++#: src/components/acp/ThreadView.tsx+msgid "{agentName} couldn't start."+msgstr "{agentName} couldn't start."+#: src/components/SyncStatusBadge.tsxmsgid "{ahead} ahead"msgstr "{ahead} ahead"@@ -3297,6 +3311,12 @@ msgstr "Couldn't share skills — {detail}."msgid "Couldn't share skills: internal error. Please restart the app."msgstr "Couldn't share skills: internal error. Please restart the app."+#. placeholder {0}: info.agent.name+#. placeholder {1}: errorText(err)+#: src/components/acp/ThreadView.tsx+msgid "Couldn't start {0}: {1}"+msgstr "Couldn't start {0}: {1}"+#: src/lib/acp/launch-agent-thread.tsmsgid "Couldn't start the agent thread — please try again."msgstr "Couldn't start the agent thread — please try again."@@ -5373,6 +5393,10 @@ msgstr "Heads up"msgid "Heads up: editing any rule or option here creates a <0>.markdownlint.json</0> file in your project to save your changes."msgstr "Heads up: editing any rule or option here creates a <0>.markdownlint.json</0> file in your project to save your changes."+#: src/components/acp/ThreadView.tsx+msgid "Held"+msgstr "Held"+#: src/editor/slash-command/embed-starter-items.tsxmsgid "Hello, world!"msgstr "Hello, world!"@@ -5419,6 +5443,10 @@ msgstr "Hide Agents"msgid "Hide Bottom Dock"msgstr "Hide Bottom Dock"+#: src/components/acp/ThreadView.tsx+msgid "Hide details"+msgstr "Hide details"+#: src/components/AppMenubar.tsx#: src/components/command-palette-commands.tsmsgid "Hide document panel"@@ -8436,8 +8464,12 @@ msgid "Queue message"msgstr "Queue message"#: src/components/acp/ThreadView.tsx-msgid "Queued"-msgstr "Queued"+msgid "Queued — sends when this run finishes"+msgstr "Queued — sends when this run finishes"++#: src/components/acp/ThreadView.tsx+msgid "Queues behind the running turn"+msgstr "Queues behind the running turn"#: src/editor/slash-command/items.tsxmsgid "Quote"@@ -9093,6 +9125,7 @@ msgstr "Resuming the conversation"msgid "Retrieving…"msgstr "Retrieving…"+#: src/components/acp/ThreadView.tsx#: src/components/ActivityModeContent.tsx#: src/components/BugReportHistory.tsx#: src/components/ConnectingBanner.tsx@@ -9110,6 +9143,10 @@ msgstr "Retry push"msgid "Retrying"msgstr "Retrying"+#: src/components/acp/ThreadView.tsx+msgid "Retrying…"+msgstr "Retrying…"+#: src/components/settings/settings-fields.tsmsgid "Reuse one tab when clicking through the sidebars. Off opens every click in its own tab."msgstr "Reuse one tab when clicking through the sidebars. Off opens every click in its own tab."@@ -9579,6 +9616,10 @@ msgstr "Send to AI"msgid "Send to chat"msgstr "Send to chat"+#: src/components/acp/ThreadView.tsx+msgid "Send when the agent is free"+msgstr "Send when the agent is free"+#: src/components/ReportBugDialogBody.tsxmsgid "Send your report by email"msgstr "Send your report by email"@@ -9814,6 +9855,10 @@ msgstr "Show Agents"msgid "Show Bottom Dock"msgstr "Show Bottom Dock"+#: src/components/acp/ThreadView.tsx+msgid "Show details"+msgstr "Show details"+#: src/components/MermaidFileViewer.tsxmsgid "Show diagram"msgstr "Show diagram"@@ -9969,6 +10014,20 @@ msgstr "Sign in"msgid "Sign in to {agentName} first"msgstr "Sign in to {agentName} first"+#: src/components/acp/ThreadView.tsx+msgid "Sign in to {agentName} to continue."+msgstr "Sign in to {agentName} to continue."++#. placeholder {0}: method.name+#: src/components/acp/ThreadView.tsx+msgid "Sign in with {0}"+msgstr "Sign in with {0}"++#. placeholder {0}: errorText(err)+#: src/components/acp/ThreadView.tsx+msgid "Sign-in failed: {0}"+msgstr "Sign-in failed: {0}"+#: src/components/AuthModal.tsx#: src/lib/transports/auth-transport.tsmsgid "Sign-in stream ended without confirmation — please try again"@@ -10256,6 +10315,14 @@ msgstr "Stay in the loop"msgid "Stays on this computer. Not committed to git."msgstr "Stays on this computer. Not committed to git."+#: src/components/acp/ThreadView.tsx+msgid "Steer now"+msgstr "Steer now"++#: src/components/acp/ThreadView.tsx+msgid "Steering — waiting for the current run to stop…"+msgstr "Steering — waiting for the current run to stop…"+#: src/components/MountStalledAffordance.tsxmsgid "Still loading"msgstr "Still loading"@@ -10297,6 +10364,10 @@ msgstr "Stopped fixing. Files already fixed stay fixed."msgid "Stopping"msgstr "Stopping"+#: src/components/acp/ThreadView.tsx+msgid "Stops the current run and sends this instead"+msgstr "Stops the current run and sends this instead"+#: src/components/settings/ProjectTemplatesSection.tsxmsgid "Stored at <0>.ok/templates/</0> in this project. Available in every folder (folder-scoped templates can override by filename)."msgstr "Stored at <0>.ok/templates/</0> in this project. Available in every folder (folder-scoped templates can override by filename)."@@ -10735,6 +10806,10 @@ msgstr "That endpoint can't be used. Enter an https:// URL — http:// is only amsgid "That folder isn't an OpenKnowledge project yet. Initialize it and open?"msgstr "That folder isn't an OpenKnowledge project yet. Initialize it and open?"+#: src/components/acp/ThreadView.tsx+msgid "That message already went out — your edit wasn't applied."+msgstr "That message already went out — your edit wasn't applied."+#. placeholder {0}: item.displayName#: src/components/acp/ThreadView.tsxmsgid "The {0} download request timed out."@@ -12303,6 +12378,10 @@ msgstr "Your local copy of branch <0>{branch}</0> is behind."msgid "Your local copy of branch <0>{branch}</0> is behind. Pull the latest changes, then open the link again."msgstr "Your local copy of branch <0>{branch}</0> is behind. Pull the latest changes, then open the link again."+#: src/components/acp/ThreadView.tsx+msgid "Your message didn't reach {agentName}."+msgstr "Your message didn't reach {agentName}."+#: src/components/ReportBugDialogBody.tsxmsgid "Your report couldn't be sent. Try again or email it instead."msgstr "Your report couldn't be sent. Try again or email it instead."diff --git a/packages/app/src/locales/pseudo/messages.json b/packages/app/src/locales/pseudo/messages.jsonindex ad61de440..cc1fb7e74 100644--- a/packages/app/src/locales/pseudo/messages.json+++ b/packages/app/src/locales/pseudo/messages.json@@ -347,6 +347,7 @@"5GBQ-F": ["Śēĺēćţ ţĥĩś ţēxţ ĩń ţĥē ƥŕōƥēŕţŷ"],"5GKMSz": ["Ĩńďēńţ ōŕ ōũţďēńţ ţĥē ćũŕŕēńţ ĺĩśţ ĩţēḿ."],"5GRxoA": ["Śēàŕćĥ ƒĩĺēś, ƒōĺďēŕś, àńď ćōḿḿàńďś ƒōŕ ţĥē ćũŕŕēńţ ŵōŕķśƥàćē."],+ "5HJpFY": ["Ǫũēũēś ƀēĥĩńď ţĥē ŕũńńĩńĝ ţũŕń"],"5LXwX8": ["Ţĥĩś ƥēŕḿàńēńţĺŷ ŕēḿōvēś ",["path"],@@ -515,6 +516,7 @@"7jIIFX": ["Ŷōũ'ŕē àĺĺ śēţ ũƥ!"],"7kb4LU": ["Àƥƥŕōvēď"],"7l15X4": ["ƒàĩĺēď"],+ "7lFX_h": ["Śţēēŕ ńōŵ"],"7m3Ade": ["ĩńśţàĺĺś:"],"7qRHf0": ["Ĩńśţàĺĺ ƒōŕ Ćĺàũďē Ćĥàţ & Ćōŵōŕķ"],"7uBlRT": ["Ćōƥŷ ţĥē ƒōćũśēď ƒĩĺē-ţŕēē ĩţēḿ śō Ƥàśţē ćàń ďũƥĺĩćàţē ĩţ."],@@ -586,7 +588,6 @@],"8vCZcs": ["Ƒàĩĺēď ţō ōƥēń ƒĩĺē."],"8vETh9": ["Śĥōŵ"],- "8wu9lr": ["Ǫũēũēď"],"92rbk2": ["Ḿĩŕŕōŕ ĺōàďĩńĝ <0>", ["mirrorRef"], "</0>"],"93LBnX": ["Ĥĩďē Àĝēńţś"],"96G6Re": ["Ńēŵ ƒōĺďēŕ"],@@ -763,6 +764,7 @@],"BlLxpG": ["Śēàŕćĥ śķĩĺĺś"],"Bn9-El": ["ďēƒàũĺţ"],+ "BowKyI": ["Śĥōŵ ďēţàĩĺś"],"Bv5a9_": ["Śēĺēćţĩōń śţàţĩśţĩćś"],"Bx4EXG": ["Àćţĩōńś ƒōŕ ", ["label"]],"By-7Pn": ["Ţōĝĝĺē à ƀũĺĺēţ ĺĩśţ."],@@ -905,6 +907,7 @@"EDl9kS": ["Śũƀśćŕĩƀē"],"EDm3wJ": ["Ĺōàďĩńĝ ďĩƒƒ ŕēńďēŕēŕ"],"EEYbdt": ["Ƥũƀĺĩśĥ"],+ "EFfGAv": ["Ţĥàţ ḿēśśàĝē àĺŕēàďŷ ŵēńţ ōũţ — ŷōũŕ ēďĩţ ŵàśń'ţ àƥƥĺĩēď."],"EHu0x2": ["Śŷńćĩńĝ"],"EJuO7B": ["Ćōńńēćţ à ĜĩţĤũƀ àććōũńţ ţō ƀŕōŵśē àńď śŷńć ŷōũŕ ŕēƥōśĩţōŕĩēś."],"EKwNEe": [@@ -1068,6 +1071,7 @@"GK-IRZ": ["Ũńďō ƀũţţōńś àŕē ďĩśàƀĺēď — ƥēŕ-śēśśĩōń śţàţē ĥàś ƀēēń ĝàŕƀàĝē-ćōĺĺēćţēď."],"GLxIKR": ["Ĥōŵ ţō ƥũśĥ ḿàńũàĺĺŷ"],"GN6L5F": ["Ƒĩĺēńàḿē"],+ "GNkUvW": ["Ǫũēũēď — śēńďś ŵĥēń ţĥĩś ŕũń ƒĩńĩśĥēś"],"GQDSBN": ["Ĺàŷōũţ ōƥţĩōńś"],"GSYWCm": ["Ĥĩďē ďōćũḿēńţ ƥàńēĺ"],"GUYwCr": ["Ďĩśḿĩśś ńōţĩćē"],@@ -1409,6 +1413,7 @@"MJqRO6": ["Ŷōũŕ ŕēƥōŕţ ĩś ƀēĩńĝ śēńţ."],"MJuO1q": ["Ćōńţēxţ ŵĩńďōŵ:"],"MKEPCY": ["Ƒōĺĺōŵ"],+ "MLVPcm": [["0"], " vēŕśĩōń ", ["1"]],"MQ5LOx": ["Ţũŕń ",["display"],@@ -1602,6 +1607,7 @@"PRnH8G": ["ōƒ ", ["0"]],"PTUuoc": ["Ćōũĺďń'ţ ũńḿàŕķ ţĥàţ ćōḿḿēńţ — ĩţ'ś śţĩĺĺ ŵàĩţĩńĝ ţō śēńď."],"PTb1Nx": ["Śŷńć ĩś ƥàũśēď. Ţũŕń ĩţ ƀàćķ ōń ţō ŕēśũḿē."],+ "PVSwOe": ["Śţēēŕĩńĝ — ŵàĩţĩńĝ ƒōŕ ţĥē ćũŕŕēńţ ŕũń ţō śţōƥ…"],"PVUn_c": ["Ōƥēń ƒōĺďēŕ"],"PVggyD": ["Ƒŕōńţḿàţţēŕ śćĥēḿàś"],"PYmp-0": ["Ĩḿƥōŕţ àś ţēḿƥĺàţē"],@@ -1858,9 +1864,11 @@["boldLevel"]," ĺēvēĺ."],+ "UJEFJY": ["Ćōũĺďń'ţ śţàŕţ ", ["0"], ": ", ["1"]],"UL8A9w": ["Ţàĝ"],"UNwKSz": ["Àũţō-ũƥďàţē ōń ƒōŕ \"", ["name"], "\""],"UPWItY": ["À ƒōĺďēŕ ćōńţàĩńĩńĝ ŚĶĨĹĹ.ḿď."],+ "UPi_yZ": ["Ĥēĺď"],"UPjaXD": ["Ćōũĺďń'ţ ďũƥĺĩćàţē \"", ["0"], "\": ", ["1"]],"UQAp48": ["Śēàŕćĥ ţēḿƥĺàţēś"],"URN-cv": ["Ćàńćēĺĺēď ḿōvĩńĝ ", ["0"], "."],@@ -1944,6 +1952,7 @@"VIwCaD": ["Ēńţŕŷ"],"VJaBca": ["Ćĥōōśē à śķĩĺĺ ƒōĺďēŕ"],"VM7H66": ["Ţĥĩś ƒĩĺē ĩś ƀĩńàŕŷ àńď ćàń'ţ ƀē śĥōŵń àś ţēxţ."],+ "VMlRqi": ["Ĥĩďē ďēţàĩĺś"],"VNNRfN": ["ḿàķē śōũŕćē"],"VNgKZz": ["Àďvàńćēď śēţţĩńĝś"],"VTulZj": ["Ōƥēń ĩń ŵōŕķţŕēē"],@@ -2471,6 +2480,7 @@"dOHMA0": ["Ƒàĩĺēď ţō ḿōvē"],"dOxPd4": ["Ƒōōţńōţē"],"dQHSCs": ["Ćōńvēŕţ (ďēĺēţē ōŕĩĝĩńàĺ)"],+ "dSORvE": ["Śţōƥś ţĥē ćũŕŕēńţ ŕũń àńď śēńďś ţĥĩś ĩńśţēàď"],"dTaauv": ["Ŕēàśōń: ", ["reason"]],"dUQ7_J": ["Àďď ḿēàńĩńĝ-ƀàśēď ŕàńķĩńĝ ţō śēàŕćĥ śō ćōńćēƥţũàĺĺŷ-ŕēĺàţēď ƥàĝēś śũŕƒàćē ēvēń ŵĥēń ţĥēŷ śĥàŕē ńō ķēŷŵōŕďś. Ţĥĩś śēţţĩńĝ àƥƥĺĩēś ōńĺŷ ţō ţĥĩś ćōḿƥũţēŕ."@@ -2541,6 +2551,7 @@"eUFXS1": ["Śōŕţ śķĩĺĺś"],"eVPynQ": ["Ōƥēń <0><1>", ["verificationUri"], "</1><2/></0> àńď ēńţēŕ ţĥĩś ćōďē:"],"eXPP7Z": ["Ćōńţēḿƥĺàţĩńĝ…"],+ "e_ToF5": ["Śĩĝń ĩń ŵĩţĥ ", ["0"]],"eaHUxx": ["Ƒĩĺēś ţōōĺƀàŕ"],"eazHgv": ["Ĝĩţ ćàń'ţ ţŕàćķ ţĥĩś ƒōĺďēŕ — ĩţ'ś ēḿƥţŷ ōŕ ćōńţàĩńś ōńĺŷ ĩĝńōŕēď ƒĩĺēś. Ţĥē ĺĩńķ ŵōń'ţ ŵōŕķ ũńţĩĺ ŷōũ àďď à ţŕàćķēď ďōćũḿēńţ."@@ -2569,6 +2580,7 @@"f9lQNJ": ["Àďďś à ḿàńàĝēď ƀĺōćķ ţō"],"fBHvBn": ["Ţĥēŕē'ś ńō ƥŕōĴēćţ ƒōĺďēŕ ƒōŕ ţĥĩś ŵĩńďōŵ, śō à ţēŕḿĩńàĺ ćàń'ţ śţàŕţ ĥēŕē."],"fBoO7w": ["Ţĥĩś ĩś à ƥŕēvĩēŵ ōƒ ", ["boldName"], ". Ĩńśţàĺĺ ĩţ ĩńţō ŷōũŕ àĝēńţś."],+ "fCSBwN": [["agentName"], " ćōũĺďń'ţ śţàŕţ."],"fDjZxw": ["Ćōƥĩēś ţĥē śķĩĺĺ ţō ", ["0"]],"fG0X0e": ["Ĩńśţàĺĺ ", ["brand"], " →"],"fGqEFq": ["Ĩńśţàĺĺ ", ["0"]],@@ -2917,6 +2929,7 @@" ŵĩĺĺ àƥƥēàŕ ōńćē ţĥē ƀŕàńćĥ śŷńćś."],"kMKqP_": ["Ĥĩďē ţĥēśē ćōḿḿēńţś"],+ "kNGLX6": ["Ŕēţŕŷĩńĝ…"],"kNqMMd": ["Ƒōĺďēŕ"],"kRTXGw": ["Ƥōĩńţ śēḿàńţĩć śēàŕćĥ àţ àńŷ ŌƥēńÀĨ-ćōḿƥàţĩƀĺē ēḿƀēďďĩńĝś ēńďƥōĩńţ — à śēĺƒ-ĥōśţēď śēŕvēŕ ōŕ àńōţĥēŕ ƥŕōvĩďēŕ. Ţĥē ÀƤĨ ķēŷ àƀōvē ĩś ƒōŕ ŵĥĩćĥēvēŕ ēńďƥōĩńţ ŷōũ śēţ ĥēŕē."@@ -2992,6 +3005,7 @@") ţĥàţ ŵōń'ţ ţōũćĥ ţĥē ŕēśţ ōƒ ŷōũŕ śŷśţēḿ."],"l7X_SM": ["Śēńď ţō ÀĨ"],+ "l9s3IX": [["agentName"], " ćōũĺďń'ţ śţàŕţ à ćōńvēŕśàţĩōń."],"lAiyU_": ["Ōńĺŷ ţĥē ćũŕŕēńţ ďōćũḿēńţ ũśēś <0>#", ["tag"], "</0>."],"lCC_D5": ["Śũƀśćŕĩƀĩńĝ..."],"lGs_bQ": ["Ƥàĝē <0>*</0>"],@@ -3177,6 +3191,7 @@["errorDetail"],". Ţŕŷ <0>ōķ śţàţũś</0> ōŕ ćĥēćķ <1>.ōķ/ĺōćàĺ/ĺàśţ-śƥàŵń-ēŕŕōŕ.ĺōĝ</1>."],+ "np2zZM": ["Śĩĝń ĩń ţō ", ["agentName"], " ţō ćōńţĩńũē."],"np9pbC": ["Śĥōŵ ", ["inAppHiddenCount"], " ḿōŕē"],"npcziF": ["Ĩńśţàĺĺ ōń"],"nqV0Kk": ["Ţĥĩś ƒōĺďēŕ ĥàśń'ţ śŷńćēď ţō ĜĩţĤũƀ ŷēţ. Ţĥē ĺĩńķ ŵĩĺĺ ŵōŕķ àƒţēŕ ţĥē ńēxţ śŷńć."],@@ -3213,6 +3228,7 @@"oCZkaG": ["Ćōƥŷ ƥàţĥ"],"oJl7eO": ["Ũńķńōŵń ćōḿƥōńēńţ: ", ["componentName"], " — śōũŕćē ēďĩţàƀĺē ƀēĺōŵ"],"oKBnk5": ["Ḿōŕē ŕēǫũēśţś ŵēŕē ƀĺōćķēď."],+ "oPU_4D": ["Śēńď ŵĥēń ţĥē àĝēńţ ĩś ƒŕēē"],"oQA-cA": ["Ƒũĺĺ ƥàţĥ"],"oS1YpJ": ["Ōƥēń ţĥē ƤŕōĴēćţ Ńàvĩĝàţōŕ."],"oWsZk8": ["Ćŕēàţē ḿĩśśĩńĝ ƥàĝē ", ["target"]],@@ -3422,6 +3438,7 @@"s0IDhW": ["Ţĥĩś ƒĩĺē ćōũĺď ńōţ ƀē ƒōũńď."],"s0Iold": ["Ēďĩţēď ĺōćàĺĺŷ śĩńćē ĩţ ŵàś ĩńśţàĺĺēď"],"s0J_k9": [["0", "plural", { "one": ["#", " ķēŷ"], "other": ["#", " ķēŷś"] }]],+ "s0QzlI": ["Śĩĝń-ĩń ƒàĩĺēď: ", ["0"]],"s0_GnA": ["Ōƥēńĩńĝ ", ["openingLabel"], "…"],"s1c0ja": ["ßũĺĺēţ Ĺĩśţ"],"s3caR3": ["Ďēĺēţĩńĝ"],@@ -3482,6 +3499,7 @@"stlgky": ["Ōń — ŷōũŕ śēàŕćĥ ǫũēŕĩēś àńď ţĥē ţēxţ ōƒ ḿàţćĥĩńĝ ƥàĝēś àŕē śēńţ ţō ŷōũŕ ēḿƀēďďĩńĝś ƥŕōvĩďēŕ (ŌƥēńÀĨ ƀŷ ďēƒàũĺţ) ţō ćōḿƥũţē ēḿƀēďďĩńĝś."],+ "str6n9": ["Ŷōũŕ ḿēśśàĝē ďĩďń'ţ ŕēàćĥ ", ["agentName"], "."],"sweBEk": ["Ḿōďēĺ: <0>", ["0"], "</0>"],"sxTdZI": ["Ĺōàďĩńĝ ƥàţĥś…"],"sxjyRq": ["Ŵōŕķţŕēēś"],diff --git a/packages/app/src/locales/pseudo/messages.po b/packages/app/src/locales/pseudo/messages.poindex 27059879b..70198a5df 100644--- a/packages/app/src/locales/pseudo/messages.po+++ b/packages/app/src/locales/pseudo/messages.po@@ -318,6 +318,12 @@ msgstr ""msgid "{0} total"msgstr ""+#. placeholder {0}: info.agent.name+#. placeholder {1}: info.agent.version+#: src/components/acp/ThreadView.tsx+msgid "{0} version {1}"+msgstr ""+#. placeholder {0}: activeData.label#: src/components/EditorWorkspace.tsxmsgid "{0} was not moved."@@ -377,6 +383,14 @@ msgstr ""msgid "{accessibleLabel} (conflict)"msgstr ""+#: src/components/acp/ThreadView.tsx+msgid "{agentName} couldn't start a conversation."+msgstr ""++#: src/components/acp/ThreadView.tsx+msgid "{agentName} couldn't start."+msgstr ""+#: src/components/SyncStatusBadge.tsxmsgid "{ahead} ahead"msgstr ""@@ -3293,6 +3307,12 @@ msgstr ""msgid "Couldn't share skills: internal error. Please restart the app."msgstr ""+#. placeholder {0}: info.agent.name+#. placeholder {1}: errorText(err)+#: src/components/acp/ThreadView.tsx+msgid "Couldn't start {0}: {1}"+msgstr ""+#: src/lib/acp/launch-agent-thread.tsmsgid "Couldn't start the agent thread — please try again."msgstr ""@@ -5369,6 +5389,10 @@ msgstr ""msgid "Heads up: editing any rule or option here creates a <0>.markdownlint.json</0> file in your project to save your changes."msgstr ""+#: src/components/acp/ThreadView.tsx+msgid "Held"+msgstr ""+#: src/editor/slash-command/embed-starter-items.tsxmsgid "Hello, world!"msgstr ""@@ -5415,6 +5439,10 @@ msgstr ""msgid "Hide Bottom Dock"msgstr ""+#: src/components/acp/ThreadView.tsx+msgid "Hide details"+msgstr ""+#: src/components/AppMenubar.tsx#: src/components/command-palette-commands.tsmsgid "Hide document panel"@@ -8432,7 +8460,11 @@ msgid "Queue message"msgstr ""#: src/components/acp/ThreadView.tsx-msgid "Queued"+msgid "Queued — sends when this run finishes"+msgstr ""++#: src/components/acp/ThreadView.tsx+msgid "Queues behind the running turn"msgstr ""#: src/editor/slash-command/items.tsx@@ -9089,6 +9121,7 @@ msgstr ""msgid "Retrieving…"msgstr ""+#: src/components/acp/ThreadView.tsx#: src/components/ActivityModeContent.tsx#: src/components/BugReportHistory.tsx#: src/components/ConnectingBanner.tsx@@ -9106,6 +9139,10 @@ msgstr ""msgid "Retrying"msgstr ""+#: src/components/acp/ThreadView.tsx+msgid "Retrying…"+msgstr ""+#: src/components/settings/settings-fields.tsmsgid "Reuse one tab when clicking through the sidebars. Off opens every click in its own tab."msgstr ""@@ -9575,6 +9612,10 @@ msgstr ""msgid "Send to chat"msgstr ""+#: src/components/acp/ThreadView.tsx+msgid "Send when the agent is free"+msgstr ""+#: src/components/ReportBugDialogBody.tsxmsgid "Send your report by email"msgstr ""@@ -9810,6 +9851,10 @@ msgstr ""msgid "Show Bottom Dock"msgstr ""+#: src/components/acp/ThreadView.tsx+msgid "Show details"+msgstr ""+#: src/components/MermaidFileViewer.tsxmsgid "Show diagram"msgstr ""@@ -9965,6 +10010,20 @@ msgstr ""msgid "Sign in to {agentName} first"msgstr ""+#: src/components/acp/ThreadView.tsx+msgid "Sign in to {agentName} to continue."+msgstr ""++#. placeholder {0}: method.name+#: src/components/acp/ThreadView.tsx+msgid "Sign in with {0}"+msgstr ""++#. placeholder {0}: errorText(err)+#: src/components/acp/ThreadView.tsx+msgid "Sign-in failed: {0}"+msgstr ""+#: src/components/AuthModal.tsx#: src/lib/transports/auth-transport.tsmsgid "Sign-in stream ended without confirmation — please try again"@@ -10252,6 +10311,14 @@ msgstr ""msgid "Stays on this computer. Not committed to git."msgstr ""+#: src/components/acp/ThreadView.tsx+msgid "Steer now"+msgstr ""++#: src/components/acp/ThreadView.tsx+msgid "Steering — waiting for the current run to stop…"+msgstr ""+#: src/components/MountStalledAffordance.tsxmsgid "Still loading"msgstr ""@@ -10293,6 +10360,10 @@ msgstr ""msgid "Stopping"msgstr ""+#: src/components/acp/ThreadView.tsx+msgid "Stops the current run and sends this instead"+msgstr ""+#: src/components/settings/ProjectTemplatesSection.tsxmsgid "Stored at <0>.ok/templates/</0> in this project. Available in every folder (folder-scoped templates can override by filename)."msgstr ""@@ -10731,6 +10802,10 @@ msgstr ""msgid "That folder isn't an OpenKnowledge project yet. Initialize it and open?"msgstr ""+#: src/components/acp/ThreadView.tsx+msgid "That message already went out — your edit wasn't applied."+msgstr ""+#. placeholder {0}: item.displayName#: src/components/acp/ThreadView.tsxmsgid "The {0} download request timed out."@@ -12299,6 +12374,10 @@ msgstr ""msgid "Your local copy of branch <0>{branch}</0> is behind. Pull the latest changes, then open the link again."msgstr ""+#: src/components/acp/ThreadView.tsx+msgid "Your message didn't reach {agentName}."+msgstr ""+#: src/components/ReportBugDialogBody.tsxmsgid "Your report couldn't be sent. Try again or email it instead."msgstr ""diff --git a/packages/core/src/acp/thread-protocol.test.ts b/packages/core/src/acp/thread-protocol.test.tsindex 307367879..0842ca2ae 100644--- a/packages/core/src/acp/thread-protocol.test.ts+++ b/packages/core/src/acp/thread-protocol.test.ts@@ -43,6 +43,34 @@ describe('parseThreadClientFrame', () => {).toBeNull();});+ test('steer requires threadId, reqId, and NON-empty content', () => {+ expect(+ parseThreadClientFrame(+ JSON.stringify({ op: 'steer', threadId: 't', reqId: 'r', content: 'do this instead' }),+ ),+ ).toMatchObject({ op: 'steer', threadId: 't', reqId: 'r', content: 'do this instead' });+ // Unlike `prompt`, empty content is refused — a steer cancels a turn.+ expect(+ parseThreadClientFrame(+ JSON.stringify({ op: 'steer', threadId: 't', reqId: 'r', content: '' }),+ ),+ ).toBeNull();+ expect(+ parseThreadClientFrame(JSON.stringify({ op: 'steer', threadId: 't', reqId: 'r' })),+ ).toBeNull();+ expect(+ parseThreadClientFrame(JSON.stringify({ op: 'steer', threadId: 't', content: 'x' })),+ ).toBeNull();+ expect(+ parseThreadClientFrame(JSON.stringify({ op: 'steer', reqId: 'r', content: 'x' })),+ ).toBeNull();+ expect(+ parseThreadClientFrame(+ JSON.stringify({ op: 'steer', threadId: 't', reqId: 'r', content: 7 }),+ ),+ ).toBeNull();+ });+test('queue_edit requires threadId, id, and non-empty content', () => {expect(parseThreadClientFrame(@@ -62,6 +90,65 @@ describe('parseThreadClientFrame', () => {).toBeNull();});+ test('queue_edit carries an optional reqId, which must be a non-empty string', () => {+ expect(+ parseThreadClientFrame(+ JSON.stringify({+ op: 'queue_edit',+ threadId: 't',+ id: 'q1',+ content: 'new text',+ reqId: 'qe-1',+ }),+ ),+ ).toMatchObject({ op: 'queue_edit', reqId: 'qe-1' });+ // Absent is the fire-and-forget shape and stays valid — the parser adds no+ // reqId of its own, so the socket keeps answering it silently.+ expect(+ parseThreadClientFrame(+ JSON.stringify({ op: 'queue_edit', threadId: 't', id: 'q1', content: 'new text' }),+ ),+ ).toEqual({ op: 'queue_edit', threadId: 't', id: 'q1', content: 'new text' });+ expect(+ parseThreadClientFrame(+ JSON.stringify({ op: 'queue_edit', threadId: 't', id: 'q1', content: 'x', reqId: '' }),+ ),+ ).toBeNull();+ expect(+ parseThreadClientFrame(+ JSON.stringify({ op: 'queue_edit', threadId: 't', id: 'q1', content: 'x', reqId: 7 }),+ ),+ ).toBeNull();+ });++ test('queue_hold requires threadId, id, and a boolean held', () => {+ expect(+ parseThreadClientFrame(+ JSON.stringify({ op: 'queue_hold', threadId: 't', id: 'q1', held: true }),+ ),+ ).toMatchObject({ op: 'queue_hold', threadId: 't', id: 'q1', held: true });+ expect(+ parseThreadClientFrame(+ JSON.stringify({ op: 'queue_hold', threadId: 't', id: 'q1', held: false }),+ ),+ ).toMatchObject({ op: 'queue_hold', held: false });+ expect(+ parseThreadClientFrame(JSON.stringify({ op: 'queue_hold', threadId: 't', id: 'q1' })),+ ).toBeNull();+ // A truthy string is the shape a hand-rolled client sends; it is not a hold.+ expect(+ parseThreadClientFrame(+ JSON.stringify({ op: 'queue_hold', threadId: 't', id: 'q1', held: 'true' }),+ ),+ ).toBeNull();+ expect(+ parseThreadClientFrame(JSON.stringify({ op: 'queue_hold', threadId: 't', held: true })),+ ).toBeNull();+ expect(+ parseThreadClientFrame(JSON.stringify({ op: 'queue_hold', id: 'q1', held: true })),+ ).toBeNull();+ });+test('queue_remove requires threadId and id', () => {expect(parseThreadClientFrame(JSON.stringify({ op: 'queue_remove', threadId: 't', id: 'q1' })),@@ -187,6 +274,44 @@ describe('parseThreadClientFrame', () => {).toBeNull();});+ test('retry requires threadId and reqId', () => {+ expect(+ parseThreadClientFrame(JSON.stringify({ op: 'retry', threadId: 't', reqId: 'r' })),+ ).toMatchObject({ op: 'retry', threadId: 't', reqId: 'r' });+ expect(parseThreadClientFrame(JSON.stringify({ op: 'retry', threadId: 't' }))).toBeNull();+ expect(parseThreadClientFrame(JSON.stringify({ op: 'retry', reqId: 'r' }))).toBeNull();+ expect(+ parseThreadClientFrame(JSON.stringify({ op: 'retry', threadId: 't', reqId: '' })),+ ).toBeNull();+ });++ test('authenticate requires threadId, reqId and methodId', () => {+ expect(+ parseThreadClientFrame(+ JSON.stringify({ op: 'authenticate', threadId: 't', reqId: 'r', methodId: 'm' }),+ ),+ ).toMatchObject({ op: 'authenticate', threadId: 't', reqId: 'r', methodId: 'm' });+ expect(+ parseThreadClientFrame(JSON.stringify({ op: 'authenticate', threadId: 't', reqId: 'r' })),+ ).toBeNull();+ expect(+ parseThreadClientFrame(JSON.stringify({ op: 'authenticate', reqId: 'r', methodId: 'm' })),+ ).toBeNull();+ expect(+ parseThreadClientFrame(JSON.stringify({ op: 'authenticate', threadId: 't', methodId: 'm' })),+ ).toBeNull();+ expect(+ parseThreadClientFrame(+ JSON.stringify({ op: 'authenticate', threadId: 't', reqId: 'r', methodId: '' }),+ ),+ ).toBeNull();+ expect(+ parseThreadClientFrame(+ JSON.stringify({ op: 'authenticate', threadId: 't', reqId: 'r', methodId: 7 }),+ ),+ ).toBeNull();+ });+test('rename requires threadId and a non-empty title', () => {expect(parseThreadClientFrame(JSON.stringify({ op: 'rename', threadId: 't', title: 'New name' })),diff --git a/packages/core/src/acp/thread-protocol.ts b/packages/core/src/acp/thread-protocol.tsindex bfec64391..fc443b684 100644--- a/packages/core/src/acp/thread-protocol.ts+++ b/packages/core/src/acp/thread-protocol.ts@@ -46,6 +46,43 @@ export type ThreadStatus =/** Runtimes OK can download on demand to launch an agent (see `managed-runtime.ts`). */export type ManagedRuntimeKind = 'node' | 'uv';+/**+ * One auth method the agent advertised at `initialize`, trimmed to what the+ * client renders — and to the `id` that `authenticate` targets. Mirrors the+ * SDK's `AuthMethod` union minus per-variant launch mechanics.+ */+export interface ThreadAuthMethod {+ id: string;+ name: string;+ description?: string;+ /**+ * The SDK's `AuthMethod` discriminant, forwarded verbatim (`env_var`,+ * `terminal`; absent means the agent drives its own sign-in). It decides+ * whether OK can complete the sign-in over the protocol or the user has to+ * go to their own terminal/environment first. Optional on the wire: events+ * persisted before this field existed replay without it.+ */+ kind?: string;+}++/**+ * Structured detail for a failure-shaped `status` event. The server has no+ * i18n layer, so it must not compose user-facing prose from wire payloads;+ * it labels the failure and forwards the agent's own message instead. The+ * app renders translatable copy from `reason`, quotes `agentMessage`, and+ * keeps `machineDetail` behind a disclosure — never in headline copy.+ */+export interface ThreadFailureDetail {+ /** Which step failed — the app maps this to translatable copy. */+ reason: 'auth-required' | 'connect' | 'session-setup' | 'prompt';+ /** The failing side's own human-readable message, when one exists. */+ agentMessage?: string;+ /** Wire-level payload (JSON-RPC `data`, stderr tail) — disclosure-only. */+ machineDetail?: string;+ /** Advertised auth methods (present only on `auth-required`). */+ authMethods?: ThreadAuthMethod[];+}+/** Agent identity as the catalog + thread UI render it. */export interface ThreadAgentInfo {/** Registry manifest id (or custom-agent id). */@@ -56,6 +93,12 @@ export interface ThreadAgentInfo {iconUrl?: string;/** 'registry' manifest or user-configured 'custom' entry. */source: 'registry' | 'custom';+ /**+ * Manifest version of the build OK launched (registry agents only). The+ * user's own terminal may hold a different one, so the thread header names+ * which build is answering.+ */+ version?: string;}/**@@ -69,6 +112,25 @@ export interface QueuedMessage {id: string;content: string;ts: number;+ /**+ * Parked: the drain skips this entry and moves to the next one, but the+ * entry keeps its place in the queue. An open edit holds its row, so a turn+ * that ends mid-edit dispatches the rest of the queue rather than the stale+ * text the user is halfway through replacing.+ */+ held?: boolean;+}++/**+ * A correction parked while the run it corrects is being stopped for it+ * ("Steer now"). Not a queue entry: it rides the turn-end continuation the+ * cancel produces, so it lands as the very next turn while the queue keeps+ * its place behind it. Ephemeral exactly like {@link QueuedMessage} — never+ * persisted, dropped on cancel/error/exit.+ */+export interface SteerMessage {+ content: string;+ ts: number;}/** Snapshot metadata for one thread (tab strip + thread header). */@@ -105,6 +167,13 @@ export interface ThreadInfo {* drops the queue on cancel, agent error/exit, and archive.*/queue?: QueuedMessage[];+ /**+ * The correction waiting for the current run to stop (see+ * {@link SteerMessage}). At most one — a second steer replaces it, because+ * the latest correction is the one the user means. Live-thread-only and+ * never persisted.+ */+ steer?: SteerMessage;}/** One entry in a thread's event log. */@@ -129,7 +198,14 @@ export type ThreadEvent =}| { kind: 'turn_started'; ts: number }| { kind: 'turn_ended'; stopReason: StopReason; ts: number }- | { kind: 'status'; status: ThreadStatus; detail?: string; ts: number }+ | {+ kind: 'status';+ status: ThreadStatus;+ detail?: string;+ /** Structured failure detail; `detail` stays the legacy/fallback string. */+ failure?: ThreadFailureDetail;+ ts: number;+ }| { kind: 'title_changed'; title: string; ts: number }| { kind: 'agent_stderr'; line: string; ts: number }| {@@ -239,6 +315,17 @@ export type ThreadClientFrame =| { op: 'subscribe'; threadId: string; sinceSeq?: number }| { op: 'unsubscribe'; threadId: string }| { op: 'prompt'; threadId: string; reqId: string; content: string }+ | {+ /**+ * Stop the running turn and send this instead. The correction parks on+ * `ThreadInfo.steer` until the turn actually ends, then dispatches ahead+ * of anything queued. With no turn running it is a plain prompt.+ */+ op: 'steer';+ threadId: string;+ reqId: string;+ content: string;+ }| {/*** Replace a queued message's content in place. Targets an entry of@@ -250,6 +337,24 @@ export type ThreadClientFrame =threadId: string;id: string;content: string;+ /**+ * When present, the server answers on it either way: `queue_edited` on+ * success, an `error` frame (`not-ready`) when the entry already+ * dispatched — so the client can tell the user their edit never landed.+ * Absent, the edit is fire-and-forget.+ */+ reqId?: string;+ }+ | {+ /**+ * Park a queued message so the drain skips it (`held: true`), or release+ * it back into the drain (`held: false`). Held entries keep their FIFO+ * position. Unknown id: no-op.+ */+ op: 'queue_hold';+ threadId: string;+ id: string;+ held: boolean;}| {/** Remove a queued message before it dispatches. Unknown id: no-op. */@@ -306,6 +411,31 @@ export type ThreadClientFrame =reqId: string;prompt?: string;}+ | {+ /**+ * Start a failed thread over in place: same thread, same transcript, a+ * fresh launch. Refused unless the thread is live, sitting in a failure+ * status, and holds no agent session — a thread that has one has a live+ * agent that a silent respawn would strand. Responds with `retried`, or+ * an `error` frame carrying this `reqId`.+ */+ op: 'retry';+ threadId: string;+ reqId: string;+ }+ | {+ /**+ * Complete an advertised sign-in on a thread parked in `auth_required`:+ * the server sends ACP's `authenticate` on the SAME connection and then+ * re-attempts the session open, so no respawn is involved. `methodId` is+ * one of the `authMethods` the failure notice carried. Responds with+ * `authenticated`, or an `error` frame carrying this `reqId`.+ */+ op: 'authenticate';+ threadId: string;+ reqId: string;+ methodId: string;+ }| {/** Permanently delete an ARCHIVED thread's transcript (refused live). */op: 'delete';@@ -317,6 +447,8 @@ export type ThreadClientFrame =export type ThreadServerFrame =| { op: 'created'; reqId: string; info: ThreadInfo }| { op: 'resumed'; reqId: string; info: ThreadInfo }+ | { op: 'retried'; reqId: string; info: ThreadInfo }+ | { op: 'authenticated'; reqId: string; info: ThreadInfo }| { op: 'subscribed'; threadId: string; fromSeq: number; info: ThreadInfo }| { op: 'event'; threadId: string; seq: number; event: ThreadEvent }| {@@ -333,6 +465,18 @@ export type ThreadServerFrame =fromSeq: number;events: ThreadEvent[];}+ | {+ /**+ * Positive ack for a `queue_edit` that carried a `reqId`. The edit has+ * no state of its own on the wire — the refreshed `info` merely reflects+ * the queue — so without a frame that means "this request applied", a+ * client correlating on `info` settles the edit the moment ANY info for+ * the thread arrives and can never see the refusal that follows.+ */+ op: 'queue_edited';+ reqId: string;+ threadId: string;+ }| { op: 'info'; info: ThreadInfo }| { op: 'threads'; threads: ThreadInfo[] }| {@@ -363,7 +507,9 @@ const CLIENT_OPS = new Set(['subscribe','unsubscribe','prompt',+ 'steer','queue_edit',+ 'queue_hold','queue_remove','permission_response','runtime_consent_response',@@ -373,6 +519,8 @@ const CLIENT_OPS = new Set(['close','rename','resume',+ 'retry',+ 'authenticate','delete','list',]);@@ -429,8 +577,17 @@ 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;+ // Unlike `prompt`, empty content is refused: a steer cancels a running+ // turn, and doing that for nothing is a Stop wearing the wrong name.+ case 'steer':+ if (!str('threadId') || !str('reqId') || !str('content')) return null;+ return frame as unknown as ThreadClientFrame;case 'queue_edit':if (!str('threadId') || !str('id') || !str('content')) return null;+ if (frame.reqId !== undefined && !str('reqId')) return null;+ return frame as unknown as ThreadClientFrame;+ case 'queue_hold':+ if (!str('threadId') || !str('id') || typeof frame.held !== 'boolean') return null;return frame as unknown as ThreadClientFrame;case 'queue_remove':if (!str('threadId') || !str('id')) return null;@@ -469,6 +626,12 @@ export function parseThreadClientFrame(raw: string): ThreadClientFrame | null {if (!str('threadId') || !str('reqId')) return null;if (frame.prompt !== undefined && typeof frame.prompt !== 'string') return null;return frame as unknown as ThreadClientFrame;+ case 'retry':+ if (!str('threadId') || !str('reqId')) return null;+ return frame as unknown as ThreadClientFrame;+ case 'authenticate':+ if (!str('threadId') || !str('reqId') || !str('methodId')) return null;+ return frame as unknown as ThreadClientFrame;case 'unsubscribe':case 'cancel':case 'close':diff --git a/packages/core/src/acp/thread-protocol.typelock.ts b/packages/core/src/acp/thread-protocol.typelock.tsindex d83326912..84e146935 100644--- a/packages/core/src/acp/thread-protocol.typelock.ts+++ b/packages/core/src/acp/thread-protocol.typelock.ts@@ -9,6 +9,7 @@*/import type {+ AuthMethod,ClientCapabilities,CreateTerminalRequest,EnvVariable,@@ -75,6 +76,15 @@ export type PinPermissionOutcome = Expect<Equal<RequestPermissionResponse['outcome']['outcome'], 'selected' | 'cancelled'>>;+// Dependents: `threadAuthMethods` forwards this discriminant verbatim onto+// `ThreadAuthMethod.kind`, and the sign-in notice offers a button only for+// methods OUTSIDE these two variants — an `env_var` / `terminal` sign-in+// needs the user's own environment or TUI, which the notice cannot supply.+// A new variant would silently get a button that can't complete.+export type PinAuthMethodKinds = Expect<+ Equal<Extract<AuthMethod, { type: string }>['type'], 'env_var' | 'terminal'>+>;+// Dependents: the server maps a user-cancelled turn to `cancelled` and the// UI treats every stop reason as a plain turn end.export type PinStopReason = Expect<diff --git a/packages/server/src/acp/harness-availability.test.ts b/packages/server/src/acp/harness-availability.test.tsindex 6f8e785b0..a0127a318 100644--- a/packages/server/src/acp/harness-availability.test.ts+++ b/packages/server/src/acp/harness-availability.test.ts@@ -1,10 +1,10 @@import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';import { tmpdir } from 'node:os';import { join } from 'node:path';-import type { TerminalCli } from '@inkeep/open-knowledge-core';import { afterEach, describe, expect, test } from 'vitest';import {ACP_AGENT_HARNESS_CLIS,+ type AcpHarnessCli,createAcpHarnessAvailabilityProbe,type HarnessAvailability,} from './harness-availability.ts';@@ -21,18 +21,22 @@ describe('ACP harness availability', () => {'claude-acp': 'claude','codex-acp': 'codex',cursor: 'cursor',+ gemini: 'gemini',opencode: 'opencode',+ 'pi-acp': 'pi',});});test('probes every mapped harness once and caches the in-flight result', async () => {- const calls: TerminalCli[] = [];+ const calls: AcpHarnessCli[] = [];let timestamp = 100;- const availability: Partial<Record<TerminalCli, HarnessAvailability>> = {+ const availability: Partial<Record<AcpHarnessCli, HarnessAvailability>> = {claude: 'present',codex: 'not-found',cursor: 'unknown',+ gemini: 'present',opencode: 'present',+ pi: 'not-found',};const probe = createAcpHarnessAvailabilityProbe({probe: async (cli) => {@@ -46,11 +50,11 @@ describe('ACP harness availability', () => {const first = probe();expect(probe()).toBe(first);expect(await first).toEqual(availability);- expect(calls).toEqual(['claude', 'codex', 'cursor', 'opencode']);+ expect(calls).toEqual(['claude', 'codex', 'cursor', 'gemini', 'opencode', 'pi']);timestamp = 151;await probe();- expect(calls).toHaveLength(8);+ expect(calls).toHaveLength(12);});// Availability drives defaulting, so it has to agree with what the launch@@ -61,7 +65,7 @@ describe('ACP harness availability', () => {test('a harness reachable only via the login shell reports present', async () => {const shimDir = mkdtempSync(join(tmpdir(), 'harness-avail-test-'));shims.push(shimDir);- for (const bin of ['claude', 'codex', 'cursor-agent', 'opencode']) {+ for (const bin of ['claude', 'codex', 'cursor-agent', 'gemini', 'opencode', 'pi']) {writeFileSync(join(shimDir, bin), '#!/bin/sh\nexit 0\n', { mode: 0o755 });}const probe = createAcpHarnessAvailabilityProbe({@@ -71,7 +75,9 @@ describe('ACP harness availability', () => {claude: 'present',codex: 'present',cursor: 'present',+ gemini: 'present',opencode: 'present',+ pi: 'present',});});diff --git a/packages/server/src/acp/harness-availability.ts b/packages/server/src/acp/harness-availability.tsindex 33836ffc8..a539a18ac 100644--- a/packages/server/src/acp/harness-availability.ts+++ b/packages/server/src/acp/harness-availability.ts@@ -14,17 +14,28 @@ import { getSharedLoginShellPathProvider } from './login-shell-path.ts';export type HarnessAvailability = 'present' | 'not-found' | 'unknown';-export const ACP_AGENT_HARNESS_CLIS: Readonly<Record<string, TerminalCli | undefined>> = {+/**+ * Harnesses this probe knows how to look for. A superset of `TerminalCli`:+ * Gemini has a first-party CLI and a registry ACP row but no docked-terminal+ * launch recipe, and the catalog signal is worth having without inventing one.+ */+export type AcpHarnessCli = TerminalCli | 'gemini';++/** Registry agent id → the first-party CLI its adapter drives. */+export const ACP_AGENT_HARNESS_CLIS: Readonly<Record<string, AcpHarnessCli | undefined>> = {'claude-acp': 'claude','codex-acp': 'codex',cursor: 'cursor',+ gemini: 'gemini',opencode: 'opencode',+ 'pi-acp': 'pi',};-const HARNESS_BINS: Readonly<Record<TerminalCli, string>> = {+const HARNESS_BINS: Readonly<Record<AcpHarnessCli, string>> = {claude: 'claude',codex: 'codex',cursor: 'cursor-agent',+ gemini: 'gemini',opencode: 'opencode',pi: 'pi',antigravity: 'agy',@@ -33,12 +44,12 @@ const HARNESS_BINS: Readonly<Record<TerminalCli, string>> = {hermes: 'hermes',};-export type AcpHarnessAvailability = Readonly<Partial<Record<TerminalCli, HarnessAvailability>>>;+export type AcpHarnessAvailability = Readonly<Partial<Record<AcpHarnessCli, HarnessAvailability>>>;const DEFAULT_TTL_MS = 60_000;async function detectHarness(- cli: TerminalCli,+ cli: AcpHarnessCli,resolveLoginShellPath: () => Promise<string | null>,): Promise<HarnessAvailability> {const launch = {@@ -70,7 +81,7 @@ async function detectHarness(export function createAcpHarnessAvailabilityProbe(opts: {- probe?: (cli: TerminalCli) => Promise<HarnessAvailability>;+ probe?: (cli: AcpHarnessCli) => Promise<HarnessAvailability>;now?: () => number;ttlMs?: number;/** Defaults to the process-shared probe the launch chain uses. */@@ -79,11 +90,11 @@ export function createAcpHarnessAvailabilityProbe(): () => Promise<AcpHarnessAvailability> {const resolveLoginShellPath =opts.resolveLoginShellPath ?? getSharedLoginShellPathProvider(getLogger('acp-harness'));- const probe = opts.probe ?? ((cli: TerminalCli) => detectHarness(cli, resolveLoginShellPath));+ const probe = opts.probe ?? ((cli: AcpHarnessCli) => detectHarness(cli, resolveLoginShellPath));const now = opts.now ?? Date.now;const ttlMs = opts.ttlMs ?? DEFAULT_TTL_MS;const harnesses = [...new Set(Object.values(ACP_AGENT_HARNESS_CLIS))].filter(- (cli): cli is TerminalCli => cli !== undefined,+ (cli): cli is AcpHarnessCli => cli !== undefined,);let cached: { expiresAt: number; value: Promise<AcpHarnessAvailability> } | null = null;diff --git a/packages/server/src/acp/launch.ts b/packages/server/src/acp/launch.tsindex 5a5903b27..db696ccef 100644--- a/packages/server/src/acp/launch.ts+++ b/packages/server/src/acp/launch.ts@@ -220,9 +220,21 @@ export function rewriteLaunchToManagedRuntime(* already resolved keeps resolving to the same binary.*/export function withLoginShellPath(launch: ResolvedLaunch, loginShellPath: string): ResolvedLaunch {- const env = { ...launch.env };- env[pathKey(env)] = mergeLoginShellPath(envPath(env), loginShellPath, delimiter);- return { ...launch, env };+ return { ...launch, env: withLoginShellPathEnv(launch.env, loginShellPath) };+}++/**+ * {@link withLoginShellPath} for a bare spawn env — the ACP terminal surface,+ * which builds its env from `mergedEnv` rather than from a `ResolvedLaunch`.+ * Same append-only merge, same case-preserving PATH key.+ */+export function withLoginShellPathEnv(+ env: Record<string, string>,+ loginShellPath: string,+): Record<string, string> {+ const next = { ...env };+ next[pathKey(next)] = mergeLoginShellPath(envPath(next), loginShellPath, delimiter);+ return next;}/** The env's PATH key (Windows spells it `Path`), for case-preserving overwrite. */diff --git a/packages/server/src/acp/login-shell-path.ts b/packages/server/src/acp/login-shell-path.tsindex 8f060d9f5..d68651722 100644--- a/packages/server/src/acp/login-shell-path.ts+++ b/packages/server/src/acp/login-shell-path.ts@@ -316,3 +316,15 @@ export function getSharedLoginShellPathProvider(log: PinoLogger): () => Promise<sharedProvider ??= createLoginShellPathProvider({ log });return sharedProvider;}++/**+ * Drop the process-wide memo so the next caller re-probes. A real answer is+ * cached for the life of the server, which is right for a burst of launches+ * and wrong the moment the machine changes underneath it: the user reads+ * "install Node", installs it, and a retry would still be answered from the+ * capture taken before the install. Retry is the one moment where paying for+ * a fresh shell startup buys a different verdict, so it resets first.+ */+export function resetSharedLoginShellPathProvider(): void {+ sharedProvider = null;+}diff --git a/packages/server/src/acp/managed-runtime-flow.integration.test.ts b/packages/server/src/acp/managed-runtime-flow.integration.test.tsindex 2eb51d535..237e2e3a9 100644--- a/packages/server/src/acp/managed-runtime-flow.integration.test.ts+++ b/packages/server/src/acp/managed-runtime-flow.integration.test.ts@@ -123,7 +123,9 @@ function makeManager(opts: {consentHome: opts.consentHome,fetchImpl: opts.fetchImpl,},- resolveLoginShellPath: opts.resolveLoginShellPath,+ // Hermetic default (see the thread-manager integration suite): never spawn+ // the developer's own login shell from a test.+ resolveLoginShellPath: opts.resolveLoginShellPath ?? (async () => null),log,});managers.push(manager);diff --git a/packages/server/src/acp/mcp-injection-skip.test.ts b/packages/server/src/acp/mcp-injection-skip.test.tsindex dd70111d7..93eca26dc 100644--- a/packages/server/src/acp/mcp-injection-skip.test.ts+++ b/packages/server/src/acp/mcp-injection-skip.test.ts@@ -86,6 +86,9 @@ function makeManager(getMcpStdioCommand: () => ({ command: 'open-knowledge', args: ['mcp', '--port', '4242'] }),probeHarnessManagedMcpEntry: probe,log,+ // Hermetic by default: every launch now merges the login shell's PATH, and+ // a test must not spawn the developer's own shell to find out what it is.+ resolveLoginShellPath: async () => null,});managers.push(manager);return manager as unknown as BuildMcpServersSeam;diff --git a/packages/server/src/acp/terminals.test.ts b/packages/server/src/acp/terminals.test.tsindex 419bad22e..b32610fef 100644--- a/packages/server/src/acp/terminals.test.ts+++ b/packages/server/src/acp/terminals.test.ts@@ -7,11 +7,12 @@ import { AcpTerminalSet } from './terminals.ts';const log = getLogger('acp-terminals-test');let sets: AcpTerminalSet[] = [];-function makeSet(events: ThreadEvent[]): AcpTerminalSet {+function makeSet(events: ThreadEvent[], loginShellPath?: string): AcpTerminalSet {const set = new AcpTerminalSet({defaultCwd: process.cwd(),emit: (event) => events.push(event),log,+ ...(loginShellPath !== undefined ? { loginShellPath } : {}),});sets.push(set);return set;@@ -74,6 +75,40 @@ describe('AcpTerminalSet', () => {expect(set.output(terminalId).output).toBe('1:kept');});+ // A GUI-launched server's PATH can't name a version manager's bin dir, so a+ // command the agent runs here would fail for a reason that has nothing to do+ // with the command. The thread manager hands the set the login shell's PATH;+ // this is where it has to land.+ test('appends the login-shell PATH to a command env', async () => {+ const events: ThreadEvent[] = [];+ const set = makeSet(events, '/opt/only-in-the-login-shell');+ const { terminalId } = set.create(node('process.stdout.write(String(process.env.PATH))'));+ await set.waitForExit(terminalId);+ const path = set.output(terminalId).output;+ expect(path).toContain('/opt/only-in-the-login-shell');+ // Appended, never prepended: everything that already resolved keeps+ // resolving to the same binary.+ expect(path.endsWith('/opt/only-in-the-login-shell')).toBe(true);+ });++ // An agent that states a PATH has stated a spawn-env contract — the same+ // rule the agent launch chain applies to a manifest PATH overlay.+ // Skipped on Windows: an overlay spelling `PATH` sits alongside the+ // inherited `Path`, and which one the OS honors is not ours to assert.+ test.skipIf(process.platform === 'win32')(+ 'a PATH the agent supplied wins over the login-shell PATH',+ async () => {+ const events: ThreadEvent[] = [];+ const set = makeSet(events, '/opt/only-in-the-login-shell');+ const { terminalId } = set.create({+ ...node('process.stdout.write(String(process.env.PATH))'),+ env: [{ name: 'PATH', value: '/agent/chose/this' }],+ });+ await set.waitForExit(terminalId);+ expect(set.output(terminalId).output).toBe('/agent/chose/this');+ },+ );+test('captures stderr interleaved and a non-zero exit code', async () => {const events: ThreadEvent[] = [];const set = makeSet(events);diff --git a/packages/server/src/acp/terminals.ts b/packages/server/src/acp/terminals.tsindex 4b1e88ab1..ffd8a2c03 100644--- a/packages/server/src/acp/terminals.ts+++ b/packages/server/src/acp/terminals.ts@@ -27,10 +27,12 @@ import type { PinoLogger } from '../logger.ts';import {envPath,mergedEnv,+ overlaySetsPath,resolveWindowsCommand,terminateAgentTree,windowsCmdWrap,withHostedAgentMarker,+ withLoginShellPathEnv,} from './launch.ts';/** Retained-output default when the agent sends no `outputByteLimit`. */@@ -119,6 +121,7 @@ export class AcpTerminalSet {private readonly emit: (event: ThreadEvent) => void;private readonly defaultCwd: string;private readonly log: PinoLogger;+ private readonly loginShellPath: string | null;private disposed = false;constructor(opts: {@@ -127,10 +130,19 @@ export class AcpTerminalSet {/** Transcript sink — the thread manager's `appendEvent`. */emit: (event: ThreadEvent) => void;log: PinoLogger;+ /**+ * The user's login-shell PATH, appended to every command's env. A+ * GUI-launched server's inherited PATH can't name a version manager's bin+ * dir, so a command the user runs fine in a terminal (`npm`, `pytest`)+ * would fail here for a reason that has nothing to do with the command.+ * Resolved once at construction: `create` answers the agent synchronously.+ */+ loginShellPath?: string | null;}) {this.defaultCwd = opts.defaultCwd;this.emit = opts.emit;this.log = opts.log;+ this.loginShellPath = opts.loginShellPath ?? null;}/** Live (not yet exited) terminal count — a test/diagnostic seam. */@@ -164,7 +176,7 @@ export class AcpTerminalSet {// `terminal: true`) would otherwise run `ok mcp`, or an env check, in a// process that never saw the marker — and fall back to handing the user a// URL, which is the failure this marker exists to prevent.- const env = withHostedAgentMarker(mergedEnv(overlay));+ const env = withHostedAgentMarker(this.spawnEnv(overlay));const cwd =params.cwd != null? isAbsolute(params.cwd)@@ -295,6 +307,18 @@ export class AcpTerminalSet {await Promise.allSettled(ids.map((id) => this.release(id)));}+ /**+ * Base env for a terminal command: the repaired inherited env plus the+ * agent's overlay, with the login shell's PATH appended. An overlay that+ * sets PATH is a spawn-env contract the agent stated explicitly (the same+ * rule the agent launch chain applies), so it is left verbatim.+ */+ private spawnEnv(overlay: Record<string, string>): Record<string, string> {+ const env = mergedEnv(overlay);+ if (this.loginShellPath === null || overlaySetsPath(overlay)) return env;+ return withLoginShellPathEnv(env, this.loginShellPath);+ }+private mustGet(terminalId: string): TerminalRecord {const record = this.terminals.get(terminalId);if (record === undefined) throw new Error(`unknown terminal '${terminalId}'`);diff --git a/packages/server/src/acp/thread-manager.integration.test.ts b/packages/server/src/acp/thread-manager.integration.test.tsindex aa13cbe01..97bbc62a6 100644--- a/packages/server/src/acp/thread-manager.integration.test.ts+++ b/packages/server/src/acp/thread-manager.integration.test.ts@@ -11,6 +11,7 @@* close path.*/+import type { ChildProcess } from 'node:child_process';import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';import { tmpdir } from 'node:os';import { dirname, join } from 'node:path';@@ -59,6 +60,8 @@ function makeManager(contentDir: string,localDir: string,extra?: {+ steerStallMs?: number;+ authenticateTimeoutMs?: number;unwatchedTurnCancelMs?: number;unwatchedTurnKillMs?: number;isIgnoredPath?: (relPosix: string) => boolean;@@ -82,6 +85,9 @@ function makeManager(isExcludedPath: () => false,isIgnoredPath: () => false,log,+ // Hermetic by default: every launch now merges the login shell's PATH, and+ // a test must not spawn the developer's own shell to find out what it is.+ resolveLoginShellPath: async () => null,...extra,});managers.push(manager);@@ -93,15 +99,24 @@ function internals(manager: AcpThreadManager): {sweep: () => void;pendingPermissionCount: (threadId: string) => number;turnActive: (threadId: string) => boolean;+ child: (threadId: string) => ChildProcess | null | undefined;} {const m = manager as unknown as {reapIdleThreads: () => void;- threads: Map<string, { pendingPermissions: Map<unknown, unknown>; turnActive: boolean }>;+ threads: Map<+ string,+ {+ pendingPermissions: Map<unknown, unknown>;+ turnActive: boolean;+ child: ChildProcess | null;+ }+ >;};return {sweep: () => m.reapIdleThreads(),pendingPermissionCount: (threadId) => m.threads.get(threadId)?.pendingPermissions.size ?? 0,turnActive: (threadId) => m.threads.get(threadId)?.turnActive ?? false,+ child: (threadId) => m.threads.get(threadId)?.child,};}@@ -972,8 +987,12 @@ const request = (method, params) =>const notify = (update) =>write({ jsonrpc: '2.0', method: 'session/update', params: { sessionId: 'sess-1', update } });let clientCaps = {};+let cancelled = false;async function handlePrompt(msg) {+ cancelled = false;const finish = () => write({ jsonrpc: '2.0', id: msg.id, result: { stopReason: 'end_turn' } });+ const finishCancelled = () =>+ write({ jsonrpc: '2.0', id: msg.id, result: { stopReason: 'cancelled' } });${promptBody}}let buffer = '';@@ -1000,6 +1019,9 @@ process.stdin.on('data', (chunk) => {reply({ protocolVersion: 1, agentCapabilities: {} });} else if (msg.method === 'session/new') {reply({ sessionId: 'sess-1' });+ } else if (msg.method === 'session/cancel') {+ // A notification, so no reply — the prompt loop is what reads the flag.+ cancelled = true;} else if (msg.method === 'session/prompt') {handlePrompt(msg).catch((err) => {notify({@@ -1590,6 +1612,11 @@ describe('AcpThreadManager prompt queueing', () => {.map((e) => e.event).filter((e): e is Extract<ThreadEvent, { kind: 'user_message' }> => e.kind === 'user_message').map((e) => e.content);+ const stopReasons = (events: Collected): string[] =>+ events+ .map((e) => e.event)+ .filter((e): e is Extract<ThreadEvent, { kind: 'turn_ended' }> => e.kind === 'turn_ended')+ .map((e) => e.stopReason);/** Agent that echoes each prompt and holds a WAIT-marked turn open until* `releasePath` exists — the deterministic gate the queue forms behind. */@@ -1611,6 +1638,34 @@ describe('AcpThreadManager prompt queueing', () => {);}+ /**+ * The same gate, but this agent HONORS `session/cancel` the compliant way:+ * it stops waiting and answers the in-flight prompt with stopReason+ * 'cancelled'. The gate agent above ignores cancel entirely — between them+ * they cover both halves of what real adapters do.+ */+ function writeCancelHonoringGateAgent(localDir: string, releasePath: string): void {+ writeRequestingAgentEntry(+ localDir,+ 'steer-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)})) {+ if (cancelled) {+ finishCancelled();+ return;+ }+ 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();@@ -1667,6 +1722,112 @@ describe('AcpThreadManager prompt queueing', () => {await manager.closeThread(info.threadId);}, 40_000);+ test('a held entry sits out the drain, then dispatches the moment it is released', 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, 'being rewritten');+ manager.sendPrompt(info.threadId, 'ready to go');+ const head = (manager.getInfo(info.threadId)?.queue ?? [])[0];+ if (head === undefined) throw new Error('queue head missing');+ expect(manager.holdQueued(info.threadId, head.id, true)).toBe(true);+ expect(manager.holdQueued(info.threadId, 'no-such-id', true)).toBe(false);++ // Turn ends: the drain skips the held head and takes the entry behind it.+ writeFileSync(releasePath, 'go');+ await waitUntil(+ () => events.filter((e) => e.event.kind === 'turn_ended').length === 2,+ 20_000,+ `two turn ends; got ${JSON.stringify(events.map((e) => e.event.kind))}`,+ );+ await waitUntil(+ () => manager.getInfo(info.threadId)?.status === 'ready',+ 20_000,+ `back to ready; got ${manager.getInfo(info.threadId)?.status}`,+ );+ expect(userMessages(events)).toEqual(['WAIT at the gate', 'ready to go']);+ const parked = manager.getInfo(info.threadId)?.queue ?? [];+ expect(parked.map((m) => m.content)).toEqual(['being rewritten']);+ expect(parked[0]?.held).toBe(true);++ // Released while nothing is running, it has no turn-end continuation left+ // to ride — the release itself has to dispatch it.+ expect(manager.holdQueued(info.threadId, head.id, false)).toBe(true);+ 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(userMessages(events)).toEqual(['WAIT at the gate', 'ready to go', 'being rewritten']);+ await waitUntil(+ () => manager.getInfo(info.threadId)?.status === 'ready',+ 20_000,+ 'ready again',+ );+ expect(manager.getInfo(info.threadId)?.queue).toBeUndefined();++ await manager.closeThread(info.threadId);+ }, 40_000);++ test('saving an edit on a held entry releases it and sends the new text', 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, 'first draft');+ const entry = (manager.getInfo(info.threadId)?.queue ?? [])[0];+ if (entry === undefined) throw new Error('queue entry missing');+ manager.holdQueued(info.threadId, entry.id, true);++ writeFileSync(releasePath, 'go');+ await waitUntil(+ () => events.filter((e) => e.event.kind === 'turn_ended').length === 1,+ 20_000,+ 'the gated turn ends',+ );+ await waitUntil(() => manager.getInfo(info.threadId)?.status === 'ready', 20_000, 'ready');+ expect(userMessages(events)).toEqual(['WAIT at the gate']);+ expect(manager.getInfo(info.threadId)?.queue?.length).toBe(1);++ // The save IS the resubmit: the hold clears with the content, and since the+ // turn already ended the edit dispatches on the spot.+ expect(manager.editQueued(info.threadId, entry.id, 'sharper draft')).toBe(true);+ await waitUntil(+ () => events.filter((e) => e.event.kind === 'turn_ended').length === 2,+ 20_000,+ `two turn ends; got ${JSON.stringify(events.map((e) => e.event.kind))}`,+ );+ expect(userMessages(events)).toEqual(['WAIT at the gate', 'sharper draft']);+ expect(agentText(events)).toContain('ran:sharper draft;');+ expect(agentText(events)).not.toContain('first draft');+ expect(manager.getInfo(info.threadId)?.queue).toBeUndefined();++ // The entry is gone, so a second save on the same id is a lost race — the+ // socket needs the `false` to tell the user their edit never landed.+ expect(manager.editQueued(info.threadId, entry.id, 'too late')).toBe(false);+ expect(manager.editQueued(info.threadId, 'no-such-id', 'ignored')).toBe(false);++ 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();@@ -1721,11 +1882,14 @@ describe('AcpThreadManager prompt queueing', () => {expect(manager.getInfo(info.threadId)?.queue).toBeUndefined();}, 40_000);- test('the queue is never persisted — a rehydrated thread comes back empty', async () => {+ test('neither the queue nor a parked steer is 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);+ // Long stall window: the steer has to still be PARKED when the thread+ // archives, or the demotion would fold it into the queue and this test+ // would only re-cover the queue.+ const manager = makeManager(contentDir, localDir, { steerStallMs: 60_000 });// 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();@@ -1737,16 +1901,240 @@ describe('AcpThreadManager prompt queueing', () => {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);+ // The gate agent ignores session/cancel, so the correction stays parked.+ manager.steerPrompt(info.threadId, 'steered while busy');+ expect(manager.getInfo(info.threadId)?.steer?.content).toBe('steered while busy');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.+ // thread from its meta. `buildMeta` strips both on the way out, so neither+ // may come back — otherwise a restart resurrects undispatchable prompts.const manager2 = makeManager(contentDir, localDir);await manager2.init();expect(manager2.getInfo(info.threadId)).toBeDefined();expect(manager2.getInfo(info.threadId)?.queue).toBeUndefined();+ expect(manager2.getInfo(info.threadId)?.steer).toBeUndefined();+ }, 40_000);++ test('a steer stops the run, goes first, and lets the queue drain behind it', async () => {+ const contentDir = tmp();+ const localDir = tmp();+ const releasePath = join(localDir, 'release-turn');+ writeCancelHonoringGateAgent(localDir, releasePath);+ const manager = makeManager(contentDir, localDir);+ const info = await manager.createThread({ agent: { source: 'custom', id: 'steer-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, 'queued before the steer');++ manager.steerPrompt(info.threadId, 'do this instead');+ // Parked, not queued — and the queue keeps its place behind it.+ expect(manager.getInfo(info.threadId)?.steer?.content).toBe('do this instead');+ expect((manager.getInfo(info.threadId)?.queue ?? []).map((m) => m.content)).toEqual([+ 'queued before the steer',+ ]);++ // Three turns: the cancelled one, the correction, then the queued message.+ // The gate is never released — the cancel is what ends turn one.+ 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(stopReasons(events)[0]).toBe('cancelled');+ expect(userMessages(events)).toEqual([+ 'WAIT at the gate',+ 'do this instead',+ 'queued before the steer',+ ]);+ const text = agentText(events);+ expect(text.indexOf('ran:do this instead;')).toBeLessThan(+ text.indexOf('ran:queued before the steer;'),+ );+ expect(manager.getInfo(info.threadId)?.steer).toBeUndefined();+ expect(manager.getInfo(info.threadId)?.queue).toBeUndefined();+ await waitUntil(+ () => manager.getInfo(info.threadId)?.status === 'ready',+ 10_000,+ 'ready after the drain',+ );++ await manager.closeThread(info.threadId);+ }, 40_000);++ test('an ignored cancel demotes the steer to the front of the queue', async () => {+ const contentDir = tmp();+ const localDir = tmp();+ const releasePath = join(localDir, 'release-turn');+ // This gate agent never reads session/cancel — the stall fallback is the+ // only thing that can rescue the correction.+ writeGateAgent(localDir, releasePath);+ const manager = makeManager(contentDir, localDir, { steerStallMs: 200 });+ 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, 'queued first');++ manager.steerPrompt(info.threadId, 'could not interrupt');+ expect(manager.getInfo(info.threadId)?.steer?.content).toBe('could not interrupt');++ await waitUntil(+ () => manager.getInfo(info.threadId)?.steer === undefined,+ 5_000,+ 'steer demoted',+ );+ expect((manager.getInfo(info.threadId)?.queue ?? []).map((m) => m.content)).toEqual([+ 'could not interrupt',+ 'queued first',+ ]);++ 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(userMessages(events)).toEqual([+ 'WAIT at the gate',+ 'could not interrupt',+ 'queued first',+ ]);++ await manager.closeThread(info.threadId);+ }, 40_000);++ /**+ * The same ignore-the-cancel gate, but this agent answers the release by+ * REJECTING the in-flight `session/prompt` instead of resolving it — the+ * other half of what real adapters do with a cancel, and the path that+ * lands in `dispatchPrompt`'s `.catch` with a cancel already requested.+ */+ function writeCancelRejectingGateAgent(localDir: string, releasePath: string): void {+ writeRequestingAgentEntry(+ localDir,+ 'rejecting-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));+ }+ write({ jsonrpc: '2.0', id: msg.id, error: { code: -32603, message: 'prompt aborted' } });+ return;+ }+ finish();+`,+ );+ }++ test('a stall-demoted steer still drains when the agent answers the cancel by rejecting', async () => {+ const contentDir = tmp();+ const localDir = tmp();+ const releasePath = join(localDir, 'release-turn');+ writeCancelRejectingGateAgent(localDir, releasePath);+ const manager = makeManager(contentDir, localDir, { steerStallMs: 200 });+ const info = await manager.createThread({ agent: { source: 'custom', id: 'rejecting-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.steerPrompt(info.threadId, 'demoted correction');+ await waitUntil(+ () => manager.getInfo(info.threadId)?.steer === undefined,+ 5_000,+ 'the steer to demote to the queue',+ );+ expect((manager.getInfo(info.threadId)?.queue ?? []).map((m) => m.content)).toEqual([+ 'demoted correction',+ ]);++ // The rejection ends the turn on the cancel path, which used to emit+ // 'ready' and stop — leaving the demoted correction queued forever.+ writeFileSync(releasePath, 'go');+ await waitUntil(+ () => events.filter((e) => e.event.kind === 'turn_ended').length === 2,+ 20_000,+ `two turn ends; got ${JSON.stringify(events.map((e) => e.event.kind))}`,+ );+ expect(userMessages(events)).toEqual(['WAIT at the gate', 'demoted correction']);+ expect(agentText(events)).toContain('ran:demoted correction;');+ await waitUntil(+ () => manager.getInfo(info.threadId)?.status === 'ready',+ 10_000,+ 'ready after the drain',+ );+ expect(manager.getInfo(info.threadId)?.queue).toBeUndefined();++ await manager.closeThread(info.threadId);+ }, 40_000);++ test('Stop clears a parked steer along with the queue', async () => {+ const contentDir = tmp();+ const localDir = tmp();+ const releasePath = join(localDir, 'release-turn');+ writeGateAgent(localDir, releasePath);+ // Long stall window: the point is what Stop does, not what the fallback does.+ const manager = makeManager(contentDir, localDir, { steerStallMs: 60_000 });+ 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');+ manager.sendPrompt(info.threadId, 'queued behind');+ manager.steerPrompt(info.threadId, 'never mind, do this');+ expect(manager.getInfo(info.threadId)?.steer).toBeDefined();++ manager.cancel(info.threadId);+ expect(manager.getInfo(info.threadId)?.steer).toBeUndefined();+ expect(manager.getInfo(info.threadId)?.queue).toBeUndefined();++ // The gate agent ignores cancel — release it and confirm neither the steer+ // nor the queue comes back to life through the turn-end continuation.+ writeFileSync(releasePath, 'go');+ await waitUntil(() => !internals(manager).turnActive(info.threadId), 10_000, 'turn ended');+ expect(userMessages(events)).toEqual(['WAIT for cancel']);++ await manager.closeThread(info.threadId);+ }, 40_000);++ test('a steer with no turn running is just a send', 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' } });+ const events: Collected = [];+ await manager.subscribe(info.threadId, 0, collect(events));+ await waitUntil(() => manager.getInfo(info.threadId)?.status === 'ready', 15_000, 'ready');++ manager.steerPrompt(info.threadId, 'nothing to interrupt');+ await waitUntil(+ () => events.filter((e) => e.event.kind === 'turn_ended').length === 1,+ 20_000,+ 'turn ended',+ );+ expect(manager.getInfo(info.threadId)?.steer).toBeUndefined();+ expect(userMessages(events)).toEqual(['nothing to interrupt']);+ expect(stopReasons(events)).toEqual(['end_turn']);++ await manager.closeThread(info.threadId);}, 40_000);});@@ -1808,3 +2196,703 @@ describe.skipIf(process.platform === 'win32')('login-shell PATH fallback', () =>expect(errorEvent()?.detail).toContain('was not found');}, 20_000);});++/**+ * Agent that reports the PATH it was spawned with as its first message. The+ * top-level command (`node`) resolves from the inherited PATH, so preflight+ * succeeds without help — what this proves is what the agent's own nested+ * lookups (`npx pi-acp` spawning `pi`) would see.+ */+function writePathEchoAgentEntry(localDir: string, id: string): void {+ const agentPath = join(localDir, `${id}.mjs`);+ writeFileSync(+ agentPath,+ `+const write = (msg) => process.stdout.write(JSON.stringify(msg) + '\\n');+let buffer = '';+process.stdin.setEncoding('utf8');+process.stdin.on('data', (chunk) => {+ buffer += chunk;+ let idx = buffer.indexOf('\\n');+ while (idx !== -1) {+ const line = buffer.slice(0, idx);+ buffer = buffer.slice(idx + 1);+ idx = buffer.indexOf('\\n');+ if (line.trim() === '') continue;+ const msg = JSON.parse(line);+ if (msg.method === 'initialize') {+ write({ jsonrpc: '2.0', id: msg.id, result: { protocolVersion: 1, agentCapabilities: {} } });+ } else if (msg.method === 'session/new') {+ write({ jsonrpc: '2.0', id: msg.id, result: { sessionId: 'path-echo-session' } });+ write({+ jsonrpc: '2.0',+ method: 'session/update',+ params: {+ sessionId: 'path-echo-session',+ update: {+ sessionUpdate: 'agent_message_chunk',+ content: { type: 'text', text: process.env.PATH ?? '' },+ },+ },+ });+ } else if (msg.id !== undefined) {+ write({ jsonrpc: '2.0', id: msg.id, result: {} });+ }+ }+});+`,+ );+ writeFileSync(+ join(localDir, 'acp-agents.json'),+ JSON.stringify([{ id, name: `Fake ${id}`, command: 'node', args: [agentPath] }]),+ );+}++describe.skipIf(process.platform === 'win32')('login-shell PATH on a launchable command', () => {+ /**+ * The `npx pi-acp` shape: the top-level command is findable, the binary the+ * adapter goes on to spawn is not. Preflight passes, so the failure-only+ * fallback never fired and the nested lookup ran against a PATH that had+ * never seen the user's profile.+ */+ test('a launch that preflights still carries the login-shell PATH', async () => {+ const contentDir = tmp();+ const localDir = tmp();+ const shimDir = tmp();+ writePathEchoAgentEntry(localDir, 'path-echo');++ const manager = makeManager(contentDir, localDir, {+ resolveLoginShellPath: async () => shimDir,+ });+ const seen: ThreadEvent[] = [];+ const info = await manager.createThread({ agent: { source: 'custom', id: 'path-echo' } });+ await manager.subscribe(info.threadId, 0, (frame: ThreadServerFrame) => {+ if (frame.op === 'event') seen.push(frame.event);+ if (frame.op === 'events') seen.push(...frame.events);+ });+ const reportedPath = (): string | undefined => {+ for (const event of seen) {+ if (event.kind !== 'session_update') continue;+ const update = event.update as {+ sessionUpdate?: string;+ content?: { type?: string; text?: string };+ };+ if (update.sessionUpdate !== 'agent_message_chunk') continue;+ if (update.content?.type === 'text') return update.content.text;+ }+ return undefined;+ };+ await waitUntil(() => reportedPath() !== undefined, 15_000, "the agent's PATH");+ // Reaching 'ready' at all means preflight resolved `node` without the shim.+ expect(manager.getInfo(info.threadId)?.status).toBe('ready');+ expect(reportedPath()).toContain(shimDir);+ }, 30_000);+});++/**+ * Agent that fails `session/new` until `markerPath` exists — the "install the+ * thing the error told you to install, then retry" shape, made deterministic.+ */+function writeMarkerGatedAgentEntry(localDir: string, id: string, markerPath: string): void {+ const agentPath = join(localDir, `${id}.mjs`);+ writeFileSync(+ agentPath,+ `+import { existsSync } from 'node:fs';+const MARKER = ${JSON.stringify(markerPath)};+const write = (msg) => process.stdout.write(JSON.stringify(msg) + '\\n');+let buffer = '';+process.stdin.setEncoding('utf8');+process.stdin.on('data', (chunk) => {+ buffer += chunk;+ let idx = buffer.indexOf('\\n');+ while (idx !== -1) {+ const line = buffer.slice(0, idx);+ buffer = buffer.slice(idx + 1);+ idx = buffer.indexOf('\\n');+ if (line.trim() === '') continue;+ const msg = JSON.parse(line);+ if (msg.method === 'initialize') {+ write({ jsonrpc: '2.0', id: msg.id, result: { protocolVersion: 1, agentCapabilities: {} } });+ } else if (msg.method === 'session/new') {+ if (existsSync(MARKER)) {+ write({ jsonrpc: '2.0', id: msg.id, result: { sessionId: 'marker-session' } });+ } else {+ write({+ jsonrpc: '2.0',+ id: msg.id,+ error: { code: -32603, message: 'harness not installed' },+ });+ }+ } else if (msg.method === 'session/prompt') {+ write({ jsonrpc: '2.0', id: msg.id, result: { stopReason: 'end_turn' } });+ } else if (msg.id !== undefined) {+ write({ jsonrpc: '2.0', id: msg.id, result: {} });+ }+ }+});+`,+ );+ writeFileSync(+ join(localDir, 'acp-agents.json'),+ JSON.stringify([{ id, name: `Fake ${id}`, command: 'node', args: [agentPath] }]),+ );+}++describe('AcpThreadManager retry', () => {+ test('a failed start retries in place and succeeds once the cause is fixed', async () => {+ const contentDir = tmp();+ const localDir = tmp();+ const marker = join(tmp(), 'installed');+ writeMarkerGatedAgentEntry(localDir, 'gated', marker);++ const manager = makeManager(contentDir, localDir);+ const seen: ThreadEvent[] = [];+ const info = await manager.createThread({ agent: { source: 'custom', id: 'gated' } });+ await manager.subscribe(info.threadId, 0, (frame: ThreadServerFrame) => {+ if (frame.op === 'event') seen.push(frame.event);+ if (frame.op === 'events') seen.push(...frame.events);+ });+ await waitUntil(+ () => manager.getInfo(info.threadId)?.status === 'error',+ 15_000,+ 'the first start to fail',+ );++ // Still broken: the retry has to report the failure it landed on rather+ // than resolve on a thread that is right back where it started.+ await expect(manager.retryThread(info.threadId)).rejects.toThrow(/harness not installed/);+ expect(manager.getInfo(info.threadId)?.status).toBe('error');++ writeFileSync(marker, '');+ const retried = await manager.retryThread(info.threadId);+ expect(retried.status).toBe('ready');+ expect(manager.getInfo(info.threadId)?.status).toBe('ready');++ // The retried thread is a working thread, not just a green status.+ manager.sendPrompt(info.threadId, 'hello');+ await waitUntil(+ () => seen.some((e) => e.kind === 'turn_ended'),+ 15_000,+ 'the first turn to finish',+ );+ expect(manager.getInfo(info.threadId)?.status).toBe('ready');+ }, 60_000);++ test('retrying a thread parked on sign-in replaces the agent it kept alive', async () => {+ const contentDir = tmp();+ const localDir = tmp();+ const marker = join(tmp(), 'signed-in-elsewhere');+ writeSilentAuthAgentEntry(localDir, 'silent-auth-retry', marker);++ const manager = makeManager(contentDir, localDir);+ const info = await manager.createThread({+ agent: { source: 'custom', id: 'silent-auth-retry' },+ });+ await manager.subscribe(info.threadId, 0, () => {});+ await waitUntil(+ () => manager.getInfo(info.threadId)?.status === 'auth_required',+ 15_000,+ 'the sign-in prompt',+ );++ // Unlike every other failure, `auth_required` keeps its process alive so a+ // sign-in costs no respawn — which makes the retry responsible for killing+ // it. A leaked agent here is a real orphan, not a status artifact.+ const original = internals(manager).child(info.threadId);+ expect(original?.pid).toBeGreaterThan(0);++ writeFileSync(marker, '');+ const retried = await manager.retryThread(info.threadId);+ expect(retried.status).toBe('ready');+ expect(internals(manager).child(info.threadId)).not.toBe(original);+ await waitUntil(+ () => original?.exitCode !== null || original?.signalCode !== null,+ 10_000,+ 'the original agent process to die',+ );++ await manager.closeThread(info.threadId);+ }, 40_000);++ test('refuses a thread that started fine', async () => {+ const contentDir = tmp();+ const localDir = tmp();+ writeExampleAgentEntry(localDir);++ const manager = makeManager(contentDir, localDir);+ const info = await manager.createThread({ agent: { source: 'custom', id: 'example' } });+ await manager.subscribe(info.threadId, 0, () => {});+ await waitUntil(() => manager.getInfo(info.threadId)?.status === 'ready', 15_000, 'ready');++ // A live session means a live agent — respawning under it would strand a+ // process whose output the user can still see.+ await expect(manager.retryThread(info.threadId)).rejects.toThrow(/did not fail to start/);+ }, 40_000);++ test('refuses an archived thread — that one resumes, it does not retry', async () => {+ const contentDir = tmp();+ const localDir = tmp();+ writeMarkerGatedAgentEntry(localDir, 'gated-archive', join(tmp(), 'never-written'));++ const manager = makeManager(contentDir, localDir);+ const info = await manager.createThread({ agent: { source: 'custom', id: 'gated-archive' } });+ await manager.subscribe(info.threadId, 0, () => {});+ await waitUntil(+ () => manager.getInfo(info.threadId)?.status === 'error',+ 15_000,+ 'the start to fail',+ );+ // A failed thread archives on close (its transcript is the only record of+ // what went wrong), so the record is still addressable afterwards.+ await manager.closeThread(info.threadId);+ expect(manager.getInfo(info.threadId)?.archived).toBe(true);+ await expect(manager.retryThread(info.threadId)).rejects.toThrow(/archived/);+ }, 40_000);+});++/**+ * Agent that advertises an auth method at `initialize` and then rejects+ * `session/new` with a baked-in JSON-RPC error — the wire shape that decides+ * whether OK reads a failure as "sign in" or as a broken launch.+ */+function writeSessionFailingAgentEntry(+ localDir: string,+ id: string,+ error: { code: number; message: string; data: unknown },+): void {+ const agentPath = join(localDir, `${id}.mjs`);+ writeFileSync(+ agentPath,+ `+const write = (msg) => process.stdout.write(JSON.stringify(msg) + '\\n');+const ERROR = ${JSON.stringify(error)};+const AUTH_METHODS = [{ id: 'test_login', name: 'Test Login', description: 'Sign in via test' }];+let buffer = '';+process.stdin.setEncoding('utf8');+process.stdin.on('data', (chunk) => {+ buffer += chunk;+ let idx = buffer.indexOf('\\n');+ while (idx !== -1) {+ const line = buffer.slice(0, idx);+ buffer = buffer.slice(idx + 1);+ idx = buffer.indexOf('\\n');+ if (line.trim() === '') continue;+ const msg = JSON.parse(line);+ if (msg.method === 'initialize') {+ write({+ jsonrpc: '2.0',+ id: msg.id,+ result: { protocolVersion: 1, agentCapabilities: {}, authMethods: AUTH_METHODS },+ });+ } else if (msg.method === 'session/new') {+ write({ jsonrpc: '2.0', id: msg.id, error: ERROR });+ } else if (msg.id !== undefined) {+ write({ jsonrpc: '2.0', id: msg.id, result: {} });+ }+ }+});+`,+ );+ writeFileSync(+ join(localDir, 'acp-agents.json'),+ JSON.stringify([{ id, name: `Fake ${id}`, command: 'node', args: [agentPath] }]),+ );+}++/**+ * Agent that parks on sign-in and then lets it through: `session/new` fails+ * with the auth code until an `authenticate` for `test_login` arrives, after+ * which it opens a session normally. Advertises one agent-driven method and+ * one `env_var` method so both discriminant shapes cross the wire.+ */+function writeAuthenticatingAgentEntry(localDir: string, id: string): void {+ const agentPath = join(localDir, `${id}.mjs`);+ writeFileSync(+ agentPath,+ `+const write = (msg) => process.stdout.write(JSON.stringify(msg) + '\\n');+const AUTH_METHODS = [+ { id: 'test_login', name: 'Test Login', description: 'Sign in via test' },+ { id: 'test_env', name: 'Env Login', type: 'env_var', vars: [{ name: 'TEST_KEY' }] },+];+let signedIn = false;+let buffer = '';+process.stdin.setEncoding('utf8');+process.stdin.on('data', (chunk) => {+ buffer += chunk;+ let idx = buffer.indexOf('\\n');+ while (idx !== -1) {+ const line = buffer.slice(0, idx);+ buffer = buffer.slice(idx + 1);+ idx = buffer.indexOf('\\n');+ if (line.trim() === '') continue;+ const msg = JSON.parse(line);+ const reply = (result) => write({ jsonrpc: '2.0', id: msg.id, result });+ const fail = (error) => write({ jsonrpc: '2.0', id: msg.id, error });+ if (msg.method === 'initialize') {+ reply({ protocolVersion: 1, agentCapabilities: {}, authMethods: AUTH_METHODS });+ } else if (msg.method === 'authenticate') {+ if (msg.params && msg.params.methodId === 'test_login') {+ signedIn = true;+ reply({});+ } else {+ fail({ code: -32602, message: 'unknown auth method', data: { detail: 'auth' } });+ }+ } else if (msg.method === 'session/new') {+ if (signedIn) reply({ sessionId: 'sess-auth' });+ else fail({ code: -32000, message: 'Authentication required', data: { detail: 'x' } });+ } else if (msg.method === 'session/prompt') {+ write({+ jsonrpc: '2.0',+ method: 'session/update',+ params: {+ sessionId: 'sess-auth',+ update: {+ sessionUpdate: 'agent_message_chunk',+ content: { type: 'text', text: 'pid ' + process.pid },+ },+ },+ });+ reply({ stopReason: 'end_turn' });+ } else if (msg.id !== undefined) {+ reply({});+ }+ }+});+`,+ );+ writeFileSync(+ join(localDir, 'acp-agents.json'),+ JSON.stringify([{ id, name: `Fake ${id}`, command: 'node', args: [agentPath] }]),+ );+}++/**+ * Agent parked on sign-in that NEVER answers `authenticate` — the abandoned+ * browser-tab shape. `session/new` keeps failing with the auth code until+ * `markerPath` exists, so a retry (which respawns) can still reach ready and+ * the recovery paths around an unanswered sign-in are drivable end to end.+ */+function writeSilentAuthAgentEntry(localDir: string, id: string, markerPath: string): void {+ const agentPath = join(localDir, `${id}.mjs`);+ writeFileSync(+ agentPath,+ `+import { existsSync } from 'node:fs';+const MARKER = ${JSON.stringify(markerPath)};+const write = (msg) => process.stdout.write(JSON.stringify(msg) + '\\n');+const AUTH_METHODS = [{ id: 'test_login', name: 'Test Login' }];+let buffer = '';+process.stdin.setEncoding('utf8');+process.stdin.on('data', (chunk) => {+ buffer += chunk;+ let idx = buffer.indexOf('\\n');+ while (idx !== -1) {+ const line = buffer.slice(0, idx);+ buffer = buffer.slice(idx + 1);+ idx = buffer.indexOf('\\n');+ if (line.trim() === '') continue;+ const msg = JSON.parse(line);+ if (msg.method === 'initialize') {+ write({+ jsonrpc: '2.0',+ id: msg.id,+ result: { protocolVersion: 1, agentCapabilities: {}, authMethods: AUTH_METHODS },+ });+ } else if (msg.method === 'authenticate') {+ // No reply, ever: the sign-in went to a browser nobody came back from.+ } else if (msg.method === 'session/new') {+ if (existsSync(MARKER)) {+ write({ jsonrpc: '2.0', id: msg.id, result: { sessionId: 'silent-auth-session' } });+ } else {+ write({+ jsonrpc: '2.0',+ id: msg.id,+ error: { code: -32000, message: 'Authentication required' },+ });+ }+ } else if (msg.method === 'session/prompt') {+ write({ jsonrpc: '2.0', id: msg.id, result: { stopReason: 'end_turn' } });+ } else if (msg.id !== undefined) {+ write({ jsonrpc: '2.0', id: msg.id, result: {} });+ }+ }+});+`,+ );+ writeFileSync(+ join(localDir, 'acp-agents.json'),+ JSON.stringify([{ id, name: `Fake ${id}`, command: 'node', args: [agentPath] }]),+ );+}++describe('AcpThreadManager auth classification', () => {+ type StatusEvent = Extract<ThreadEvent, { kind: 'status' }>;++ const collectStatuses = (into: StatusEvent[]) => (frame: ThreadServerFrame) => {+ const push = (event: ThreadEvent): void => {+ if (event.kind === 'status') into.push(event);+ };+ if (frame.op === 'event') push(frame.event);+ if (frame.op === 'events') for (const event of frame.events) push(event);+ };++ const withStatus = (statuses: StatusEvent[], status: string): StatusEvent | undefined =>+ statuses.find((e) => e.status === status);++ test('an auth-required session/new failure parks on sign-in with the advertised methods', async () => {+ const contentDir = tmp();+ const localDir = tmp();+ writeSessionFailingAgentEntry(localDir, 'auth-agent', {+ code: -32000,+ message: 'Authentication required',+ data: { detail: 'x' },+ });+ const manager = makeManager(contentDir, localDir);+ const statuses: StatusEvent[] = [];+ const info = await manager.createThread({ agent: { source: 'custom', id: 'auth-agent' } });+ await manager.subscribe(info.threadId, 0, collectStatuses(statuses));+ // The broadcast is batched, so the status event lands after the snapshot+ // flips — wait for the event itself, which is what the app renders from.+ await waitUntil(+ () => withStatus(statuses, 'auth_required') !== undefined,+ 15_000,+ `auth_required; got ${JSON.stringify(statuses.map((e) => e.status))}`,+ );+ expect(manager.getInfo(info.threadId)?.status).toBe('auth_required');++ const event = withStatus(statuses, 'auth_required');+ expect(event?.failure?.reason).toBe('auth-required');+ expect(event?.failure?.authMethods).toEqual([+ { id: 'test_login', name: 'Test Login', description: 'Sign in via test' },+ ]);+ expect(event?.failure?.agentMessage).toBe('Authentication required');+ expect(event?.failure?.machineDetail).toContain('"detail":"x"');+ // The wire payload belongs in the disclosure, never in the headline the+ // user reads first.+ expect(event?.detail ?? '').not.toContain('"detail":"x"');++ await manager.closeThread(info.threadId);+ }, 30_000);++ test('a non-auth session/new failure is an error, not a sign-in prompt, and kills the agent', async () => {+ const contentDir = tmp();+ const localDir = tmp();+ writeSessionFailingAgentEntry(localDir, 'broken-agent', {+ code: -32603,+ message: 'Failed to initialize session services',+ data: { cause: 'services' },+ });+ const manager = makeManager(contentDir, localDir);+ const statuses: StatusEvent[] = [];+ const info = await manager.createThread({ agent: { source: 'custom', id: 'broken-agent' } });+ await manager.subscribe(info.threadId, 0, collectStatuses(statuses));+ await waitUntil(+ () => withStatus(statuses, 'error') !== undefined,+ 15_000,+ `error; got ${JSON.stringify(statuses.map((e) => e.status))}`,+ );+ expect(manager.getInfo(info.threadId)?.status).toBe('error');++ // An agent that advertises auth methods used to make every session failure+ // look like a sign-in prompt — the classification now comes from the error+ // code alone.+ expect(withStatus(statuses, 'auth_required')).toBeUndefined();+ const event = withStatus(statuses, 'error');+ expect(event?.failure?.reason).toBe('session-setup');+ expect(event?.failure?.agentMessage).toBe('Failed to initialize session services');+ expect(event?.failure?.machineDetail).toContain('"cause":"services"');++ // A session that never opened leaves the process nothing to do.+ await waitUntil(+ () => internals(manager).child(info.threadId) === null,+ 10_000,+ 'agent child torn down',+ );++ await manager.closeThread(info.threadId);+ }, 30_000);++ test('closing a failed thread archives it instead of erasing its evidence', async () => {+ const contentDir = tmp();+ const localDir = tmp();+ writeSessionFailingAgentEntry(localDir, 'broken-agent', {+ code: -32603,+ message: 'Failed to initialize session services',+ data: { cause: 'services' },+ });+ const manager = makeManager(contentDir, localDir);+ // init() creates the threads dir the archive's meta write lands in.+ await manager.init();+ const info = await manager.createThread({ agent: { source: 'custom', id: 'broken-agent' } });+ await manager.subscribe(info.threadId, 0, () => {});+ await waitUntil(() => manager.getInfo(info.threadId)?.status === 'error', 15_000, 'error');++ // The thread never took a user message (the composer is disabled on a+ // failed start), so the empty-thread discard used to delete the only+ // record of what went wrong.+ await manager.closeThread(info.threadId);+ expect(manager.getInfo(info.threadId)).toBeDefined();+ expect(manager.getInfo(info.threadId)?.archived).toBe(true);+ }, 30_000);++ test('signing in re-opens the session on the same agent process', async () => {+ const contentDir = tmp();+ const localDir = tmp();+ writeAuthenticatingAgentEntry(localDir, 'signin-agent');+ const manager = makeManager(contentDir, localDir);+ const statuses: StatusEvent[] = [];+ const info = await manager.createThread({ agent: { source: 'custom', id: 'signin-agent' } });+ await manager.subscribe(info.threadId, 0, collectStatuses(statuses));+ await waitUntil(+ () => withStatus(statuses, 'auth_required') !== undefined,+ 15_000,+ `auth_required; got ${JSON.stringify(statuses.map((e) => e.status))}`,+ );+ // The SDK's discriminant rides the wire: the client has to tell a sign-in+ // it can drive from one that needs the user's own environment.+ expect(withStatus(statuses, 'auth_required')?.failure?.authMethods).toEqual([+ { id: 'test_login', name: 'Test Login', description: 'Sign in via test' },+ { id: 'test_env', name: 'Env Login', kind: 'env_var' },+ ]);++ // The child's identity IS the assertion: a thread parked on sign-in keeps+ // its agent alive precisely so authenticating costs no respawn.+ const child = internals(manager).child(info.threadId);+ expect(child).toBeDefined();++ const signedIn = await manager.authenticateThread(info.threadId, 'test_login');+ expect(signedIn.status).toBe('ready');+ expect(manager.getInfo(info.threadId)?.status).toBe('ready');+ expect(internals(manager).child(info.threadId)).toBe(child);++ // …and the session that opened behind the sign-in takes a real turn.+ manager.sendPrompt(info.threadId, 'hello');+ await waitUntil(() => internals(manager).turnActive(info.threadId), 5_000, 'turn active');+ await waitUntil(() => !internals(manager).turnActive(info.threadId), 10_000, 'turn ended');++ await manager.closeThread(info.threadId);+ }, 30_000);++ test('a rejected sign-in parks the thread back on sign-in with a fresh notice', async () => {+ const contentDir = tmp();+ const localDir = tmp();+ writeAuthenticatingAgentEntry(localDir, 'signin-agent');+ const manager = makeManager(contentDir, localDir);+ const statuses: StatusEvent[] = [];+ const info = await manager.createThread({ agent: { source: 'custom', id: 'signin-agent' } });+ await manager.subscribe(info.threadId, 0, collectStatuses(statuses));+ const authNotices = (): StatusEvent[] => statuses.filter((e) => e.status === 'auth_required');+ await waitUntil(() => authNotices().length > 0, 15_000, 'auth_required');++ await expect(manager.authenticateThread(info.threadId, 'not_a_method')).rejects.toThrow(+ /unknown auth method/,+ );+ expect(manager.getInfo(info.threadId)?.status).toBe('auth_required');+ // A refused sign-in is an answer the user can act on again, so it leaves+ // its own notice — with the methods still offered.+ await waitUntil(() => authNotices().length > 1, 10_000, 'a second sign-in notice');+ const latest = authNotices().at(-1);+ expect(latest?.failure?.reason).toBe('auth-required');+ expect(latest?.failure?.agentMessage).toBe('unknown auth method');+ expect(latest?.failure?.authMethods?.map((m) => m.id)).toEqual(['test_login', 'test_env']);++ await manager.closeThread(info.threadId);+ }, 30_000);++ test('signing in a thread that never asked for one is refused', async () => {+ const contentDir = tmp();+ const localDir = tmp();+ writeAuthenticatingAgentEntry(localDir, 'signin-agent');+ const manager = makeManager(contentDir, localDir);+ const statuses: StatusEvent[] = [];+ const info = await manager.createThread({ agent: { source: 'custom', id: 'signin-agent' } });+ await manager.subscribe(info.threadId, 0, collectStatuses(statuses));+ await waitUntil(() => withStatus(statuses, 'auth_required') !== undefined, 15_000, 'auth');+ await manager.authenticateThread(info.threadId, 'test_login');++ await expect(manager.authenticateThread(info.threadId, 'test_login')).rejects.toThrow(+ /not waiting for a sign-in/,+ );++ await manager.closeThread(info.threadId);+ }, 30_000);++ test('an unanswered sign-in gives up on its own and leaves the thread usable', async () => {+ const contentDir = tmp();+ const localDir = tmp();+ const marker = join(tmp(), 'signed-in-elsewhere');+ writeSilentAuthAgentEntry(localDir, 'silent-auth', marker);+ const manager = makeManager(contentDir, localDir, { authenticateTimeoutMs: 200 });+ const statuses: StatusEvent[] = [];+ const info = await manager.createThread({ agent: { source: 'custom', id: 'silent-auth' } });+ await manager.subscribe(info.threadId, 0, collectStatuses(statuses));+ await waitUntil(() => withStatus(statuses, 'auth_required') !== undefined, 15_000, 'auth');++ // ACP puts no ceiling on `authenticate`; without one of our own an+ // abandoned browser flow held the thread's latch forever.+ await expect(manager.authenticateThread(info.threadId, 'test_login')).rejects.toThrow(+ /didn't complete in time/,+ );+ expect(manager.getInfo(info.threadId)?.status).toBe('auth_required');+ const latest = statuses.filter((e) => e.status === 'auth_required').at(-1);+ expect(latest?.failure?.authMethods?.map((m) => m.id)).toEqual(['test_login']);++ // …and the thread still takes a retry, which is the way out of it.+ writeFileSync(marker, '');+ const retried = await manager.retryThread(info.threadId);+ expect(retried.status).toBe('ready');++ const events: ThreadEvent[] = [];+ await manager.subscribe(info.threadId, 0, (frame: ThreadServerFrame) => {+ if (frame.op === 'event') events.push(frame.event);+ if (frame.op === 'events') events.push(...frame.events);+ });+ manager.sendPrompt(info.threadId, 'hello');+ await waitUntil(() => events.some((e) => e.kind === 'turn_ended'), 15_000, 'a completed turn');++ await manager.closeThread(info.threadId);+ }, 40_000);++ test('a retry breaks an in-flight sign-in and owns the thread afterwards', async () => {+ const contentDir = tmp();+ const localDir = tmp();+ const marker = join(tmp(), 'signed-in-elsewhere');+ writeSilentAuthAgentEntry(localDir, 'silent-auth', marker);+ // No authenticate timeout worth waiting for — the retry is what ends it.+ const manager = makeManager(contentDir, localDir);+ const statuses: StatusEvent[] = [];+ const info = await manager.createThread({ agent: { source: 'custom', id: 'silent-auth' } });+ await manager.subscribe(info.threadId, 0, collectStatuses(statuses));+ await waitUntil(() => withStatus(statuses, 'auth_required') !== undefined, 15_000, 'auth');++ const authNoticesBeforeRetry = statuses.filter((e) => e.status === 'auth_required').length;+ // Captured as a settled value, not left dangling: the retry rejects it and+ // an unobserved rejection would fail the run.+ const signIn = manager+ .authenticateThread(info.threadId, 'test_login')+ .then(() => null)+ .catch((err: unknown) => err);+ expect(manager.getInfo(info.threadId)?.status).toBe('installing');++ writeFileSync(marker, '');+ const retried = await manager.retryThread(info.threadId);+ expect(retried.status).toBe('ready');++ // The sign-in stands down without a word — its own failure notice would+ // otherwise overwrite the ready state the retry just established.+ expect(String(await signIn)).toMatch(/restarted/);+ expect(manager.getInfo(info.threadId)?.status).toBe('ready');+ await waitUntil(+ () => statuses.at(-1)?.status === 'ready',+ 10_000,+ `ready to be the last status event; got ${JSON.stringify(statuses.map((e) => e.status))}`,+ );+ expect(statuses.filter((e) => e.status === 'auth_required').length).toBe(+ authNoticesBeforeRetry,+ );++ await manager.closeThread(info.threadId);+ }, 40_000);+});diff --git a/packages/server/src/acp/thread-manager.ts b/packages/server/src/acp/thread-manager.tsindex 2206658e5..18640eb3c 100644--- a/packages/server/src/acp/thread-manager.ts+++ b/packages/server/src/acp/thread-manager.ts@@ -52,8 +52,11 @@ import {} from '@inkeep/open-knowledge-core';import type {QueuedMessage,+ SteerMessage,ThreadAgentInfo,+ ThreadAuthMethod,ThreadEvent,+ ThreadFailureDetail,ThreadInfo,ThreadServerFrame,ThreadStatus,@@ -83,7 +86,10 @@ import {terminateAgentTree,withLoginShellPath,} from './launch.ts';-import { getSharedLoginShellPathProvider } from './login-shell-path.ts';+import {+ getSharedLoginShellPathProvider,+ resetSharedLoginShellPathProvider,+} from './login-shell-path.ts';import {cleanupManagedRuntimeStaging,describeRuntime,@@ -141,6 +147,21 @@ const REPLAY_CHUNK_SIZE = 512;*/const DEFAULT_UNWATCHED_TURN_CANCEL_MS = 10 * 60 * 1000;const DEFAULT_UNWATCHED_TURN_KILL_MS = 20 * 60 * 1000;+/**+ * How long a parked steer waits for the agent to honor the cancel before it+ * gives up on jumping the line. ACP has no steering primitive — `session/cancel`+ * is a request, and an agent that ignores it would otherwise leave the+ * correction parked forever. On expiry it demotes to the front of the queue,+ * which is honest about what actually happens next.+ */+const DEFAULT_STEER_STALL_MS = 10_000;+/**+ * Ceiling on the ACP `authenticate` round trip. The call is unbounded by+ * protocol and an agent-driven sign-in usually detours through a browser —+ * an abandoned OAuth tab would otherwise leave the request pending forever,+ * and with it the latch that keeps the thread from taking prompts.+ */+const DEFAULT_AUTHENTICATE_TIMEOUT_MS = 5 * 60 * 1000;const STDERR_TAIL_LINES = 40;/*** `session/load` replays history BEFORE its response resolves per protocol,@@ -151,6 +172,14 @@ const STDERR_TAIL_LINES = 40;*/const RESUME_REPLAY_QUIESCENCE_MS = 300;const RESUME_REPLAY_MAX_WAIT_MS = 3_000;+/**+ * JSON-RPC code of the SDK's `RequestError.authRequired()`. The ONLY signal+ * that a `session/new` failure is an auth failure — an agent advertising+ * `authMethods` at initialize is a static fact about the agent, not about+ * this error, and branching on it labeled every Cursor/Gemini failure+ * (including their internal -32603s) as "sign in first".+ */+const AUTH_REQUIRED_CODE = -32000;export class ThreadOpError extends Error {readonly code:@@ -168,6 +197,19 @@ export class ThreadOpError extends Error {}}+/** The bounded `authenticate` round trip ran out of time. Internal marker. */+class AuthenticateTimeoutError extends Error {+ constructor() {+ super('authenticate timed out');+ this.name = 'AuthenticateTimeoutError';+ }+}++/** A retry took the thread over mid-sign-in; the sign-in stands down silently. */+function threadRestartedDuringSignIn(): ThreadOpError {+ return new ThreadOpError('not-ready', 'the thread was restarted during the sign-in');+}+type Subscriber = (frame: ThreadServerFrame) => void;interface ThreadRecord {@@ -176,10 +218,26 @@ interface ThreadRecord {docName?: string;/** Agent reference used to launch — and re-launch on resume. */agentRef: { source: 'registry' | 'custom'; id: string };+ /**+ * The remembered settings the create frame carried. Every path that opens a+ * session for this thread AFTER the first attempt (retry, post-`authenticate`+ * re-open) replays them, so a recovered session lands on the user's chosen+ * model/mode exactly like a first launch. Not persisted: a resumed session+ * already carries the settings it was opened with.+ */+ launchSettings?: { config?: Record<string, string | boolean>; modeId?: string };/** Session cwd — agents key their session stores by it; resume passes it back verbatim. */cwd: string;child: ChildProcess | null;conn: ClientConnection | null;+ /**+ * The live connection's `initialize` response. Kept because a thread parked+ * in `auth_required` re-opens its session on the SAME connection after+ * `authenticate`, and that needs the capabilities (MCP transport) and the+ * advertised auth methods again. Never persisted — it describes one+ * process, and dies with it.+ */+ lastInit: InitializeResponse | null;sessionId: string | null;/** Writer id for CRDT attribution — `acp-<uuid>`, AGENT_ID_RE-safe. */agentSessionId: string;@@ -192,6 +250,12 @@ interface ThreadRecord {/** The persisted log ends inside a turn (crash mid-stream) — resume appends a synthetic `turn_ended`. */midTurnOnDisk: boolean;resumeInFlight: boolean;+ /**+ * An `authenticate` round trip is open. Deliberately NOT `resumeInFlight`:+ * that latch also gates `retryThread`, and retry is the one operation that+ * must still work while a sign-in the user walked away from is parked.+ */+ authInFlight: boolean;/** Drop incoming `session_update`s (a `session/load` replay duplicating the retained log). */suppressUpdates: boolean;lastSuppressedAt: number;@@ -217,6 +281,8 @@ interface ThreadRecord {* rejection then reads as "cancelled", not an agent error (agents SHOULD* resolve with stopReason 'cancelled', but some abort the request). */cancelRequested: boolean;+ /** Countdown on a parked `info.steer` — fires only if the agent never stops. */+ steerStallTimer: ReturnType<typeof setTimeout> | null;/** Since when the thread has had zero subscribers; null while watched. */unwatchedSince: number | null;/** The unwatched-turn backstop already sent its cancel for this stretch. */@@ -335,6 +401,10 @@ export interface AcpThreadManagerOptions {log: PinoLogger;maxThreads?: number;idleReapMs?: number;+ /** How long a parked steer waits for the cancel to land before demoting to the queue. */+ steerStallMs?: number;+ /** Ceiling on one ACP `authenticate` round trip before the sign-in gives up. */+ authenticateTimeoutMs?: number;/** Unwatched-mid-turn backstop: politely cancel after this long with zero subscribers. */unwatchedTurnCancelMs?: number;/** …and force-close the thread if the turn is STILL running after this long. */@@ -363,6 +433,8 @@ export class AcpThreadManager {private readonly reapTimer: ReturnType<typeof setInterval>;private readonly maxThreads: number;private readonly idleReapMs: number;+ private readonly steerStallMs: number;+ private readonly authenticateTimeoutMs: number;private readonly unwatchedTurnCancelMs: number;private readonly unwatchedTurnKillMs: number;private readonly persistence: ThreadPersistenceStore;@@ -372,10 +444,15 @@ export class AcpThreadManager {constructor(opts: AcpThreadManagerOptions) {this.opts = opts;+ // Looked up per call rather than captured: `retryThread` drops the+ // process-wide memo so a binary installed since the failure is seen, and a+ // captured provider would keep answering from the pre-install capture.this.resolveLoginShellPath =- opts.resolveLoginShellPath ?? getSharedLoginShellPathProvider(opts.log);+ opts.resolveLoginShellPath ?? (() => getSharedLoginShellPathProvider(opts.log)());this.maxThreads = opts.maxThreads ?? MAX_ACP_THREADS;this.idleReapMs = opts.idleReapMs ?? DEFAULT_IDLE_REAP_MS;+ this.steerStallMs = opts.steerStallMs ?? DEFAULT_STEER_STALL_MS;+ this.authenticateTimeoutMs = opts.authenticateTimeoutMs ?? DEFAULT_AUTHENTICATE_TIMEOUT_MS;this.unwatchedTurnCancelMs = opts.unwatchedTurnCancelMs ?? DEFAULT_UNWATCHED_TURN_CANCEL_MS;this.unwatchedTurnKillMs = opts.unwatchedTurnKillMs ?? DEFAULT_UNWATCHED_TURN_KILL_MS;this.persistence = new ThreadPersistenceStore({@@ -400,6 +477,12 @@ export class AcpThreadManager {async init(): Promise<void> {if (this.initialized) return;this.initialized = true;+ // Warm the login-shell PATH capture off the launch path — every launch+ // merges its answer into the spawn env, and the probe costs a shell+ // startup (bounded, but seconds on a heavy profile).+ void this.resolveLoginShellPath().catch(() => {+ // No verdict is a normal outcome; the launch chain asks again.+ });await this.persistence.init();const metas = await this.persistence.scan();for (const meta of metas) {@@ -545,9 +628,11 @@ export class AcpThreadManager {},docName: params.docName,agentRef: { source: params.agent.source, id: params.agent.id },+ launchSettings: params.settings,cwd: this.opts.contentDir,child: null,conn: null,+ lastInit: null,sessionId: null,agentSessionId: `acp-${threadId}`,events: [],@@ -556,6 +641,7 @@ export class AcpThreadManager {logResolution: null,midTurnOnDisk: false,resumeInFlight: false,+ authInFlight: false,suppressUpdates: false,lastSuppressedAt: 0,subscribers: new Set(),@@ -565,6 +651,7 @@ export class AcpThreadManager {terminals: null,turnActive: false,cancelRequested: false,+ steerStallTimer: null,// Born unwatched — the creating socket subscribes right after `created`.unwatchedSince: now,unwatchedCancelSent: false,@@ -616,7 +703,13 @@ export class AcpThreadManager {throw new ThreadOpError('unknown-agent', `agent '${agent.id}' is not in the registry`);}return {- info: { id: manifest.id, name: manifest.name, iconUrl: manifest.icon, source: 'registry' },+ info: {+ id: manifest.id,+ name: manifest.name,+ iconUrl: manifest.icon,+ source: 'registry',+ version: manifest.version,+ },custom: null,};}@@ -652,9 +745,28 @@ export class AcpThreadManager {launch = launchable;if (record.closed) return null;+ // Resolved before the spawn because `terminal/create` answers the agent+ // synchronously — the set needs the value in hand at construction.+ const loginShellPath = await this.resolveLoginShellPath().catch(() => null);+ if (record.closed) return null;++ // Fresh per spawn: a resume/retry respawns the agent, and terminals from+ // the previous process are dead by construction (disposed on its exit).+ // Built BEFORE the child handlers so the exit handler can dispose THIS+ // spawn's set: a fast retry replaces `record.terminals` while the old+ // child is still dying, and a handler reading the field would then dispose+ // the new agent's live terminals on the old agent's exit.+ const terminals = new AcpTerminalSet({+ defaultCwd: record.cwd,+ emit: (event) => this.appendEvent(record, event),+ log: this.opts.log,+ loginShellPath,+ });+this.emitStatus(record, 'spawning');const child = spawnAcpAgent(launch, record.cwd);record.child = child;+ record.terminals = terminals;child.stderr?.setEncoding('utf8');child.stderr?.on('data', (chunk: string) => {@@ -665,23 +777,36 @@ export class AcpThreadManager {}});child.on('error', (err) => {- this.emitStatus(record, 'error', `agent failed to start: ${err.message}`);+ this.emitStatus(record, 'error', `agent failed to start: ${err.message}`, {+ reason: 'connect',+ agentMessage: err.message,+ });});child.on('exit', (code, signal) => {record.child = null;// Commands the agent asked OK to run die with the agent — nothing// should keep executing for a conversation that can no longer see it.- record.terminals?.disposeAll().catch((err: unknown) => {+ terminals.disposeAll().catch((err: unknown) => {this.opts.log.warn({ err, threadId: record.info.threadId },'[acp-threads] terminal cleanup on agent exit failed',);});if (record.closed || record.info.archived === true) return;+ // A thread already in 'error' reported its failure (with the stderr+ // tail attached) — the process dying afterwards, whether by itself or+ // via the failed-startup teardown, is that failure's echo, not news.+ // The prompts parked on the dead process are still owed an answer,+ // though: without this an agent that died holding a permission request+ // leaves it hanging until the 10-minute timeout.+ if (record.info.status === 'error') {+ this.failPendingPermissions(record);+ return;+ }const tail = record.stderrTail.slice(-10).join('\n');this.emitStatus(record,- record.info.status === 'error' ? 'error' : 'exited',+ 'exited',`agent exited (${signal ?? code ?? 'unknown'})${tail ? `\n${tail}` : ''}`,);this.failPendingPermissions(record);@@ -695,15 +820,6 @@ export class AcpThreadManager {Readable.toWeb(child.stdout) as unknown as ReadableStream<Uint8Array>,);- // Fresh per spawn: a resume respawns the agent, and terminals from the- // previous process are dead by construction (disposed on its exit).- const terminals = new AcpTerminalSet({- defaultCwd: record.cwd,- emit: (event) => this.appendEvent(record, event),- log: this.opts.log,- });- record.terminals = terminals;-const conn = acpClient({ name: 'open-knowledge' }).onRequest(acpMethods.client.session.requestPermission, (ctx) =>this.handlePermissionRequest(record, ctx.params.toolCall, ctx.params.options),@@ -783,9 +899,14 @@ export class AcpThreadManager {},});} catch (err) {- throw new ThreadOpError('spawn-failed', `initialize failed: ${describeAgentError(err)}`);+ this.opts.log.warn(+ { err, threadId: record.info.threadId },+ '[acp-threads] initialize failed',+ );+ throw new ThreadOpError('spawn-failed', `initialize failed: ${agentErrorMessage(err)}`);}if (record.closed) return null;+ record.lastInit = init;return { conn, init, launch };}@@ -803,7 +924,13 @@ export class AcpThreadManager {): Promise<ResolvedLaunch | null> {try {await preflightLaunch(launch);- return launch;+ // Preflight only proves the TOP-LEVEL command resolves. The adapter goes+ // on to spawn the real harness itself (`npx pi-acp` spawns `pi`), and+ // that lookup runs against the env we hand it — so a launch that+ // preflighted still needs the login shell's PATH, not just one that+ // failed. The merge is append-only: it can add resolutions, never+ // redirect a command that already resolved to a different binary.+ return await this.withLoginShellPathIfEligible(launch);} catch (err) {if (!(err instanceof AgentLaunchError) || err.code !== 'command-not-found') throw err;// A terminal would have found it: adopt the login shell's PATH rather@@ -832,10 +959,7 @@ export class AcpThreadManager {* the command — in which case the caller carries on to the managed runtime.*/private async retryWithLoginShellPath(launch: ResolvedLaunch): Promise<ResolvedLaunch | null> {- if (launch.pathFromOverlay || isPathQualified(launch.cmd)) return null;- const loginShellPath = await this.resolveLoginShellPath().catch(() => null);- if (loginShellPath === null) return null;- const retry = withLoginShellPath(launch, loginShellPath);+ const retry = await this.withLoginShellPathIfEligible(launch);if (envPath(retry.env) === envPath(launch.env)) return null;try {await preflightLaunch(retry);@@ -859,6 +983,20 @@ export class AcpThreadManager {return retry;}+ /**+ * Append the login shell's PATH to a launch's env, or return it untouched+ * when the fallback doesn't apply: a manifest/custom-agent PATH overlay is a+ * spawn-env contract that wins verbatim, and a path-qualified command names+ * its own location, so neither is ours to extend. A probe with no verdict+ * (Windows, no `$SHELL`, a hung profile) also changes nothing.+ */+ private async withLoginShellPathIfEligible(launch: ResolvedLaunch): Promise<ResolvedLaunch> {+ if (launch.pathFromOverlay || isPathQualified(launch.cmd)) return launch;+ const loginShellPath = await this.resolveLoginShellPath().catch(() => null);+ if (loginShellPath === null) return launch;+ return withLoginShellPath(launch, loginShellPath);+ }+/*** Return a managed runtime for `runtimeKind`, downloading it if the user* consents. Null means the thread closed while we waited; a throw means the@@ -1092,12 +1230,54 @@ export class AcpThreadManager {} catch (err) {const detail =err instanceof AgentLaunchError || err instanceof ThreadOpError ? err.message : String(err);- this.emitStatus(record, 'error', detail);+ this.emitStatus(record, 'error', detail, {+ reason: 'connect',+ agentMessage: detail,+ machineDetail: stderrTailDetail(record),+ });+ // Awaited, not fire-and-forget: a retry issued while the old process is+ // still inside its kill grace would find `child` already nulled and+ // no-op its own teardown, leaving two agents alive for one thread.+ await this.teardownFailedAgent(record);return;}if (handshake === null) return;const { conn, init, launch } = handshake;+ if (!(await this.openSession(record, conn, init, params.settings))) return;+ // Startup latency is a known UX sore point (npx resolution + node boot ++ // handshake, serialized) — keep it measurable per launch kind.+ this.opts.log.info(+ {+ threadId: record.info.threadId,+ agentId: record.info.agent.id,+ launchKind: launch.kind,+ msToReady: Date.now() - record.info.createdAt,+ },+ '[acp-threads] agent ready',+ );++ if (params.prompt !== undefined && params.prompt !== '') {+ this.sendPrompt(record.info.threadId, params.prompt);+ }+ }++ /**+ * Open the agent session on an already-initialized connection: `session/new`,+ * the remembered launch settings, then `ready`. Shared by the first start+ * and by the post-`authenticate` second attempt, which re-runs exactly this+ * sequence on the connection it already holds.+ *+ * Outcomes are reported as status events rather than thrown; the boolean+ * says only whether the thread reached `ready` (false also covers a thread+ * closed mid-flight).+ */+ private async openSession(+ record: ThreadRecord,+ conn: ClientConnection,+ init: InitializeResponse,+ settings?: { config?: Record<string, string | boolean>; modeId?: string },+ ): Promise<boolean> {const mcpServers = await this.buildMcpServers(record, init);try {const session = await conn.agent.request(acpMethods.agent.session.new, {@@ -1115,50 +1295,46 @@ export class AcpThreadManager {this.emitInfo(record);}} catch (err) {- const authMethods = (init.authMethods ?? [])- .map((m) => (typeof m === 'object' && m !== null ? (m as { name?: string }).name : null))- .filter((n): n is string => typeof n === 'string');- if (authMethods.length > 0) {- this.emitStatus(- record,- 'auth_required',- `sign in first (${authMethods.join(' / ')}), then start a new thread — ${describeAgentError(err)}`,- );+ const machineDetail = joinMachineDetail(agentErrorData(err), stderrTailDetail(record));+ if (isAuthRequiredError(err)) {+ this.emitStatus(record, 'auth_required', `sign in required: ${agentErrorMessage(err)}`, {+ reason: 'auth-required',+ agentMessage: agentErrorMessage(err),+ machineDetail,+ authMethods: threadAuthMethods(init.authMethods),+ });+ // The child stays alive on purpose: the connection is initialized and+ // can take `authenticate` + a session/new retry without a respawn.} else {- this.emitStatus(record, 'error', `session setup failed: ${describeAgentError(err)}`);+ this.emitStatus(record, 'error', `session setup failed: ${agentErrorMessage(err)}`, {+ reason: 'session-setup',+ agentMessage: agentErrorMessage(err),+ machineDetail,+ });+ // A session that never opened leaves nothing for the process to do —+ // without this it idles until the reaper, holding a live-thread slot.+ // Awaited so a retry can't spawn a second agent alongside this one+ // while it is still inside its kill grace.+ await this.teardownFailedAgent(record);}- return;+ return false;}- if (record.closed) return;+ if (record.closed) return false;- if (params.settings?.config !== undefined) {- await this.applyInitialConfig(record, conn, params.settings.config);- if (record.closed) return;+ if (settings?.config !== undefined) {+ await this.applyInitialConfig(record, conn, settings.config);+ if (record.closed) return false;}- if (params.settings?.modeId !== undefined) {+ if (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;+ await this.applyInitialMode(record, conn, settings.modeId);+ if (record.closed) return false;}this.setPresence(record, 'idle');this.emitStatus(record, 'ready');- // Startup latency is a known UX sore point (npx resolution + node boot +- // handshake, serialized) — keep it measurable per launch kind.- this.opts.log.info(- {- threadId: record.info.threadId,- agentId: record.info.agent.id,- launchKind: launch.kind,- msToReady: Date.now() - record.info.createdAt,- },- '[acp-threads] agent ready',- );-- if (params.prompt !== undefined && params.prompt !== '') {- this.sendPrompt(record.info.threadId, params.prompt);- }+ return true;}/**@@ -1294,9 +1470,10 @@ export class AcpThreadManager {// A rejected session/load|resume (unknown or expired sessionId, cwd// mismatch) — expected at steady state: agents expire their own// session stores (Claude defaults to 30 days).+ this.opts.log.warn({ err, threadId }, '[acp-threads] resume rejected by the agent');throw new ThreadOpError('resume-unsupported',- `couldn't resume the previous session: ${describeAgentError(err)}`,+ `couldn't resume the previous session: ${agentErrorMessage(err)}`,);}} finally {@@ -1304,6 +1481,183 @@ export class AcpThreadManager {}}+ /**+ * Start a failed thread over in place: same thread, same transcript, a fresh+ * launch. Confined to threads that never opened an agent session — one that+ * did has a live agent, and respawning under it would strand a process the+ * user can still see the output of.+ *+ * Retry is also the moment a stale environment answer stops being free: the+ * user reads "install Node", installs it, and comes back. So the login-shell+ * PATH memo is dropped first, and the agent manifest is re-resolved rather+ * than reused. Dropping that memo is process-global and deliberate: every+ * other thread and probe pays one fresh login-shell startup afterwards,+ * which is the right trade for the retry seeing what the user just installed.+ *+ * Resolves once the thread reaches `ready`; rejects with the failure the+ * retry landed on, so the caller can say why the second attempt failed too.+ */+ async retryThread(threadId: string): Promise<ThreadInfo> {+ if (this.destroyed) throw new ThreadOpError('capacity', 'server is shutting down');+ const t = this.mustGet(threadId);+ if (t.info.archived === true) {+ throw new ThreadOpError('not-ready', 'the thread is archived — resume it instead');+ }+ // `authInFlight` is a retryable state of its own: a sign-in the user+ // abandoned in a browser tab shows as `installing`, and retry is the only+ // way out of it. Breaking that latch is safe — closing the connection+ // rejects the parked request, and `authenticateThread` stands down when it+ // sees the connection it captured is no longer the record's.+ if (t.info.status !== 'error' && t.info.status !== 'auth_required' && !t.authInFlight) {+ throw new ThreadOpError('not-ready', 'this thread did not fail to start');+ }+ if (t.sessionId !== null) {+ throw new ThreadOpError('not-ready', 'this thread already has an agent session');+ }+ if (t.resumeInFlight) {+ throw new ThreadOpError('not-ready', 'a retry is already in progress');+ }+ t.resumeInFlight = true;+ try {+ resetSharedLoginShellPathProvider();+ // Before anything is torn down: an unknown agent (or an unreachable+ // registry) must reject the retry outright rather than leave the thread+ // half-dismantled.+ const { info: agentInfo, custom } = await this.resolveAgentInfo(t.agentRef);+ // `auth_required` keeps its child alive on purpose (the connection can+ // take an `authenticate` without a respawn) — a retry replaces it.+ await this.teardownFailedAgent(t);+ t.info.agent = agentInfo;+ t.stderrTail = [];+ t.cancelRequested = false;+ t.turnActive = false;+ this.emitStatus(t, 'installing');+ try {+ await this.startThread(t, { agent: t.agentRef, settings: t.launchSettings }, custom);+ } catch (err) {+ const detail = err instanceof Error ? err.message : String(err);+ this.emitStatus(t, 'error', detail, { reason: 'connect', agentMessage: detail });+ throw new ThreadOpError('spawn-failed', detail);+ }+ if (t.closed) throw new ThreadOpError('not-ready', 'thread closed during retry');+ // `startThread` reports every outcome as a status event rather than a+ // throw, so the settled status is what says whether this worked.+ const settled = this.getInfo(threadId)?.status;+ if (settled === 'ready' || settled === 'running') {+ this.opts.log.info(+ { threadId, agentId: t.info.agent.id },+ '[acp-threads] thread retry succeeded',+ );+ return { ...t.info };+ }+ throw new ThreadOpError('spawn-failed', lastFailureMessage(t) ?? 'the agent failed to start');+ } finally {+ t.resumeInFlight = false;+ }+ }++ /**+ * Complete an advertised sign-in on a thread parked in `auth_required`, then+ * re-open the session on the SAME connection. The child was kept alive for+ * exactly this: an initialized connection takes `authenticate` plus a second+ * `session/new` without a respawn, so signing in costs the user nothing but+ * the round trip.+ *+ * Resolves once the thread is ready; rejects with whatever the sign-in — or+ * the session that followed it — failed on. A thread whose process is gone+ * has nothing to authenticate against and is sent to Retry instead.+ */+ async authenticateThread(threadId: string, methodId: string): Promise<ThreadInfo> {+ if (this.destroyed) throw new ThreadOpError('capacity', 'server is shutting down');+ const t = this.mustGet(threadId);+ if (t.info.archived === true) {+ throw new ThreadOpError('not-ready', 'the thread is archived — resume it instead');+ }+ if (t.info.status !== 'auth_required') {+ throw new ThreadOpError('not-ready', 'this thread is not waiting for a sign-in');+ }+ const conn = t.conn;+ const init = t.lastInit;+ if (conn === null || init === null || t.child === null) {+ throw new ThreadOpError(+ 'not-ready',+ `${t.info.agent.name} is no longer running — use Retry to start it again`,+ );+ }+ if (t.resumeInFlight) {+ throw new ThreadOpError('not-ready', 'the thread is starting over — wait for the retry');+ }+ if (t.authInFlight) {+ throw new ThreadOpError('not-ready', 'a sign-in is already in progress');+ }+ t.authInFlight = true;+ try {+ // There is no sign-in status of its own; `installing` is the progress+ // signal every client already renders as "the agent is on its way".+ this.emitStatus(t, 'installing');+ try {+ await this.requestAuthenticate(conn, methodId);+ } catch (err) {+ // A retry that ran while this sign-in was parked closed the connection+ // (which is what rejected the request) and now owns the thread — its+ // status is the live one, so this path must say nothing at all.+ if (t.conn !== conn) throw threadRestartedDuringSignIn();+ const timedOut = err instanceof AuthenticateTimeoutError;+ const message = timedOut+ ? `the sign-in didn't complete in time — try again`+ : agentErrorMessage(err);+ // Back to where the user was, with the methods still offered — a+ // rejected (or abandoned) sign-in is a retryable answer, not a dead+ // thread.+ this.emitStatus(t, 'auth_required', `sign-in failed: ${message}`, {+ reason: 'auth-required',+ agentMessage: message,+ machineDetail: joinMachineDetail(agentErrorData(err), stderrTailDetail(t)),+ authMethods: threadAuthMethods(init.authMethods),+ });+ throw new ThreadOpError('not-ready', message);+ }+ if (t.closed) throw new ThreadOpError('not-ready', 'thread closed during sign-in');+ if (t.conn !== conn) throw threadRestartedDuringSignIn();+ // Same session-open sequence the launch runs, on the same connection —+ // including the failure classification, so a still-unauthenticated agent+ // parks on sign-in again and any other failure tears the process down.+ // The create-time settings ride along so a session recovered through a+ // sign-in opens on the same model/mode a first launch would have.+ if (!(await this.openSession(t, conn, init, t.launchSettings))) {+ throw new ThreadOpError(+ 'not-ready',+ lastFailureMessage(t) ?? `${t.info.agent.name} still couldn't start a conversation`,+ );+ }+ this.opts.log.info(+ { threadId, agentId: t.info.agent.id, methodId },+ '[acp-threads] thread signed in',+ );+ return { ...t.info };+ } finally {+ t.authInFlight = false;+ }+ }++ /**+ * One `authenticate` round trip, bounded. ACP puts no ceiling on it and an+ * agent-driven sign-in usually detours through the browser, so an abandoned+ * flow would otherwise hold the request — and the thread — open forever.+ */+ private async requestAuthenticate(conn: ClientConnection, methodId: string): Promise<void> {+ let timer: ReturnType<typeof setTimeout> | undefined;+ const expiry = new Promise<never>((_resolve, reject) => {+ timer = setTimeout(() => reject(new AuthenticateTimeoutError()), this.authenticateTimeoutMs);+ timer.unref?.();+ });+ try {+ await Promise.race([conn.agent.request(acpMethods.agent.authenticate, { methodId }), expiry]);+ } finally {+ if (timer !== undefined) clearTimeout(timer);+ }+ }+/** Tear down a half-resumed agent and return the record to archived rest. */private async abortResume(t: ThreadRecord): Promise<void> {t.closed = true;@@ -1321,6 +1675,7 @@ export class AcpThreadManager {}t.child = null;t.conn = null;+ t.lastInit = null;t.closed = false;t.turnActive = false;this.opts.agentPresenceBroadcaster?.clearPresence(toBroadcasterKey(t.agentSessionId));@@ -1354,6 +1709,9 @@ export class AcpThreadManager {// a prompt slipping in here would race the session/resume|load request.throw new ThreadOpError('not-ready', 'the thread is still resuming');}+ if (t.authInFlight) {+ throw new ThreadOpError('not-ready', 'the thread is still signing in');+ }if (t.sessionId === null || t.conn === null) {throw new ThreadOpError('not-ready', 'thread has no live agent session');}@@ -1376,33 +1734,150 @@ export class AcpThreadManager {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 {+ /**+ * Stop the running turn and send `content` as the next one — "steer now".+ *+ * ACP has no mid-turn steering primitive: `session/cancel` is the only+ * sanctioned control, and it is a request the agent may take its time+ * over (or ignore). So the correction parks on `info.steer` and rides the+ * turn-end continuation the cancel produces, ahead of anything queued.+ * If the agent never stops, {@link demoteStalledSteer} converts it into an+ * ordinary queued message rather than leaving it stranded.+ */+ steerPrompt(threadId: string, content: string): void {+ const t = this.mustGet(threadId);+ if (t.info.archived === true) {+ throw new ThreadOpError('not-ready', 'the thread is archived — resume it first');+ }+ if (t.resumeInFlight) {+ throw new ThreadOpError('not-ready', 'the thread is still resuming');+ }+ if (t.authInFlight) {+ throw new ThreadOpError('not-ready', 'the thread is still signing in');+ }+ if (t.sessionId === null || t.conn === null) {+ throw new ThreadOpError('not-ready', 'thread has no live agent session');+ }+ if (!t.turnActive) {+ // Nothing to steer away from — a correction with no run to correct is+ // just a message.+ this.dispatchPrompt(t, content, { echo: true });+ return;+ }+ // Latest correction wins: a second steer replaces the parked one (and its+ // countdown) rather than lining up behind it.+ this.clearSteer(t);+ t.info.steer = { content, ts: Date.now() };+ t.info.lastActivityAt = Date.now();+ this.emitInfo(t);+ const timer = setTimeout(() => this.demoteStalledSteer(t), this.steerStallMs);+ timer.unref?.();+ t.steerStallTimer = timer;+ // The queue survives a steer: those messages were always meant for after+ // this turn, and the steer only claims the slot in front of them.+ this.cancelTurn(t, { clearQueue: false });+ }++ /**+ * The cancel went unanswered for {@link steerStallMs}. Demote the parked+ * correction to the FRONT of the queue: it still goes first, but the user+ * now sees it as a queued row that says when it sends, instead of a promise+ * of an interruption that never came.+ */+ private demoteStalledSteer(t: ThreadRecord): void {+ t.steerStallTimer = null;+ const steer = t.info.steer;+ if (steer === undefined || t.closed || !t.turnActive) return;+ t.info.steer = undefined;+ // Deliberately allowed to exceed MAX_QUEUED_PROMPTS by one. That cap gates+ // NEW sends; dropping a correction the user already committed to (or+ // evicting someone else's queued message to make room) is the worse trade.+ t.info.queue = [+ { id: crypto.randomUUID(), content: steer.content, ts: steer.ts },+ ...(t.info.queue ?? []),+ ];+ this.emitInfo(t);+ }++ /** Drop any parked steer along with its stall countdown. Broadcast is the+ * caller's — most call sites are already emitting for another reason. */+ private clearSteer(t: ThreadRecord): void {+ if (t.steerStallTimer !== null) {+ clearTimeout(t.steerStallTimer);+ t.steerStallTimer = null;+ }+ t.info.steer = undefined;+ }++ /** Pop the parked steer, or null. Broadcast rides the dispatch that follows. */+ private takeSteer(t: ThreadRecord): SteerMessage | null {+ const steer = t.info.steer;+ if (steer === undefined) return null;+ this.clearSteer(t);+ return steer;+ }++ /** Replace a queued message's content in place, releasing any hold — a save+ * IS the resubmit. `false` when the id is unknown: the entry raced its own+ * dispatch (or a cancel), so the transcript already shows what ran. */+ editQueued(threadId: string, id: string, content: string): boolean {+ const t = this.mustGet(threadId);+ const queue = t.info.queue ?? [];+ if (!queue.some((m) => m.id === id)) return false;+ t.info.queue = queue.map((m) => (m.id === id ? { ...m, content, held: false } : m));+ this.emitInfo(t);+ this.drainIfIdle(t);+ return true;+ }++ /** Park a queued message so the drain skips it (`held`), or release it back+ * into line. Unknown id: no-op returning `false`. */+ holdQueued(threadId: string, id: string, held: boolean): boolean {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));+ if (!queue.some((m) => m.id === id)) return false;+ t.info.queue = queue.map((m) => (m.id === id ? { ...m, held } : m));this.emitInfo(t);+ if (!held) this.drainIfIdle(t);+ return true;}- /** Remove a queued message before it dispatches. Unknown id: no-op. */- removeQueued(threadId: string, id: string): void {+ /** Remove a queued message before it dispatches. Unknown id: `false`. */+ removeQueued(threadId: string, id: string): boolean {const t = this.mustGet(threadId);const queue = t.info.queue ?? [];const next = queue.filter((m) => m.id !== id);- if (next.length === queue.length) return;+ if (next.length === queue.length) return false;t.info.queue = next.length > 0 ? next : undefined;this.emitInfo(t);+ return true;+ }++ /**+ * Dispatch the next releasable entry when no turn is running. The normal+ * drain point is the turn-end continuation; an entry that becomes+ * dispatchable AFTER the turn ended (a hold released, an edit saved) has no+ * such continuation left to ride and would otherwise wait forever.+ */+ private drainIfIdle(t: ThreadRecord): void {+ if (t.turnActive || t.closed || t.resumeInFlight) return;+ if (t.info.archived === true || t.sessionId === null || t.conn === null) return;+ const next = this.takeNextQueued(t);+ if (next === null) return;+ this.dispatchPrompt(t, next.content, { echo: true });}- /** Pop the next queued prompt, or null. Broadcast rides the dispatch that- * follows (its status flip emits the refreshed info snapshot). */+ /** Pop the next dispatchable queued prompt, or null. Held entries are+ * skipped in place — they keep their position for when they're released.+ * 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;+ const index = queue.findIndex((m) => m.held !== true);+ if (index === -1) return null;+ const next = queue[index];+ const rest = [...queue.slice(0, index), ...queue.slice(index + 1)];t.info.queue = rest.length > 0 ? rest : undefined;return next ?? null;}@@ -1485,11 +1960,18 @@ 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.+ // Deliver the steer, then 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 both via its terminal status.if (t.sessionId !== null && t.conn !== null) {+ // The steer goes first by construction — the user stopped THIS run+ // for it, so it cannot wait behind messages queued before it.+ const steer = this.takeSteer(t);+ if (steer !== null) {+ this.dispatchPrompt(t, steer.content, { echo: true });+ return;+ }const next = this.takeNextQueued(t);if (next !== null) {this.dispatchPrompt(t, next.content, { echo: true });@@ -1503,24 +1985,52 @@ export class AcpThreadManager {t.turnActive = false;if (t.closed) return;this.appendEvent(t, { kind: 'turn_ended', stopReason: 'cancelled', ts: Date.now() });+ // Some agents answer a cancel by rejecting the prompt request rather+ // than resolving it 'cancelled'. That is still the turn ending, so the+ // steer is still owed — whatever the rejection turns out to mean.+ if (t.sessionId !== null && t.conn !== null) {+ const steer = this.takeSteer(t);+ if (steer !== null) {+ this.dispatchPrompt(t, steer.content, { echo: true });+ return;+ }+ }if (t.cancelRequested) {// The user asked for this — an aborted request is a completed// cancel, not an agent failure.this.emitStatus(t, 'ready');- } else {- this.emitStatus(t, 'error', `prompt failed: ${describeAgentError(err)}`);+ this.setPresence(t, 'idle');+ // Last, so a prompt this dispatches keeps its own 'writing' presence:+ // a steer that stall-demoted to the front of the queue is waiting on+ // this very turn ending, and the rejection path has no other drain.+ this.drainIfIdle(t);+ return;}+ this.emitStatus(t, 'error', `prompt failed: ${agentErrorMessage(err)}`, {+ reason: 'prompt',+ agentMessage: agentErrorMessage(err),+ machineDetail: joinMachineDetail(agentErrorData(err), stderrTailDetail(t)),+ });this.setPresence(t, 'idle');});}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) {+ this.cancelTurn(this.mustGet(threadId), { clearQueue: true });+ }++ /**+ * Send the ACP cancel for the running turn. `clearQueue` is the whole+ * difference between Stop and a steer: Stop means "stop the plan", so+ * everything waiting goes with the turn; a steer only replaces what runs+ * next, so the queue keeps its place behind the correction.+ */+ private cancelTurn(t: ThreadRecord, opts: { clearQueue: boolean }): void {+ if (opts.clearQueue && (t.info.queue !== undefined || t.info.steer !== undefined)) {+ // Before the conn guard, so a cancel racing agent death still clears.+ // The app folds both back into the composer, so the words survive.t.info.queue = undefined;+ this.clearSteer(t);this.emitInfo(t);}if (t.conn === null || t.sessionId === null) return;@@ -1530,7 +2040,18 @@ export class AcpThreadManager {// only actually stops when we do (the agent is awaiting our response).this.failPendingPermissions(t);this.restoreRunningAfterPermission(t);- void t.conn.agent.notify(acpMethods.agent.session.cancel, { sessionId: t.sessionId });+ // Caught, not `void`ed: the notification's write can still be in flight+ // when the connection closes (a thread closed right after a Stop), and an+ // unhandled rejection there would take the server process with it. A+ // cancel that lost its connection has already had its effect.+ t.conn.agent+ .notify(acpMethods.agent.session.cancel, { sessionId: t.sessionId })+ .catch((err: unknown) => {+ this.opts.log.debug(+ { err, threadId: t.info.threadId },+ '[acp-threads] cancel notification never reached the agent',+ );+ });}setMode(threadId: string, modeId: string): void {@@ -1753,6 +2274,7 @@ export class AcpThreadManager {const t = this.threads.get(threadId);if (t === undefined || t.info.archived === true || t.closed) return;t.closed = true; // Suppress exit/conn status handlers during teardown.+ this.clearSteer(t);this.failPendingPermissions(t);this.failPendingRuntimeConsent(t);try {@@ -1774,6 +2296,7 @@ export class AcpThreadManager {}t.child = null;t.conn = null;+ t.lastInit = null;await t.terminals?.disposeAll();t.terminals = null;this.opts.agentPresenceBroadcaster?.clearPresence(toBroadcasterKey(t.agentSessionId));@@ -1783,7 +2306,12 @@ export class AcpThreadManager {// Never-used thread (no user message ever recorded): discard it rather than// archive. The agent is dead above; drop the record and its (possibly// partial) persisted log so a spawned-but-untouched agent leaves no history.- if (!t.hadUserMessage) {+ // EXCEPT a thread that failed to start: its transcript is the only record+ // of what went wrong (a startup failure disables the composer, so such a+ // thread can never receive a user message — discarding meant every failed+ // launch erased its own evidence the moment the tab closed).+ const failedStart = t.info.status === 'error' || t.info.status === 'auth_required';+ if (!t.hadUserMessage && !failedStart) {this.threads.delete(threadId);t.subscribers.clear();if (t.flushTimer !== null) {@@ -2096,17 +2624,80 @@ export class AcpThreadManager {}}- private emitStatus(t: ThreadRecord, status: ThreadStatus, detail?: string): void {- // A terminal status is the single choke point where queued prompts die —+ private emitStatus(+ t: ThreadRecord,+ status: ThreadStatus,+ detail?: string,+ failure?: ThreadFailureDetail,+ ): void {+ // A terminal status is the single choke point where waiting 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;+ // archive), messages must not fire into a dead agent. The parked steer+ // goes with the queue: it exists to jump a run that no longer exists.+ if (status === 'exited' || status === 'error') {+ t.info.queue = undefined;+ this.clearSteer(t);+ }t.info.status = status;t.info.lastActivityAt = Date.now();- this.appendEvent(t, { kind: 'status', status, detail, ts: Date.now() });+ if (status === 'error' || status === 'auth_required') {+ // Failure statuses reach the server log too — without this line a+ // failed launch left no operator-visible trace anywhere but the+ // (user-deletable) thread transcript.+ this.opts.log.warn(+ {+ threadId: t.info.threadId,+ agentId: t.info.agent.id,+ status,+ detail,+ reason: failure?.reason,+ },+ '[acp-threads] thread failure status',+ );+ }+ this.appendEvent(t, {+ kind: 'status',+ status,+ detail,+ ...(failure !== undefined ? { failure } : {}),+ ts: Date.now(),+ });this.emitInfo(t);}+ /**+ * Kill a failed thread's agent process and drop its connection while+ * keeping the record (and its failure status) addressable — the user still+ * needs to read the banner, and close/retry still need the thread.+ */+ private async teardownFailedAgent(t: ThreadRecord): Promise<void> {+ const child = t.child;+ const conn = t.conn;+ // Captured before the field is cleared so a retry that spawns a fresh set+ // in the meantime cannot have it disposed out from under it.+ const terminals = t.terminals;+ t.child = null;+ t.conn = null;+ t.lastInit = null;+ t.terminals = null;+ try {+ conn?.close();+ } catch {+ // Already closed.+ }+ // Before the kill: the agent is going away, and a command it left running+ // would otherwise outlive both it and the thread's ability to show output.+ await terminals?.disposeAll().catch((err: unknown) => {+ this.opts.log.warn(+ { err, threadId: t.info.threadId },+ '[acp-threads] terminal cleanup on failed-agent teardown failed',+ );+ });+ if (child !== null) {+ await terminateAgentTree(child, { graceMs: KILL_GRACE_MS });+ }+ }+private emitInfo(t: ThreadRecord): void {// Info changes (status, title, modes, config) are the meta snapshot's// refresh signal — bounded per turn, unlike per-event activity.@@ -2121,9 +2712,10 @@ 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;+ // The queue and the parked steer are ephemeral by contract — persisting+ // either would resurrect ghost prompts into an archived thread after a+ // mid-turn crash.+ const { queue: _queue, steer: _steer, ...info } = t.info;return {version: 1,info,@@ -2282,14 +2874,15 @@ export async function confineToContentDir(function rehydratedRecord(meta: PersistedThreadMeta): ThreadRecord {const status = meta.info.status === 'error' ? 'error' : 'exited';return {- // `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 },+ // `queue`/`steer: undefined` belt-and-suspenders: buildMeta never persists+ // either, but a meta written by a different build must not resurrect them.+ info: { ...meta.info, status, archived: true, queue: undefined, steer: undefined },docName: meta.docName,agentRef: meta.agentRef,cwd: meta.cwd,child: null,conn: null,+ lastInit: null,sessionId: meta.sessionId,agentSessionId: `acp-${meta.info.threadId}`,events: [],@@ -2298,6 +2891,7 @@ function rehydratedRecord(meta: PersistedThreadMeta): ThreadRecord {logResolution: null,midTurnOnDisk: false,resumeInFlight: false,+ authInFlight: false,suppressUpdates: false,lastSuppressedAt: 0,subscribers: new Set(),@@ -2307,6 +2901,7 @@ function rehydratedRecord(meta: PersistedThreadMeta): ThreadRecord {terminals: null,turnActive: false,cancelRequested: false,+ steerStallTimer: null,unwatchedSince: null,unwatchedCancelSent: false,pendingBroadcast: [],@@ -2344,17 +2939,83 @@ function declinedRuntimeHint(runtimeKind: ManagedRuntimeKind): string {return `This agent needs \`${d.provides}\`, which isn't installed. OK can download a private copy of ${d.displayName} for you, or install ${d.displayName} yourself (${installUrl}) and it'll be used automatically.`;}-function describeAgentError(err: unknown): string {- if (err instanceof Error) {- const data = (err as { data?: unknown }).data;- if (data !== undefined && data !== null) {- try {- return `${err.message} (${JSON.stringify(data).slice(0, 300)})`;- } catch {- return err.message;- }- }- return err.message;+/**+ * True when a request failed with the ACP auth-required code. Structural+ * (`code` field) rather than `instanceof RequestError` so a dual-package+ * SDK instance can't defeat the check.+ */+function isAuthRequiredError(err: unknown): boolean {+ return (+ typeof err === 'object' &&+ err !== null &&+ (err as { code?: unknown }).code === AUTH_REQUIRED_CODE+ );+}++/** The failing side's own human-readable message — never wire payloads. */+function agentErrorMessage(err: unknown): string {+ return err instanceof Error ? err.message : String(err);+}++/** JSON-RPC `data` payload, serialized for the disclosure — never headline copy. */+function agentErrorData(err: unknown): string | undefined {+ if (typeof err !== 'object' || err === null) return undefined;+ const data = (err as { data?: unknown }).data;+ if (data === undefined || data === null) return undefined;+ try {+ return JSON.stringify(data).slice(0, 300);+ } catch {+ return undefined;+ }+}++/** What the most recent failure status said — the reason a retried op rejects with. */+function lastFailureMessage(t: ThreadRecord): string | undefined {+ for (let i = t.events.length - 1; i >= 0; i -= 1) {+ const event = t.events[i];+ if (event === undefined || event.kind !== 'status') continue;+ if (event.status !== 'error' && event.status !== 'auth_required') continue;+ return event.detail ?? event.failure?.agentMessage;}- return String(err);+ return undefined;+}++/**+ * The stderr the agent wrote — its real diagnostic, usually. The whole+ * retained tail, not a slice of it: this feeds the failure disclosure, which+ * exists precisely so the evidence is there when someone goes looking.+ */+function stderrTailDetail(t: ThreadRecord): string | undefined {+ const tail = t.stderrTail.join('\n');+ return tail === '' ? undefined : tail;+}++function joinMachineDetail(...parts: Array<string | undefined>): string | undefined {+ const joined = parts.filter((p): p is string => p !== undefined && p !== '').join('\n');+ return joined === '' ? undefined : joined;+}++/** Trim the SDK's `AuthMethod[]` to the wire shape the client renders. */+function threadAuthMethods(methods: InitializeResponse['authMethods']): ThreadAuthMethod[] {+ return (methods ?? []).flatMap((m) => {+ if (typeof m !== 'object' || m === null) return [];+ const { id, name, description, type } = m as {+ id?: unknown;+ name?: unknown;+ description?: unknown;+ type?: unknown;+ };+ if (typeof id !== 'string' || typeof name !== 'string') return [];+ return [+ {+ id,+ name,+ ...(typeof description === 'string' ? { description } : {}),+ // The SDK's discriminant travels as-is: an absent `type` means the+ // agent handles the sign-in itself, which the client must be able to+ // tell apart from `env_var` / `terminal` methods it can't complete.+ ...(typeof type === 'string' ? { kind: type } : {}),+ },+ ];+ });}diff --git a/packages/server/src/acp/thread-socket.test.ts b/packages/server/src/acp/thread-socket.test.tsindex 0f447b89a..b6a12afc5 100644--- a/packages/server/src/acp/thread-socket.test.ts+++ b/packages/server/src/acp/thread-socket.test.ts@@ -43,7 +43,11 @@ afterEach(async () => {});/** Same minimal capability-matrix agent as the manager integration suite. */-function writeFixtureAgent(localDir: string, caps: string): void {+function writeFixtureAgent(+ localDir: string,+ caps: string,+ extraEnv?: Record<string, string>,+): void {const agentPath = join(localDir, 'fixture-agent.mjs');writeFileSync(agentPath,@@ -69,7 +73,17 @@ process.stdin.on('data', (chunk) => {} else if (msg.method === 'session/new') {reply({ sessionId: 'sess-fixed' });} else if (msg.method === 'session/prompt') {- reply({ stopReason: 'end_turn' });+ if (caps.includes('gate-prompt')) {+ (async () => {+ const fs = await import('node:fs');+ while (!fs.existsSync(process.env.FAKE_RELEASE)) {+ await new Promise((r) => setTimeout(r, 20));+ }+ reply({ stopReason: 'end_turn' });+ })();+ } else {+ reply({ stopReason: 'end_turn' });+ }} else if (msg.method === 'session/resume') {reply({});} else if (msg.id !== undefined) {@@ -87,7 +101,7 @@ process.stdin.on('data', (chunk) => {name: 'Fixture',command: 'node',args: [agentPath],- env: { FAKE_CAPS: caps },+ env: { FAKE_CAPS: caps, ...extraEnv },},]),);@@ -164,6 +178,9 @@ function makeManager(contentDir: string, localDir: string): AcpThreadManager {isExcludedPath: () => false,isIgnoredPath: () => false,log,+ // Hermetic (see the thread-manager integration suite): every launch merges+ // the login shell's PATH, and a test must not spawn the developer's shell.+ resolveLoginShellPath: async () => null,});managers.push(manager);return manager;@@ -269,7 +286,11 @@ describe('/collab/thread socket — history ops', () => {socket.emit(JSON.stringify({ op: 'prompt', threadId, reqId: 'p0', content: 'hello' }));await waitStatus(manager, threadId, 'ready');socket.emit(JSON.stringify({ op: 'close', threadId }));- await waitStatus(manager, threadId, 'exited');+ // The close op's own `threads` response is the signal that the close+ // FINISHED: the 'exited' status flips mid-teardown, while the record is+ // still marked closing, and a resume that lands in that window is refused+ // for a reason that has nothing to do with what this test asserts.+ await socket.awaitFrame('threads');socket.emit(JSON.stringify({ op: 'resume', threadId, reqId: 'r9' }));const err = await socket.awaitFrame('error');@@ -279,6 +300,52 @@ describe('/collab/thread socket — history ops', () => {socket.close();}, 45_000);+ // The op is routed and its reqId echoed on the error path — the client+ // matches its pending promise on that id, so a dropped reqId hangs the UI.+ test('retry on a healthy thread answers the reqId with not-ready', async () => {+ const localDir = tmp();+ writeFixtureAgent(localDir, '');+ const manager = makeManager(tmp(), localDir);+ await manager.init();+ const socket = attachFakeSocket(manager);++ socket.emit(+ JSON.stringify({ op: 'create', reqId: 'c1', agent: { source: 'custom', id: 'fixture' } }),+ );+ const created = await socket.awaitFrame('created');+ const threadId = created.info.threadId;+ await waitStatus(manager, threadId, 'ready');++ socket.emit(JSON.stringify({ op: 'retry', threadId, reqId: 'rt1' }));+ const err = await socket.awaitFrame('error');+ expect(err.code).toBe('not-ready');+ expect(err.reqId).toBe('rt1');+ socket.close();+ }, 45_000);++ test('authenticate on a healthy thread answers the reqId with not-ready', async () => {+ const localDir = tmp();+ writeFixtureAgent(localDir, '');+ const manager = makeManager(tmp(), localDir);+ await manager.init();+ const socket = attachFakeSocket(manager);++ socket.emit(+ JSON.stringify({ op: 'create', reqId: 'c1', agent: { source: 'custom', id: 'fixture' } }),+ );+ const created = await socket.awaitFrame('created');+ const threadId = created.info.threadId;+ await waitStatus(manager, threadId, 'ready');++ socket.emit(+ JSON.stringify({ op: 'authenticate', threadId, reqId: 'au1', methodId: 'test_login' }),+ );+ const err = await socket.awaitFrame('error');+ expect(err.code).toBe('not-ready');+ expect(err.reqId).toBe('au1');+ socket.close();+ }, 45_000);+test('rename round-trips live and archived; a manual title survives first-prompt adoption', async () => {const localDir = tmp();writeFixtureAgent(localDir, '');@@ -369,6 +436,61 @@ describe('/collab/thread socket — history ops', () => {}, 45_000);});+describe('/collab/thread socket — steer', () => {+ test('steer routes to the manager; unknown thread and empty content fail distinctly', async () => {+ const localDir = tmp();+ writeFixtureAgent(localDir, '');+ const manager = makeManager(tmp(), localDir);+ await manager.init();+ const socket = attachFakeSocket(manager);++ const errors = () =>+ socket.frames.filter(+ (f): f is Extract<ThreadServerFrame, { op: 'error' }> => 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: 'create', reqId: 'c1', agent: { source: 'custom', id: 'fixture' } }),+ );+ const created = await socket.awaitFrame('created', 20_000);+ const threadId = created.info.threadId;+ await waitStatus(manager, threadId, 'ready');++ // Empty content fails structural parse and never reaches the manager.+ socket.emit(JSON.stringify({ op: 'steer', threadId, reqId: 's0', content: '' }));+ socket.emit(+ JSON.stringify({ op: 'steer', threadId: 'missing', reqId: 's1', content: 'go left' }),+ );+ await awaitErrors(2);+ expect(errors().map((f) => f.code)).toEqual(['bad-frame', 'unknown-thread']);+ expect(errors()[1]).toMatchObject({ reqId: 's1', threadId: 'missing' });++ // No turn is running, so the steer dispatches as an ordinary prompt.+ socket.emit(JSON.stringify({ op: 'steer', threadId, reqId: 's2', content: 'go left' }));+ const deadline = Date.now() + 10_000;+ for (;;) {+ const echoed = socket.frames.some(+ (f) =>+ f.op === 'events' &&+ f.events.some((e) => e.kind === 'user_message' && e.content === 'go left'),+ );+ if (echoed) break;+ if (Date.now() > deadline) throw new Error('steer never reached the transcript');+ await new Promise((r) => setTimeout(r, 25));+ }+ expect(errors()).toHaveLength(2);++ socket.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());@@ -400,4 +522,106 @@ describe('/collab/thread socket — queue ops', () => {expect(errors().map((f) => f.code)).toEqual(['unknown-thread', 'unknown-thread', 'bad-frame']);expect(errors()[0]?.threadId).toBe('missing');});++ test('a queue_edit that lost its race answers the reqId; without one it stays silent', async () => {+ const localDir = tmp();+ writeFixtureAgent(localDir, '');+ const manager = makeManager(tmp(), localDir);+ await manager.init();+ const socket = attachFakeSocket(manager);++ socket.emit(+ JSON.stringify({ op: 'create', reqId: 'c1', agent: { source: 'custom', id: 'fixture' } }),+ );+ const created = await socket.awaitFrame('created', 20_000);+ const threadId = created.info.threadId;+ const errors = () =>+ socket.frames.filter(+ (f): f is Extract<ThreadServerFrame, { op: 'error' }> => f.op === 'error',+ );++ // Nothing is queued on this thread, so every id is already-dispatched.+ socket.emit(+ JSON.stringify({ op: 'queue_edit', threadId, id: 'gone', content: 'my correction' }),+ );+ socket.emit(JSON.stringify({ op: 'queue_hold', threadId, id: 'gone', held: true }));+ socket.emit(+ JSON.stringify({+ op: 'queue_edit',+ threadId,+ id: 'gone',+ content: 'my correction',+ reqId: 'qe-1',+ }),+ );++ const deadline = Date.now() + 10_000;+ while (errors().length === 0) {+ if (Date.now() > deadline) throw new Error('no error frame for the reqId-carrying edit');+ await new Promise((r) => setTimeout(r, 10));+ }+ // Exactly one: the reqId-less edit and the hold are fire-and-forget.+ expect(errors()).toHaveLength(1);+ expect(errors()[0]).toMatchObject({+ code: 'not-ready',+ reqId: 'qe-1',+ threadId,+ message: 'queued message already dispatched',+ });++ socket.close();+ }, 45_000);++ test('a queue_edit that applies answers its reqId with a queue_edited ack', async () => {+ const localDir = tmp();+ const releasePath = join(localDir, 'release-turn');+ writeFixtureAgent(localDir, 'gate-prompt', { FAKE_RELEASE: releasePath });+ const manager = makeManager(tmp(), localDir);+ await manager.init();+ const socket = attachFakeSocket(manager);++ socket.emit(+ JSON.stringify({ op: 'create', reqId: 'c1', agent: { source: 'custom', id: 'fixture' } }),+ );+ const created = await socket.awaitFrame('created', 20_000);+ const threadId = created.info.threadId;+ const status = () => manager.getInfo(threadId)?.status;+ let deadline = Date.now() + 15_000;+ while (status() !== 'ready') {+ if (Date.now() > deadline) throw new Error(`never ready (status ${status()})`);+ await new Promise((r) => setTimeout(r, 25));+ }++ // First prompt parks on the gate; the second queues behind it.+ socket.emit(JSON.stringify({ op: 'prompt', threadId, reqId: 'p1', content: 'hold the turn' }));+ deadline = Date.now() + 10_000;+ while (status() !== 'running') {+ if (Date.now() > deadline) throw new Error('turn never opened');+ await new Promise((r) => setTimeout(r, 10));+ }+ socket.emit(JSON.stringify({ op: 'prompt', threadId, reqId: 'p2', content: 'queued text' }));+ deadline = Date.now() + 10_000;+ while ((manager.getInfo(threadId)?.queue ?? []).length === 0) {+ if (Date.now() > deadline) throw new Error('prompt never queued');+ await new Promise((r) => setTimeout(r, 10));+ }+ const queued = manager.getInfo(threadId)?.queue?.[0];+ if (queued === undefined) throw new Error('queue entry missing');++ socket.emit(+ JSON.stringify({+ op: 'queue_edit',+ threadId,+ id: queued.id,+ content: 'edited text',+ reqId: 'qe-ok',+ }),+ );+ const ack = await socket.awaitFrame('queue_edited', 10_000);+ expect(ack).toMatchObject({ op: 'queue_edited', reqId: 'qe-ok', threadId });+ expect(manager.getInfo(threadId)?.queue?.[0]?.content).toBe('edited text');++ writeFileSync(releasePath, 'go');+ socket.close();+ }, 45_000);});diff --git a/packages/server/src/acp/thread-socket.ts b/packages/server/src/acp/thread-socket.tsindex e69406771..3ee29d44a 100644--- a/packages/server/src/acp/thread-socket.ts+++ b/packages/server/src/acp/thread-socket.ts@@ -10,7 +10,10 @@* socket it is trusted to the same level as the mutating HTTP surface.*/-import type { ThreadServerFrame } from '@inkeep/open-knowledge-core/acp/thread-protocol';+import type {+ ThreadErrorCode,+ ThreadServerFrame,+} from '@inkeep/open-knowledge-core/acp/thread-protocol';import { parseThreadClientFrame } from '@inkeep/open-knowledge-core/acp/thread-protocol';import type { PinoLogger } from '../logger.ts';import { type AcpThreadManager, ThreadOpError } from './thread-manager.ts';@@ -86,6 +89,16 @@ export function attachAcpThreadSocket(await subscribeTo(frame.threadId, 0);return;}+ case 'retry': {+ const info = await manager.retryThread(frame.threadId);+ send({ op: 'retried', reqId: frame.reqId, info });+ return;+ }+ case 'authenticate': {+ const info = await manager.authenticateThread(frame.threadId, frame.methodId);+ send({ op: 'authenticated', reqId: frame.reqId, info });+ return;+ }case 'delete': {const sink = subscriptions.get(frame.threadId);if (sink !== undefined) {@@ -108,8 +121,30 @@ export function attachAcpThreadSocket(manager.sendPrompt(frame.threadId, frame.content);return;}+ case 'steer': {+ manager.steerPrompt(frame.threadId, frame.content);+ return;+ }case 'queue_edit': {- manager.editQueued(frame.threadId, frame.id, frame.content);+ const applied = manager.editQueued(frame.threadId, frame.id, frame.content);+ // Both outcomes answer on the reqId when the client asked to be+ // told. A positive ack is what makes the refusal reliable: the+ // `info` frames this thread emits for unrelated reasons would+ // otherwise settle the edit before the error could arrive.+ if (frame.reqId !== undefined) {+ if (applied) {+ send({ op: 'queue_edited', reqId: frame.reqId, threadId: frame.threadId });+ } else {+ sendError('not-ready', 'queued message already dispatched', {+ reqId: frame.reqId,+ threadId: frame.threadId,+ });+ }+ }+ return;+ }+ case 'queue_hold': {+ manager.holdQueued(frame.threadId, frame.id, frame.held);return;}case 'queue_remove': {@@ -206,17 +241,7 @@ export function attachAcpThreadSocket(}function errorFrame(- code:- | 'bad-frame'- | 'unknown-thread'- | 'unknown-agent'- | 'capacity'- | 'spawn-failed'- | 'install-failed'- | 'agent-error'- | 'not-ready'- | 'resume-unsupported'- | 'internal',+ code: ThreadErrorCode,message: string,extra?: { reqId?: string; threadId?: string },): ThreadServerFrame {diff --git a/packages/server/src/api-extension.ts b/packages/server/src/api-extension.tsindex 9348988a4..1a19a0b6b 100644--- a/packages/server/src/api-extension.ts+++ b/packages/server/src/api-extension.ts@@ -9139,7 +9139,7 @@ export function createApiExtension(featured: z.boolean(),harness: z.object({- cli: z.enum(['claude', 'codex', 'cursor', 'opencode', 'pi']),+ cli: z.enum(['claude', 'codex', 'cursor', 'gemini', 'opencode', 'pi']),availability: z.enum(['present', 'not-found', 'unknown']),}).optional(),