Beautiful, AI-native markdown IDE and LLM wiki
TypeScript 2nd-brainagent-skillsclaudecodexcompany-braindocsknowledge-knowledge-baseknowledge-managementllmllm-wikillm-wiki-karpathymarkdownmarkdown-editormdmdxnotespkmsecond-brainskills
feat(ok): quiet the agent thread transcript (#2888)
sarahfde7083aefd6
diff --git a/.changeset/acp-tool-call-transcript-density.md b/.changeset/acp-tool-call-transcript-density.mdnew file mode 100644index 000000000..bdca66c26--- /dev/null+++ b/.changeset/acp-tool-call-transcript-density.md@@ -0,0 +1,11 @@+---+"@inkeep/open-knowledge": patch+---++Quiet the agent thread transcript: tool calls, permission prompts, and thoughts now signal by exception instead of decorating every row.++Permission prompts lay out as at most three controls — refusal pinned far left, the least-privilege grant far right, and every escalating grant collapsed into a secondary split button beside it. Options are grouped by stance rather than by looking up one option per `kind`, since ACP treats `kind` as a styling hint and agents do offer several grants that differ only by name ("Allow for This Session" vs "Allow and Don't Ask Again"). The card is neutral rather than amber, and a settled prompt whose gated tool call is in the transcript now renders on that call's row instead of as a second card restating the tool name; a prompt whose call never appears keeps its standalone card so an outcome is never unreachable.++Tool calls render collapsed, with failures the exception that opens itself. Completion is no longer badged — a call that finishes while you watch flashes a check that fades, and a replayed transcript carries no per-row status chrome at all, so the one row that failed is the one that stands out. Status still reaches assistive technology in every state. A row only draws its border when expanded, calls with nothing to reveal are no longer interactive controls, and consecutive calls sit tighter as a single burst of activity. An approval leaves no trace; a refusal says so in words, and only when the row's own status does not already explain it.++Agent thoughts parse markdown instead of printing literal `**` around the summary line agents prefix them with, with emphasis flattened so a thought stays quieter than the reply. Code renders one size down to sit optically level with surrounding prose, and a markdown fence wrapping a whole tool-output block no longer leaves its backticks on screen.diff --git a/packages/app/src/components/acp/AgentMarkdown.tsx b/packages/app/src/components/acp/AgentMarkdown.tsxindex 8a3f864f4..19d74c7d9 100644--- a/packages/app/src/components/acp/AgentMarkdown.tsx+++ b/packages/app/src/components/acp/AgentMarkdown.tsx@@ -25,7 +25,14 @@ export function AgentMarkdown({ text }: { text: string }): ReactNode {// blocks: Streamdown bundles it into the line-number counter classes,// so `lineNumbers={false}` alone collapses multi-line code onto one// visual line.- className="[&>*:first-child]:mt-0 [&>*:last-child]:mb-0 [&_pre_code>span]:block"+ //+ // Code drops a notch to 13px (Streamdown hard-codes `text-sm` on both+ // inline and block code) so the mono face, which reads larger than the+ // UI face at a matched point size, sits optically level with the prose+ // around it. Deliberately not `!`: the descendant selector already+ // outranks Streamdown's own class, which leaves an `!` override on a+ // wrapper — the thought bubble's flattening — free to win.+ className="[&>*:first-child]:mt-0 [&>*:last-child]:mb-0 [&_pre_code>span]:block [&_code]:text-1sm [&_pre]:text-1sm"lineNumbers={false}controls={{ code: { copy: true, download: false }, table: false, mermaid: false }}// Plain hardened anchors instead of Streamdown's confirm-modal flow:diff --git a/packages/app/src/components/acp/ThreadView.dom.test.tsx b/packages/app/src/components/acp/ThreadView.dom.test.tsxindex eceeed8e9..e45404295 100644--- a/packages/app/src/components/acp/ThreadView.dom.test.tsx+++ b/packages/app/src/components/acp/ThreadView.dom.test.tsx@@ -8,7 +8,14 @@*/import type { ThreadInfo } from '@inkeep/open-knowledge-core/acp/thread-protocol';-import { cleanup, fireEvent, render as rtlRender, screen, within } from '@testing-library/react';+import {+ act,+ cleanup,+ fireEvent,+ render as rtlRender,+ screen,+ within,+} from '@testing-library/react';import userEvent from '@testing-library/user-event';import { afterEach, describe, expect, test, vi } from 'vitest';import { TooltipProvider } from '@/components/ui/tooltip';@@ -95,6 +102,7 @@ function makeModel(overrides?: Partial<ThreadRenderModel>): ThreadRenderModel {turnActive: true,tokenUsage: null,terminals: {},+ permissionsByToolCall: {},...overrides,};}@@ -123,12 +131,25 @@ function permission(overrides?: Partial<Extract<RenderedItem, { kind: 'permissiotoolKind: 'execute',options: [{ optionId: 'yes', name: 'Allow', kind: 'allow_once' }],resolved: null,+ toolCallId: null,+ mergedIntoToolCall: false,...overrides,};}+/**+ * Tool-call bodies are collapsed by default (failures excepted), so any test+ * asserting on body content has to open the card first.+ */+async function openToolCall(): Promise<void> {+ await userEvent.click(screen.getByRole('button', { name: /Run tests/ }));+}+afterEach(() => {cleanup();+ // No-op when timers are already real; makes cleanup unconditional even if a+ // test using fake timers fails before its own teardown would run.+ vi.useRealTimers();respondPermission.mockClear();setConfigOption.mockClear();setMode.mockClear();@@ -262,7 +283,7 @@ describe('ThreadView terminal card', () => {expect(screen.getByTestId('agent-thread-terminal-exit').textContent).toBe('exit 0');});- test('a failing command shows a destructive exit badge; ANSI is stripped', () => {+ test('a failing command shows a destructive exit badge; ANSI is stripped', async () => {model = makeModel({items: [toolCall({ terminalIds: ['t1'] })],terminals: {@@ -273,6 +294,7 @@ describe('ThreadView terminal card', () => {},});render(<ThreadView info={makeInfo()} />);+ await openToolCall();const badge = screen.getByTestId('agent-thread-terminal-exit');expect(badge.textContent).toBe('exit 3');const card = screen.getByTestId('agent-thread-terminal');@@ -280,19 +302,20 @@ describe('ThreadView terminal card', () => {expect(card.textContent).not.toContain('[31m');});- test('a still-running terminal shows no exit badge', () => {+ test('a still-running terminal shows no exit badge', async () => {model = makeModel({items: [toolCall({ terminalIds: ['t1'] })],terminals: { t1: terminal({ exit: null }) },});render(<ThreadView info={makeInfo()} />);+ await openToolCall();expect(screen.getByTestId('agent-thread-terminal').textContent).toContain('running');expect(screen.queryByTestId('agent-thread-terminal-exit')).toBeNull();});});describe('ThreadView inline diff', () => {- test('unchanged lines render once as context, not as remove+add pairs', () => {+ test('unchanged lines render once as context, not as remove+add pairs', async () => {model = makeModel({items: [toolCall({@@ -302,6 +325,7 @@ describe('ThreadView inline diff', () => {],});render(<ThreadView info={makeInfo()} />);+ await openToolCall();const transcript = screen.getByTestId('agent-thread-transcript');const occurrences = (transcript.textContent?.match(/same/g) ?? []).length;expect(occurrences).toBe(1);@@ -309,7 +333,7 @@ describe('ThreadView inline diff', () => {expect(transcript.textContent).toContain('+ new');});- test('long unchanged runs collapse into a gap row', () => {+ test('long unchanged runs collapse into a gap row', async () => {const lines = Array.from({ length: 30 }, (_, i) => `line ${i}`).join('\n');model = makeModel({items: [@@ -320,12 +344,13 @@ describe('ThreadView inline diff', () => {],});render(<ThreadView info={makeInfo()} />);+ await openToolCall();expect(screen.getByTestId('agent-thread-transcript').textContent).toContain('unchanged lines');});});describe('ThreadView permissions', () => {- test('stacks choices in least-privilege order with one primary action', () => {+ test('pins refusal left and the least-privilege grant right, with escalating grants between', () => {model = makeModel({items: [permission({@@ -344,17 +369,65 @@ describe('ThreadView permissions', () => {render(<ThreadView info={makeInfo({ status: 'awaiting_permission' })} />);const card = screen.getByTestId('agent-thread-permission');- const buttons = within(card).getAllByRole('button');- expect(buttons.map((button) => button.textContent)).toEqual([- 'Allow',- 'Always allow all mcp__open-knowledge__exec',- 'Deny',- ]);- expect(buttons.map((button) => button.getAttribute('data-variant'))).toEqual([- 'default',- 'outline',- 'outline',- ]);+ const deny = screen.getByTestId('agent-thread-permission-deny');+ const secondary = screen.getByTestId('agent-thread-permission-allow-more');+ const primary = screen.getByTestId('agent-thread-permission-allow');++ // Refusal first in the DOM (far left), primary grant last (far right).+ expect(deny.compareDocumentPosition(secondary) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();+ expect(+ secondary.compareDocumentPosition(primary) & Node.DOCUMENT_POSITION_FOLLOWING,+ ).toBeTruthy();++ // Only the least-privilege grant carries primary emphasis.+ expect(primary.textContent).toBe('Allow');+ expect(primary.getAttribute('data-variant')).toBe('default');+ expect(deny.getAttribute('data-variant')).toBe('outline');+ expect(secondary.getAttribute('data-variant')).toBe('outline');++ // A lone escalating grant needs no chevron — it is directly actionable.+ expect(within(card).queryByTestId('agent-thread-permission-allow-more-more')).toBeNull();+ });++ test('collapses several escalating grants behind one secondary button', async () => {+ // Claude's four-option shape: `kind` is a hint, not a key — two distinct+ // grants share `allow_always` and differ only by name.+ model = makeModel({+ items: [+ permission({+ options: [+ { optionId: 'yes', name: 'Allow', kind: 'allow_once' },+ { optionId: 'session', name: 'Allow for This Session', kind: 'allow_always' },+ { optionId: 'forever', name: "Allow and Don't Ask Again", kind: 'allow_always' },+ { optionId: 'no', name: 'Decline', kind: 'reject_once' },+ ],+ }),+ ],+ });+ render(<ThreadView info={makeInfo({ status: 'awaiting_permission' })} />);++ expect(screen.getByTestId('agent-thread-permission-deny').textContent).toBe('Decline');+ expect(screen.getByTestId('agent-thread-permission-allow').textContent).toBe('Allow');+ const secondary = screen.getByTestId('agent-thread-permission-allow-more');+ expect(secondary.textContent).toBe('Allow for This Session');+ // The last grant is folded away, not rendered as a fourth top-level button.+ expect(screen.queryByRole('button', { name: "Allow and Don't Ask Again" })).toBeNull();++ // The secondary button answers directly — no trip through the menu.+ await userEvent.click(secondary);+ expect(respondPermission).toHaveBeenCalledWith('thread-1', 'r1', {+ kind: 'selected',+ optionId: 'session',+ });++ // Its chevron lists every escalating grant, the button's own included.+ await userEvent.click(screen.getByTestId('agent-thread-permission-allow-more-more'));+ expect(await screen.findByRole('menuitem', { name: 'Allow for This Session' })).toBeDefined();+ fireEvent.click(screen.getByRole('menuitem', { name: "Allow and Don't Ask Again" }));+ expect(respondPermission).toHaveBeenCalledWith('thread-1', 'r1', {+ kind: 'selected',+ optionId: 'forever',+ });});test('clicking an offered option approves with that optionId (selected outcome)', async () => {@@ -374,7 +447,7 @@ describe('ThreadView permissions', () => {expect(respondPermission).toHaveBeenCalledWith('thread-1', 'r1', { kind: 'cancelled' });});- test('offers no extra Deny when the agent already has a reject option', () => {+ test("answers with the agent's own reject option rather than a second Deny", async () => {model = makeModel({items: [permission({@@ -386,7 +459,15 @@ describe('ThreadView permissions', () => {],});render(<ThreadView info={makeInfo({ status: 'awaiting_permission' })} />);- expect(screen.queryByTestId('agent-thread-permission-deny')).toBeNull();+ // One refusal control, and it routes through the agent's option (selected)+ // instead of the protocol-level `cancelled` fallback.+ const deny = screen.getByTestId('agent-thread-permission-deny');+ expect(deny.textContent).toBe('Reject');+ await userEvent.click(deny);+ expect(respondPermission).toHaveBeenCalledWith('thread-1', 'r1', {+ kind: 'selected',+ optionId: 'no',+ });});test("summarizes a chosen reject option as denied, never 'Approved'", () => {@@ -450,12 +531,292 @@ describe('ThreadView status + usage', () => {});});+describe('ThreadView tool-call status', () => {+ test('a settled successful call carries no visible status chrome', () => {+ model = makeModel({+ items: [toolCall({ status: 'completed', content: ['out'] })],+ turnActive: false,+ });+ render(<ThreadView info={makeInfo({ status: 'ready' })} />);+ // Replayed rows never flash a check, and "done" is not painted on the row.+ expect(screen.queryByTestId('agent-thread-tool-check')).toBeNull();+ expect(screen.queryByTestId('agent-thread-tool-failed')).toBeNull();+ expect(screen.queryByTestId('agent-thread-tool-spinner')).toBeNull();+ // …but the status still reaches assistive tech.+ expect(screen.getByRole('button', { name: /Run tests/ }).textContent).toContain('done');+ });++ test('a live call spins, then flashes a check on completion', () => {+ model = makeModel({ items: [toolCall({ status: 'in_progress', content: ['out'] })] });+ const { rerender } = render(<ThreadView info={makeInfo()} />);+ expect(screen.getByTestId('agent-thread-tool-spinner')).toBeDefined();+ expect(screen.queryByTestId('agent-thread-tool-check')).toBeNull();++ model = makeModel({+ items: [toolCall({ status: 'completed', content: ['out'] })],+ turnActive: false,+ });+ rerender(<ThreadView info={makeInfo({ status: 'ready' })} />);+ expect(screen.queryByTestId('agent-thread-tool-spinner')).toBeNull();+ // Only a call that completed while mounted acknowledges the transition.+ expect(screen.getByTestId('agent-thread-tool-check')).toBeDefined();+ });++ test('a fenced output block renders without its backticks', async () => {+ model = makeModel({+ items: [toolCall({ status: 'completed', content: ['```json\n{"ok":true}\n```'] })],+ turnActive: false,+ });+ render(<ThreadView info={makeInfo({ status: 'ready' })} />);+ await openToolCall();+ const body = screen.getByTestId('agent-thread-tool-call').textContent ?? '';+ expect(body).toContain('{"ok":true}');+ expect(body).not.toContain('```');+ });++ test('a fence opening partway through is output, not a wrapper', async () => {+ model = makeModel({+ items: [toolCall({ status: 'completed', content: ['see:\n```\ncode\n```'] })],+ turnActive: false,+ });+ render(<ThreadView info={makeInfo({ status: 'ready' })} />);+ await openToolCall();+ expect(screen.getByTestId('agent-thread-tool-call').textContent).toContain('```');+ });++ test('the completion check fades out once its window elapses', async () => {+ // Without this, deleting the setTimeout would leave a check pinned to every+ // recently-completed row and the "flashes a check" test above would still pass.+ vi.useFakeTimers({ shouldAdvanceTime: true });+ model = makeModel({ items: [toolCall({ status: 'in_progress', content: ['out'] })] });+ const { rerender } = render(<ThreadView info={makeInfo()} />);++ model = makeModel({+ items: [toolCall({ status: 'completed', content: ['out'] })],+ turnActive: false,+ });+ rerender(<ThreadView info={makeInfo({ status: 'ready' })} />);+ // `.className` on an <svg> is an SVGAnimatedString, not a string.+ expect(screen.getByTestId('agent-thread-tool-check').getAttribute('class')).toContain(+ 'opacity-100',+ );++ // Past COMPLETION_CHECK_MS the element stays mounted (so the row doesn't+ // reflow) but transitions to transparent.+ await act(async () => {+ vi.advanceTimersByTime(2_000);+ });+ expect(screen.getByTestId('agent-thread-tool-check').getAttribute('class')).toContain(+ 'opacity-0',+ );+ });++ test('a failed call keeps its badge — the exception is what gets marked', () => {+ model = makeModel({+ items: [toolCall({ status: 'failed', content: ['boom'] })],+ turnActive: false,+ });+ render(<ThreadView info={makeInfo({ status: 'ready' })} />);+ expect(screen.getByTestId('agent-thread-tool-failed').textContent).toBe('failed');+ });++ test('a call with nothing to reveal is not an interactive control', () => {+ model = makeModel({ items: [toolCall({ status: 'completed' })], turnActive: false });+ render(<ThreadView info={makeInfo({ status: 'ready' })} />);+ expect(screen.queryByRole('button', { name: /Run tests/ })).toBeNull();+ expect(screen.getByTestId('agent-thread-tool-call').textContent).toContain('Run tests');+ });+});++describe('ThreadView permission merged into its tool call', () => {+ const gated = (resolved: { optionId: string | null; auto: boolean }) =>+ permission({ toolCallId: 'c1', mergedIntoToolCall: true, resolved });++ function modelWithGatedCall(resolved: { optionId: string | null; auto: boolean }) {+ const item = gated(resolved);+ return makeModel({+ items: [toolCall({ status: 'completed' }), item],+ permissionsByToolCall: { c1: item },+ turnActive: false,+ });+ }++ test('an approval leaves no trace — the card goes, and nothing replaces it', () => {+ model = modelWithGatedCall({ optionId: 'yes', auto: false });+ render(<ThreadView info={makeInfo({ status: 'ready' })} />);+ // The call ran; that it was allowed is not separately worth saying.+ expect(screen.queryByTestId('agent-thread-permission')).toBeNull();+ expect(screen.queryByTestId('agent-thread-tool-permission')).toBeNull();+ });++ test('an auto-approval leaves no trace either', () => {+ model = modelWithGatedCall({ optionId: 'yes', auto: true });+ render(<ThreadView info={makeInfo({ status: 'ready' })} />);+ expect(screen.queryByTestId('agent-thread-permission')).toBeNull();+ expect(screen.queryByTestId('agent-thread-tool-permission')).toBeNull();+ });++ test('a refusal marks the row in words — it changed what happened', () => {+ model = modelWithGatedCall({ optionId: null, auto: false });+ render(<ThreadView info={makeInfo({ status: 'ready' })} />);+ expect(screen.getByTestId('agent-thread-tool-permission').textContent).toContain('Denied');+ });++ test('a dismissed prompt marks the row too — it also did not get an answer', () => {+ // `auto: true` with no chosen option is the timeout/turn-cancel path.+ model = modelWithGatedCall({ optionId: null, auto: true });+ render(<ThreadView info={makeInfo({ status: 'ready' })} />);+ expect(screen.getByTestId('agent-thread-tool-permission').textContent).toContain(+ 'Not answered',+ );+ });++ test('stays quiet when the failed row already says the call did not run', () => {+ // The FAILED badge and the body cover it; a third statement is noise.+ const item = gated({ optionId: null, auto: false });+ model = makeModel({+ items: [toolCall({ status: 'failed', content: ['User refused permission'] }), item],+ permissionsByToolCall: { c1: item },+ turnActive: false,+ });+ render(<ThreadView info={makeInfo({ status: 'ready' })} />);+ expect(screen.queryByTestId('agent-thread-tool-permission')).toBeNull();+ });++ test('drops an option name that only repeats the outcome, keeps a distinctive one', () => {+ const synonym = permission({+ toolCallId: 'c1',+ mergedIntoToolCall: true,+ options: [{ optionId: 'no', name: 'Reject', kind: 'reject_once' }],+ resolved: { optionId: 'no', auto: false },+ });+ model = makeModel({+ items: [toolCall({ status: 'completed' }), synonym],+ permissionsByToolCall: { c1: synonym },+ turnActive: false,+ });+ render(<ThreadView info={makeInfo({ status: 'ready' })} />);+ // "Denied — Reject" says the same word twice.+ expect(screen.getByTestId('agent-thread-tool-permission').textContent).toBe('Denied');++ cleanup();+ const distinctive = permission({+ toolCallId: 'c1',+ mergedIntoToolCall: true,+ options: [{ optionId: 'never', name: 'Always deny', kind: 'reject_always' }],+ resolved: { optionId: 'never', auto: false },+ });+ model = makeModel({+ items: [toolCall({ status: 'completed' }), distinctive],+ permissionsByToolCall: { c1: distinctive },+ turnActive: false,+ });+ render(<ThreadView info={makeInfo({ status: 'ready' })} />);+ // The persistence is not implied by "Denied", so it survives.+ expect(screen.getByTestId('agent-thread-tool-permission').textContent).toContain('Always deny');+ });++ test('a pending prompt keeps its card — it is the thing you act on', () => {+ const item = permission({ toolCallId: 'c1', mergedIntoToolCall: true });+ model = makeModel({+ items: [toolCall({ status: 'in_progress' }), item],+ permissionsByToolCall: { c1: item },+ });+ render(<ThreadView info={makeInfo({ status: 'awaiting_permission' })} />);+ expect(screen.getByTestId('agent-thread-permission')).toBeDefined();+ expect(screen.queryByTestId('agent-thread-tool-permission')).toBeNull();+ });++ test('an unmergeable outcome keeps the standalone card as its fallback', () => {+ // No toolCallId from the agent — the outcome must stay reachable somewhere.+ model = makeModel({+ items: [permission({ resolved: { optionId: 'yes', auto: false } })],+ turnActive: false,+ });+ render(<ThreadView info={makeInfo({ status: 'ready' })} />);+ expect(screen.getByTestId('agent-thread-permission-outcome').textContent).toContain('Approved');+ });+});++describe('ThreadView tool-call collapse', () => {+ test('stays collapsed through a live run — no open-then-fold flicker', async () => {+ model = makeModel({+ items: [toolCall({ status: 'in_progress', content: ['running output'] })],+ });+ const { rerender } = render(<ThreadView info={makeInfo()} />);+ expect(screen.queryByText('running output')).toBeNull();++ // Completing changes nothing about the body: there is no fold to jank.+ model = makeModel({+ items: [toolCall({ status: 'completed', content: ['running output'] })],+ turnActive: false,+ });+ rerender(<ThreadView info={makeInfo({ status: 'ready' })} />);+ expect(screen.queryByText('running output')).toBeNull();+ expect(screen.getByRole('button', { name: /Run tests/ }).getAttribute('aria-expanded')).toBe(+ 'false',+ );++ // Still openable on demand.+ await openToolCall();+ expect(screen.getByText('running output')).toBeDefined();+ });++ test('opens a call that fails while you watch, and leaves replayed ones closed', () => {+ model = makeModel({ items: [toolCall({ status: 'in_progress', content: ['boom'] })] });+ const { rerender } = render(<ThreadView info={makeInfo()} />);+ expect(screen.queryByText('boom')).toBeNull();++ model = makeModel({+ items: [toolCall({ status: 'failed', content: ['boom'] })],+ turnActive: false,+ });+ rerender(<ThreadView info={makeInfo({ status: 'ready' })} />);+ // An error is the one body worth showing unasked.+ expect(screen.getByText('boom')).toBeDefined();++ // A failure already on screen at mount (replay) opens too — but that is the+ // mount state, not a transition, so it never animates a hundred rows at once.+ cleanup();+ model = makeModel({+ items: [toolCall({ status: 'failed', content: ['old failure'] })],+ turnActive: false,+ });+ render(<ThreadView info={makeInfo({ status: 'ready' })} />);+ expect(screen.getByText('old failure')).toBeDefined();+ });++ test('keeps a card open when the user expanded it before completion', async () => {+ // The regression this guards: a fold-on-completion rule wiping a manual+ // toggle mid-run. So the expand has to happen while the call is still+ // in_progress, and the completion has to arrive as a live transition.+ model = makeModel({+ items: [toolCall({ status: 'in_progress', content: ['review me'] })],+ });+ const { rerender } = render(<ThreadView info={makeInfo()} />);+ expect(screen.queryByText('review me')).toBeNull();+ await openToolCall();+ expect(screen.getByText('review me')).toBeDefined();++ model = makeModel({+ items: [toolCall({ status: 'completed', content: ['review me'] })],+ turnActive: false,+ });+ rerender(<ThreadView info={makeInfo({ status: 'ready' })} />);+ expect(screen.getByText('review me')).toBeDefined();+ expect(screen.getByRole('button', { name: /Run tests/ }).getAttribute('aria-expanded')).toBe(+ 'true',+ );+ });+});+describe('ThreadView raw input', () => {test('collapses raw tool input by default and reveals it on request', async () => {model = makeModel({items: [toolCall({ rawInput: { docName: 'notes/today', position: 'append' } })],});render(<ThreadView info={makeInfo()} />);+ await openToolCall();const block = screen.getByTestId('agent-thread-tool-raw-input');const trigger = screen.getByRole('button', { name: 'Input' });expect(trigger.getAttribute('aria-expanded')).toBe('false');diff --git a/packages/app/src/components/acp/ThreadView.tsx b/packages/app/src/components/acp/ThreadView.tsxindex 49e6d2615..39df472ea 100644--- a/packages/app/src/components/acp/ThreadView.tsx+++ b/packages/app/src/components/acp/ThreadView.tsx@@ -18,7 +18,6 @@ import {Check,ChevronDown,ChevronRight,- CircleDot,Download,FileText,Loader2,@@ -34,6 +33,7 @@ import {import {Fragment,type ReactNode,+ type RefObject,useEffect,useId,useLayoutEffect,@@ -44,11 +44,13 @@ import { focusComposerInputOnCardPointer } from '@/components/focus-composer-on-import { useOptionalPageList } from '@/components/PageListContext';import { Badge } from '@/components/ui/badge';import { Button } from '@/components/ui/button';+import { ButtonGroup, ButtonGroupSeparator } from '@/components/ui/button-group';import { Checkbox } from '@/components/ui/checkbox';import {DropdownMenu,DropdownMenuCheckboxItem,DropdownMenuContent,+ DropdownMenuItem,DropdownMenuLabel,DropdownMenuRadioGroup,DropdownMenuRadioItem,@@ -71,7 +73,9 @@ import {useAgentThreadModel,} from '@/lib/acp/thread-client';import {+ type PermissionOutcome,type RenderedItem,+ type RenderedPermission,type RenderedTerminal,type RenderedToolCall,resolvePermissionOutcome,@@ -91,6 +95,13 @@ import { RegisteredAgentIcon } from './RegisteredAgentIcon';*/const CANCEL_STALL_MS = 10_000;+/**+ * How long a finished tool call holds its check before fading. Long enough to+ * register as an acknowledgement, short enough that a settled transcript — the+ * state you scroll back through — carries no per-row status chrome at all.+ */+const COMPLETION_CHECK_MS = 1_400;+const TOOL_ICONS: Record<string, typeof Wrench> = {read: FileText,edit: SquarePen,@@ -326,7 +337,7 @@ export function ThreadView({ info }: { info: ThreadInfo }): ReactNode {{model === null || model.items.length === 0 ? (<ThreadEmptyState status={status} archived={archived} agent={info.agent} />) : (- <div className="flex flex-col gap-2">+ <div className="flex flex-col gap-2 [&>[data-tool-call]+[data-tool-call]]:-mt-1">{model.items.map((item, index) => (<ThreadItem// biome-ignore lint/suspicious/noArrayIndexKey: transcript is append-only; index is stable@@ -339,20 +350,20 @@ export function ThreadView({ info }: { info: ThreadInfo }): ReactNode {// only a dead thread makes answering impossible.actionable={!archived && status !== 'exited' && status !== 'error'}terminals={model.terminals}+ permissionsByToolCall={model.permissionsByToolCall}/>))}{turnActive ? (status === 'awaiting_permission' ? (<div- className="flex items-center gap-2 px-1 py-1 text-amber-700 text-sm dark:text-amber-400"+ className="flex items-center gap-2 px-1 py-1 text-muted-foreground text-sm shimmer"data-testid="agent-thread-awaiting-permission">- <CircleDot className="size-3.5" aria-hidden="true" /><span>{t`Waiting for your approval`}</span></div>) : (<div- className="flex items-center gap-2 px-1 py-1 text-muted-foreground text-sm"+ className="flex items-center gap-2 px-1 py-1 text-muted-foreground text-sm shimmer"data-testid="agent-thread-working"><Loader2 className="size-3.5 animate-spin" aria-hidden="true" />@@ -364,7 +375,7 @@ export function ThreadView({ info }: { info: ThreadInfo }): ReactNode {// already in the transcript above — show that the agent is on// its way rather than a silent gap until the turn opens.<div- className="flex items-center gap-2 px-1 py-1 text-muted-foreground text-sm"+ className="flex items-center gap-2 px-1 py-1 text-muted-foreground text-sm shimmer"data-testid="agent-thread-starting"><Loader2 className="size-3.5 animate-spin" aria-hidden="true" />@@ -848,20 +859,33 @@ function ThreadItem({threadId,actionable,terminals,+ permissionsByToolCall,}: {item: RenderedItem;threadId: string;/** The thread can still take answers (live agent, not archived/dead). */actionable: boolean;terminals: Record<string, RenderedTerminal>;+ permissionsByToolCall: Record<string, RenderedPermission>;}): ReactNode {switch (item.kind) {case 'message':return <MessageBubble item={item} />;case 'tool_call':- return <ToolCallCard call={item} terminals={terminals} />;+ return (+ <ToolCallCard+ call={item}+ terminals={terminals}+ permission={permissionsByToolCall[item.toolCallId]}+ />+ );case 'permission':- return <PermissionPrompt item={item} threadId={threadId} actionable={actionable} />;+ // A settled prompt whose gated call is in the transcript is shown on that+ // call's row instead, so this card would only restate it. Pending prompts+ // always render — they are the thing you have to act on.+ return item.mergedIntoToolCall && item.resolved !== null ? null : (+ <PermissionPrompt item={item} threadId={threadId} actionable={actionable} />+ );case 'runtime_consent':return <RuntimeConsentPrompt item={item} threadId={threadId} />;case 'notice':@@ -883,7 +907,16 @@ function ThreadItem({function MessageBubble({ item }: { item: Extract<RenderedItem, { kind: 'message' }> }): ReactNode {if (item.role === 'thought') {- return <div className="px-1 text-muted-foreground text-xs italic">{item.text}</div>;+ // Thoughts carry markdown like any other agent output, so they parse —+ // otherwise an agent's bold summary line shows its literal `**`. But a+ // thought must never compete with the reply for attention, so emphasis is+ // flattened to one quiet weight and size: the markup still structures the+ // text, it just can't shout.+ return (+ <div className="px-1 text-muted-foreground text-xs italic **:font-normal! **:text-xs!">+ <AgentMarkdown text={item.text} />+ </div>+ );}const isUser = item.role === 'user';return (@@ -931,14 +964,62 @@ function formatRawInput(rawInput: unknown): string | null {return text.length > 2_000 ? `${text.slice(0, 2_000)}…` : text;}+/**+ * Drop a markdown fence that wraps an entire tool-output block. The block is+ * rendered literally — tool output frequently isn't markdown, and a renderer+ * would mangle it — so an agent that fences its output leaves its backticks+ * on screen. Only a fence enclosing the WHOLE block is removed; one that opens+ * partway through is part of the output.+ */+function stripWrappingFence(text: string): string {+ const trimmed = text.trim();+ if (!trimmed.startsWith('```')) return text;+ const lines = trimmed.split('\n');+ // The opening line may carry an info string (```json), so drop it entirely.+ if (lines.length < 2 || lines[lines.length - 1]?.trim() !== '```') return text;+ return lines.slice(1, -1).join('\n');+}+function ToolCallCard({call,terminals,+ permission,}: {call: RenderedToolCall;terminals: Record<string, RenderedTerminal>;+ /** The prompt that gated this call, when one did. */+ permission?: RenderedPermission;}): ReactNode {- const [open, setOpen] = useState(call.status !== 'completed');+ // Collapsed by default, failures excepted. Opening a call while it runs and+ // folding it up a beat later showed a body too briefly to read, and the fold+ // yanked the bottom-pinned transcript. Starting closed removes that motion+ // entirely; the spinner already says the call is live, and anything you+ // actually want to watch is one click away. An error is the one body worth+ // showing unasked.+ const [open, setOpen] = useState(call.status === 'failed');+ const userToggledRef = useRef(false);+ const prevStatusRef = useRef(call.status);+ const [completedLive, setCompletedLive] = useState(false);+ const [checkVisible, setCheckVisible] = useState(false);+ // Keyed on the live transition, never mount state: a replayed transcript+ // mounts every call already settled, and would otherwise flash a hundred+ // checks at once and expand every historical failure.+ useEffect(() => {+ const prev = prevStatusRef.current;+ prevStatusRef.current = call.status;+ if (prev === call.status) return;+ if (call.status === 'failed' && !userToggledRef.current) setOpen(true);+ if (prev !== 'completed' && call.status === 'completed') {+ setCompletedLive(true);+ setCheckVisible(true);+ const timer = setTimeout(() => setCheckVisible(false), COMPLETION_CHECK_MS);+ return () => clearTimeout(timer);+ }+ }, [call.status]);+ const toggleOpen = (): void => {+ userToggledRef.current = true;+ setOpen((value) => !value);+ };const Icon = TOOL_ICONS[call.toolKind] ?? Wrench;const callTerminals = call.terminalIds.map((id) => terminals[id])@@ -950,25 +1031,50 @@ function ToolCallCard({call.locations.length > 0 ||callTerminals.length > 0 ||rawInput !== null;+ const expanded = open && hasBody;+ const row = (+ <>+ <Icon className="size-3.5 shrink-0 text-muted-foreground" aria-hidden="true" />+ <span className="truncate">{call.title}</span>+ {/* One auto margin, not two: sibling `ml-auto`s split the free space+ between them instead of the first absorbing it, which floated the+ marks apart mid-row. */}+ <span className="ml-auto flex shrink-0 items-center gap-1.5">+ <PermissionRefusalMark permission={permission} status={call.status} />+ <ToolStatusIndicator+ status={call.status}+ completedLive={completedLive}+ checkVisible={checkVisible}+ />+ </span>+ </>+ );return (<div- className="rounded-md border border-border/60 text-xs"+ // The box earns its way in only when there is something inside it. A+ // collapsed row is a line of text, so a run of calls reads as a list+ // rather than a ladder of empty rectangles.+ className={cn('text-xs', expanded && 'rounded-md border border-border/60')}+ data-tool-call=""data-testid="agent-thread-tool-call">- <Button- type="button"- variant="ghost"- size="sm"- className="h-auto w-full justify-start gap-1.5 rounded-md px-2 py-1.5 font-normal"- onClick={() => setOpen((o) => !o)}- disabled={!hasBody}- aria-expanded={open}- >- <Icon className="size-3.5 shrink-0 text-muted-foreground" aria-hidden="true" />- <span className="truncate">{call.title}</span>- <ToolStatusBadge status={call.status} />- </Button>- {open && hasBody ? (+ {hasBody ? (+ <Button+ type="button"+ variant="ghost"+ size="sm"+ className="h-auto w-full justify-start gap-1.5 rounded-md px-2 py-1.5 font-normal"+ onClick={toggleOpen}+ aria-expanded={open}+ >+ {row}+ </Button>+ ) : (+ // Nothing to reveal — render the row as text rather than a control that+ // only ever reports itself disabled.+ <div className="flex w-full items-center gap-1.5 px-2 py-1.5">{row}</div>+ )}+ {expanded ? (<div className="flex flex-col gap-1.5 border-border/60 border-t px-2 py-1.5">{call.diffs.map((diff, index) => (// biome-ignore lint/suspicious/noArrayIndexKey: diffs are positional within a card@@ -983,7 +1089,7 @@ function ToolCallCard({key={index}className="overflow-x-auto whitespace-pre-wrap break-words rounded bg-muted/50 px-2 py-1 font-mono text-[11px]">- {text}+ {stripWrappingFence(text)}</pre>))}{rawInput !== null ? <RawInputBlock text={rawInput} /> : null}@@ -1007,7 +1113,104 @@ function ToolCallCard({);}-function ToolStatusBadge({ status }: { status: RenderedToolCall['status'] }): ReactNode {+/**+ * Agents name their refusal option "Reject" and their grant "Allow", so pinning+ * that onto "Denied"/"Approved" says the same word twice. Keep the name only+ * when it carries something the outcome doesn't — the persistence in "Always+ * deny", say.+ */+const OUTCOME_SYNONYM_NAMES = new Set([+ 'accept',+ 'allow',+ 'approve',+ 'decline',+ 'deny',+ 'no',+ 'ok',+ 'reject',+ 'yes',+]);++function informativeOptionName(name: string | null): string | null {+ if (name === null) return null;+ const normalized = name.trim().toLocaleLowerCase();+ return normalized === '' || OUTCOME_SYNONYM_NAMES.has(normalized) ? null : name;+}++/**+ * One phrasing of a settled permission, shared by the standalone card and the+ * mark on a tool call's row so the two can never drift apart.+ */+function usePermissionOutcomeLabel(): (outcome: PermissionOutcome) => string | null {+ const { t } = useLingui();+ return (outcome) => {+ if (outcome === null) return null;+ // `dismissed` covers timeout, Stop-cancel, and agent exit alike — don't+ // claim a specific cause the event doesn't carry.+ if (outcome.kind === 'dismissed') return t`Not answered`;+ const optionName = informativeOptionName(outcome.optionName);+ if (outcome.kind === 'approved') {+ if (outcome.auto) return t`Auto-approved`;+ return optionName !== null ? t`Approved — ${optionName}` : t`Approved`;+ }+ if (outcome.auto) return t`Auto-denied`;+ return optionName !== null ? t`Denied — ${optionName}` : t`Denied`;+ };+}++/**+ * The outcome of the prompt that gated this call, carried on the call's own row+ * rather than as a sibling card restating the tool name beside it.+ *+ * An approval leaves no trace at all: the call ran, which is the whole message,+ * and every comparable agent panel drops the prompt once answered rather than+ * minting a permanent "you allowed this" marker. Only a refusal changed what+ * happened — and it says so in words, since a lone glyph gives the reader no+ * way to learn what it means.+ */+function PermissionRefusalMark({+ permission,+ status,+}: {+ permission?: RenderedPermission;+ status: RenderedToolCall['status'];+}): ReactNode {+ const outcomeLabel = usePermissionOutcomeLabel();+ if (permission === undefined || !permission.mergedIntoToolCall) return null;+ const outcome = resolvePermissionOutcome(permission);+ if (outcome === null || outcome.kind === 'approved') return null;+ // A refused call almost always lands as `failed`, whose badge and body+ // already say it didn't run and why. Speak only where nothing else does —+ // an agent that leaves the call unfinished after a refusal.+ if (status === 'failed') return null;+ return (+ <span className="shrink-0 text-muted-foreground" data-testid="agent-thread-tool-permission">+ {outcomeLabel(outcome)}+ </span>+ );+}++/**+ * Status by exception. Completion is the expected outcome, so a settled call+ * shows nothing — a badge on every row buries the one row that failed. Live+ * calls spin; a call that finishes while you are watching flashes a check that+ * then fades, so the acknowledgement rides the transition instead of becoming+ * permanent chrome. The check keeps its box after fading to opacity 0 so the+ * row does not reflow underneath the pointer.+ *+ * Every state keeps its label in the a11y tree: dropping the visible badge is a+ * density decision, not a reason to withhold status from assistive tech.+ */+function ToolStatusIndicator({+ status,+ completedLive,+ checkVisible,+}: {+ status: RenderedToolCall['status'];+ /** This call transitioned to completed while mounted (not a replayed row). */+ completedLive: boolean;+ checkVisible: boolean;+}): ReactNode {const { t } = useLingui();const label =status === 'completed'@@ -1018,12 +1221,36 @@ function ToolStatusBadge({ status }: { status: RenderedToolCall['status'] }): Re? t`running`: t`pending`;return (- <Badge- variant={status === 'failed' ? 'destructive' : 'secondary'}- className="ml-auto shrink-0 px-1.5 py-0 text-[10px]"- >- {label}- </Badge>+ <span className="flex shrink-0 items-center">+ <span className="sr-only">{label}</span>+ {status === 'failed' ? (+ <Badge+ variant="destructive"+ className="rounded-sm px-1.5 py-0 text-[10px]"+ data-testid="agent-thread-tool-failed"+ >+ {label}+ </Badge>+ ) : status === 'in_progress' || status === 'pending' ? (+ // `pending` (accepted, not yet started) and `in_progress` both read as+ // "this call is in flight" — the distinction is the agent's bookkeeping,+ // not something worth two different marks on the row.+ <Loader2+ className="size-3.5 animate-spin text-muted-foreground"+ aria-hidden="true"+ data-testid="agent-thread-tool-spinner"+ />+ ) : completedLive ? (+ <Check+ className={cn(+ 'size-3.5 text-muted-foreground/70 transition-opacity duration-500 motion-reduce:transition-none',+ checkVisible ? 'opacity-100' : 'opacity-0',+ )}+ aria-hidden="true"+ data-testid="agent-thread-tool-check"+ />+ ) : null}+ </span>);}@@ -1095,14 +1322,14 @@ function TerminalBlock({ terminal }: { terminal: RenderedTerminal }): ReactNode</span><span className="ml-auto shrink-0">{exit === null ? (- <span className="flex items-center gap-1 text-[10px] text-muted-foreground">+ <span className="flex items-center gap-1 text-[10px] text-muted-foreground shimmer"><Loader2 className="size-3 animate-spin" aria-hidden="true" />{t`running`}</span>) : (<Badgevariant={failed ? 'destructive' : 'secondary'}- className="px-1.5 py-0 font-mono text-[10px]"+ className="px-1.5 py-0 font-mono text-[10px] rounded-sm"data-testid="agent-thread-terminal-exit">{exit.signal !== null ? exit.signal : t`exit ${exit.exitCode ?? 0}`}@@ -1167,71 +1394,34 @@ function PermissionPrompt({actionable: boolean;}): ReactNode {const { t } = useLingui();+ const outcomeLabel = usePermissionOutcomeLabel();const client = getAgentThreadClient();const outcome = resolvePermissionOutcome(item);const pending = outcome === null;const cardRef = useRef<HTMLDivElement>(null);const primaryRef = useRef<HTMLButtonElement>(null);- // The agent's own choices may already include a refusal; only add our- // explicit Deny (the ACP `cancelled` outcome) when they don't — without it- // "no" exists only when the agent thinks to offer one.- const hasRejectOption = item.options.some((option) => option.kind.startsWith('reject'));- const options = [...item.options].sort(- (a, b) => permissionOptionRank(a.kind) - permissionOptionRank(b.kind),- );- // The safest useful default is a one-time grant. A persistent grant is the- // final focus fallback, after any refusal the agent exposes.- const defaultOptionId =- options.find((option) => option.kind === 'allow_once')?.optionId ??- options.find((option) => option.kind.startsWith('reject'))?.optionId ??- (hasRejectOption- ? (options.find((option) => option.kind === 'allow_always')?.optionId ?? options[0]?.optionId)- : undefined);-- const optionVariant = (kind: (typeof options)[number]['kind']) =>- kind === 'allow_once' ? 'default' : 'outline';- const optionLabel = (option: (typeof options)[number]) =>- option.kind === 'reject_once' && option.name.trim().toLocaleLowerCase() === 'reject'- ? t`Deny`- : option.name;-- const optionButtons = options.map((option) => (- <Button- key={option.optionId}- ref={option.optionId === defaultOptionId ? primaryRef : undefined}- type="button"- size="sm"- variant={optionVariant(option.kind)}- className="h-auto min-h-7 max-w-full self-start whitespace-normal text-left text-xs"- onClick={() =>- client.respondPermission(threadId, item.requestId, {- kind: 'selected',- optionId: option.optionId,- })- }- data-permission-kind={option.kind}- >- {optionLabel(option)}- </Button>- ));- const denyButton = !hasRejectOption ? (- // ACP has no first-class per-tool deny beyond the agent's own reject- // options; `cancelled` is the protocol's only refusal channel, and agents- // may treat it as cancelling the whole turn. Shown only when the agent- // offered no reject option, so "no" exists at all.- <Button- ref={defaultOptionId === undefined ? primaryRef : undefined}- type="button"- size="sm"- variant="outline"- className="h-7 self-start text-xs"- onClick={() => client.respondPermission(threadId, item.requestId, { kind: 'cancelled' })}- data-testid="agent-thread-permission-deny"- >- {t`Deny`}- </Button>- ) : null;+ const selectOption = (optionId: string): void => {+ client.respondPermission(threadId, item.requestId, { kind: 'selected', optionId });+ };++ // Group by stance, never by looking up one option per kind: ACP `kind` is a+ // styling hint, not a key, and agents do offer several allows separated only+ // by `name` ("Allow for This Session" vs "Allow and Don't Ask Again").+ const allowOptions = item.options.filter((option) => option.kind.startsWith('allow'));+ const rejectOptions = item.options.filter((option) => option.kind.startsWith('reject'));+ // The least-privilege grant is the primary action; every escalating grant+ // keeps the agent's own ordering behind the secondary button beside it.+ const primaryAllow = allowOptions.find((o) => o.kind === 'allow_once') ?? allowOptions[0];+ const secondaryAllows = allowOptions.filter((option) => option !== primaryAllow);+ const primaryReject = rejectOptions.find((o) => o.kind === 'reject_once') ?? rejectOptions[0];+ const denyOptions =+ primaryReject === undefined+ ? []+ : [primaryReject, ...rejectOptions.filter((option) => option !== primaryReject)];+ // Focus lands on the primary grant; with no grant offered at all, the refusal+ // is the only actionable control left to take it.+ const focusRefForDeny = primaryAllow === undefined ? primaryRef : undefined;// Move focus onto the primary option when a live prompt appears — but only// if focus is already inside this thread's panel (e.g. on the composer the@@ -1244,33 +1434,16 @@ function PermissionPrompt({primaryRef.current?.focus();}, [pending, actionable]);- const resolvedLabel =- outcome === null- ? null- : outcome.kind === 'dismissed'- ? // Covers timeout, Stop-cancel, and agent exit alike — don't claim a- // specific cause the event doesn't carry.- t`Not answered`- : outcome.kind === 'approved'- ? outcome.auto- ? t`Auto-approved`- : outcome.optionName !== null- ? t`Approved — ${outcome.optionName}`- : t`Approved`- : outcome.auto- ? t`Auto-denied`- : outcome.optionName !== null- ? t`Denied — ${outcome.optionName}`- : t`Denied`;+ const resolvedLabel = outcomeLabel(outcome);return (<divref={cardRef}className={cn(+ // Neutral chrome throughout: a permission request is a routine choice,+ // and an alarm-colored card overstates it.'rounded-md border px-2.5 py-2 text-sm',- pending && actionable- ? 'border-amber-500/40 bg-amber-500/5'- : 'border-border/60 bg-muted/20',+ pending && actionable ? 'border-border bg-muted/30' : 'border-border/60 bg-muted/20',)}data-testid="agent-thread-permission">@@ -1287,21 +1460,150 @@ function PermissionPrompt({// impossible, so don't render buttons that would silently no-op.<div className="text-muted-foreground text-xs">{t`This request is no longer active.`}</div>) : (- <div className="flex flex-col items-start gap-1.5">- {optionButtons}- {denyButton}+ // Refusal pinned far left, the primary grant far right, and every+ // escalating grant collapsed into the secondary button beside it — so+ // the row stays at most three controls however many options an agent+ // offers, and the two opposite answers never sit next to each other.+ <div className="flex flex-wrap items-center justify-between gap-2">+ {denyOptions.length > 0 ? (+ <PermissionOptionCluster+ options={denyOptions}+ onSelect={selectOption}+ buttonRef={focusRefForDeny}+ testId="agent-thread-permission-deny"+ moreLabel={t`More refusal options`}+ menuAlign="start"+ />+ ) : (+ // ACP has no first-class per-tool deny beyond the agent's own+ // reject options; `cancelled` is the protocol's only refusal+ // channel, and agents may treat it as cancelling the whole turn.+ // Shown only when the agent offered none, so "no" exists at all.+ <Button+ ref={focusRefForDeny}+ type="button"+ size="sm"+ variant="outline"+ className="text-xs"+ onClick={() =>+ client.respondPermission(threadId, item.requestId, { kind: 'cancelled' })+ }+ data-testid="agent-thread-permission-deny"+ >+ {t`Deny`}+ </Button>+ )}+ <div className="ml-auto flex items-center gap-1.5">+ {secondaryAllows.length > 0 ? (+ <PermissionOptionCluster+ options={secondaryAllows}+ onSelect={selectOption}+ testId="agent-thread-permission-allow-more"+ moreLabel={t`More grant options`}+ menuAlign="end"+ />+ ) : null}+ {primaryAllow !== undefined ? (+ <Button+ ref={primaryRef}+ type="button"+ size="sm"+ // The `default` Button variant is `font-mono uppercase`, which+ // is right for fixed UI verbs and wrong for a label the agent+ // wrote — "Allow for This Session" must not render shouted.+ className="text-xs normal-case font-sans"+ title={primaryAllow.name}+ onClick={() => selectOption(primaryAllow.optionId)}+ data-testid="agent-thread-permission-allow"+ data-permission-kind={primaryAllow.kind}+ >+ <span className="max-w-52 truncate">{primaryAllow.name}</span>+ </Button>+ ) : null}+ </div></div>)}</div>);}-function permissionOptionRank(- kind: Extract<RenderedItem, { kind: 'permission' }>['options'][number]['kind'],-): number {- if (kind === 'allow_once') return 0;- if (kind === 'allow_always') return 1;- return 2;+/**+ * One cluster of permission choices that share a stance. `options[0]` is the+ * directly-actionable button — a single click answers with it, so the common+ * two-option case never costs an extra trip through a menu — and any further+ * options collapse behind its chevron. The menu repeats the primary so it+ * reads as the complete list of choices at that stance.+ *+ * Agent-authored names run long ("Always allow all mcp__open-knowledge__exec"),+ * so the button label is width-capped with the full string on its tooltip;+ * the menu, which has room, always shows names in full.+ */+function PermissionOptionCluster({+ options,+ onSelect,+ buttonRef,+ testId,+ moreLabel,+ menuAlign,+}: {+ options: Extract<RenderedItem, { kind: 'permission' }>['options'];+ onSelect: (optionId: string) => void;+ buttonRef?: RefObject<HTMLButtonElement | null>;+ testId: string;+ moreLabel: string;+ menuAlign: 'start' | 'end';+}): ReactNode {+ const primary = options[0];+ if (primary === undefined) return null;++ const primaryButton = (+ <Button+ ref={buttonRef}+ type="button"+ size="sm"+ variant="outline"+ className="text-xs"+ title={primary.name}+ onClick={() => onSelect(primary.optionId)}+ data-testid={testId}+ data-permission-kind={primary.kind}+ >+ <span className="max-w-52 truncate">{primary.name}</span>+ </Button>+ );++ if (options.length === 1) return primaryButton;++ return (+ <ButtonGroup>+ {primaryButton}+ <ButtonGroupSeparator />+ <DropdownMenu>+ <DropdownMenuTrigger asChild>+ <Button+ type="button"+ size="icon-sm"+ variant="outline"+ aria-label={moreLabel}+ data-testid={`${testId}-more`}+ >+ <ChevronDown className="size-3.5" aria-hidden="true" />+ </Button>+ </DropdownMenuTrigger>+ <DropdownMenuContent align={menuAlign} className="max-w-72">+ {options.map((option) => (+ <DropdownMenuItem+ key={option.optionId}+ onSelect={() => onSelect(option.optionId)}+ data-permission-kind={option.kind}+ >+ {option.name}+ </DropdownMenuItem>+ ))}+ </DropdownMenuContent>+ </DropdownMenu>+ </ButtonGroup>+ );}/**diff --git a/packages/app/src/lib/acp/thread-event-model.test.ts b/packages/app/src/lib/acp/thread-event-model.test.tsindex cd02f7a55..5026a8da6 100644--- a/packages/app/src/lib/acp/thread-event-model.test.ts+++ b/packages/app/src/lib/acp/thread-event-model.test.ts@@ -144,6 +144,57 @@ describe('buildThreadRenderModel', () => {expect(perm.resolved).toEqual({ optionId: 'allow', auto: false });});+ test('links a permission to the call it gates, whichever event lands first', () => {+ const request = ev({+ kind: 'permission_request',+ requestId: 'p1',+ toolCall: { toolCallId: 'c1', title: 'Write file', kind: 'edit' } as never,+ options: [{ optionId: 'allow', name: 'Allow', kind: 'allow_once' }],+ ts: 1,+ });+ const call = ev({+ kind: 'session_update',+ update: { sessionUpdate: 'tool_call', toolCallId: 'c1', title: 'Write file' } as never,+ ts: 2,+ });+ const resolve = ev({+ kind: 'permission_resolved',+ requestId: 'p1',+ optionId: 'allow',+ auto: false,+ ts: 3,+ });++ // Agents ask first and stream the call after; some do the reverse. Either+ // order has to end up merged, or the outcome shows twice or not at all.+ for (const events of [+ [request, call, resolve],+ [call, request, resolve],+ ] satisfies ThreadEvent[][]) {+ const model = buildThreadRenderModel(events);+ const perm = model.items.find((i) => i.kind === 'permission');+ if (perm?.kind !== 'permission') throw new Error('unreachable');+ expect(perm.toolCallId).toBe('c1');+ expect(perm.mergedIntoToolCall).toBe(true);+ expect(model.permissionsByToolCall.c1?.resolved).toEqual({ optionId: 'allow', auto: false });+ }+ });++ test('leaves a permission unmerged when its call never appears', () => {+ const events: ThreadEvent[] = [+ ev({+ kind: 'permission_request',+ requestId: 'p1',+ toolCall: { toolCallId: 'c-missing', title: 'Write file', kind: 'edit' } as never,+ options: [{ optionId: 'allow', name: 'Allow', kind: 'allow_once' }],+ ts: 1,+ }),+ ];+ const perm = buildThreadRenderModel(events).items.find((i) => i.kind === 'permission');+ if (perm?.kind !== 'permission') throw new Error('unreachable');+ expect(perm.mergedIntoToolCall).toBe(false);+ });+test('keeps the latest plan as a checklist', () => {const events: ThreadEvent[] = [ev({@@ -390,6 +441,16 @@ describe('resolvePermissionOutcome', () => {expect(resolvePermissionOutcome(permission(null))).toBeNull();});+ test('an option whose kind is neither allow nor reject is dismissed, not approved', () => {+ // Runtime defense-in-depth behind `PinPermissionOptionKind`: if a later ACP+ // release adds a kind and the pin is updated without revisiting this, the+ // label must not read "Approved" for an answer we can't classify. `as never`+ // is the only way past the union the typelock guards.+ const item = permission({ optionId: 'escalate', auto: false });+ item.options = [{ optionId: 'escalate', name: 'Escalate', kind: 'escalate_once' as never }];+ expect(resolvePermissionOutcome(item)).toEqual({ kind: 'dismissed' });+ });+test('an allow option approves (auto and manual)', () => {expect(resolvePermissionOutcome(permission({ optionId: 'yes', auto: false }))).toEqual({kind: 'approved',diff --git a/packages/app/src/lib/acp/thread-event-model.ts b/packages/app/src/lib/acp/thread-event-model.tsindex 7fc1902ab..943e65320 100644--- a/packages/app/src/lib/acp/thread-event-model.ts+++ b/packages/app/src/lib/acp/thread-event-model.ts@@ -47,13 +47,22 @@ export interface RenderedToolCall {rawInput: unknown;}-interface RenderedPermission {+export interface RenderedPermission {kind: 'permission';requestId: string;title: string;toolKind: string;options: PermissionOption[];resolved: { optionId: string | null; auto: boolean } | null;+ /** The tool call this prompt gates. Null if the agent omitted it. */+ toolCallId: string | null;+ /**+ * That tool call is in the transcript, so its row can carry this outcome and+ * the prompt need not restate it as a second card. False keeps the standalone+ * card as the fallback — an outcome must never become unreachable just+ * because the call it gated never showed up.+ */+ mergedIntoToolCall: boolean;}interface RenderedNotice {@@ -128,6 +137,13 @@ export interface ThreadRenderModel {tokenUsage: { used?: number; size?: number } | null;/** Terminals by id, for tool calls that embed them (`terminalIds`). */terminals: Record<string, RenderedTerminal>;+ /**+ * Permission prompts keyed by the tool call they gate, so a call's row can+ * show its own approval instead of a sibling card repeating the tool name.+ * Maintained by the fold rather than derived per render — same reason+ * `terminals` is: a streamed turn re-renders on every chunk.+ */+ permissionsByToolCall: Record<string, RenderedPermission>;}function textFromContent(content: unknown): string | null {@@ -145,6 +161,9 @@ export class ThreadRenderModelBuilder {/** Item index by toolCallId / permission requestId / `role:messageId`. */private toolCallIndex = new Map<string, number>();private permissionIndex = new Map<string, number>();+ /** Item index of the permission gating a given toolCallId. */+ private permissionByToolCall = new Map<string, number>();+ private permissionsByToolCall: Record<string, RenderedPermission> = {};private messageIndex = new Map<string, number>();private runtimeConsentIndex = new Map<string, number>();/** Item index of the most recent consent card — progress events target it. */@@ -157,6 +176,7 @@ export class ThreadRenderModelBuilder {turnActive: false,tokenUsage: null,terminals: {},+ permissionsByToolCall: {},};/**@@ -179,6 +199,7 @@ export class ThreadRenderModelBuilder {turnActive: this.turnActive,tokenUsage: this.tokenUsage,terminals: { ...this.terminals },+ permissionsByToolCall: { ...this.permissionsByToolCall },};this.dirty = false;}@@ -193,6 +214,8 @@ export class ThreadRenderModelBuilder {this.terminals = {};this.toolCallIndex = new Map();this.permissionIndex = new Map();+ this.permissionByToolCall = new Map();+ this.permissionsByToolCall = {};this.messageIndex = new Map();this.runtimeConsentIndex = new Map();this.lastConsentIndex = null;@@ -249,26 +272,41 @@ export class ThreadRenderModelBuilder {this.items.push({ kind: 'notice', text: event.detail, tone: 'info' });}break;- case 'permission_request':- this.permissionIndex.set(event.requestId, this.items.length);- this.items.push({+ case 'permission_request': {+ const toolCallId = event.toolCall.toolCallId ?? null;+ const permission: RenderedPermission = {kind: 'permission',requestId: event.requestId,title: event.toolCall.title ?? 'Permission required',toolKind: event.toolCall.kind ?? 'other',options: event.options,resolved: null,- });+ toolCallId,+ // The gated call may not have streamed in yet; `tool_call` back-fills+ // this when it lands, so the order of the two events doesn't matter.+ mergedIntoToolCall: toolCallId !== null && this.toolCallIndex.has(toolCallId),+ };+ this.permissionIndex.set(event.requestId, this.items.length);+ if (toolCallId !== null) {+ this.permissionByToolCall.set(toolCallId, this.items.length);+ this.permissionsByToolCall[toolCallId] = permission;+ }+ this.items.push(permission);break;+ }case 'permission_resolved': {const index = this.permissionIndex.get(event.requestId);if (index === undefined) break;const target = this.items[index];if (target.kind !== 'permission') break;- this.items[index] = {+ const resolved: RenderedPermission = {...target,resolved: { optionId: event.optionId, auto: event.auto },};+ this.items[index] = resolved;+ if (resolved.toolCallId !== null) {+ this.permissionsByToolCall[resolved.toolCallId] = resolved;+ }break;}case 'runtime_consent_request':@@ -353,6 +391,20 @@ export class ThreadRenderModelBuilder {}}+ /**+ * Mark the permission gating `toolCallId` as carried by that call's row.+ * No-op when no prompt gated it, or when it is already merged.+ */+ private mergePermissionInto(toolCallId: string): void {+ const index = this.permissionByToolCall.get(toolCallId);+ if (index === undefined) return;+ const target = this.items[index];+ if (target === undefined || target.kind !== 'permission' || target.mergedIntoToolCall) return;+ const merged: RenderedPermission = { ...target, mergedIntoToolCall: true };+ this.items[index] = merged;+ this.permissionsByToolCall[toolCallId] = merged;+ }+private pushMessageChunk(role: RenderedMessage['role'], messageId: string, text: string): void {const key = `${role}:${messageId}`;const index = this.messageIndex.get(key);@@ -405,6 +457,10 @@ export class ThreadRenderModelBuilder {mergeToolContent(call, update.content);this.toolCallIndex.set(update.toolCallId, this.items.length);this.items.push(call);+ // The prompt for this call arrived first (the usual order: the agent+ // asks, then streams the call). Now that the row exists to carry the+ // outcome, fold the standalone card away.+ this.mergePermissionInto(update.toolCallId);break;}case 'tool_call_update': {@@ -500,8 +556,16 @@ export function resolvePermissionOutcome(// claiming "approved" for it could mislabel a refusal.return { kind: 'dismissed' };}+ // Classify from both prefixes rather than treating "not a refusal" as assent.+ // The four known kinds partition cleanly, but a kind added by a later ACP+ // release would otherwise be labelled "Approved" — the wrong direction to be+ // wrong in for a security decision. An unrecognized kind is an answer we+ // can't read, which is what `dismissed` already means.+ const denied = chosen.kind.startsWith('reject');+ const approved = chosen.kind.startsWith('allow');+ if (!denied && !approved) return { kind: 'dismissed' };return {- kind: chosen.kind.startsWith('reject') ? 'denied' : 'approved',+ kind: denied ? 'denied' : 'approved',auto: resolved.auto,optionName: chosen.name,};diff --git a/packages/app/src/locales/en/messages.json b/packages/app/src/locales/en/messages.jsonindex c4caacda6..f1519cd48 100644--- a/packages/app/src/locales/en/messages.json+++ b/packages/app/src/locales/en/messages.json@@ -484,6 +484,7 @@"9bCiQ8": ["No pages are missing incoming graph links."],"9bG48P": ["Sending"],"9clcD5": ["Open documents tagged #", ["chip"]],+ "9dVehq": ["More grant options"],"9dw5bW": ["Create with ", ["0"]],"9euN0m": [[@@ -1030,7 +1031,6 @@"L-rMC9": ["Reset to default"],"L1BQTH": [["0"], " isn't installed yet — opening its download page."],"L1ZE3M": ["Document statistics"],- "L1qaHQ": ["Approved — ", ["0"]],"L1rRuU": ["Embeddings API endpoint"],"L3CEC1": ["this item"],"L4Cdd9": ["or create a new file <0/>"],@@ -1759,6 +1759,7 @@"_IGfXZ": ["OpenKnowledge quit unexpectedly last time."],"_IX_7x": ["Other"],"_JOGC0": ["Send feedback…"],+ "_LczaQ": ["Denied — ", ["optionName"]],"_NX6gG": ["Managing project AI tools is unavailable in this build."],"_PACVa": ["Release notes"],"_PBJRl": ["Add at least one letter or number."],@@ -2516,7 +2517,6 @@"ot5BRK": ["Duplicate selected file or folder"],"otE4aj": ["Show external URL nodes"],"ou1hFW": ["Toggle an ordered list."],- "ouTaKR": ["Denied — ", ["0"]],"outYNy": ["Duplicate name \"", ["keyName"], "\""],"ovIGrT": ["Local collaboration data for \"",@@ -2630,6 +2630,7 @@"rZ9HZq": ["To do"],"rZVMkf": ["Visual editor replace input focused"],"rageVb": ["Custom HTML with a live preview pane (sandboxed iframe)."],+ "rbrHTd": ["Approved — ", ["optionName"]],"rdU729": ["Layout"],"rfFpcF": ["Remove ", ["chip"]],"rg7hNd": ["Rate your experience"],@@ -2900,6 +2901,7 @@"xhlFsx": ["Inherited — set a value here to replace it."],"xi9KGG": ["Show Terminal"],"xiv-dW": ["No files yet."],+ "xlQpTE": ["More refusal options"],"xloBjn": ["Relative Path"],"xnP32l": ["No description yet — add one so agents know when to use this skill."],"xrVr_k": ["Couldn't create skill: ", ["0"]],diff --git a/packages/app/src/locales/en/messages.po b/packages/app/src/locales/en/messages.poindex 9dda539f4..31dcb0bdd 100644--- a/packages/app/src/locales/en/messages.po+++ b/packages/app/src/locales/en/messages.po@@ -1099,10 +1099,9 @@ msgstr "Applying your change"msgid "Approved"msgstr "Approved"-#. placeholder {0}: outcome.optionName#: src/components/acp/ThreadView.tsx-msgid "Approved — {0}"-msgstr "Approved — {0}"+msgid "Approved — {optionName}"+msgstr "Approved — {optionName}"#: src/components/acp/ThreadView.tsxmsgid "Archived"@@ -2867,10 +2866,9 @@ msgstr "Deleting"msgid "Denied"msgstr "Denied"-#. placeholder {0}: outcome.optionName#: src/components/acp/ThreadView.tsx-msgid "Denied — {0}"-msgstr "Denied — {0}"+msgid "Denied — {optionName}"+msgstr "Denied — {optionName}"#: src/components/acp/ThreadView.tsxmsgid "Deny"@@ -5161,6 +5159,14 @@ msgstr "Modify the link target, anchor, and display label."msgid "More"msgstr "More"+#: src/components/acp/ThreadView.tsx+msgid "More grant options"+msgstr "More grant options"++#: src/components/acp/ThreadView.tsx+msgid "More refusal options"+msgstr "More refusal options"+#: src/editor/components/PreviewBlockedNotice.tsxmsgid "More requests were blocked."msgstr "More requests were blocked."diff --git a/packages/app/src/locales/pseudo/messages.json b/packages/app/src/locales/pseudo/messages.jsonindex 4a966c1f3..e77170eaf 100644--- a/packages/app/src/locales/pseudo/messages.json+++ b/packages/app/src/locales/pseudo/messages.json@@ -484,6 +484,7 @@"9bCiQ8": ["Ńō ƥàĝēś àŕē ḿĩśśĩńĝ ĩńćōḿĩńĝ ĝŕàƥĥ ĺĩńķś."],"9bG48P": ["Śēńďĩńĝ"],"9clcD5": ["Ōƥēń ďōćũḿēńţś ţàĝĝēď #", ["chip"]],+ "9dVehq": ["Ḿōŕē ĝŕàńţ ōƥţĩōńś"],"9dw5bW": ["Ćŕēàţē ŵĩţĥ ", ["0"]],"9euN0m": [[@@ -1030,7 +1031,6 @@"L-rMC9": ["Ŕēśēţ ţō ďēƒàũĺţ"],"L1BQTH": [["0"], " ĩśń'ţ ĩńśţàĺĺēď ŷēţ — ōƥēńĩńĝ ĩţś ďōŵńĺōàď ƥàĝē."],"L1ZE3M": ["Ďōćũḿēńţ śţàţĩśţĩćś"],- "L1qaHQ": ["Àƥƥŕōvēď — ", ["0"]],"L1rRuU": ["Ēḿƀēďďĩńĝś ÀƤĨ ēńďƥōĩńţ"],"L3CEC1": ["ţĥĩś ĩţēḿ"],"L4Cdd9": ["ōŕ ćŕēàţē à ńēŵ ƒĩĺē <0/>"],@@ -1759,6 +1759,7 @@"_IGfXZ": ["ŌƥēńĶńōŵĺēďĝē ǫũĩţ ũńēxƥēćţēďĺŷ ĺàśţ ţĩḿē."],"_IX_7x": ["Ōţĥēŕ"],"_JOGC0": ["Śēńď ƒēēďƀàćķ…"],+ "_LczaQ": ["Ďēńĩēď — ", ["optionName"]],"_NX6gG": ["Ḿàńàĝĩńĝ ƥŕōĴēćţ ÀĨ ţōōĺś ĩś ũńàvàĩĺàƀĺē ĩń ţĥĩś ƀũĩĺď."],"_PACVa": ["Ŕēĺēàśē ńōţēś"],"_PBJRl": ["Àďď àţ ĺēàśţ ōńē ĺēţţēŕ ōŕ ńũḿƀēŕ."],@@ -2516,7 +2517,6 @@"ot5BRK": ["Ďũƥĺĩćàţē śēĺēćţēď ƒĩĺē ōŕ ƒōĺďēŕ"],"otE4aj": ["Śĥōŵ ēxţēŕńàĺ ŨŔĹ ńōďēś"],"ou1hFW": ["Ţōĝĝĺē àń ōŕďēŕēď ĺĩśţ."],- "ouTaKR": ["Ďēńĩēď — ", ["0"]],"outYNy": ["Ďũƥĺĩćàţē ńàḿē \"", ["keyName"], "\""],"ovIGrT": ["Ĺōćàĺ ćōĺĺàƀōŕàţĩōń ďàţà ƒōŕ \"",@@ -2630,6 +2630,7 @@"rZ9HZq": ["Ţō ďō"],"rZVMkf": ["Vĩśũàĺ ēďĩţōŕ ŕēƥĺàćē ĩńƥũţ ƒōćũśēď"],"rageVb": ["Ćũśţōḿ ĤŢḾĹ ŵĩţĥ à ĺĩvē ƥŕēvĩēŵ ƥàńē (śàńďƀōxēď ĩƒŕàḿē)."],+ "rbrHTd": ["Àƥƥŕōvēď — ", ["optionName"]],"rdU729": ["Ĺàŷōũţ"],"rfFpcF": ["Ŕēḿōvē ", ["chip"]],"rg7hNd": ["Ŕàţē ŷōũŕ ēxƥēŕĩēńćē"],@@ -2900,6 +2901,7 @@"xhlFsx": ["Ĩńĥēŕĩţēď — śēţ à vàĺũē ĥēŕē ţō ŕēƥĺàćē ĩţ."],"xi9KGG": ["Śĥōŵ Ţēŕḿĩńàĺ"],"xiv-dW": ["Ńō ƒĩĺēś ŷēţ."],+ "xlQpTE": ["Ḿōŕē ŕēƒũśàĺ ōƥţĩōńś"],"xloBjn": ["Ŕēĺàţĩvē Ƥàţĥ"],"xnP32l": ["Ńō ďēśćŕĩƥţĩōń ŷēţ — àďď ōńē śō àĝēńţś ķńōŵ ŵĥēń ţō ũśē ţĥĩś śķĩĺĺ."],"xrVr_k": ["Ćōũĺďń'ţ ćŕēàţē śķĩĺĺ: ", ["0"]],diff --git a/packages/app/src/locales/pseudo/messages.po b/packages/app/src/locales/pseudo/messages.poindex edfcc18b5..cbfe7d14c 100644--- a/packages/app/src/locales/pseudo/messages.po+++ b/packages/app/src/locales/pseudo/messages.po@@ -1095,9 +1095,8 @@ msgstr ""msgid "Approved"msgstr ""-#. placeholder {0}: outcome.optionName#: src/components/acp/ThreadView.tsx-msgid "Approved — {0}"+msgid "Approved — {optionName}"msgstr ""#: src/components/acp/ThreadView.tsx@@ -2863,9 +2862,8 @@ msgstr ""msgid "Denied"msgstr ""-#. placeholder {0}: outcome.optionName#: src/components/acp/ThreadView.tsx-msgid "Denied — {0}"+msgid "Denied — {optionName}"msgstr ""#: src/components/acp/ThreadView.tsx@@ -5157,6 +5155,14 @@ msgstr ""msgid "More"msgstr ""+#: src/components/acp/ThreadView.tsx+msgid "More grant options"+msgstr ""++#: src/components/acp/ThreadView.tsx+msgid "More refusal options"+msgstr ""+#: src/editor/components/PreviewBlockedNotice.tsxmsgid "More requests were blocked."msgstr ""diff --git a/packages/core/src/acp/thread-protocol.typelock.ts b/packages/core/src/acp/thread-protocol.typelock.tsindex 3725a55d6..d83326912 100644--- a/packages/core/src/acp/thread-protocol.typelock.ts+++ b/packages/core/src/acp/thread-protocol.typelock.ts@@ -51,10 +51,11 @@ export type PinSessionUpdateKinds = Expect<>;// Dependents: `resolvePermissionOutcome` classifies by kind PREFIX-// (`startsWith('reject')` → denied, everything else → approved), and the-// permission card renders its own Deny only when no reject-kind option-// exists. A fifth kind outside these four would silently classify as an-// approval.+// (`startsWith('allow')` → approved, `startsWith('reject')` → denied,+// anything else → dismissed), and the permission card renders its own Deny+// only when no reject-kind option exists. A fifth kind outside these four+// classifies as dismissed — decide whether it warrants its own label rather+// than leaving it in the unreadable-answer bucket.export type PinPermissionOptionKind = Expect<Equal<PermissionOption['kind'], 'allow_once' | 'allow_always' | 'reject_once' | 'reject_always'>>;