Beautiful, AI-native markdown IDE and LLM wiki
TypeScript 2nd-brainagent-skillsclaudecodexcompany-braindocsknowledge-knowledge-baseknowledge-managementllmllm-wikillm-wiki-karpathymarkdownmarkdown-editormdmdxnotespkmsecond-brainskills
Mid-message slash picker, unsent-chat agent switch, themed tool card (PRD-8506, PRD-8761, PRD-8808) (#4913)
Abrahamb38c5c4a9119
diff --git a/.changeset/prd-8506-8761-8808-composer-and-picker.md b/.changeset/prd-8506-8761-8808-composer-and-picker.mdnew file mode 100644index 000000000..9c90bedc1--- /dev/null+++ b/.changeset/prd-8506-8761-8808-composer-and-picker.md@@ -0,0 +1,5 @@+---+"@inkeep/open-knowledge": patch+---++The agent composer's slash picker now opens after a space anywhere in a message and completes the command name as plain text there, picking another agent while a chat is still unsent moves your draft to that agent, and the tool hover card follows the active theme.diff --git a/docs/content/features/editor.mdx b/docs/content/features/editor.mdxindex 2a73a5e03..332fd43e8 100644--- a/docs/content/features/editor.mdx+++ b/docs/content/features/editor.mdx@@ -152,7 +152,7 @@ Select text in the WYSIWYG editor and the selection bubble menu shows a **CommenThe desktop app on macOS, Windows, and Linux has a built-in terminal with real interactive shells inside the editor window. On Windows, the terminal requires Windows 10 version 1809 (build 17763) or later, Windows 11, or Windows Server 2019 or later. On Linux, OpenKnowledge inherits Electron's supported distribution range: releases of the major distributions that both Chromium and the distribution vendor still support. Toggle it with `Cmd+J` on macOS or `Ctrl+J` on Windows and Linux, with `` Ctrl+` `` on any desktop platform (which also works from inside a focused terminal), or with **View ▸ Show / Hide Terminal**. It opens at the placement saved for this installation (the bottom dock by default). Right-click a bottom-dock tab and choose **Move to right panel**, use the matching command in the command palette or **Terminal** menu, or use the right-panel header button to move it back to the bottom. Moving or hiding the Terminal keeps its live shells, tabs, and scrollback intact.-The terminal is also the editor's AI-chat surface: opening it starts your remembered CLI pick, or a plain shell when you have none, and the tab strip's **+** button opens another tab with whatever you picked last — a CLI chat or a plain shell. Its dropdown switches that pick and opens a tab in the thing you picked, in one action. A CLI pick sticks and is shared with the Ask AI composer; the plain-shell pick is remembered for the terminal only. In-app agents run in the Agents panel, which has its own tab strip and **+** button; picking an agent there sticks the same way and also becomes your Ask AI default. In an in-app chat, the **Add to prompt (+)** menu offers files and page mentions, plus selected comments when available. **Commands** appears when the selected agent provides commands and the prompt draft is empty. With text selected in the editor, `Cmd+J` on macOS, `Ctrl+J` on Windows or Linux, and `` Ctrl+` `` on any desktop platform stage the passage into the active CLI's input (or open a new CLI tab when none is running) instead of toggling — they share one handler. `Cmd+Shift+J` on macOS or `Ctrl+Shift+J` on Windows or Linux always stages it into a new CLI tab; the passage sits in the input for you to add to, and nothing is submitted until you press Enter. **Terminal ▸ New Terminal Window** (see [Terminal menu](#terminal-menu)) opens a dedicated window with the same multi-session tabs, switched with `Cmd+<number>` on macOS or `Ctrl+<number>` on Windows and Linux, and shells starting at the project root.+The terminal is also the editor's AI-chat surface: opening it starts your remembered CLI pick, or a plain shell when you have none, and the tab strip's **+** button opens another tab with whatever you picked last — a CLI chat or a plain shell. Its dropdown switches that pick and opens a tab in the thing you picked, in one action. A CLI pick sticks and is shared with the Ask AI composer; the plain-shell pick is remembered for the terminal only. In-app agents run in the Agents panel, which has its own tab strip and **+** button; picking an agent there sticks the same way and also becomes your Ask AI default. Picking a different agent while the open chat has not been sent yet switches that chat to the chosen agent and keeps what you have typed and attached; until that new chat has started, the agents in the **+** menu are greyed out, and the original chat stays if the new one cannot start (while a dropped file is still being read, the pick opens a new chat beside the original instead); a chat that already has a message keeps its agent, and the pick opens a new chat beside it. In an in-app chat, the **Add to prompt (+)** menu offers files and page mentions, plus selected comments when available. **Commands** appears when the selected agent provides commands and the prompt draft is empty. With text selected in the editor, `Cmd+J` on macOS, `Ctrl+J` on Windows or Linux, and `` Ctrl+` `` on any desktop platform stage the passage into the active CLI's input (or open a new CLI tab when none is running) instead of toggling — they share one handler. `Cmd+Shift+J` on macOS or `Ctrl+Shift+J` on Windows or Linux always stages it into a new CLI tab; the passage sits in the input for you to add to, and nothing is submitted until you press Enter. **Terminal ▸ New Terminal Window** (see [Terminal menu](#terminal-menu)) opens a dedicated window with the same multi-session tabs, switched with `Cmd+<number>` on macOS or `Ctrl+<number>` on Windows and Linux, and shells starting at the project root.On Windows, type `wsl` in any terminal tab to enter your default WSL distribution; OpenKnowledge's CLI detection and bundled `ok` command stay Windows-side, so install agent CLIs on Windows for them to appear in the launcher.diff --git a/packages/app/src/components/SessionsHost.agents.dom.test.tsx b/packages/app/src/components/SessionsHost.agents.dom.test.tsxindex 51c4ba04c..96d6a6659 100644--- a/packages/app/src/components/SessionsHost.agents.dom.test.tsx+++ b/packages/app/src/components/SessionsHost.agents.dom.test.tsx@@ -11,7 +11,12 @@ import {reloadEnabledAgentsFromStorage,setAgentEnabled,} from '@/lib/acp/enabled-agents';-import { subscribeStagedThreadDraft } from '@/lib/acp/thread-draft-staging';+import {+ registerThreadDraftReader,+ resetStagedThreadDrafts,+ subscribeStagedThreadDraft,+} from '@/lib/acp/thread-draft-staging';+import type { ThreadRenderModel } from '@/lib/acp/thread-event-model';import type { OkDesktopBridge } from '@/lib/desktop-bridge-types';import type { ThreadLaunchIntent } from './EditorPane';import { requestPreferredSession } from './handoff/preferred-session-events';@@ -69,6 +74,21 @@ const deleteThread = vi.fn((id: string) => {setArchivedThreads(archivedThreads.filter((t) => t.threadId !== id));});const markThreadViewed = vi.fn((_id: string) => {});+const threadModels = new Map<string, ThreadRenderModel>();+function setThreadModel(threadId: string, model: ThreadRenderModel | null) {+ if (model === null) threadModels.delete(threadId);+ else threadModels.set(threadId, model);+}+function emptyThreadModel(items: ThreadRenderModel['items'] = []): ThreadRenderModel {+ return {+ items,+ plan: [],+ turnActive: false,+ tokenUsage: null,+ terminals: {},+ permissionsByToolCall: {},+ };+}let connectionStatus: 'idle' | 'connecting' | 'open' | 'closed' = 'open';function setConnectionStatus(next: typeof connectionStatus) {@@ -119,6 +139,7 @@ vi.doMock('@/lib/acp/thread-client', () => ({openArchivedThread,deleteThread,markThreadViewed,+ getThreadModel: (threadId: string) => threadModels.get(threadId) ?? null,}),ThreadChannelUnavailableError: class ThreadChannelUnavailableError extends Error {},}));@@ -146,6 +167,7 @@ type MockAgent = {};let mockRegisteredAgent: MockAgent | null = null;+let mockExtraAgents: MockAgent[] = [];let mockPersistedDefaultAgent: MockAgent | null = null;const registerAgent = vi.fn((_agent: MockAgent) => {});@@ -154,7 +176,7 @@ const { pickEffectiveDefaultAgent } = await vi.importActual<>('@/lib/acp/registered-agents');function presentedAgents(): MockAgent[] {- const list = mockRegisteredAgent === null ? [] : [mockRegisteredAgent];+ const list = mockRegisteredAgent === null ? [] : [mockRegisteredAgent, ...mockExtraAgents];const persisted = mockPersistedDefaultAgent;if (persisted !== null &&@@ -175,9 +197,10 @@ vi.doMock('@/lib/acp/registered-agents', () => ({let mockInflightLaunch = false;let mockLaunchOutcome: 'started' | 'deduped' | 'failed' = 'started';+let mockLaunchGate: Promise<'started' | 'deduped' | 'failed'> | null = null;const launchAgentThread = vi.fn(() => {mockInflightLaunch = true;- return Promise.resolve(mockLaunchOutcome);+ return mockLaunchGate ?? Promise.resolve(mockLaunchOutcome);});const toastError = vi.fn((_message: string) => {});vi.doMock('sonner', () => ({@@ -904,7 +927,10 @@ describe('SessionsHost — agents panel (web / no bridge)', () => {catalogError = null;refetchCatalog.mockClear();mockRegisteredAgent = null;+ mockExtraAgents = [];mockPersistedDefaultAgent = null;+ threadModels.clear();+ resetStagedThreadDrafts();initialRosterIds = null;localStorage.clear();reloadEnabledAgentsFromStorage();@@ -2989,3 +3015,224 @@ describe('SessionsHost — agents panel (web / no bridge)', () => {await waitFor(() => expect(screen.queryByTestId('agent-thread-reconnecting')).toBeNull());});});++describe('switching the agent of an unsent chat', () => {+ const CURRENT: MockAgent = { source: 'registry', id: 'a', name: 'Agent' };+ const OTHER: MockAgent = { source: 'registry', id: 'codex-acp', name: 'Codex' };+ const DRAFT_DOC = {+ type: 'doc',+ content: [{ type: 'paragraph', content: [{ type: 'text', text: 'quoted passage' }] }],+ };+ const DRAFT_IMAGE = {+ kind: 'image',+ mimeType: 'image/png',+ data: 'aGk=',+ name: 'a.png',+ } as const;++ beforeEach(() => {+ closeThread.mockClear();+ launchAgentThread.mockClear();+ registerAgent.mockClear();+ mockLaunchOutcome = 'started';+ mockInflightLaunch = false;+ mockRegisteredAgent = null;+ mockExtraAgents = [];+ mockPersistedDefaultAgent = null;+ mockLaunchGate = null;+ threadModels.clear();+ resetStagedThreadDrafts();+ setOpenThreads([]);+ localStorage.clear();+ });+ afterEach(() => {+ cleanup();+ });++ async function pickFromHeaderMenu(name: string) {+ const user = userEvent.setup();+ const [trigger] = screen.getAllByRole('button', {+ name: /Choose what a new (tab|chat) starts/,+ });+ if (trigger === undefined) throw new Error('header picker trigger missing');+ await user.click(trigger);+ await user.click(await screen.findByRole('menuitem', { name }));+ }++ test('picking another agent while the open chat is unsent switches it and carries the draft', async () => {+ mockRegisteredAgent = CURRENT;+ mockExtraAgents = [OTHER];+ render(<Harness />);+ setOpenThreads([makeThread({ threadId: 't1' })]);+ await screen.findByTestId('thread-view');+ setThreadModel('t1', emptyThreadModel());+ const stopReading = registerThreadDraftReader('t1', () => ({+ text: 'quoted passage',+ doc: DRAFT_DOC,+ attachments: [DRAFT_IMAGE],+ uploadsPending: false,+ }));++ await pickFromHeaderMenu('Codex');+ stopReading();++ expect(launchAgentThread).toHaveBeenCalledTimes(1);+ expect(launchAgentThread.mock.calls[0]).toEqual([+ { source: 'registry', id: 'codex-acp' },+ null,+ null,+ null,+ { doc: DRAFT_DOC, attachments: [DRAFT_IMAGE] },+ undefined,+ ]);+ await waitFor(() => expect(closeThread).toHaveBeenCalledWith('t1'));+ });++ test.each(['failed', 'deduped'] as const)(+ 'a replacement launch that ends %s leaves the unsent chat and its draft in place',+ async (outcome) => {+ mockRegisteredAgent = CURRENT;+ mockExtraAgents = [OTHER];+ mockLaunchOutcome = outcome;+ render(<Harness />);+ setOpenThreads([makeThread({ threadId: 't1' })]);+ await screen.findByTestId('thread-view');+ setThreadModel('t1', emptyThreadModel());+ const stopReading = registerThreadDraftReader('t1', () => ({+ text: 'quoted passage',+ doc: DRAFT_DOC,+ attachments: [],+ }));++ await pickFromHeaderMenu('Codex');+ await waitFor(() => expect(launchAgentThread).toHaveBeenCalledTimes(1));+ await act(async () => {+ await Promise.resolve();+ });+ stopReading();++ expect(closeThread).not.toHaveBeenCalled();+ },+ );++ test('a chat that already has a message keeps its agent and the pick opens a new chat', async () => {+ mockRegisteredAgent = CURRENT;+ mockExtraAgents = [OTHER];+ render(<Harness />);+ setOpenThreads([makeThread({ threadId: 't1' })]);+ await screen.findByTestId('thread-view');+ setThreadModel(+ 't1',+ emptyThreadModel([{ kind: 'message', role: 'user', text: 'hello', messageId: 'm1' }]),+ );+ const stopReading = registerThreadDraftReader('t1', () => ({+ text: 'a follow-up',+ doc: DRAFT_DOC,+ attachments: [],+ uploadsPending: false,+ }));++ await pickFromHeaderMenu('Codex');+ stopReading();++ expect(closeThread).not.toHaveBeenCalled();+ expect(launchAgentThread).toHaveBeenCalledTimes(1);+ expect(launchAgentThread.mock.calls[0]).toEqual([+ { source: 'registry', id: 'codex-acp' },+ null,+ null,+ null,+ null,+ undefined,+ ]);+ });++ test('the agent list is unavailable until a switch has settled', async () => {+ const THIRD: MockAgent = { source: 'registry', id: 'cursor', name: 'Cursor' };+ mockRegisteredAgent = CURRENT;+ mockExtraAgents = [OTHER, THIRD];+ const gate = Promise.withResolvers<'started' | 'deduped' | 'failed'>();+ mockLaunchGate = gate.promise;+ render(<Harness />);+ setOpenThreads([makeThread({ threadId: 't1' })]);+ await screen.findByTestId('thread-view');+ setThreadModel('t1', emptyThreadModel());+ const stopReading = registerThreadDraftReader('t1', () => ({+ text: 'quoted passage',+ doc: DRAFT_DOC,+ attachments: [],+ uploadsPending: false,+ }));++ await pickFromHeaderMenu('Codex');+ expect(launchAgentThread).toHaveBeenCalledTimes(1);+ expect(launchAgentThread.mock.calls[0]?.[4]).toEqual({ doc: DRAFT_DOC, attachments: [] });++ const user = userEvent.setup();+ const [trigger] = screen.getAllByRole('button', {+ name: /Choose what a new (tab|chat) starts/,+ });+ if (trigger === undefined) throw new Error('header picker trigger missing');+ await user.click(trigger);+ const cursorItem = await screen.findByRole('menuitem', { name: 'Cursor' });+ expect(cursorItem.getAttribute('aria-disabled')).toBe('true');+ expect(screen.getByRole('menuitem', { name: 'Codex' }).getAttribute('aria-disabled')).toBe(+ 'true',+ );+ await user.click(cursorItem);+ expect(launchAgentThread).toHaveBeenCalledTimes(1);+ expect(closeThread).not.toHaveBeenCalled();+ await user.keyboard('{Escape}');++ await act(async () => {+ gate.resolve('started');+ await gate.promise;+ });+ stopReading();+ await waitFor(() => expect(closeThread).toHaveBeenCalledWith('t1'));++ await user.click(trigger);+ const cursorAgain = await screen.findByRole('menuitem', { name: 'Cursor' });+ expect(cursorAgain.getAttribute('aria-disabled')).toBeNull();+ });++ test('a chat with a file still being read is not switched', async () => {+ mockRegisteredAgent = CURRENT;+ mockExtraAgents = [OTHER];+ render(<Harness />);+ setOpenThreads([makeThread({ threadId: 't1' })]);+ await screen.findByTestId('thread-view');+ setThreadModel('t1', emptyThreadModel());+ const stopReading = registerThreadDraftReader('t1', () => ({+ text: 'quoted passage',+ doc: DRAFT_DOC,+ attachments: [],+ uploadsPending: true,+ }));++ await pickFromHeaderMenu('Codex');+ await act(async () => {+ await Promise.resolve();+ });+ stopReading();++ expect(closeThread).not.toHaveBeenCalled();+ expect(launchAgentThread).toHaveBeenCalledTimes(1);+ expect(launchAgentThread.mock.calls[0]?.[4]).toBeNull();+ });++ test('picking the agent the unsent chat already uses opens a new chat as before', async () => {+ mockRegisteredAgent = CURRENT;+ mockExtraAgents = [OTHER];+ render(<Harness />);+ setOpenThreads([makeThread({ threadId: 't1' })]);+ await screen.findByTestId('thread-view');+ setThreadModel('t1', emptyThreadModel());++ await pickFromHeaderMenu('Agent');++ expect(closeThread).not.toHaveBeenCalled();+ expect(launchAgentThread).toHaveBeenCalledTimes(1);+ expect(launchAgentThread.mock.calls[0]?.[0]).toEqual({ source: 'registry', id: 'a' });+ });+});diff --git a/packages/app/src/components/SessionsHost.tsx b/packages/app/src/components/SessionsHost.tsxindex 0299d47d0..a700aad50 100644--- a/packages/app/src/components/SessionsHost.tsx+++ b/packages/app/src/components/SessionsHost.tsx@@ -65,7 +65,13 @@ import {useInitialRosterThreadIds,useOpenAgentThreadTabs,} from '@/lib/acp/thread-client';-import { stageThreadDraft } from '@/lib/acp/thread-draft-staging';+import {+ isEmptyThreadDraft,+ readThreadDraft,+ stageThreadDraft,+ type ThreadDraftContent,+} from '@/lib/acp/thread-draft-staging';+import { threadHasUserMessage } from '@/lib/acp/thread-event-model';import type { OkDesktopBridge, OkTerminalRestartSnapshot } from '@/lib/desktop-bridge-types';import { emitDiagnosticBreadcrumb } from '@/lib/diagnostic-breadcrumb';import {@@ -141,7 +147,7 @@ type AgentPaneLaunchRequest = {readonly attachments?: readonly AttachmentPart[];} & (| { readonly prompt?: string | null; readonly stageDraft?: never }- | { readonly prompt?: never; readonly stageDraft: string }+ | { readonly prompt?: never; readonly stageDraft: string | ThreadDraftContent });type EmptyAgentLaunchState = 'idle' | 'launching' | 'deduped' | 'failed';@@ -929,12 +935,48 @@ export function SessionsHost({openSession(null, null, 'user');}+ function unsentActiveThread(): { threadId: string; agent: ThreadInfo['agent'] } | null {+ const active = sessionsRef.current.find((session) => session.id === activeSessionIdRef.current);+ if (active == null || active.kind !== 'thread') return null;+ const info = threadInfoById.get(active.threadId);+ if (info === undefined || info.archived === true) return null;+ const model = getAgentThreadClient().getThreadModel(active.threadId);+ if (model === null) return null;+ if (threadHasUserMessage(model)) return null;+ return { threadId: active.threadId, agent: info.agent };+ }+function pickNewChatAgent(agent: RegisteredAgent) {+ const unsent = unsentActiveThread();+ if (unsent !== null && switchingThreads.has(unsent.threadId)) return;dismissCoveringHistory();registerAgent(agent);writePreferBareTerminal(false);saveStickyAgent(threadAgentId(agent));- void launchAgentForPane({ agent });+ if (unsent === null || (unsent.agent.source === agent.source && unsent.agent.id === agent.id)) {+ void launchAgentForPane({ agent });+ return;+ }+ const draft = readThreadDraft(unsent.threadId);+ if (draft?.uploadsPending === true) {+ void launchAgentForPane({ agent });+ return;+ }+ const request: AgentPaneLaunchRequest =+ draft !== null && !isEmptyThreadDraft(draft) && draft.doc !== null+ ? { agent, stageDraft: { doc: draft.doc, attachments: draft.attachments } }+ : { agent };+ const switchingFrom = unsent.threadId;+ setSwitchingThreads((previous) => new Set(previous).add(switchingFrom));+ void launchAgentForPane(request).then((outcome) => {+ setSwitchingThreads((previous) => {+ if (!previous.has(switchingFrom)) return previous;+ const next = new Set(previous);+ next.delete(switchingFrom);+ return next;+ });+ if (outcome === 'started') getAgentThreadClient().closeThread(switchingFrom);+ });}function setSessionTitle(id: string, title: string) {@@ -1055,6 +1097,7 @@ export function SessionsHost({}}const closeActiveRef = useRef(() => {});+ const [switchingThreads, setSwitchingThreads] = useState<ReadonlySet<string>>(() => new Set());useEffect(() => {persistSuppressedRef.current = dockPersistSuppressed;@@ -1759,6 +1802,13 @@ export function SessionsHost({const panelSessions = [...sessions].sort((a, b) => a.ordinal - b.ordinal);+ const agentPickPending = sessions.some(+ (session) =>+ session.id === activeSessionId &&+ session.kind === 'thread' &&+ switchingThreads.has(session.threadId),+ );+const newButton = (<TerminalNewChatButtonselected={newSessionChoice}@@ -1766,6 +1816,7 @@ export function SessionsHost({showAgents={hostThreads}registeredAgents={enabledRegisteredAgents}onPickAgent={pickNewChatAgent}+ agentPickPending={agentPickPending}onOpenSettings={openAgentSettings}liveThreadCount={liveThreadCount}showClis={terminalAvailable}@@ -1782,6 +1833,7 @@ export function SessionsHost({showAgentsregisteredAgents={enabledRegisteredAgents}onPickAgent={pickNewChatAgent}+ agentPickPending={agentPickPending}onOpenSettings={openAgentSettings}liveThreadCount={liveThreadCount}showClis={terminalAvailable}diff --git a/packages/app/src/components/TerminalNewChatButton.tsx b/packages/app/src/components/TerminalNewChatButton.tsxindex 305aa820d..d0e45002d 100644--- a/packages/app/src/components/TerminalNewChatButton.tsx+++ b/packages/app/src/components/TerminalNewChatButton.tsx@@ -37,6 +37,7 @@ interface TerminalNewChatButtonProps {readonly onPickAgent: (agent: RegisteredAgent) => void;readonly onOpenSettings: () => void;readonly liveThreadCount: number;+ readonly agentPickPending?: boolean;readonly showClis: boolean;readonly onPickCli: (cli: TerminalCli) => void;readonly onPickTerminal: () => void;@@ -53,6 +54,7 @@ export function TerminalNewChatButton({onPickAgent,onOpenSettings,liveThreadCount,+ agentPickPending = false,showClis,onPickCli,onPickTerminal,@@ -66,6 +68,7 @@ export function TerminalNewChatButton({const catalog = useAgentCatalogQuery(menuOpen && showAgents);const maxThreads = catalog.data?.maxThreads ?? 8;const atCap = liveThreadCount >= maxThreads;+ const agentsDisabled = atCap || agentPickPending;const hasMenu = showAgents || showClis;const panel = presentation === 'panel';const agentName = selected.kind === 'agent' ? selected.agent?.name : undefined;@@ -109,7 +112,7 @@ export function TerminalNewChatButton({selected.kind === 'agent' &&selected.agent?.source === agent.source &&selected.agent?.id === agent.id,- disabled: atCap,+ disabled: agentsDisabled,onSelect: () => onPickAgent(agent),})): undefined@@ -222,7 +225,7 @@ export function TerminalNewChatButton({<DropdownMenuItemkey={`${agent.source}:${agent.id}`}onSelect={() => onPickAgent(agent)}- disabled={atCap}+ disabled={agentsDisabled}data-testid={`terminal-new-chat-agent-${agent.id}`}aria-current={isSelected ? 'true' : undefined}>diff --git a/packages/app/src/components/acp/ThreadView.dom.test.tsx b/packages/app/src/components/acp/ThreadView.dom.test.tsxindex 4a3fd7639..ceb5c347d 100644--- a/packages/app/src/components/acp/ThreadView.dom.test.tsx+++ b/packages/app/src/components/acp/ThreadView.dom.test.tsx@@ -137,9 +137,12 @@ vi.doMock('@/lib/acp/model-candidates', async () => {});const { ThreadView } = await import('./ThreadView');-const { resetStagedThreadDrafts, subscribeStagedThreadDraft } = await import(- '@/lib/acp/thread-draft-staging'-);+const {+ readThreadDraft,+ resetStagedThreadDrafts,+ stageThreadDraftContent,+ subscribeStagedThreadDraft,+} = await import('@/lib/acp/thread-draft-staging');const { launchAgentThread } = await import('@/lib/acp/launch-agent-thread');const { ThreadContextWindowError, ThreadResumeError } = await import('@/lib/acp/thread-client');const { buildThreadRenderModel } = await import('@/lib/acp/thread-event-model');@@ -1668,6 +1671,12 @@ describe('ThreadView tool-call status', () => {const tooltip = await screen.findByRole('tooltip');expect(tooltip.textContent).toContain('read-only shell commands');expect(tooltip.textContent).toContain('mcp__open-knowledge__exec');+ const surface = screen.getByTestId('agent-thread-tool-tooltip');+ expect(surface.className).toContain('bg-popover');+ expect(surface.className).toContain('text-popover-foreground');+ expect(surface.className).not.toContain('bg-foreground');+ expect(surface.className).not.toContain('text-background');+ expect(surface.querySelector('svg')).toBeNull();});test('a tool with nothing to add gets no tooltip wrapper at all', async () => {@@ -4226,6 +4235,63 @@ describe('ThreadView auth-required dead ends', () => {await waitFor(() => expect(staged.text).toBe('finish the migration'));});+ test('registers a draft reader for its composer while mounted', () => {+ model = makeModel({ turnActive: false, items: [] });+ const view = render(<ThreadView info={makeInfo({ status: 'ready' })} />);+ const composer = screen.getByTestId('agent-thread-composer') as HTMLTextAreaElement;+ fireEvent.change(composer, { target: { value: ' typed so far ' } });+ const draft = readThreadDraft('thread-1');+ expect(draft?.text).toBe('typed so far');+ expect(draft?.doc).toEqual({+ type: 'doc',+ content: [{ type: 'paragraph', content: [{ type: 'text', text: ' typed so far ' }] }],+ });+ expect(draft?.attachments).toEqual([]);+ expect(draft?.uploadsPending).toBe(false);+ view.unmount();+ expect(readThreadDraft('thread-1')).toBeNull();+ });++ test('images carried into an agent that does not accept them are dropped with a notice', async () => {+ model = makeModel({ turnActive: false, items: [] });+ render(+ <ThreadView info={makeInfo({ status: 'ready', promptCapabilities: { image: false } })} />,+ );+ await act(async () => {+ stageThreadDraftContent('thread-1', {+ doc: {+ type: 'doc',+ content: [{ type: 'paragraph', content: [{ type: 'text', text: 'carried over' }] }],+ },+ attachments: [{ kind: 'image', mimeType: 'image/png', data: 'aGk=', name: 'a.png' }],+ });+ });+ const composer = screen.getByTestId('agent-thread-composer') as HTMLTextAreaElement;+ expect(composer.value).toBe('carried over');+ await waitFor(() =>+ expect(screen.queryByTestId('agent-thread-pending-image-preview')).toBeNull(),+ );+ expect(toastError).toHaveBeenCalledWith("Claude doesn't accept image attachments.");+ });++ test('staged draft content fills the composer and queues its attachments', async () => {+ model = makeModel({ turnActive: false, items: [] });+ render(<ThreadView info={makeInfo({ status: 'ready' })} />);+ await act(async () => {+ stageThreadDraftContent('thread-1', {+ doc: {+ type: 'doc',+ content: [{ type: 'paragraph', content: [{ type: 'text', text: 'carried over' }] }],+ },+ attachments: [{ kind: 'image', mimeType: 'image/png', data: 'aGk=', name: 'a.png' }],+ });+ });+ const composer = screen.getByTestId('agent-thread-composer') as HTMLTextAreaElement;+ expect(composer.value).toBe('carried over');+ expect(screen.getByTestId('agent-thread-pending-images')).toBeTruthy();+ expect(screen.getAllByTestId('agent-thread-pending-image-preview')).toHaveLength(1);+ });+const IN_FLIGHT_CASES = [{kind: 'new-chat',@@ -5298,6 +5364,28 @@ describe('ThreadView attachment budget and clear fence (PRD-8453)', () => {expect(screen.getByTestId('agent-thread-send')).toHaveProperty('disabled', false);});+ test('the draft reader reports an in-flight read and clears it once the read settles', async () => {+ model = makeModel({ items: [], turnActive: false });+ render(+ <ThreadView info={makeInfo({ status: 'ready', promptCapabilities: { image: true } })} />,+ );+ const composer = screen.getByTestId('agent-thread-composer');+ fireEvent.change(composer, { target: { value: 'describe the screenshot' } });++ fireDrop([smallPng('shot.png')]);++ expect(screen.queryAllByTestId('agent-thread-pending-upload')).toHaveLength(1);+ expect(readThreadDraft('thread-1')?.uploadsPending).toBe(true);+ await waitFor(() =>+ expect(screen.queryAllByTestId('agent-thread-pending-image-preview')).toHaveLength(1),+ );+ const settled = readThreadDraft('thread-1');+ expect(settled?.uploadsPending).toBe(false);+ expect(settled?.attachments).toEqual([+ expect.objectContaining({ kind: 'image', name: 'shot.png' }),+ ]);+ });+test('the drop highlight survives a dragleave that bubbles from a child', async () => {model = makeModel({ items: [], turnActive: false });render(diff --git a/packages/app/src/components/acp/ThreadView.tsx b/packages/app/src/components/acp/ThreadView.tsxindex aff7f59b3..8aada9ecf 100644--- a/packages/app/src/components/acp/ThreadView.tsx+++ b/packages/app/src/components/acp/ThreadView.tsx@@ -148,7 +148,11 @@ import {useAgentThread,useAgentThreadModel,} from '@/lib/acp/thread-client';-import { subscribeStagedThreadDraft } from '@/lib/acp/thread-draft-staging';+import {+ registerThreadDraftReader,+ subscribeStagedThreadDraft,+ subscribeStagedThreadDraftContent,+} from '@/lib/acp/thread-draft-staging';import {type PermissionOutcome,type RenderedItem,@@ -156,6 +160,7 @@ import {type RenderedTerminal,type RenderedToolCall,resolvePermissionOutcome,+ threadHasUserMessage,} from '@/lib/acp/thread-event-model';import {describeToolCall,@@ -322,6 +327,10 @@ function nextStartOutcome(}}+function composerInstruction(handle: ComposerMentionInputHandle | null): string {+ return handle?.getContent().instruction.trim() ?? '';+}+export function ThreadView({info,active = true,@@ -366,7 +375,7 @@ export function ThreadView({}, [dropNotice]);const imagesAccepted = info.promptCapabilities?.image === true;const uploadsPending = pendingUploads.length > 0;- const composerText = (): string => composerRef.current?.getContent().instruction.trim() ?? '';+ const composerText = (): string => composerInstruction(composerRef.current);const composerAttachments = (): readonly AttachmentPart[] => {const chips = composerRef.current?.getContent().attachments ?? [];return [...chips, ...pendingAttachments];@@ -490,11 +499,41 @@ export function ThreadView({const prevTurnActiveRef = useRef(false);useEffect(() => {- return subscribeStagedThreadDraft(info.threadId, (text) => {+ return registerThreadDraftReader(info.threadId, () => ({+ text: composerInstruction(composerRef.current),+ doc: composerRef.current?.getDoc() ?? null,+ attachments: attachmentsRef.current,+ uploadsPending,+ }));+ }, [info.threadId, uploadsPending]);++ useEffect(() => {+ const stopStaging = subscribeStagedThreadDraft(info.threadId, (text) => {composerRef.current?.appendText(text);});+ const stopStagingContent = subscribeStagedThreadDraftContent(info.threadId, (content) => {+ composerRef.current?.setDoc(content.doc);+ if (content.attachments.length > 0) {+ attachmentsRef.current = [...attachmentsRef.current, ...content.attachments];+ setPendingAttachments(attachmentsRef.current);+ }+ });+ return () => {+ stopStagingContent();+ stopStaging();+ };}, [info.threadId]);+ useEffect(() => {+ if (info.promptCapabilities == null || imagesAccepted) return;+ const kept = pendingAttachments.filter((part) => part.kind !== 'image');+ if (kept.length === pendingAttachments.length) return;+ attachmentsRef.current = kept;+ setPendingAttachments(kept);+ const agentName = agentDisplayName(info.agent.name);+ toast.error(t`${agentName} doesn't accept image attachments.`);+ }, [info.promptCapabilities, imagesAccepted, pendingAttachments, info.agent.name, t]);+const model = useAgentThreadModel(info.threadId);const status = info.status;const agentName = agentDisplayName(info.agent.name);@@ -1352,7 +1391,7 @@ export function ThreadView({) : null}<ThreadComposerinfo={info}- hasStartedWork={items.some((item) => item.kind === 'message' && item.role === 'user')}+ hasStartedWork={threadHasUserMessage({ items })}onNewChat={startFreshThread}composerRef={composerRef}mentionRecency={mentionRecency}@@ -2942,9 +2981,16 @@ function toolTitleText(text: ToolTooltipText | null): string | undefined {function ToolTooltipContent({ text }: { text: ToolTooltipText }): ReactNode {return (- <TooltipContent side="top" align="start" className="max-w-72">+ <TooltipContent+ side="top"+ align="start"+ sideOffset={6}+ arrow={false}+ className="max-w-72 border border-border bg-popover text-popover-foreground shadow-md"+ data-testid="agent-thread-tool-tooltip"+ >{text.purpose !== null ? <span className="block">{text.purpose}</span> : null}- <span className="block font-mono text-[10px] opacity-70" dir="ltr">+ <span className="block font-mono text-[10px] text-muted-foreground" dir="ltr">{text.id}</span></TooltipContent>diff --git a/packages/app/src/components/acp/composer-mention-input.test-helper.tsx b/packages/app/src/components/acp/composer-mention-input.test-helper.tsxindex 3ff2fc12a..a464be6b4 100644--- a/packages/app/src/components/acp/composer-mention-input.test-helper.tsx+++ b/packages/app/src/components/acp/composer-mention-input.test-helper.tsx@@ -3,6 +3,24 @@ import { type Ref, useImperativeHandle, useRef } from 'react';import type { ComposerMentionInputHandle } from '@/editor/ComposerMentionInput';import type { MentionRecency } from '@/editor/composer-mention/composer-mention';+function docPlainText(doc: {+ content?: readonly { content?: readonly Record<string, unknown>[] }[];+}): string {+ return (doc.content ?? [])+ .map((paragraph) =>+ (paragraph.content ?? [])+ .map((node) => {+ if (node.type === 'text') return String(node.text ?? '');+ const attrs = (node.attrs ?? {}) as Record<string, unknown>;+ if (node.type === 'composerMention') return `@${String(attrs.path ?? '')}`;+ if (node.type === 'composerCommand') return `/${String(attrs.name ?? '')}`;+ return '';+ })+ .join(''),+ )+ .join('\n');+}+export function mentionRecencyAttribute(recency: MentionRecency | undefined): string | undefined {return recency === undefined ? undefined : JSON.stringify(recency);}@@ -71,6 +89,20 @@ export function MockComposerMentionInput({el.value = el.value.trim() === '' ? text : `${el.value.replace(/\s+$/, '')}\n\n${text}`;notify();},+ getDoc: () => ({+ type: 'doc',+ content: (localRef.current?.value ?? '')+ .split('\n')+ .map((line) =>+ line === ''+ ? { type: 'paragraph' }+ : { type: 'paragraph', content: [{ type: 'text', text: line }] },+ ),+ }),+ setDoc: (doc) => {+ if (localRef.current) localRef.current.value = docPlainText(doc);+ notify();+ },getContent: () => ({instruction: localRef.current?.value ?? '',mentions: [],diff --git a/packages/app/src/components/ui/tooltip.dom.test.tsx b/packages/app/src/components/ui/tooltip.dom.test.tsxindex 7c94a5504..af4269435 100644--- a/packages/app/src/components/ui/tooltip.dom.test.tsx+++ b/packages/app/src/components/ui/tooltip.dom.test.tsx@@ -89,6 +89,29 @@ describe('Tooltip runtime contracts', () => {expect(screen.getByRole('tooltip').textContent).toBe('Tooltip body');});+ test.each([+ { arrow: undefined, svgs: 1 },+ { arrow: false, svgs: 0 },+ ])('renders the arrow unless arrow=false ($arrow)', async ({ arrow, svgs }) => {+ const { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } = await import('./tooltip');+ render(+ <TooltipProvider>+ <Tooltip open>+ <TooltipTrigger asChild>+ <button type="button">Target</button>+ </TooltipTrigger>+ <TooltipContent arrow={arrow}>Tooltip body</TooltipContent>+ </Tooltip>+ </TooltipProvider>,+ );+ await act(async () => {+ await Promise.resolve();+ });+ const content = document.querySelector('[data-slot="tooltip-content"]');+ expect(content).toBeTruthy();+ expect(content?.querySelectorAll('svg').length).toBe(svgs);+ });+test('content carries delayed-open motion and reduced-motion opt-in at runtime', async () => {await renderOpenTooltip();diff --git a/packages/app/src/components/ui/tooltip.tsx b/packages/app/src/components/ui/tooltip.tsxindex 10559640c..bd18798e5 100644--- a/packages/app/src/components/ui/tooltip.tsx+++ b/packages/app/src/components/ui/tooltip.tsx@@ -40,9 +40,10 @@ function TooltipTrigger({function TooltipContent({className,sideOffset = 0,+ arrow = true,children,...props-}: React.ComponentProps<typeof TooltipPrimitive.Content>) {+}: React.ComponentProps<typeof TooltipPrimitive.Content> & { arrow?: boolean }) {return (<TooltipPrimitive.Portal><TooltipPrimitive.Content@@ -55,7 +56,9 @@ function TooltipContent({{...props}>{children}- <TooltipPrimitive.Arrow className="z-50 size-2.5 translate-y-[calc(-50%_-_2px)] rotate-45 rounded-[2px] bg-foreground fill-foreground" />+ {arrow ? (+ <TooltipPrimitive.Arrow className="z-50 size-2.5 translate-y-[calc(-50%_-_2px)] rotate-45 rounded-[2px] bg-foreground fill-foreground" />+ ) : null}</TooltipPrimitive.Content></TooltipPrimitive.Portal>);diff --git a/packages/app/src/editor/ComposerMentionInput.tsx b/packages/app/src/editor/ComposerMentionInput.tsxindex 248a84192..6fa632dc7 100644--- a/packages/app/src/editor/ComposerMentionInput.tsx+++ b/packages/app/src/editor/ComposerMentionInput.tsx@@ -18,6 +18,7 @@ import {composerFirstLineText,composerSlashSuggestionKey,getSlashCommands,+ reconcileCommandNodes,resolveSlashTokenHint,type SlashCommandItem,type SlashTokenHint,@@ -51,6 +52,8 @@ export interface ComposerMentionInputHandle {clear: () => void;setText: (text: string) => void;appendText: (text: string) => void;+ getDoc: () => JSONContent | null;+ setDoc: (doc: JSONContent) => void;getContent: () => {instruction: string;mentions: string[];@@ -206,6 +209,7 @@ export function ComposerMentionInput({if (setSlashCommands(editor, slashCommands ?? null)) {const view = (editor as unknown as { editorView?: ComposerEditorView }).editorView;if (view) view.dispatch(editor.state.tr.setMeta('addToHistory', false));+ reconcileCommandNodes(editor);}setSlashHint(resolveSlashTokenHint(composerFirstLineText(editor), getSlashCommands(editor)));}, [editor, slashCommands]);@@ -226,9 +230,15 @@ export function ComposerMentionInput({onMentionsChangeRef.current?.(serializeComposerContent(editor).mentions);}, [editor]);- useImperativeHandle(- ref,- () => ({+ useImperativeHandle(ref, () => {+ const notifyContentMutation = (): void => {+ if (!editor) return;+ onEmptyChangeRef.current(isComposerEmpty(editor));+ onContentChangeRef.current?.(editor.getJSON());+ onMentionsChangeRef.current?.(serializeComposerContent(editor).mentions);+ setSlashHint(resolveSlashTokenHint(composerFirstLineText(editor), getSlashCommands(editor)));+ };+ return {focus: () => editor?.commands.focus(),refuseDrop: (reason: string) => {dropRefusalIdRef.current += 1;@@ -240,12 +250,7 @@ export function ComposerMentionInput({setText: (text: string) => {if (!editor) return;editor.commands.setContent(textToParagraphs(text));- onEmptyChangeRef.current(isComposerEmpty(editor));- onContentChangeRef.current?.(editor.getJSON());- onMentionsChangeRef.current?.(serializeComposerContent(editor).mentions);- setSlashHint(- resolveSlashTokenHint(composerFirstLineText(editor), getSlashCommands(editor)),- );+ notifyContentMutation();},appendText: (text: string) => {if (!editor || text === '') return;@@ -257,12 +262,14 @@ export function ComposerMentionInput({...textToParagraphs(text),]);}- onEmptyChangeRef.current(isComposerEmpty(editor));- onContentChangeRef.current?.(editor.getJSON());- onMentionsChangeRef.current?.(serializeComposerContent(editor).mentions);- setSlashHint(- resolveSlashTokenHint(composerFirstLineText(editor), getSlashCommands(editor)),- );+ notifyContentMutation();+ },+ getDoc: () => (editor ? editor.getJSON() : null),+ setDoc: (doc: JSONContent) => {+ if (!editor) return;+ editor.commands.setContent(doc);+ reconcileCommandNodes(editor);+ notifyContentMutation();},getContent: () =>editor@@ -277,9 +284,8 @@ export function ComposerMentionInput({return;editor.chain().focus().insertContent('/').run();},- }),- [editor],- );+ };+ }, [editor]);const dropPolicy = attachmentDrop;const dropSurfaceProps =diff --git a/packages/app/src/editor/composer-mention/composer-slash-command.test.ts b/packages/app/src/editor/composer-mention/composer-slash-command.test.tsindex c94d13b9f..b55242eeb 100644--- a/packages/app/src/editor/composer-mention/composer-slash-command.test.ts+++ b/packages/app/src/editor/composer-mention/composer-slash-command.test.ts@@ -4,6 +4,7 @@ import {leadingSlashToken,resolveSlashTokenHint,type SlashCommandItem,+ slashTokenTailLength,} from './composer-slash-command';const COMMANDS: SlashCommandItem[] = [@@ -57,6 +58,14 @@ describe('leadingSlashToken', () => {});});+describe('slashTokenTailLength', () => {+ test('counts the rest of the token after the caret and stops at whitespace', () => {+ expect(slashTokenTailLength('iew please')).toBe(3);+ expect(slashTokenTailLength(' please')).toBe(0);+ expect(slashTokenTailLength('')).toBe(0);+ });+});+describe('resolveSlashTokenHint', () => {test('no leading token resolves to null', () => {expect(resolveSlashTokenHint('plain prose', COMMANDS)).toBeNull();diff --git a/packages/app/src/editor/composer-mention/composer-slash-command.ts b/packages/app/src/editor/composer-mention/composer-slash-command.tsindex c8cd03cfa..047cf84c1 100644--- a/packages/app/src/editor/composer-mention/composer-slash-command.ts+++ b/packages/app/src/editor/composer-mention/composer-slash-command.ts@@ -4,6 +4,7 @@ import { PluginKey, Plugin as PmPlugin } from '@tiptap/pm/state';import { Decoration, DecorationSet } from '@tiptap/pm/view';import { ReactRenderer } from '@tiptap/react';import Suggestion, { type SuggestionKeyDownProps, type SuggestionProps } from '@tiptap/suggestion';+import { getEditorView } from '@/editor/utils/get-editor-view';import {clearSuggestionSelectableCount,createSuggestionPopup,@@ -86,6 +87,35 @@ export function setSlashCommands(editor: Editor, commands: SlashCommandItem[] |return true;}+export function reconcileCommandNodes(editor: Editor): boolean {+ const commands = getSlashCommands(editor);+ if (commands === null) return false;+ const view = getEditorView(editor);+ if (view === undefined) return false;+ const { state } = view;+ const found: { pos: number; node: PmNode }[] = [];+ state.doc.descendants((node, pos) => {+ if (node.type.name === 'composerCommand') found.push({ pos, node });+ });+ if (found.length === 0) return false;+ const tr = state.tr;+ for (const { pos, node } of found.reverse()) {+ const name = String(node.attrs.name ?? '');+ const command = commands.find((c) => c.name === name);+ if (command === undefined) {+ tr.replaceWith(pos, pos + node.nodeSize, state.schema.text(`/${name}`));+ continue;+ }+ const hint = command.input?.hint ?? '';+ if (node.attrs.description !== command.description || node.attrs.hint !== hint) {+ tr.setNodeMarkup(pos, undefined, { name, description: command.description, hint });+ }+ }+ if (!tr.docChanged) return false;+ view.dispatch(tr.setMeta('addToHistory', false));+ return true;+}+export function filterSlashCommands(commands: readonly SlashCommandItem[],query: string,@@ -110,6 +140,12 @@ export function leadingSlashToken(text: string): { name: string; length: numberreturn { name: match[1] ?? '', length: match[0].length };}+const SLASH_TRIGGER_PREFIXES: readonly string[] = [' ', '\t', '\n', '\u00a0'];++export function slashTokenTailLength(textAfterCaret: string): number {+ return /^\S*/.exec(textAfterCaret)?.[0].length ?? 0;+}+export type SlashTokenHint =| { kind: 'known'; name: string; description: string }| { kind: 'unknown'; name: string; agentHasCommands: boolean };@@ -246,8 +282,7 @@ export const ComposerSlashCommand = Extension.create<SlashCommandOptions, SlashCeditor: this.editor,pluginKey: composerSlashSuggestionKey,char: '/',- startOfLine: true,- allow: ({ range }) => range.from === 1,+ allowedPrefixes: [...SLASH_TRIGGER_PREFIXES],items: ({ query }) => {const commands = liveCommands();@@ -256,26 +291,31 @@ export const ComposerSlashCommand = Extension.create<SlashCommandOptions, SlashC},command: ({ editor, range, props: item }) => {- const leading = editor.state.doc.firstChild?.firstChild ?? null;- const tokenLength = leading?.isText- ? (leadingSlashToken(leading.text ?? '')?.length ?? 0)- : 0;+ const $to = editor.state.doc.resolve(range.to);+ const following = editor.state.doc.textBetween(range.to, $to.end());+ const tail = slashTokenTailLength(following);+ const spacer = /^\s/.test(following.slice(tail)) ? '' : ' ';+ const atMessageStart = range.from === 1;try {editor.chain().focus()- .deleteRange({ from: range.from, to: Math.max(range.to, 1 + tokenLength) })- .insertContent([- {- type: 'composerCommand',- attrs: {- name: item.name,- description: item.description,- hint: item.input?.hint ?? '',- },- },- { type: 'text', text: ' ' },- ])+ .deleteRange({ from: range.from, to: range.to + tail })+ .insertContent(+ atMessageStart+ ? [+ {+ type: 'composerCommand',+ attrs: {+ name: item.name,+ description: item.description,+ hint: item.input?.hint ?? '',+ },+ },+ ...(spacer === '' ? [] : [{ type: 'text', text: spacer }]),+ ]+ : [{ type: 'text', text: `/${item.name}${spacer}` }],+ ).run();} catch (err) {console.error('[composer-slash-command] insert failed', { item, range }, err);diff --git a/packages/app/src/editor/composer-mention/composer-slash-input.dom.test.tsx b/packages/app/src/editor/composer-mention/composer-slash-input.dom.test.tsxindex 597b50dd5..2303e78bb 100644--- a/packages/app/src/editor/composer-mention/composer-slash-input.dom.test.tsx+++ b/packages/app/src/editor/composer-mention/composer-slash-input.dom.test.tsx@@ -200,6 +200,59 @@ describe('token decoration + hint line', () => {});});+describe('carried command nodes', () => {+ const commandDoc = (name: string, description: string) => ({+ type: 'doc',+ content: [+ {+ type: 'paragraph',+ content: [+ { type: 'composerCommand', attrs: { name, description, hint: '' } },+ { type: 'text', text: ' now' },+ ],+ },+ ],+ });++ test('a command the agent does not offer becomes plain text and is flagged', () => {+ const { ref, box, editor } = renderComposer({ slashCommands: COMMANDS });+ act(() => ref.current?.setDoc(commandDoc('deploy', 'Ship it')));+ expect(box.querySelector('[data-composer-command]')).toBeNull();+ expect(editor.state.doc.textContent).toBe('/deploy now');+ expect(screen.getByTestId('composer-slash-hint').textContent).toContain(+ "/deploy isn't a command this agent offers",+ );+ });++ test("a command the agent offers keeps its node and takes that agent's metadata", () => {+ const { ref, box, editor } = renderComposer({ slashCommands: COMMANDS });+ act(() => ref.current?.setDoc(commandDoc('review', 'stale description')));+ expect(box.querySelector('[data-composer-command="review"]')).not.toBeNull();+ const node = editor.state.doc.firstChild?.firstChild;+ expect(node?.attrs.description).toBe('Review the current diff');+ });++ test('a later command list update re-checks a carried node', () => {+ const { ref, box, rerender } = renderComposer({ slashCommands: null });+ act(() => ref.current?.setDoc(commandDoc('deploy', 'Ship it')));+ expect(box.querySelector('[data-composer-command="deploy"]')).not.toBeNull();+ rerender(+ <ComposerMentionInput+ attachmentDrop={{ kind: 'host' }}+ ref={ref}+ ariaLabel="Message Agent"+ onEmptyChange={() => {}}+ onSubmit={() => {}}+ slashCommands={COMMANDS}+ />,+ );+ expect(box.querySelector('[data-composer-command]')).toBeNull();+ expect(screen.getByTestId('composer-slash-hint').textContent).toContain(+ "/deploy isn't a command this agent offers",+ );+ });+});+describe('picker lifecycle', () => {test('the imperative command affordance opens the same picker as typing slash', async () => {const { editor, ref } = renderComposer({ slashCommands: COMMANDS });@@ -334,12 +387,36 @@ describe('picker lifecycle', () => {expect(onEscape).not.toHaveBeenCalled();});- test('a slash mid-text does not open the picker', async () => {- const { editor } = renderComposer({ slashCommands: COMMANDS });+ test('a slash after whitespace mid-message opens the picker and completes plain text', async () => {+ const { editor, ref, box } = renderComposer({ slashCommands: COMMANDS });editor.commands.focus('end');editor.commands.insertContent('see /rev');- await new Promise((resolve) => setTimeout(resolve, 20));- expect(composerSlashSuggestionKey.getState(editor.state)?.active).toBeFalsy();- expect(screen.queryByTestId('composer-slash-menu')).toBeNull();+ expect(await pressKeyOnceItemsLoad(editor, 'Enter')).toBe(true);+ expect(editor.state.doc.textContent).toBe('see /review ');+ expect(box.querySelector('[data-composer-command]')).toBeNull();+ expect(box.querySelector('.composer-slash-token')).toBeNull();+ expect(ref.current?.getContent().instruction).toBe('see /review');+ expect(screen.getByTestId('composer-slash-hint').textContent).toBe('');});++ test('a mid-message pick with the caret mid-token replaces the whole token', async () => {+ const { editor } = renderComposer({ slashCommands: COMMANDS });+ editor.commands.focus('end');+ editor.commands.insertContent('run /create_plan now');+ editor.commands.setTextSelection(8);+ expect(await pressKeyOnceItemsLoad(editor, 'Enter')).toBe(true);+ expect(editor.state.doc.textContent).toBe('run /create_plan now');+ });++ test.each(['and/or', 'see docs/rev', 'https://example.test/rev'])(+ 'a slash inside %s never opens the picker',+ async (text) => {+ const { editor } = renderComposer({ slashCommands: COMMANDS });+ editor.commands.focus('end');+ editor.commands.insertContent(text);+ await new Promise((resolve) => setTimeout(resolve, 20));+ expect(composerSlashSuggestionKey.getState(editor.state)?.active).toBeFalsy();+ expect(screen.queryByTestId('composer-slash-menu')).toBeNull();+ },+ );});diff --git a/packages/app/src/lib/acp/launch-agent-thread.ts b/packages/app/src/lib/acp/launch-agent-thread.tsindex 13c1bf82e..df87fcc24 100644--- a/packages/app/src/lib/acp/launch-agent-thread.ts+++ b/packages/app/src/lib/acp/launch-agent-thread.ts@@ -3,7 +3,11 @@ import { t } from '@lingui/core/macro';import { toast } from 'sonner';import { agentDisplayName } from '@/lib/acp/agent-display';import { getAgentThreadClient, ThreadChannelUnavailableError } from '@/lib/acp/thread-client';-import { stageThreadDraft } from '@/lib/acp/thread-draft-staging';+import {+ stageThreadDraft,+ stageThreadDraftContent,+ type ThreadDraftContent,+} from '@/lib/acp/thread-draft-staging';const inflightLaunches = new Set<string>();const IMAGE_CAPABILITY_WATCH_MS = 60_000;@@ -49,7 +53,7 @@ export function launchAgentThread(prompt: string | null,docName: string | null,titleHint: string | null,- stageDraft?: string | null,+ stageDraft?: string | ThreadDraftContent | null,attachments?: readonly AttachmentPart[],): Promise<ThreadLaunchOutcome> {const launchKey = `${agent.source}:${agent.id}`;@@ -67,7 +71,8 @@ export function launchAgentThread(warnWhenLaunchedImagesAreUnsupported(info, attachments);if (stageDraft != null) {try {- stageThreadDraft(info.threadId, stageDraft);+ if (typeof stageDraft === 'string') stageThreadDraft(info.threadId, stageDraft);+ else stageThreadDraftContent(info.threadId, stageDraft);} catch (err) {console.error('[agent-threads] draft staging failed for', info.threadId, err);}diff --git a/packages/app/src/lib/acp/thread-draft-staging.test.ts b/packages/app/src/lib/acp/thread-draft-staging.test.tsindex 090226cb6..67a7488a4 100644--- a/packages/app/src/lib/acp/thread-draft-staging.test.ts+++ b/packages/app/src/lib/acp/thread-draft-staging.test.ts@@ -1,8 +1,13 @@import { afterEach, describe, expect, test, vi } from 'vitest';import {+ isEmptyThreadDraft,+ readThreadDraft,+ registerThreadDraftReader,resetStagedThreadDrafts,stageThreadDraft,+ stageThreadDraftContent,subscribeStagedThreadDraft,+ subscribeStagedThreadDraftContent,} from './thread-draft-staging';afterEach(() => {@@ -72,3 +77,69 @@ describe('thread draft staging', () => {expect(older).not.toHaveBeenCalled();});});++describe('thread draft readers', () => {+ const snapshot = (text: string) => ({+ text,+ doc: { type: 'doc', content: [{ type: 'paragraph', content: [{ type: 'text', text }] }] },+ attachments: [],+ uploadsPending: false,+ });++ test('reads the live draft through the registered reader and nothing once it unregisters', () => {+ expect(readThreadDraft('t1')).toBeNull();+ const stop = registerThreadDraftReader('t1', () => snapshot('typed so far'));+ expect(readThreadDraft('t1')?.text).toBe('typed so far');+ stop();+ expect(readThreadDraft('t1')).toBeNull();+ });++ test('a stale unregister does not remove a newer reader', () => {+ const stopFirst = registerThreadDraftReader('t2', () => snapshot('first'));+ registerThreadDraftReader('t2', () => snapshot('second'));+ stopFirst();+ expect(readThreadDraft('t2')?.text).toBe('second');+ });++ test('a draft with no text and no attachments is empty', () => {+ expect(+ isEmptyThreadDraft({ text: '', doc: null, attachments: [], uploadsPending: false }),+ ).toBe(true);+ expect(isEmptyThreadDraft(snapshot('x'))).toBe(false);+ expect(+ isEmptyThreadDraft({+ text: '',+ doc: null,+ attachments: [{ kind: 'image', mimeType: 'image/png', data: 'aGk=', name: 'a.png' }],+ uploadsPending: false,+ }),+ ).toBe(false);+ });+});++describe('thread draft content staging', () => {+ const content = {+ doc: { type: 'doc', content: [{ type: 'paragraph', content: [{ type: 'text', text: 'hi' }] }] },+ attachments: [{ kind: 'image', mimeType: 'image/png', data: 'aGk=', name: 'a.png' }],+ } as const;++ test('holds content until a subscriber arrives, then delivers it once', () => {+ stageThreadDraftContent('t3', content);+ const seen: unknown[] = [];+ const stop = subscribeStagedThreadDraftContent('t3', (c) => seen.push(c));+ expect(seen).toEqual([content]);+ stop();+ const later: unknown[] = [];+ const stopLater = subscribeStagedThreadDraftContent('t3', (c) => later.push(c));+ expect(later).toEqual([]);+ stopLater();+ });++ test('delivers straight to a live subscriber', () => {+ const seen: unknown[] = [];+ const stop = subscribeStagedThreadDraftContent('t4', (c) => seen.push(c));+ stageThreadDraftContent('t4', content);+ expect(seen).toEqual([content]);+ stop();+ });+});diff --git a/packages/app/src/lib/acp/thread-draft-staging.ts b/packages/app/src/lib/acp/thread-draft-staging.tsindex 917df1eb5..0f5342059 100644--- a/packages/app/src/lib/acp/thread-draft-staging.ts+++ b/packages/app/src/lib/acp/thread-draft-staging.ts@@ -1,7 +1,28 @@+import type { AttachmentPart } from '@inkeep/open-knowledge-core/acp/thread-protocol';+import type { JSONContent } from '@tiptap/core';++export interface ThreadDraftContent {+ readonly doc: JSONContent;+ readonly attachments: readonly AttachmentPart[];+}++export interface ThreadDraftSnapshot {+ readonly text: string;+ readonly doc: JSONContent | null;+ readonly attachments: readonly AttachmentPart[];+ readonly uploadsPending: boolean;+}+const pending = new Map<string, string>();const listeners = new Map<string, (text: string) => void>();+const pendingContent = new Map<string, ThreadDraftContent>();++const contentListeners = new Map<string, (content: ThreadDraftContent) => void>();++const readers = new Map<string, () => ThreadDraftSnapshot>();+export function stageThreadDraft(threadId: string, text: string): void {if (text.trim() === '') return;const listener = listeners.get(threadId);@@ -27,7 +48,53 @@ export function subscribeStagedThreadDraft(};}+export function stageThreadDraftContent(threadId: string, content: ThreadDraftContent): void {+ const listener = contentListeners.get(threadId);+ if (listener !== undefined) {+ listener(content);+ return;+ }+ pendingContent.set(threadId, content);+}++export function subscribeStagedThreadDraftContent(+ threadId: string,+ onContent: (content: ThreadDraftContent) => void,+): () => void {+ contentListeners.set(threadId, onContent);+ const held = pendingContent.get(threadId);+ if (held !== undefined) {+ pendingContent.delete(threadId);+ onContent(held);+ }+ return () => {+ if (contentListeners.get(threadId) === onContent) contentListeners.delete(threadId);+ };+}++export function registerThreadDraftReader(+ threadId: string,+ read: () => ThreadDraftSnapshot,+): () => void {+ readers.set(threadId, read);+ return () => {+ if (readers.get(threadId) === read) readers.delete(threadId);+ };+}++export function readThreadDraft(threadId: string): ThreadDraftSnapshot | null {+ const read = readers.get(threadId);+ return read === undefined ? null : read();+}++export function isEmptyThreadDraft(snapshot: ThreadDraftSnapshot): boolean {+ return snapshot.text === '' && snapshot.attachments.length === 0;+}+export function resetStagedThreadDrafts(): void {pending.clear();listeners.clear();+ pendingContent.clear();+ contentListeners.clear();+ readers.clear();}diff --git a/packages/app/src/lib/acp/thread-event-model.test.ts b/packages/app/src/lib/acp/thread-event-model.test.tsindex ea55f7770..eb328a88f 100644--- a/packages/app/src/lib/acp/thread-event-model.test.ts+++ b/packages/app/src/lib/acp/thread-event-model.test.ts@@ -4,6 +4,7 @@ import {buildThreadRenderModel,type RenderedItem,resolvePermissionOutcome,+ threadHasUserMessage,} from './thread-event-model';function ev(event: ThreadEvent): ThreadEvent {@@ -936,3 +937,22 @@ describe('sent-message timestamps', () => {expect(message.sentAt).toBeUndefined();});});++describe('threadHasUserMessage', () => {+ test('is true only once a user message is in the transcript', () => {+ expect(threadHasUserMessage({ items: [] })).toBe(false);+ expect(+ threadHasUserMessage({+ items: [{ kind: 'message', role: 'agent', text: 'hello', messageId: 'a1' }],+ }),+ ).toBe(false);+ expect(+ threadHasUserMessage({+ items: [+ { kind: 'message', role: 'agent', text: 'hello', messageId: 'a1' },+ { kind: 'message', role: 'user', text: 'hi', messageId: 'u1' },+ ],+ }),+ ).toBe(true);+ });+});diff --git a/packages/app/src/lib/acp/thread-event-model.ts b/packages/app/src/lib/acp/thread-event-model.tsindex 2f4fb4668..f5f0f811d 100644--- a/packages/app/src/lib/acp/thread-event-model.ts+++ b/packages/app/src/lib/acp/thread-event-model.ts@@ -615,6 +615,10 @@ export class ThreadRenderModelBuilder {}}+export function threadHasUserMessage(model: Pick<ThreadRenderModel, 'items'>): boolean {+ return model.items.some((item) => item.kind === 'message' && item.role === 'user');+}+export function buildThreadRenderModel(events: readonly ThreadEvent[],agent: CodexLegacyAgentIdentity | null,diff --git a/packages/server/src/acp/thread-manager.ts b/packages/server/src/acp/thread-manager.tsindex f3e428236..f76937166 100644--- a/packages/server/src/acp/thread-manager.ts+++ b/packages/server/src/acp/thread-manager.ts@@ -1025,29 +1025,30 @@ export class AcpThreadManager {).connect(stream);record.conn = conn;- conn.closed.then(- async () => {- await drainStderr();- if (record.conn !== conn || launchStatusMuted()) return;- if (record.info.status !== 'exited' && record.info.status !== 'error') {- this.emitStatus(record, 'exited', 'agent connection closed');- }- },- async (err: unknown) => {- await drainStderr();- if (record.conn !== conn || launchStatusMuted()) return;+ const settleClosedConnection = async (failure: { err: unknown } | null): Promise<void> => {+ await drainStderr();+ if (record.conn !== conn || launchStatusMuted()) return;+ if (failure !== null) {this.opts.log.warn(- { err, threadId: record.info.threadId },+ { err: failure.err, threadId: record.info.threadId },'[acp-threads] agent connection closed with error',);- if (record.info.status !== 'exited' && record.info.status !== 'error') {- this.emitStatus(- record,- 'error',- `agent connection failed: ${err instanceof Error ? err.message : String(err)}`,- );- }- },+ }+ if (record.info.status === 'exited' || record.info.status === 'error') return;+ if (failure === null) {+ this.emitStatus(record, 'exited', 'agent connection closed');+ return;+ }+ const { err } = failure;+ this.emitStatus(+ record,+ 'error',+ `agent connection failed: ${err instanceof Error ? err.message : String(err)}`,+ );+ };+ conn.closed.then(+ () => settleClosedConnection(null),+ (err: unknown) => settleClosedConnection({ err }),);let init: InitializeResponse;