Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

feat(web): add kind icons and live peek window to agent tool groups (#6750)

Eric Hayesb8be59874b64
diff --git a/apps/web/src/features/block-agent/component/AgentMessage.test.tsx b/apps/web/src/features/block-agent/component/AgentMessage.test.tsx
index d428dda74f..e8929c3663 100644
--- a/apps/web/src/features/block-agent/component/AgentMessage.test.tsx
+++ b/apps/web/src/features/block-agent/component/AgentMessage.test.tsx
@@ -7,7 +7,7 @@ import type {
MessagePart,
} from '@service-agent-fold/generated/types';
import { cleanup, render } from '@solidjs/testing-library';
-import type { JSX } from 'solid-js';
+import { createSignal, type JSX } from 'solid-js';
import { createStore, reconcile } from 'solid-js/store';
import { afterEach, describe, expect, it, vi } from 'vitest';
import { Message } from './AgentMessage';
@@ -37,10 +37,15 @@ vi.mock('./parts/TextPart', () => ({
}));
vi.mock('./parts/ToolCallPart', () => ({
ToolCallPart: (props: {
- part: { id: string };
- context: { partIndex: number };
+ part: { id: string; status: string };
+ context: { partIndex: number; inFlight: boolean };
}) => (
- <div data-index={props.context.partIndex} data-testid="tool">
+ <div
+ data-index={props.context.partIndex}
+ data-status={props.part.status}
+ data-live={String(props.context.inFlight)}
+ data-testid="tool"
+ >
{props.part.id}
</div>
),
@@ -71,13 +76,13 @@ vi.mock('../ui', () => ({
ToolGroup: (props: {
count: number;
active: boolean;
- latest: { label: string; detail?: string };
+ live: boolean;
children: JSX.Element;
}) => (
<div
data-active={String(props.active)}
data-count={props.count}
- data-latest={`${props.latest.label}${props.latest.detail ? ` · ${props.latest.detail}` : ''}`}
+ data-live={String(props.live)}
data-testid="group"
>
{props.children}
@@ -147,7 +152,7 @@ describe('Message tool grouping', () => {
const group = view.getByTestId('group');
expect(group.dataset.count).toBe('3');
expect(group.dataset.active).toBe('false');
- expect(group.dataset.latest).toBe('Bash · cargo test');
+ expect(group.dataset.live).toBe('false');
expect(view.getAllByTestId('tool').map((el) => el.dataset.index)).toEqual([
'1',
'2',
@@ -190,6 +195,45 @@ describe('Message tool grouping', () => {
expect(view.getByTestId('permission')).toBeTruthy();
});
+ it('keeps DisplayResults outside the tool groups before and after it', () => {
+ const [reply, setReply] = createSignal(
+ message(
+ [
+ tool('a'),
+ tool('b'),
+ tool('display', {
+ name: { kind: 'mcp', server: 'macro', tool: 'DisplayResults' },
+ status: 'pending',
+ detail: { kind: 'macro', input: null, output: null, error: null },
+ }),
+ tool('c'),
+ tool('d'),
+ ],
+ null
+ )
+ );
+ const view = render(() => <Message message={reply()} inFlight />);
+ const groups = view.getAllByTestId('group');
+ const display = view.getByText('display');
+ expect(groups.map((group) => group.dataset.count)).toEqual(['2', '2']);
+ expect(display.closest('[data-testid="group"]')).toBeNull();
+ expect(view.getAllByTestId('tool').map((row) => row.dataset.index)).toEqual(
+ ['0', '1', '2', '3', '4']
+ );
+
+ setReply((previous) => ({
+ ...previous,
+ parts: previous.parts.map((part) =>
+ part.kind === 'tool_use' && part.id === 'display'
+ ? { ...part, status: 'completed' }
+ : part
+ ),
+ }));
+ expect(view.getByText('display')).toBe(display);
+ expect(display.closest('[data-testid="group"]')).toBeNull();
+ expect(view.getAllByTestId('group')).toEqual(groups);
+ });
+
it('reads as active while a call in the run is still running', () => {
const view = render(() => (
<Message
@@ -229,7 +273,7 @@ describe('Message tool grouping', () => {
);
expect(view.getByTestId('group')).toBe(group);
expect(group.dataset.count).toBe('3');
- expect(group.dataset.latest).toBe('Read · c.rs');
+ expect(group.dataset.live).toBe('true');
expect(view.getAllByTestId('tool').map((el) => el.dataset.index)).toEqual([
'1',
'2',
@@ -252,6 +296,50 @@ describe('Message tool grouping', () => {
expect(view.getByTestId('group').dataset.count).toBe('2');
expect(view.getByTestId('text')).toBe(prose);
});
+
+ it('updates immutable streamed calls without remounting their rows', () => {
+ const [reply, setReply] = createSignal(
+ message([tool('a'), tool('b', { status: 'running' })], null)
+ );
+ const view = render(() => <Message message={reply()} inFlight />);
+ const group = view.getByTestId('group');
+ const rows = view.getAllByTestId('tool');
+
+ setReply(
+ message([tool('a'), tool('b'), tool('c', { status: 'running' })], null)
+ );
+ expect(view.getByTestId('group')).toBe(group);
+ expect(view.getAllByTestId('tool')[0]).toBe(rows[0]);
+ expect(view.getAllByTestId('tool')[1]).toBe(rows[1]);
+ expect(rows[1].dataset.status).toBe('completed');
+ expect(view.getAllByTestId('tool')[2].dataset.status).toBe('running');
+ });
+
+ it('marks a completed batch as live so its arrivals remain visible briefly', () => {
+ const view = render(() => (
+ <Message message={message([tool('a'), tool('b')], null)} inFlight />
+ ));
+ expect(view.getByTestId('group').dataset.live).toBe('true');
+ expect(view.getByTestId('group').dataset.active).toBe('false');
+ });
+
+ it('preserves unfinished call status when another part follows the group', () => {
+ const view = render(() => (
+ <Message
+ message={message(
+ [tool('a'), tool('b', { status: 'running' }), text('Answer')],
+ null
+ )}
+ inFlight
+ />
+ ));
+ expect(view.getByTestId('group').dataset.active).toBe('true');
+ expect(view.getByTestId('group').dataset.live).toBe('false');
+ expect(view.getAllByTestId('tool').map((row) => row.dataset.live)).toEqual([
+ 'true',
+ 'true',
+ ]);
+ });
});
describe('Message working tail', () => {
@@ -264,6 +352,28 @@ describe('Message working tail', () => {
));
expect(view.getByTestId('working').textContent).toBe('Running tools');
});
+
+ it('does not duplicate the active tool or group with a working shimmer', () => {
+ const view = render(() => (
+ <Message
+ message={message([tool('a'), tool('b', { status: 'running' })], null)}
+ inFlight
+ />
+ ));
+ expect(view.getByTestId('group').dataset.active).toBe('true');
+ expect(view.queryByTestId('working')).toBeNull();
+ });
+
+ it('does not duplicate an active batch when its final call completes first', () => {
+ const view = render(() => (
+ <Message
+ message={message([tool('a', { status: 'running' }), tool('b')], null)}
+ inFlight
+ />
+ ));
+ expect(view.getByTestId('group').dataset.active).toBe('true');
+ expect(view.queryByTestId('working')).toBeNull();
+ });
});
describe('Message thought shimmer', () => {
@@ -272,6 +382,50 @@ describe('Message thought shimmer', () => {
text: value,
});
+ it('keeps consecutive thoughts visible without creating an empty tool group', () => {
+ const [reply, setReply] = createSignal(
+ message(
+ [
+ text('Looking.'),
+ thought('First thought'),
+ thought('Second thought'),
+ text('Answer.'),
+ ],
+ null
+ )
+ );
+ const view = render(() => <Message message={reply()} inFlight />);
+ const thoughts = view.getAllByTestId('thought');
+ expect(thoughts.map((row) => row.textContent)).toEqual([
+ 'First thought',
+ 'Second thought',
+ ]);
+ expect(thoughts.map((row) => row.dataset.active)).toEqual([
+ 'false',
+ 'false',
+ ]);
+ expect(view.queryByTestId('group')).toBeNull();
+ expect(view.getAllByTestId('text').map((row) => row.textContent)).toEqual([
+ 'Looking.',
+ 'Answer.',
+ ]);
+
+ setReply(
+ message(
+ [
+ text('Looking.'),
+ thought('First thought'),
+ thought('Updated thought'),
+ text('Answer continued.'),
+ ],
+ null
+ )
+ );
+ expect(view.getAllByTestId('thought')[0]).toBe(thoughts[0]);
+ expect(view.getAllByTestId('thought')[1]).toBe(thoughts[1]);
+ expect(thoughts[1].textContent).toBe('Updated thought');
+ });
+
it('keeps grouped thoughts at their real indices when the group opens', () => {
const view = render(() => (
<Message
@@ -341,7 +495,7 @@ describe('Message thought shimmer', () => {
expect(view.getByTestId('thought').dataset.active).toBe('false');
});
- it('drops the working row when the turn settles with a call still open', () => {
+ it('settles a lone active call without adding another working row', () => {
const [state, setState] = createStore({ inFlight: true });
const view = render(() => (
<Message
@@ -349,9 +503,11 @@ describe('Message thought shimmer', () => {
inFlight={state.inFlight}
/>
));
- expect(view.getByTestId('working')).toBeTruthy();
+ expect(view.getByTestId('tool').dataset.live).toBe('true');
+ expect(view.queryByTestId('working')).toBeNull();
setState('inFlight', false);
+ expect(view.getByTestId('tool').dataset.live).toBe('false');
expect(view.queryByTestId('working')).toBeNull();
});
diff --git a/apps/web/src/features/block-agent/component/AgentMessage.tsx b/apps/web/src/features/block-agent/component/AgentMessage.tsx
index 91e1030d8c..a2be2b8aac 100644
--- a/apps/web/src/features/block-agent/component/AgentMessage.tsx
+++ b/apps/web/src/features/block-agent/component/AgentMessage.tsx
@@ -17,7 +17,7 @@ import type {
MessagePart,
} from '@service-agent-fold/generated/types';
import { UserMessageBubble } from '@ui';
-import { For, Index, type JSX, Show } from 'solid-js';
+import { For, Index, type JSX, Match, Show, Switch } from 'solid-js';
import { match } from 'ts-pattern';
import { isControlMessage } from '../state/control-message';
import { thoughtIsStreaming } from '../state/thought-streaming';
@@ -34,7 +34,7 @@ import { ControlPart } from './parts/ControlPart';
import { ElicitationPart } from './parts/ElicitationPart';
import { PermissionPart } from './parts/PermissionPart';
import { PlanPart } from './parts/PlanPart';
-import { type ToolUsePart, toolCallDetail, toolLabel } from './parts/shared';
+import type { ToolUsePart } from './parts/shared';
import { TextPart } from './parts/TextPart';
import { ToolCallPart } from './parts/ToolCallPart';
@@ -54,41 +54,56 @@ function AgentMessagePart(props: {
/** The turn is still in flight — the tail thought reads "Thinking". */
inFlight: boolean;
}): JSX.Element {
- return match(props.part)
- .with({ kind: 'text' }, (part) => (
- <TextPart text={part.text} inFlight={props.inFlight} />
- ))
- .with({ kind: 'attachment' }, (part) => <AttachmentPart part={part} />)
- .with({ kind: 'thought' }, (part) => (
- <Thought
- text={part.text}
- active={thoughtIsStreaming(
- props.inFlight,
- props.index,
- props.message.parts.length
+ // Match accessors keep a part's renderer mounted when a streamed snapshot
+ // replaces the object, preserving disclosures while updating their contents.
+ return (
+ <Switch>
+ <Match when={props.part.kind === 'text' && props.part}>
+ {(part) => <TextPart text={part().text} inFlight={props.inFlight} />}
+ </Match>
+ <Match when={props.part.kind === 'attachment' && props.part}>
+ {(part) => <AttachmentPart part={part()} />}
+ </Match>
+ <Match when={props.part.kind === 'thought' && props.part}>
+ {(part) => (
+ <Thought
+ text={part().text}
+ active={thoughtIsStreaming(
+ props.inFlight,
+ props.index,
+ props.message.parts.length
+ )}
+ />
+ )}
+ </Match>
+ <Match when={props.part.kind === 'tool_use' && props.part}>
+ {(part) => (
+ <ToolCallPart
+ part={part()}
+ context={{
+ sessionId: props.message.agentSessionId,
+ // Turn and side identify a message within its session.
+ messageId: `${props.message.agentSessionId}:${props.message.turn}:${props.message.author.kind}`,
+ partIndex: props.index,
+ inFlight: props.inFlight,
+ }}
+ />
)}
- />
- ))
- .with({ kind: 'tool_use' }, (part) => (
- <ToolCallPart
- part={part}
- context={{
- sessionId: props.message.agentSessionId,
- // The turn and side identify a message within its session (see
- // `@core/agent-fold/message-id.ts`), so they make its stable id.
- messageId: `${props.message.agentSessionId}:${props.message.turn}:${props.message.author.kind}`,
- partIndex: props.index,
- inFlight: props.inFlight,
- }}
- />
- ))
- .with({ kind: 'permission' }, (part) => <PermissionPart part={part} />)
- .with({ kind: 'plan' }, (part) => <PlanPart part={part} />)
- .with({ kind: 'control' }, (part) => <ControlPart part={part} />)
- .with({ kind: 'elicitation' }, (part) => (
- <ElicitationPart part={part} turn={props.message.turn} />
- ))
- .exhaustive();
+ </Match>
+ <Match when={props.part.kind === 'permission' && props.part}>
+ {(part) => <PermissionPart part={part()} />}
+ </Match>
+ <Match when={props.part.kind === 'plan' && props.part}>
+ {(part) => <PlanPart part={part()} />}
+ </Match>
+ <Match when={props.part.kind === 'control' && props.part}>
+ {(part) => <ControlPart part={part()} />}
+ </Match>
+ <Match when={props.part.kind === 'elicitation' && props.part}>
+ {(part) => <ElicitationPart part={part()} turn={props.message.turn} />}
+ </Match>
+ </Switch>
+ );
}
/**
@@ -106,34 +121,29 @@ function ToolGroupPart(props: {
const parts = () => props.message.parts.slice(props.start, props.end);
const calls = () =>
parts().filter((part): part is ToolUsePart => part.kind === 'tool_use');
+ const live = () => props.inFlight && props.end === props.message.parts.length;
// A call the log left running in a finished turn is over (see
// `settledToolStatus`), so a settled turn's run is never "Calling".
const active = () =>
props.inFlight && calls().some((call) => isToolActive(call.status));
+ const renderParts = () => (
+ <Index each={parts()}>
+ {(part, offset) => (
+ <AgentMessagePart
+ part={part()}
+ message={props.message}
+ index={props.start + offset}
+ inFlight={props.inFlight}
+ />
+ )}
+ </Index>
+ );
return (
- <Show when={calls().at(-1)}>
- {(latest) => (
- <ToolGroup
- count={calls().length}
- active={active()}
- latest={{
- label: toolLabel(latest().name),
- detail: toolCallDetail(latest()),
- }}
- >
- <For each={parts()}>
- {(part, offset) => (
- <AgentMessagePart
- part={part}
- message={props.message}
- index={props.start + offset()}
- inFlight={props.inFlight}
- />
- )}
- </For>
- </ToolGroup>
- )}
+ <Show when={calls().length > 0} fallback={renderParts()}>
+ <ToolGroup count={calls().length} active={active()} live={live()}>
+ {renderParts()}
+ </ToolGroup>
</Show>
);
}
@@ -146,6 +156,12 @@ function ToolGroupPart(props: {
* or elicitation prompt is waiting on the reader, not working.
*/
function showsWorkingLine(message: FoldedMessage): boolean {
+ if (
+ message.parts.some(
+ (part) => part.kind === 'tool_use' && isToolActive(part.status)
+ )
+ )
+ return false;
const last = message.parts[message.parts.length - 1];
if (last === undefined) return true;
return match(last)
diff --git a/apps/web/src/features/block-agent/component/parts/DisplayResultsToolCall.test.tsx b/apps/web/src/features/block-agent/component/parts/DisplayResultsToolCall.test.tsx
new file mode 100644
index 0000000000..bfe4a93b33
--- /dev/null
+++ b/apps/web/src/features/block-agent/component/parts/DisplayResultsToolCall.test.tsx
@@ -0,0 +1,149 @@
+/** @vitest-environment jsdom */
+
+import type { View } from '@app/features/dynamic-ui/schema';
+import { cleanup, render } from '@solidjs/testing-library';
+import type { JSX } from 'solid-js';
+import { createStore, reconcile } from 'solid-js/store';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import { DisplayResultsToolCall } from './DisplayResultsToolCall';
+import type { ToolCallCommon } from './shared';
+
+// Keep the real dashboard schema validation and streaming behavior; replace
+// entity widgets and Lexical context with presentation markers.
+vi.mock('@app/features/dynamic-ui/DashboardToolView.lazy', async () => ({
+ DashboardToolView: (
+ await import('@app/features/dynamic-ui/DashboardToolView')
+ ).default,
+}));
+
+vi.mock('@app/features/dynamic-ui/widget', () => ({
+ Widget: {
+ Compose: (props: { view: View }) => (
+ <div data-testid="dashboard">{JSON.stringify(props.view)}</div>
+ ),
+ },
+}));
+
+vi.mock(
+ '@core/component/LexicalMarkdown/component/core/StaticMarkdown',
+ () => ({
+ StaticMarkdownContext: (props: { children?: JSX.Element }) =>
+ props.children,
+ })
+);
+
+vi.mock('@core/component/LexicalMarkdown/theme', () => ({ aiChatTheme: {} }));
+
+vi.mock('../../ui', async () => ({
+ isToolActive: (await import('../../ui/types')).isToolActive,
+ ToolCard: (await import('../../ui/ToolCard')).ToolCard,
+}));
+
+afterEach(cleanup);
+
+function common(
+ status: ToolCallCommon['status'] = 'completed'
+): ToolCallCommon {
+ return {
+ id: 'display-results',
+ label: 'DisplayResults',
+ server: 'macro',
+ status,
+ muted: status === 'failed',
+ trailing: status === 'failed' ? 'Failed' : undefined,
+ };
+}
+
+describe('DisplayResultsToolCall', () => {
+ it('renders completed results inline without a tool row', () => {
+ const view = {
+ title: 'This week',
+ widgets: [{ type: 'md', markdown: 'hi' }],
+ };
+ const rendered = render(() => (
+ <DisplayResultsToolCall input={{ view }} common={common()} />
+ ));
+
+ expect(rendered.getByTestId('dashboard').textContent).toBe(
+ JSON.stringify(view)
+ );
+ expect(rendered.container.querySelector('[data-tool-row]')).toBeNull();
+ });
+
+ it('waits for partial arguments, streams valid updates, and keeps the final view without a response', () => {
+ const [props, setProps] = createStore<{
+ input: unknown;
+ common: ToolCallCommon;
+ }>({ input: null, common: common('running') });
+ const rendered = render(() => <DisplayResultsToolCall {...props} />);
+
+ for (const status of ['pending', 'running'] as const) {
+ for (const input of [null, {}, { view: null }, { view: {} }]) {
+ setProps(reconcile({ input, common: common(status) }));
+ expect(rendered.container.textContent).toBe('');
+ }
+ }
+
+ const view = {
+ title: 'This week',
+ widgets: [{ type: 'md', markdown: 'First results' }],
+ };
+ setProps(reconcile({ input: { view }, common: common('running') }));
+ expect(rendered.getByTestId('dashboard').textContent).toBe(
+ JSON.stringify(view)
+ );
+
+ const finalView = {
+ title: 'All results',
+ widgets: [{ type: 'md', markdown: 'Final results' }],
+ };
+ setProps(reconcile({ input: { view: finalView }, common: common() }));
+ expect(rendered.getByTestId('dashboard').textContent).toBe(
+ JSON.stringify(finalView)
+ );
+ expect(rendered.container.querySelector('[data-tool-row]')).toBeNull();
+ });
+
+ it.each([null, {}, { view: null }, { view: { widgets: 'invalid-payload' } }])(
+ 'reports malformed completed input without exposing its payload: %j',
+ (input) => {
+ const rendered = render(() => (
+ <DisplayResultsToolCall input={input} common={common()} />
+ ));
+
+ expect(rendered.container.textContent).toContain(
+ "Couldn't render dashboard"
+ );
+ expect(rendered.container.textContent).not.toContain('invalid-payload');
+ expect(rendered.queryByTestId('dashboard')).toBeNull();
+ expect(rendered.queryByRole('button')).toBeNull();
+ }
+ );
+
+ it.each([
+ { status: 'failed', error: null },
+ { status: 'completed', error: 'private-error-details' },
+ { status: 'running', error: 'private-error-details' },
+ ] as const)('shows only a failed summary for %j', ({ status, error }) => {
+ const rendered = render(() => (
+ <DisplayResultsToolCall
+ input={{
+ view: { widgets: [{ type: 'md', markdown: 'Hidden result' }] },
+ }}
+ error={error}
+ common={common(status)}
+ />
+ ));
+
+ expect(rendered.getByText('Failed')).toBeTruthy();
+ const row = rendered.container.querySelector('[data-tool-row]');
+ expect(row?.getAttribute('data-tool-status')).toBe('failed');
+ expect(row?.classList.contains('opacity-75')).toBe(true);
+ expect(rendered.queryByTestId('dashboard')).toBeNull();
+ expect(rendered.queryByRole('button')).toBeNull();
+ expect(rendered.container.textContent).not.toContain(
+ 'private-error-details'
+ );
+ expect(rendered.container.querySelector('.magic-chip-shimmer')).toBeNull();
+ });
+});
diff --git a/apps/web/src/features/block-agent/component/parts/DisplayResultsToolCall.tsx b/apps/web/src/features/block-agent/component/parts/DisplayResultsToolCall.tsx
new file mode 100644
index 0000000000..95a77891b5
--- /dev/null
+++ b/apps/web/src/features/block-agent/component/parts/DisplayResultsToolCall.tsx
@@ -0,0 +1,56 @@
+/** DisplayResults is message content, rendered directly from the call's view. */
+
+import { DashboardToolView } from '@app/features/dynamic-ui/DashboardToolView.lazy';
+import { ErrorBoundary, Show, Suspense } from 'solid-js';
+import { isToolActive, ToolCard } from '../../ui';
+import type { ToolCallCommon } from './shared';
+
+export function DisplayResultsToolCall(props: {
+ input: unknown;
+ error?: string | null;
+ common: ToolCallCommon;
+}) {
+ const pending = () => isToolActive(props.common.status);
+ const failed = () => props.common.status === 'failed' || props.error != null;
+ // The dashboard validates partial streamed input with the same schema used
+ // for the tool. Pass missing views through so it can distinguish an open
+ // call from malformed completed input.
+ const view = () =>
+ typeof props.input === 'object' &&
+ props.input !== null &&
+ 'view' in props.input
+ ? props.input.view
+ : undefined;
+ const unavailable = () => (
+ <p class="text-xs text-ink-extra-muted" role="status">
+ Unable to display these results.
+ </p>
+ );
+
+ return (
+ <Show
+ when={!failed()}
+ fallback={
+ <ToolCard
+ title={props.common.label}
+ subtitle={props.common.server}
+ status="failed"
+ muted
+ trailing="Failed"
+ />
+ }
+ >
+ <ErrorBoundary fallback={unavailable()}>
+ <Suspense
+ fallback={
+ <Show when={!pending()}>
+ <p class="text-xs text-ink-extra-muted">Loading results…</p>
+ </Show>
+ }
+ >
+ <DashboardToolView view={view()} pending={pending()} />
+ </Suspense>
+ </ErrorBoundary>
+ </Show>
+ );
+}
diff --git a/apps/web/src/features/block-agent/component/parts/EditToolCall.tsx b/apps/web/src/features/block-agent/component/parts/EditToolCall.tsx
index a543f0d2f7..896de2ad32 100644
--- a/apps/web/src/features/block-agent/component/parts/EditToolCall.tsx
+++ b/apps/web/src/features/block-agent/component/parts/EditToolCall.tsx
@@ -1,7 +1,8 @@
/** File modifications: +/− badge in the row, Pierre-rendered diffs in the body. */
+import PencilIcon from '@phosphor/pencil-simple.svg';
import type { ToolDetail } from '@service-agent-fold/generated/types';
-import { Show } from 'solid-js';
+import { createMemo, Show } from 'solid-js';
import { countDiffChanges } from '../../state/session-summary';
import { DiffChanges, PierreDiff, ToolCard } from '../../ui';
import { pathsSubtitle, type ToolCallCommon } from './shared';
@@ -10,13 +11,20 @@ export function EditToolCall(props: {
detail: Extract<ToolDetail, { kind: 'edit' }>;
common: ToolCallCommon;
}) {
- const changes = () => countDiffChanges(props.detail.diffs);
+ const changes = createMemo(() => countDiffChanges(props.detail.diffs));
+ const hasChanges = () => changes().additions + changes().deletions > 0;
return (
<ToolCard
+ icon={<PencilIcon class="size-4" />}
title={props.common.label}
subtitle={pathsSubtitle(props.detail.diffs.map((diff) => diff.path))}
- trailing={props.common.trailing ?? <DiffChanges {...changes()} />}
+ trailing={
+ props.common.trailing ??
+ (props.common.status === 'completed' && hasChanges() ? (
+ <DiffChanges {...changes()} />
+ ) : undefined)
+ }
status={props.common.status}
muted={props.common.muted}
hasContent={props.detail.diffs.length > 0}
diff --git a/apps/web/src/features/block-agent/component/parts/ElicitationPart.test.tsx b/apps/web/src/features/block-agent/component/parts/ElicitationPart.test.tsx
index b9d7edaf06..944b4aa06a 100644
--- a/apps/web/src/features/block-agent/component/parts/ElicitationPart.test.tsx
+++ b/apps/web/src/features/block-agent/component/parts/ElicitationPart.test.tsx
@@ -46,9 +46,14 @@ vi.mock('../../ui', () => ({
subtitle?: string;
trailing?: JSX.Element;
status: string;
+ hasContent?: boolean;
children?: JSX.Element;
}) => (
- <div data-testid="tool-card" data-status={props.status}>
+ <div
+ data-testid="tool-card"
+ data-status={props.status}
+ data-expandable={props.hasContent ?? true}
+ >
<span data-testid="title">{props.title}</span>
<span data-testid="subtitle">{props.subtitle}</span>
<span data-testid="trailing">{props.trailing}</span>
@@ -331,6 +336,29 @@ describe('ElicitationPart', () => {
expect(getByTestId('body').textContent).not.toContain('Red');
});
+ it('keeps unrecognized answer payloads out of the disclosure', () => {
+ const { getByTestId } = render(() => (
+ <ElicitationPart
+ turn={0}
+ part={part({
+ outcome: {
+ kind: 'accepted',
+ answers: [
+ {
+ name: 'unknown',
+ label: 'Unsupported answer',
+ value: { kind: 'unrecognized', raw: { hiddenPayload: 42 } },
+ },
+ ],
+ },
+ })}
+ />
+ ));
+ expect(getByTestId('tool-card').dataset.expandable).toBe('false');
+ expect(getByTestId('trailing').textContent).toBe('Answered');
+ expect(getByTestId('body').textContent).toBe('');
+ });
+
it('a url request shows the host and opens only after consent', async () => {
const open = vi.spyOn(window, 'open').mockImplementation(() => null);
pending = {
diff --git a/apps/web/src/features/block-agent/component/parts/ElicitationPart.tsx b/apps/web/src/features/block-agent/component/parts/ElicitationPart.tsx
index 6f1e511238..6d6ca50f92 100644
--- a/apps/web/src/features/block-agent/component/parts/ElicitationPart.tsx
+++ b/apps/web/src/features/block-agent/component/parts/ElicitationPart.tsx
@@ -215,7 +215,7 @@ function answerText(value: AnsweredValue): string {
.with({ kind: 'choices' }, (v) =>
v.choices.map((choice) => choice.title ?? choice.value).join(', ')
)
- .with({ kind: 'unrecognized' }, (v) => JSON.stringify(v.raw))
+ .with({ kind: 'unrecognized' }, () => '')
.exhaustive();
}
@@ -227,8 +227,10 @@ function ResolvedQuestion(props: { part: ElicitationPartData }) {
// The harness's own reading outranks what we sent: it is what the agent
// actually acted on. Both arrive from the fold in the same shape.
const shown = (): AnsweredField[] =>
- props.part.reported ??
- (props.part.outcome.kind === 'accepted' ? props.part.outcome.answers : []);
+ (
+ props.part.reported ??
+ (props.part.outcome.kind === 'accepted' ? props.part.outcome.answers : [])
+ ).filter((answer) => answer.value.kind !== 'unrecognized');
return (
<ToolCard
diff --git a/apps/web/src/features/block-agent/component/parts/ExchangeToolCall.tsx b/apps/web/src/features/block-agent/component/parts/ExchangeToolCall.tsx
index 242a9e3479..bdac34c480 100644
--- a/apps/web/src/features/block-agent/component/parts/ExchangeToolCall.tsx
+++ b/apps/web/src/features/block-agent/component/parts/ExchangeToolCall.tsx
@@ -1,18 +1,12 @@
/**
- * The card for a call the fold has no special rendering for: a tool on an
- * MCP server it does not know, a harness tool this block does not model,
- * ACP's `switch_mode`. What there is to show is the exchange itself - the
- * arguments the agent sent and the result it got - so the body is those,
- * labelled, as JSON.
- *
- * An MCP tool shows its server beside its name (`ReadContent · macro`), the
- * way the chat block's MCP row does; a failed call keeps the fold's error
- * text as its subtitle, the chat block's failed-tool treatment.
+ * A summary-only row for calls without a registered result renderer.
+ * The MCP server stays beside the tool name; raw arguments and results are
+ * never exposed as a fallback disclosure.
*/
import type { ToolDetail } from '@service-agent-fold/generated/types';
import type { JSX } from 'solid-js';
-import { FoldedExchange, ToolCard } from '../../ui';
+import { ToolCard } from '../../ui';
import type { ToolCallCommon } from './shared';
type ExchangeDetail = Extract<ToolDetail, { kind: 'other' }>;
@@ -21,26 +15,16 @@ export function ExchangeToolCall(props: {
detail: ExchangeDetail;
common: ToolCallCommon;
}): JSX.Element {
- const hasContent = () =>
- props.detail.input != null ||
- props.detail.result != null ||
- Boolean(props.detail.output) ||
- Boolean(props.detail.error);
return (
<ToolCard
title={props.common.label}
- subtitle={props.detail.error ?? props.common.server}
+ subtitle={props.common.server}
status={props.common.status}
- muted={props.common.muted}
- trailing={props.common.trailing}
- hasContent={hasContent()}
- >
- <FoldedExchange
- request={props.detail.input}
- response={props.detail.result}
- responseText={props.detail.output}
- error={props.detail.error}
- />
- </ToolCard>
+ muted={props.common.muted || props.detail.error != null}
+ trailing={
+ props.common.trailing ??
+ (props.detail.error != null ? 'Failed' : undefined)
+ }
+ />
);
}
diff --git a/apps/web/src/features/block-agent/component/parts/MacroToolCall.tsx b/apps/web/src/features/block-agent/component/parts/MacroToolCall.tsx
index c799497824..cd37868dc5 100644
--- a/apps/web/src/features/block-agent/component/parts/MacroToolCall.tsx
+++ b/apps/web/src/features/block-agent/component/parts/MacroToolCall.tsx
@@ -2,133 +2,217 @@
* A Macro tool the fold recognized by name — reached over Macro's MCP
* server, or called natively by Macro's own agent.
*
- * The fold has already named the tool and removed any MCP envelope, so
- * `detail.input` / `detail.output` are the tool's own JSON. When the chat
- * block has a component for that tool, it renders here with that JSON — the
- * same chip a chat shows for `ReadContent`, `ListEntities`, `CreateDocument`
- * and the rest. The chat renderer validates the JSON against the tool's
- * schema and shows nothing for a shape it does not know; then, or when a
- * chat component assumes chat context it does not have here, the card falls
- * back to a labelled row with the JSON.
+ * Successful calls reuse their registered result renderer and its disclosure.
+ * Running, stopped, failed, and unsupported calls keep a summary-only row.
+ * Only registered result renderers supply disclosures; raw payloads stay hidden.
*/
-import { RenderTool } from '@core/component/AI/component/tool/handler';
+import {
+ hasToolRenderer,
+ RenderTool,
+} from '@core/component/AI/component/tool/handler';
+import ReadIcon from '@phosphor/file-text.svg';
+import GlobeIcon from '@phosphor/globe.svg';
+import ListIcon from '@phosphor/list-bullets.svg';
+import SearchIcon from '@phosphor/magnifying-glass.svg';
+import PencilIcon from '@phosphor/pencil-simple.svg';
+import WrenchIcon from '@phosphor/wrench.svg';
import type { ToolDetail } from '@service-agent-fold/generated/types';
import {
deserializeToolCall,
deserializeToolResponse,
+ type NamedTool,
+ type ToolName,
} from '@service-cognition/generated/tools/tool';
-import { createMemo, ErrorBoundary, type JSX, Show } from 'solid-js';
-import { DashboardToolView } from '../../../dynamic-ui/DashboardToolView.lazy';
-import { FoldedExchange, ToolCard } from '../../ui';
+import { createMemo, ErrorBoundary, type JSX, Show, Suspense } from 'solid-js';
+import { match } from 'ts-pattern';
+import { ToolCard } from '../../ui';
import type { ToolCallCommon, ToolCallContext } from './shared';
type MacroDetail = Extract<ToolDetail, { kind: 'macro' }>;
+type ToolResponse = NamedTool<ToolName, 'response'>;
export function MacroToolCall(props: {
detail: MacroDetail;
common: ToolCallCommon;
context?: ToolCallContext;
}): JSX.Element {
- const finished = () =>
- props.common.status === 'completed' || props.common.status === 'failed';
- const displayResults = () =>
- props.common.label === 'DisplayResults' &&
- props.common.status !== 'failed' &&
- props.detail.error == null;
- const dashboardView = () => {
- const input = props.detail.input;
- return input != null && typeof input === 'object' && 'view' in input
- ? input.view
- : undefined;
- };
- // The chat renderer renders nothing for a tool it has no component for or
- // arguments that do not fit the tool's schema, and it shows a *completed*
- // call whose response it cannot read as failed. A call it would drop or
- // misreport keeps the generic card, so no row vanishes or lies.
- const chatRenders = createMemo(() => {
- if (props.detail.error != null || props.common.status === 'failed') {
- return false;
- }
- const call = deserializeToolCall({
+ const response = createMemo(() =>
+ deserializeToolResponse({
id: props.common.id,
name: props.common.label,
- json: props.detail.input,
- });
- if (call.isErr()) return false;
- if (props.common.status !== 'completed') return true;
- return deserializeToolResponse({
+ json: props.detail.output,
+ }).unwrapOr(undefined)
+ );
+ const call = createMemo(() =>
+ deserializeToolCall({
id: props.common.id,
name: props.common.label,
- json: props.detail.output,
- }).isOk();
- });
-
- return (
- <Show
- when={displayResults()}
- fallback={
- <Show
- when={chatRenders()}
- fallback={<GenericMacroToolCall {...props} />}
- >
- <ErrorBoundary fallback={<GenericMacroToolCall {...props} />}>
- <RenderTool
- tool_id={props.common.id}
- name={props.common.label}
- json={props.detail.input}
- response={
- props.detail.output == null
- ? undefined
- : { json: props.detail.output, name: props.common.label }
- }
- chat_id={props.context?.sessionId ?? ''}
- message_id={props.context?.messageId ?? ''}
- part_index={props.context?.partIndex ?? 0}
- isComplete={finished()}
- renderContext={{
- renderContext: { isStreaming: !finished(), grouped: false },
- }}
- />
- </ErrorBoundary>
- </Show>
- }
- >
- {/* The view is the tool's user-facing result. Keep its streamed input
- reactive and let the dashboard validate it, even without a response. */}
- <ErrorBoundary fallback={<GenericMacroToolCall {...props} />}>
- <DashboardToolView view={dashboardView()} pending={!finished()} />
- </ErrorBoundary>
- </Show>
+ json: props.detail.input,
+ }).unwrapOr(undefined)
);
-}
+ const subtitle = () => {
+ const input = call()?.data;
+ if (input && 'query' in input && typeof input.query === 'string') {
+ return input.query;
+ }
+ if (input && 'url' in input && typeof input.url === 'string') {
+ return input.url;
+ }
+ if (
+ (props.common.label === 'WebSearch' ||
+ props.common.label === 'WebFetch') &&
+ input &&
+ 'input' in input &&
+ typeof input.input === 'string'
+ ) {
+ return input.input;
+ }
+ if (
+ (props.common.label === 'SearchSkills' ||
+ props.common.label === 'NameSearch') &&
+ input &&
+ 'name' in input &&
+ typeof input.name === 'string'
+ ) {
+ return input.name;
+ }
+ return props.common.server;
+ };
+ const error = () => props.detail.error ?? responseError(response());
+ const failure = () => error() != null;
-/**
- * The labelled row with the tool's own JSON - request, response, error - for
- * a tool the chat has no component for.
- */
-function GenericMacroToolCall(props: {
- detail: MacroDetail;
- common: ToolCallCommon;
-}): JSX.Element {
- return (
+ const fallback = () => (
<ToolCard
+ icon={<MacroToolIcon name={props.common.label} />}
title={props.common.label}
- subtitle={props.detail.error ?? props.common.server}
+ subtitle={subtitle()}
status={props.common.status}
- muted={props.common.muted}
- trailing={props.common.trailing}
- hasContent={
- props.detail.input != null ||
- props.detail.output != null ||
- Boolean(props.detail.error)
+ muted={props.common.muted || failure()}
+ trailing={
+ props.common.trailing ??
+ (failure()
+ ? 'Failed'
+ : props.common.status === 'completed'
+ ? resultSummary(response())
+ : undefined)
}
- >
- <FoldedExchange
- request={props.detail.input}
- response={props.detail.output}
- error={props.detail.error}
- />
- </ToolCard>
+ />
);
+ const canRenderResults = () =>
+ props.common.status === 'completed' &&
+ !props.common.muted &&
+ props.common.trailing == null &&
+ !failure() &&
+ call() !== undefined &&
+ response() !== undefined &&
+ hasToolRenderer(props.common.label);
+
+ return (
+ <Show when={canRenderResults()} fallback={fallback()}>
+ <ErrorBoundary fallback={fallback()}>
+ <Suspense fallback={fallback()}>
+ <RenderTool
+ tool_id={props.common.id}
+ name={props.common.label}
+ json={props.detail.input}
+ response={{ json: props.detail.output, name: props.common.label }}
+ chat_id={props.context?.sessionId ?? ''}
+ message_id={props.context?.messageId ?? ''}
+ part_index={props.context?.partIndex ?? 0}
+ isComplete={true}
+ renderContext={{
+ renderContext: { isStreaming: false, grouped: true },
+ }}
+ />
+ </Suspense>
+ </ErrorBoundary>
+ </Show>
+ );
+}
+
+/** Counts come from schema-validated results, never prose or input guesses. */
+function resultSummary(response: ToolResponse | undefined): string | undefined {
+ if (!response) return undefined;
+ const data = response.data;
+ if (typeof data !== 'object' || data === null) return undefined;
+ if ('results' in data && Array.isArray(data.results)) {
+ const additional =
+ 'additional_matches' in data && Array.isArray(data.additional_matches)
+ ? data.additional_matches.length
+ : 0;
+ const count = data.results.length + additional;
+ return `${count} ${count === 1 ? 'result' : 'results'}`;
+ }
+ if ('items' in data && Array.isArray(data.items)) {
+ return `${data.items.length} ${data.items.length === 1 ? 'item' : 'items'}`;
+ }
+ if (
+ isResponse(response, 'WebSearch') &&
+ Array.isArray(response.data.content)
+ ) {
+ const count = response.data.content.length;
+ return `${count} ${count === 1 ? 'result' : 'results'}`;
+ }
+ return undefined;
+}
+
+/** The generated NamedTool type does not correlate its name and data unions. */
+function isResponse<Name extends ToolName>(
+ response: ToolResponse | undefined,
+ name: Name
+): response is NamedTool<Name, 'response'> {
+ return response?.name === name;
+}
+
+function responseError(response: ToolResponse | undefined): string | undefined {
+ if (!response) return undefined;
+ const data = response.data;
+ if (typeof data !== 'object' || data === null) return undefined;
+ if ('success' in data && data.success === false) {
+ return 'message' in data && typeof data.message === 'string'
+ ? data.message || 'The tool did not succeed.'
+ : 'The tool did not succeed.';
+ }
+ if (
+ isResponse(response, 'WebFetch') &&
+ response.data.content.type === 'web_fetch_tool_result_error'
+ ) {
+ return response.data.content.error_code;
+ }
+ if (
+ isResponse(response, 'WebSearch') &&
+ !Array.isArray(response.data.content)
+ ) {
+ return response.data.content.error_code;
+ }
+ return undefined;
+}
+
+function MacroToolIcon(props: { name: string }): JSX.Element {
+ return match(props.name)
+ .with(
+ 'ContentSearch',
+ 'NameSearch',
+ 'SearchSkills',
+ 'SearchTools',
+ 'WebSearch',
+ () => <SearchIcon class="size-4" />
+ )
+ .with(
+ 'ReadContent',
+ 'ReadMetadata',
+ 'ReadThread',
+ 'ReadChat',
+ 'ReadProject',
+ () => <ReadIcon class="size-4" />
+ )
+ .with('WebFetch', () => <GlobeIcon class="size-4" />)
+ .with('EditDocument', 'EditSpreadsheet', 'CreateDocument', () => (
+ <PencilIcon class="size-4" />
+ ))
+ .with('ListEntities', 'ListSkills', 'ListCalendarEvents', () => (
+ <ListIcon class="size-4" />
+ ))
+ .otherwise(() => <WrenchIcon class="size-4" />);
}
diff --git a/apps/web/src/features/block-agent/component/parts/OutputToolCall.tsx b/apps/web/src/features/block-agent/component/parts/OutputToolCall.tsx
index 5472da513b..2ef9d06fff 100644
--- a/apps/web/src/features/block-agent/component/parts/OutputToolCall.tsx
+++ b/apps/web/src/features/block-agent/component/parts/OutputToolCall.tsx
@@ -3,6 +3,8 @@
* reported in the body — the chat block's GenericTool analog.
*/
+import BrainIcon from '@phosphor/brain.svg';
+import GlobeIcon from '@phosphor/globe.svg';
import type { ToolDetail } from '@service-agent-fold/generated/types';
import { Show } from 'solid-js';
import { FoldedOutput, ToolCard } from '../../ui';
@@ -14,6 +16,13 @@ export function OutputToolCall(props: {
}) {
return (
<ToolCard
+ icon={
+ props.detail.kind === 'fetch' ? (
+ <GlobeIcon class="size-4" />
+ ) : (
+ <BrainIcon class="size-4" />
+ )
+ }
title={props.common.label}
status={props.common.status}
muted={props.common.muted}
diff --git a/apps/web/src/features/block-agent/component/parts/PathsToolCall.tsx b/apps/web/src/features/block-agent/component/parts/PathsToolCall.tsx
index 5d06380e30..b9a5f8b9cd 100644
--- a/apps/web/src/features/block-agent/component/parts/PathsToolCall.tsx
+++ b/apps/web/src/features/block-agent/component/parts/PathsToolCall.tsx
@@ -1,7 +1,11 @@
/** A read, delete, or move: path (or count) in the row, full list in the body. */
+import MoveIcon from '@phosphor/arrows-left-right.svg';
+import ReadIcon from '@phosphor/file-text.svg';
+import TrashIcon from '@phosphor/trash.svg';
import type { ToolDetail } from '@service-agent-fold/generated/types';
import { Show } from 'solid-js';
+import { match } from 'ts-pattern';
import { FoldedPathList, ToolCard } from '../../ui';
import { pathsSubtitle, type ToolCallCommon } from './shared';
@@ -11,14 +15,24 @@ export function PathsToolCall(props: {
}) {
return (
<ToolCard
+ icon={match(props.detail.kind)
+ .with('read', () => <ReadIcon class="size-4" />)
+ .with('delete', () => <TrashIcon class="size-4" />)
+ .with('move', () => <MoveIcon class="size-4" />)
+ .exhaustive()}
title={props.common.label}
subtitle={pathsSubtitle(props.detail.paths)}
status={props.common.status}
muted={props.common.muted}
- trailing={props.common.trailing}
- hasContent={props.detail.paths.length > 1}
+ trailing={
+ props.common.trailing ??
+ (props.common.status === 'completed' && props.detail.paths.length > 0
+ ? `${props.detail.paths.length} ${props.detail.paths.length === 1 ? 'file' : 'files'}`
+ : undefined)
+ }
+ hasContent={props.detail.paths.length > 0}
>
- <Show when={props.detail.paths.length > 1}>
+ <Show when={props.detail.paths.length > 0}>
<FoldedPathList paths={props.detail.paths} />
</Show>
</ToolCard>
diff --git a/apps/web/src/features/block-agent/component/parts/SearchToolCall.tsx b/apps/web/src/features/block-agent/component/parts/SearchToolCall.tsx
index 47d74a9502..d6c61eaf55 100644
--- a/apps/web/src/features/block-agent/component/parts/SearchToolCall.tsx
+++ b/apps/web/src/features/block-agent/component/parts/SearchToolCall.tsx
@@ -1,5 +1,6 @@
/** A search: scope in the row, reported hits in the body. */
+import SearchIcon from '@phosphor/magnifying-glass.svg';
import type { ToolDetail } from '@service-agent-fold/generated/types';
import { Show } from 'solid-js';
import { FoldedOutput, ToolCard } from '../../ui';
@@ -11,6 +12,7 @@ export function SearchToolCall(props: {
}) {
return (
<ToolCard
+ icon={<SearchIcon class="size-4" />}
title={props.common.label}
subtitle={pathsSubtitle(props.detail.paths)}
status={props.common.status}
diff --git a/apps/web/src/features/block-agent/component/parts/SubagentToolCall.tsx b/apps/web/src/features/block-agent/component/parts/SubagentToolCall.tsx
index 2d19a46381..91c9649885 100644
--- a/apps/web/src/features/block-agent/component/parts/SubagentToolCall.tsx
+++ b/apps/web/src/features/block-agent/component/parts/SubagentToolCall.tsx
@@ -4,13 +4,13 @@
* same part components), and what it reported back.
*/
+import AgentIcon from '@phosphor/sparkle.svg';
import type {
MessagePart,
SubagentResult,
ToolDetail,
} from '@service-agent-fold/generated/types';
-import { For, type JSX, Show } from 'solid-js';
-import { match } from 'ts-pattern';
+import { Index, type JSX, Match, Show, Switch } from 'solid-js';
import { thoughtIsStreaming } from '../../state/thought-streaming';
import { FoldedOutput, Thought, ToolCard } from '../../ui';
import type { ToolCallCommon, ToolCallContext } from './shared';
@@ -19,7 +19,7 @@ import { ToolCallPart } from './ToolCallPart';
type SubagentDetail = Extract<ToolDetail, { kind: 'subagent' }>;
-/** `1 tool · 3.5s · 26k tokens`, from whatever the harness reported. */
+/** `1 tool · 3.5s`, from whatever the harness reported. */
function resultSummary(result: SubagentResult): string | undefined {
const facts: string[] = [];
if (result.toolUses != null) {
@@ -32,13 +32,6 @@ function resultSummary(result: SubagentResult): string | undefined {
: `${result.durationMs}ms`
);
}
- if (result.tokens != null) {
- facts.push(
- result.tokens >= 1000
- ? `${Math.round(result.tokens / 1000)}k tokens`
- : `${result.tokens} tokens`
- );
- }
return facts.length > 0 ? facts.join(' · ') : undefined;
}
@@ -51,29 +44,37 @@ function ChildPart(props: {
}) {
const inFlight = () => props.context?.inFlight ?? false;
return (
- match(props.part)
- .with({ kind: 'text' }, (part) => <TextPart text={part.text} />)
- .with({ kind: 'thought' }, (part) => (
- <Thought
- text={part.text}
- active={thoughtIsStreaming(inFlight(), props.index, props.childCount)}
- />
- ))
- .with({ kind: 'tool_use' }, (part) => (
- <ToolCallPart
- part={part}
- context={
- props.context && {
- ...props.context,
- // A child's slot is its own; the parent's index is not it.
- partIndex: props.index,
+ <Switch>
+ <Match when={props.part.kind === 'text' && props.part}>
+ {(part) => <TextPart text={part().text} />}
+ </Match>
+ <Match when={props.part.kind === 'thought' && props.part}>
+ {(part) => (
+ <Thought
+ text={part().text}
+ active={thoughtIsStreaming(
+ inFlight(),
+ props.index,
+ props.childCount
+ )}
+ />
+ )}
+ </Match>
+ <Match when={props.part.kind === 'tool_use' && props.part}>
+ {(part) => (
+ <ToolCallPart
+ part={part()}
+ context={
+ props.context && {
+ ...props.context,
+ // A child's slot is its own; the parent's index is not it.
+ partIndex: props.index,
+ }
}
- }
- />
- ))
- // A subagent's permission, plan, or control has nowhere to nest today;
- // the harnesses that attribute children only attribute tool calls.
- .otherwise(() => null)
+ />
+ )}
+ </Match>
+ </Switch>
);
}
@@ -91,7 +92,10 @@ export function SubagentToolCall(props: {
inFlight: working() && props.context.inFlight,
};
const subtitle = () =>
- [props.detail.agentType, props.detail.background ? 'background' : undefined]
+ [
+ props.detail.agentType ?? 'subagent',
+ props.detail.background ? 'background' : undefined,
+ ]
.filter(Boolean)
.join(' · ') || undefined;
const trailing = () =>
@@ -99,9 +103,7 @@ export function SubagentToolCall(props: {
(props.detail.result?.error != null ? (
<span class="text-ink">Failed</span>
) : props.detail.result ? (
- <Show when={resultSummary(props.detail.result)}>
- {(summary) => <span>{summary()}</span>}
- </Show>
+ resultSummary(props.detail.result)
) : undefined);
const hasBody = () =>
props.detail.prompt != null ||
@@ -110,12 +112,12 @@ export function SubagentToolCall(props: {
return (
<ToolCard
+ icon={<AgentIcon class="size-4" />}
title={props.detail.title}
subtitle={subtitle()}
status={props.common.status}
muted={props.common.muted || props.detail.result?.error != null}
trailing={trailing()}
- defaultOpen={props.detail.children.length > 0}
hasContent={hasBody()}
>
<Show when={hasBody()}>
@@ -129,16 +131,16 @@ export function SubagentToolCall(props: {
</Show>
<Show when={props.detail.children.length > 0}>
<div class="flex flex-col gap-1 border-l-2 border-edge-muted pl-2">
- <For each={props.detail.children}>
+ <Index each={props.detail.children}>
{(child, index) => (
<ChildPart
- part={child}
- index={index()}
+ part={child()}
+ index={index}
childCount={props.detail.children.length}
context={childContext()}
/>
)}
- </For>
+ </Index>
</div>
</Show>
<Show when={props.detail.result}>
@@ -155,6 +157,11 @@ export function SubagentToolCall(props: {
<span class="text-xs text-ink-extra-muted">{model()}</span>
)}
</Show>
+ <Show when={result().tokens != null}>
+ <span class="text-xs text-ink-extra-muted">
+ {result().tokens?.toLocaleString()} tokens
+ </span>
+ </Show>
</div>
)}
</Show>
diff --git a/apps/web/src/features/block-agent/component/parts/TerminalToolCall.tsx b/apps/web/src/features/block-agent/component/parts/TerminalToolCall.tsx
index 0ff2869ed9..d7cdb974f6 100644
--- a/apps/web/src/features/block-agent/component/parts/TerminalToolCall.tsx
+++ b/apps/web/src/features/block-agent/component/parts/TerminalToolCall.tsx
@@ -1,5 +1,6 @@
/** A shell command: `$ cmd` in the row, ANSI-colored output in the body. */
+import TerminalIcon from '@phosphor/terminal.svg';
import type { ToolDetail } from '@service-agent-fold/generated/types';
import { Show } from 'solid-js';
import { FoldedTerminal, ToolCard } from '../../ui';
@@ -9,19 +10,26 @@ export function TerminalToolCall(props: {
detail: Extract<ToolDetail, { kind: 'terminal' }>;
common: ToolCallCommon;
}) {
+ const failed = () =>
+ props.detail.exitCode != null && props.detail.exitCode !== 0;
return (
<ToolCard
+ icon={<TerminalIcon class="size-4" />}
title={props.common.label}
subtitle={props.detail.command ?? undefined}
status={props.common.status}
- muted={props.common.muted}
- trailing={props.common.trailing}
- hasContent={Boolean(props.detail.output)}
+ muted={props.common.muted || failed()}
+ trailing={
+ props.common.trailing ??
+ (failed() ? `Failed · exit ${props.detail.exitCode}` : undefined)
+ }
+ hasContent={props.detail.output != null || props.detail.exitCode != null}
>
- <Show when={props.detail.output}>
- {(output) => (
- <FoldedTerminal output={output()} exitCode={props.detail.exitCode} />
- )}
+ <Show when={props.detail.output != null || props.detail.exitCode != null}>
+ <FoldedTerminal
+ output={props.detail.output ?? ''}
+ exitCode={props.detail.exitCode}
+ />
</Show>
</ToolCard>
);
diff --git a/apps/web/src/features/block-agent/component/parts/ToolCallPart.test.tsx b/apps/web/src/features/block-agent/component/parts/ToolCallPart.test.tsx
index 188c5c1fc1..2998c3fa76 100644
--- a/apps/web/src/features/block-agent/component/parts/ToolCallPart.test.tsx
+++ b/apps/web/src/features/block-agent/component/parts/ToolCallPart.test.tsx
@@ -4,65 +4,41 @@
import type { MessagePart } from '@service-agent-fold/generated/types';
import { render } from '@solidjs/testing-library';
-import type { JSX } from 'solid-js';
-import { createStore, reconcile } from 'solid-js/store';
+import { createSignal, type JSX } from 'solid-js';
import { describe, expect, it, vi } from 'vitest';
-import type { View } from '../../../dynamic-ui/schema';
import type { ToolCallContext } from './shared';
import { ToolCallPart } from './ToolCallPart';
-// The chat block's tool renderer is mocked to a marker: it transitively pulls
-// in every per-tool component (split layout, queries, icon sprites). The layer
-// under test is the dispatcher's routing — chat component vs. generic card —
-// not the chat components themselves, which have their own tests.
+// Rich renderers own their result controls; this test verifies dispatch and
+// context without mounting their split-layout and query dependencies.
vi.mock('@core/component/AI/component/tool/handler', () => ({
+ hasToolRenderer: (name: string) => name !== 'ListSkills',
RenderTool: (props: {
name: string;
json: unknown;
+ response?: { json: unknown };
isComplete: boolean;
- response?: { json: unknown; name: string };
+ renderContext: {
+ renderContext: { grouped?: boolean; isStreaming: boolean };
+ };
}) => (
<div
- data-complete={String(props.isComplete)}
- data-has-response={String(props.response !== undefined)}
- data-response={
- props.response === undefined
- ? undefined
- : JSON.stringify(props.response.json)
- }
data-testid="macro-tool"
+ data-response={JSON.stringify(props.response?.json)}
+ data-grouped={String(props.renderContext.renderContext.grouped)}
+ data-streaming={String(props.renderContext.renderContext.isStreaming)}
>
{props.name}
</div>
),
}));
-// Exercise the dashboard's validation and streaming behavior, while replacing
-// the entity-heavy widgets and Lexical context with presentation markers.
-vi.mock('@app/features/dynamic-ui/DashboardToolView.lazy', async () => ({
- DashboardToolView: (
- await import('@app/features/dynamic-ui/DashboardToolView')
- ).default,
-}));
-
-vi.mock('@app/features/dynamic-ui/widget', () => ({
- Widget: {
- Compose: (props: { view: View }) => (
- <div data-testid="dashboard">{JSON.stringify(props.view)}</div>
- ),
- },
-}));
-
-vi.mock(
- '@core/component/LexicalMarkdown/component/core/StaticMarkdown',
- () => ({
- StaticMarkdownContext: (props: { children?: JSX.Element }) =>
- props.children,
- })
-);
-
-vi.mock('@core/component/LexicalMarkdown/theme', () => ({
- aiChatTheme: {},
+vi.mock('@app/features/dynamic-ui/DashboardToolView.lazy', () => ({
+ DashboardToolView: (props: { view: unknown; pending?: boolean }) => (
+ <div data-testid="dashboard-view" data-pending={props.pending}>
+ {JSON.stringify(props.view)}
+ </div>
+ ),
}));
// The entity link a finished email's outcome carries needs the query client
@@ -97,11 +73,13 @@ vi.mock('../../ui', async () => ({
trailing?: JSX.Element;
status: string;
muted?: boolean;
+ hasContent?: boolean;
children?: JSX.Element;
}) => (
<div
data-muted={String(props.muted ?? false)}
data-status={props.status}
+ data-expandable={String(props.hasContent ?? 'children' in props)}
data-testid="tool-card"
>
<span data-testid="title">{props.title}</span>
@@ -126,24 +104,6 @@ vi.mock('../../ui', async () => ({
FoldedOutput: (props: { text: string }) => (
<pre data-testid="output">{props.text}</pre>
),
- FoldedExchange: (props: {
- request?: unknown;
- response?: unknown;
- responseText?: string | null;
- error?: string | null;
- }) => (
- <div data-testid="exchange">
- <pre data-testid="request">
- {props.request == null ? '' : JSON.stringify(props.request, null, 2)}
- </pre>
- <pre data-testid="response">
- {props.response == null
- ? (props.responseText ?? '')
- : JSON.stringify(props.response, null, 2)}
- </pre>
- <pre data-testid="error">{props.error ?? ''}</pre>
- </div>
- ),
FoldedPathList: (props: { paths: string[] }) => (
<div data-testid="path-list">{props.paths.join(',')}</div>
),
@@ -223,7 +183,7 @@ describe('ToolCallPart routing', () => {
expect(rendered.getByTestId('subtitle').textContent).toBe('deepwiki');
});
- it('shows an MCP call as its request and response', () => {
+ it('reuses a known renderer for calls from the explicit Macro MCP server', () => {
const rendered = render(() => (
<ToolCallPart
part={{
@@ -239,17 +199,11 @@ describe('ToolCallPart routing', () => {
}}
/>
));
- expect(rendered.getByTestId('title').textContent).toBe('ReadContent');
- expect(rendered.getByTestId('request').textContent).toContain(
- '"documentId": "4a4886d8-9f4b-4f7e-a5a3-3f5c8b6c0e46"'
- );
- expect(rendered.getByTestId('response').textContent).toContain(
- '"text": "Q3 plan"'
- );
- expect(rendered.getByTestId('error').textContent).toBe('');
+ expect(rendered.getByTestId('macro-tool').textContent).toBe('ReadContent');
+ expect(rendered.queryByTestId('tool-card')).toBeNull();
});
- it('shows a failed MCP call faded, with the error as subtitle and in the body', () => {
+ it('shows a failed MCP call as a summary without a disclosure', () => {
const rendered = render(() => (
<ToolCallPart
part={{
@@ -269,9 +223,77 @@ describe('ToolCallPart routing', () => {
/>
));
expect(rendered.getByTestId('tool-card').dataset.muted).toBe('true');
- expect(rendered.getByTestId('subtitle').textContent).toBe('user declined');
- expect(rendered.getByTestId('error').textContent).toBe('user declined');
+ expect(rendered.getByTestId('subtitle').textContent).toBe('ops');
expect(rendered.getByTestId('trailing').textContent).toBe('Failed');
+ expect(rendered.getByTestId('tool-card').dataset.expandable).toBe('false');
+ expect(rendered.getByTestId('body').textContent).toBe('');
+ });
+
+ it('does not select a Macro renderer for an external server with the same tool name', () => {
+ const rendered = render(() => (
+ <ToolCallPart
+ part={{
+ ...toolUse({
+ kind: 'other',
+ acpKind: 'other',
+ output: null,
+ error: null,
+ input: { documentId: '4a4886d8-9f4b-4f7e-a5a3-3f5c8b6c0e46' },
+ result: { content: { text: 'Q3 plan' }, comments: [] },
+ }),
+ name: { kind: 'mcp', server: 'external', tool: 'ReadContent' },
+ }}
+ />
+ ));
+ expect(rendered.queryByTestId('macro-tool')).toBeNull();
+ expect(rendered.getByTestId('subtitle').textContent).toBe('external');
+ expect(rendered.getByTestId('tool-card').dataset.expandable).toBe('false');
+ expect(rendered.getByTestId('body').textContent).toBe('');
+ });
+
+ it('keeps malformed Macro MCP results hidden instead of exposing JSON', () => {
+ const rendered = render(() => (
+ <ToolCallPart
+ part={{
+ ...toolUse({
+ kind: 'other',
+ acpKind: 'other',
+ output: null,
+ error: null,
+ input: { documentId: '4a4886d8-9f4b-4f7e-a5a3-3f5c8b6c0e46' },
+ result: { unexpected: 'payload' },
+ }),
+ name: { kind: 'mcp', server: 'macro', tool: 'ReadContent' },
+ }}
+ />
+ ));
+ expect(rendered.queryByTestId('macro-tool')).toBeNull();
+ expect(rendered.getByTestId('tool-card').dataset.expandable).toBe('false');
+ expect(rendered.getByTestId('body').textContent).toBe('');
+ });
+
+ it('updates a generic Macro MCP result without remounting its existing renderer', () => {
+ const call = (text: string): ToolUsePart => ({
+ ...toolUse({
+ kind: 'other',
+ acpKind: 'other',
+ output: null,
+ error: null,
+ input: { documentId: '4a4886d8-9f4b-4f7e-a5a3-3f5c8b6c0e46' },
+ result: { content: { text }, comments: [] },
+ }),
+ name: { kind: 'mcp', server: 'macro', tool: 'ReadContent' },
+ });
+ const [part, setPart] = createSignal(call('First result'));
+ const rendered = render(() => <ToolCallPart part={part()} />);
+ const result = rendered.getByTestId('macro-tool');
+ setPart(call('Updated result'));
+ expect(rendered.getByTestId('macro-tool')).toBe(result);
+ expect(JSON.parse(result.dataset.response ?? '')).toEqual({
+ content: { text: 'Updated result' },
+ comments: [],
+ });
+ expect(rendered.queryByTestId('tool-card')).toBeNull();
});
it('renders an edit with computed +/− counts and the diff body', () => {
@@ -302,7 +324,7 @@ describe('ToolCallPart routing', () => {
expect(rendered.getByTestId('path-list').textContent).toBe('a.rs,b.rs');
});
- it('routes unmodeled kinds to the exchange card, with reported text as the response', () => {
+ it('keeps unmodeled tool output hidden without a registered renderer', () => {
const rendered = render(() => (
<ToolCallPart
part={toolUse({
@@ -315,8 +337,8 @@ describe('ToolCallPart routing', () => {
})}
/>
));
- expect(rendered.getByTestId('request').textContent).toBe('');
- expect(rendered.getByTestId('response').textContent).toBe('raw result');
+ expect(rendered.getByTestId('tool-card').dataset.expandable).toBe('false');
+ expect(rendered.getByTestId('body').textContent).toBe('');
});
it('routes fetch and think to the plain output card', () => {
@@ -341,139 +363,67 @@ describe('ToolCallPart Macro tools', () => {
{ name: 'ReadContent', status: 'running', ...overrides }
);
- it('renders a known Macro tool with the chat component', () => {
+ it('keeps a running Macro tool on the compact active row', () => {
const rendered = render(() => (
<ToolCallPart part={readContent()} context={context(true)} />
));
- expect(rendered.getByTestId('macro-tool').textContent).toBe('ReadContent');
- expect(rendered.getByTestId('macro-tool').dataset.complete).toBe('false');
- expect(rendered.queryByTestId('tool-card')).toBeNull();
+ expect(rendered.getByTestId('title').textContent).toBe('ReadContent');
+ expect(rendered.getAllByTestId('tool-card')).toHaveLength(1);
+ expect(rendered.getByTestId('tool-card').dataset.expandable).toBe('false');
});
- it('does not leave a call the turn cut off streaming in the chat component', () => {
+ it('marks a Macro call cut off by the turn as stopped', () => {
// The turn ended with this call still `running` in the log; it settles
// and, with no response to show, keeps the labelled card.
const rendered = render(() => (
<ToolCallPart part={readContent()} context={context(false)} />
));
- expect(rendered.queryByTestId('macro-tool')).toBeNull();
expect(rendered.getByTestId('tool-card').dataset.status).toBe('completed');
});
- it('passes the unwrapped output as the chat response once complete', () => {
+ it('keeps a stopped call labelled even when it already has renderable output', () => {
const rendered = render(() => (
<ToolCallPart
part={readContent({
- status: 'completed',
detail: {
kind: 'macro',
input: { documentId: '4a4886d8-9f4b-4f7e-a5a3-3f5c8b6c0e46' },
- output: { content: { text: 'hi' }, comments: [] },
+ output: { content: { text: 'partial' }, comments: [] },
error: null,
},
})}
+ context={context(false)}
/>
));
- expect(rendered.getByTestId('macro-tool').dataset.complete).toBe('true');
- expect(rendered.getByTestId('macro-tool').dataset.hasResponse).toBe('true');
+ expect(rendered.getByTestId('trailing').textContent).toBe('Stopped');
+ expect(rendered.queryByTestId('macro-tool')).toBeNull();
});
- it('renders the displayResults view as a dashboard', () => {
- const view = {
- title: 'This week',
- widgets: [{ type: 'md', markdown: 'hi' }],
- };
+ it('reuses the registered result renderer without an outer tool disclosure', () => {
const rendered = render(() => (
<ToolCallPart
- part={toolUse(
- {
+ part={readContent({
+ status: 'completed',
+ detail: {
kind: 'macro',
- input: { view },
- output: { message: 'The results have been displayed to the user.' },
+ input: { documentId: '4a4886d8-9f4b-4f7e-a5a3-3f5c8b6c0e46' },
+ output: { content: { text: 'hi' }, comments: [] },
error: null,
},
- { name: 'DisplayResults', status: 'completed' }
- )}
+ })}
/>
));
- expect(rendered.getByTestId('dashboard').textContent).toBe(
- JSON.stringify(view)
- );
- expect(rendered.queryByTestId('tool-card')).toBeNull();
- });
-
- it('renders a view as its arguments arrive and keeps it when no response arrives', () => {
- const displayResults = (
- input: unknown,
- status: ToolUsePart['status'] = 'running'
- ) =>
- toolUse(
- { kind: 'macro', input, output: null, error: null },
- { name: 'DisplayResults', status }
- );
- const [part, setPart] = createStore(displayResults(null));
- const rendered = render(() => (
- <ToolCallPart part={part} context={context(true)} />
- ));
-
- for (const input of [null, {}, { view: null }, { view: {} }]) {
- setPart(reconcile(displayResults(input)));
- expect(rendered.container.textContent).toBe('');
- }
-
- const view = {
- title: 'This week',
- widgets: [{ type: 'md', markdown: 'First results' }],
- };
- setPart(reconcile(displayResults({ view })));
- expect(rendered.getByTestId('dashboard').textContent).toBe(
- JSON.stringify(view)
- );
-
- const finalView = {
- title: 'All results',
- widgets: [{ type: 'md', markdown: 'Final results' }],
- };
- setPart(reconcile(displayResults({ view: finalView }, 'completed')));
- expect(rendered.getByTestId('dashboard').textContent).toBe(
- JSON.stringify(finalView)
- );
+ const richTool = rendered.getByTestId('macro-tool');
+ expect(JSON.parse(richTool.dataset.response ?? '')).toEqual({
+ content: { text: 'hi' },
+ comments: [],
+ });
+ expect(richTool.dataset.grouped).toBe('true');
+ expect(richTool.dataset.streaming).toBe('false');
expect(rendered.queryByTestId('tool-card')).toBeNull();
});
- it.each([null, {}, { view: null }, { view: { widgets: 'invalid' } }])(
- 'reports malformed completed dashboard input: %j',
- (input) => {
- const rendered = render(() => (
- <ToolCallPart
- part={toolUse(
- { kind: 'macro', input, output: null, error: null },
- { name: 'DisplayResults' }
- )}
- />
- ));
- expect(rendered.container.textContent).toContain(
- "Couldn't render dashboard"
- );
- expect(rendered.queryByTestId('dashboard')).toBeNull();
- }
- );
-
- it('keeps a failed displayResults call on a faded card', () => {
- const rendered = render(() => (
- <ToolCallPart
- part={toolUse(
- { kind: 'macro', input: { view: null }, output: null, error: null },
- { name: 'DisplayResults', status: 'failed' }
- )}
- />
- ));
- expect(rendered.getByTestId('tool-card').dataset.muted).toBe('true');
- expect(rendered.getByTestId('trailing').textContent).toBe('Failed');
- expect(rendered.queryByTestId('dashboard')).toBeNull();
- });
-
- it('keeps a Macro tool the chat has no component for on a labelled card', () => {
+ it('keeps an unknown Macro tool on a labelled card', () => {
const rendered = render(() => (
<ToolCallPart
part={toolUse(
@@ -487,18 +437,12 @@ describe('ToolCallPart Macro tools', () => {
)}
/>
));
- expect(rendered.queryByTestId('macro-tool')).toBeNull();
expect(rendered.getByTestId('title').textContent).toBe('BrandNewTool');
- expect(rendered.getByTestId('request').textContent).toContain(
- '"anything": 1'
- );
- expect(rendered.getByTestId('response').textContent).toContain(
- '"result": "ok"'
- );
+ expect(rendered.getByTestId('tool-card').dataset.expandable).toBe('false');
+ expect(rendered.getByTestId('body').textContent).toBe('');
});
- it('keeps a completed call whose output the chat cannot read on the card', () => {
- // The chat renderer would show this as failed; the call succeeded.
+ it('preserves a completed call whose output does not fit the tool schema', () => {
const rendered = render(() => (
<ToolCallPart
part={readContent({
@@ -512,9 +456,9 @@ describe('ToolCallPart Macro tools', () => {
})}
/>
));
- expect(rendered.queryByTestId('macro-tool')).toBeNull();
expect(rendered.getByTestId('tool-card').dataset.muted).toBe('false');
expect(rendered.getByTestId('trailing').textContent).toBe('');
+ expect(rendered.getByTestId('tool-card').dataset.expandable).toBe('false');
});
it('keeps a known tool whose arguments do not fit its schema on the card', () => {
@@ -530,11 +474,10 @@ describe('ToolCallPart Macro tools', () => {
})}
/>
));
- expect(rendered.queryByTestId('macro-tool')).toBeNull();
expect(rendered.getByTestId('tool-card')).not.toBeNull();
});
- it('shows a failed Macro tool with its error, faded', () => {
+ it('shows a failed Macro tool as a faded summary', () => {
const rendered = render(() => (
<ToolCallPart
part={toolUse(
@@ -548,12 +491,9 @@ describe('ToolCallPart Macro tools', () => {
)}
/>
));
- expect(rendered.queryByTestId('macro-tool')).toBeNull();
expect(rendered.getByTestId('tool-card').dataset.muted).toBe('true');
- expect(rendered.getByTestId('subtitle').textContent).toBe(
- 'permission denied'
- );
expect(rendered.getByTestId('trailing').textContent).toBe('Failed');
+ expect(rendered.getByTestId('tool-card').dataset.expandable).toBe('false');
});
});
@@ -578,10 +518,10 @@ describe('ToolCallPart user tools', () => {
const rendered = render(() => (
<ToolCallPart part={email({ kind: 'pending' })} />
));
- expect(rendered.queryByTestId('macro-tool')).toBeNull();
expect(rendered.getByTestId('title').textContent).toBe('SendEmail');
expect(rendered.getByTestId('subtitle').textContent).toBe('Q3 plan');
expect(rendered.getByTestId('trailing').textContent).toBe('Awaiting you');
+ expect(rendered.getByTestId('tool-card').dataset.expandable).toBe('true');
const body = rendered.getByTestId('body');
expect(body.textContent).toContain('Alice <[email protected]>');
expect(body.textContent).toContain('Q3 plan');
@@ -705,13 +645,12 @@ describe('ToolCallPart user tools', () => {
const rendered = render(() => (
<ToolCallPart part={email({ kind: 'failed', message: 'no inbox' })} />
));
- expect(rendered.queryByTestId('macro-tool')).toBeNull();
expect(rendered.getByTestId('tool-card').dataset.muted).toBe('true');
expect(rendered.getByTestId('body').textContent).toBe('no inbox');
expect(rendered.getByTestId('trailing').textContent).toBe('Failed');
});
- it('shows a draft the schema rejects as JSON, with the outcome still labelled', () => {
+ it('keeps a draft the schema rejects summary-only, with its outcome still labelled', () => {
const rendered = render(() => (
<ToolCallPart
part={toolUse(
@@ -724,11 +663,128 @@ describe('ToolCallPart user tools', () => {
)}
/>
));
- expect(rendered.queryByTestId('macro-tool')).toBeNull();
expect(rendered.getByTestId('trailing').textContent).toBe('Answered');
- expect(rendered.getByTestId('body').textContent).toContain(
- '"subject": "no recipients or body"'
+ expect(rendered.getByTestId('tool-card').dataset.expandable).toBe('false');
+ expect(rendered.getByTestId('body').textContent).toBe('');
+ });
+
+ it('does not add a disclosure for a failed user tool with no recognized draft', () => {
+ const rendered = render(() => (
+ <ToolCallPart
+ part={toolUse(
+ {
+ kind: 'user_tool',
+ input: { privatePayload: 'not a draft' },
+ outcome: { kind: 'failed', message: 'Failed to prepare draft' },
+ },
+ { name: 'SendEmail' }
+ )}
+ />
+ ));
+ expect(rendered.getByTestId('trailing').textContent).toBe('Failed');
+ expect(rendered.getByTestId('tool-card').dataset.expandable).toBe('false');
+ expect(rendered.getByTestId('body').textContent).toBe('');
+ });
+});
+
+describe('ToolCallPart inline results', () => {
+ it.each(['native', 'mcp'] as const)(
+ 'does not route an unrelated %s tool named DisplayResults to the dashboard',
+ (kind) => {
+ const part = toolUse({
+ kind: 'other',
+ input: { view: { widgets: [] } },
+ result: null,
+ output: null,
+ error: null,
+ acpKind: 'other',
+ });
+ part.name =
+ kind === 'mcp'
+ ? { kind, server: 'external', tool: 'DisplayResults' }
+ : { kind, name: 'DisplayResults' };
+ const rendered = render(() => <ToolCallPart part={part} />);
+ expect(rendered.queryByTestId('dashboard-view')).toBeNull();
+ expect(rendered.getByTestId('tool-card').dataset.expandable).toBe(
+ 'false'
+ );
+ }
+ );
+
+ it.each(['macro', 'other'] as const)(
+ 'renders %s DisplayResults from call arguments before any response',
+ (kind) => {
+ const input = { view: { kind: 'text', text: 'Launch checklist' } };
+ const part = toolUse(
+ kind === 'macro'
+ ? { kind, input, output: null, error: null }
+ : {
+ kind,
+ input,
+ result: null,
+ output: null,
+ error: null,
+ acpKind: 'other',
+ },
+ { name: 'DisplayResults', status: 'running' }
+ );
+ if (kind === 'other')
+ part.name = { kind: 'mcp', server: 'macro', tool: 'DisplayResults' };
+ const rendered = render(() => (
+ <ToolCallPart part={part} context={context(true)} />
+ ));
+ expect(rendered.getByTestId('dashboard-view').textContent).toBe(
+ JSON.stringify(input.view)
+ );
+ expect(rendered.queryByTestId('tool-card')).toBeNull();
+ expect(rendered.queryByTestId('macro-tool')).toBeNull();
+ }
+ );
+
+ it('updates inline results as the call arguments change', () => {
+ const [part, setPart] = createSignal(
+ toolUse(
+ {
+ kind: 'macro',
+ input: { view: { text: 'First' } },
+ output: null,
+ error: null,
+ },
+ { name: 'DisplayResults', status: 'running' }
+ )
+ );
+ const rendered = render(() => (
+ <ToolCallPart part={part()} context={context(true)} />
+ ));
+ const dashboard = rendered.getByTestId('dashboard-view');
+ setPart(
+ toolUse(
+ {
+ kind: 'macro',
+ input: { view: { text: 'Updated' } },
+ output: null,
+ error: null,
+ },
+ { name: 'DisplayResults', status: 'running' }
+ )
+ );
+ expect(rendered.getByTestId('dashboard-view')).toBe(dashboard);
+ expect(dashboard.textContent).toBe('{"text":"Updated"}');
+ });
+
+ it('passes settled missing input to dashboard validation without a tool disclosure', () => {
+ const rendered = render(() => (
+ <ToolCallPart
+ part={toolUse(
+ { kind: 'macro', input: null, output: null, error: null },
+ { name: 'DisplayResults' }
+ )}
+ />
+ ));
+ expect(rendered.getByTestId('dashboard-view').dataset.pending).toBe(
+ 'false'
);
+ expect(rendered.queryByTestId('tool-card')).toBeNull();
});
});
@@ -784,7 +840,33 @@ describe('ToolCallPart subagents', () => {
it('summarizes the result in the trailing slot', () => {
const rendered = render(() => <ToolCallPart part={subagent()} />);
expect(rendered.getAllByTestId('trailing')[0]?.textContent).toBe(
- '1 tool · 3.5s · 26k tokens'
+ '1 tool · 3.5s'
+ );
+ });
+
+ it('preserves a nested tool body while the subagent streams updated children', () => {
+ const [part, setPart] = createSignal(subagent({ result: null }));
+ const rendered = render(() => <ToolCallPart part={part()} />);
+ const terminal = rendered.getByTestId('terminal');
+ setPart(
+ subagent({
+ children: [
+ toolUse(
+ {
+ kind: 'terminal',
+ command: 'python3 -c "print(5+5)"',
+ output: '10\nFinished',
+ exitCode: 0,
+ },
+ { id: 'child', name: 'Bash' }
+ ),
+ ],
+ })
+ );
+ expect(rendered.getByTestId('terminal')).toBe(terminal);
+ expect(terminal.textContent).toBe('10\nFinished');
+ expect(rendered.getAllByTestId('trailing')[0]?.textContent).toBe(
+ '1 tool · 3.5s'
);
});
@@ -900,7 +982,7 @@ describe('ToolCallPart settling', () => {
));
expect(rendered.getByTestId('tool-card').dataset.status).toBe('completed');
expect(rendered.getByTestId('tool-card').dataset.muted).toBe('false');
- expect(rendered.getByTestId('trailing').textContent).toBe('');
+ expect(rendered.getByTestId('trailing').textContent).toBe('Stopped');
});
it('settles a call with no turn to place it in', () => {
@@ -975,3 +1057,170 @@ describe('ToolCallPart failed treatment', () => {
expect(rendered.queryByTestId('diff-changes')).toBeNull();
});
});
+
+describe('ToolCallPart result summaries', () => {
+ it.each([
+ {
+ name: 'MoveToProject',
+ input: {},
+ output: { success: false, message: 'Denied' },
+ },
+ {
+ name: 'WebFetch',
+ input: { input: 'https://status.macro.com' },
+ output: {
+ tool_use_id: 'call-1',
+ content: {
+ type: 'web_fetch_tool_result_error',
+ error_code: 'url_not_accessible',
+ },
+ },
+ },
+ {
+ name: 'WebSearch',
+ input: { input: 'launch checklist' },
+ output: {
+ tool_use_id: 'call-1',
+ content: {
+ type: 'web_search_tool_result_error',
+ error_code: 'unavailable',
+ },
+ },
+ },
+ ])(
+ 'shows a validated $name response failure even if the call completed',
+ ({ name, input, output }) => {
+ const rendered = render(() => (
+ <ToolCallPart
+ part={toolUse(
+ { kind: 'macro', input, output, error: null },
+ { name }
+ )}
+ />
+ ));
+ expect(rendered.getByTestId('trailing').textContent).toBe('Failed');
+ expect(rendered.getByTestId('tool-card').dataset.muted).toBe('true');
+ expect(rendered.queryByTestId('macro-tool')).toBeNull();
+ }
+ );
+
+ it('updates a mounted terminal body when a streamed response replaces the part', () => {
+ const [part, setPart] = createSignal(
+ toolUse(
+ {
+ kind: 'terminal',
+ command: 'bun run check',
+ output: 'Checking…',
+ exitCode: null,
+ },
+ { status: 'running' }
+ )
+ );
+ const rendered = render(() => (
+ <ToolCallPart part={part()} context={context(true)} />
+ ));
+ const body = rendered.getByTestId('terminal');
+ setPart(
+ toolUse({
+ kind: 'terminal',
+ command: 'bun run check',
+ output: 'All checks passed',
+ exitCode: 0,
+ })
+ );
+ expect(rendered.getByTestId('terminal')).toBe(body);
+ expect(body.textContent).toBe('All checks passed');
+ expect(rendered.getByTestId('tool-card').dataset.status).toBe('completed');
+ });
+
+ it('shows a reported terminal exit failure even if the harness completed the call', () => {
+ const rendered = render(() => (
+ <ToolCallPart
+ part={toolUse({
+ kind: 'terminal',
+ command: 'false',
+ output: '',
+ exitCode: 1,
+ })}
+ />
+ ));
+ expect(rendered.getByTestId('trailing').textContent).toBe(
+ 'Failed · exit 1'
+ );
+ expect(rendered.getByTestId('tool-card').dataset.muted).toBe('true');
+ expect(rendered.getByTestId('terminal')).toBeTruthy();
+ });
+
+ it('counts completed file reads and keeps a single path available in the body', () => {
+ const rendered = render(() => (
+ <ToolCallPart
+ part={toolUse({ kind: 'read', paths: ['docs/launch.md'] })}
+ />
+ ));
+ expect(rendered.getByTestId('trailing').textContent).toBe('1 file');
+ expect(rendered.getByTestId('path-list').textContent).toBe(
+ 'docs/launch.md'
+ );
+ });
+
+ it('does not present pending edit diffs as completed changes', () => {
+ const rendered = render(() => (
+ <ToolCallPart
+ part={toolUse(
+ {
+ kind: 'edit',
+ diffs: [{ path: 'a.ts', oldText: 'a', newText: 'b' }],
+ },
+ { status: 'running' }
+ )}
+ context={context(true)}
+ />
+ ));
+ expect(rendered.queryByTestId('diff-changes')).toBeNull();
+ });
+
+ it.each([0, 1, 3])(
+ 'counts %i validated results when the tool has no registered renderer',
+ (count) => {
+ const rendered = render(() => (
+ <ToolCallPart
+ part={toolUse(
+ {
+ kind: 'macro',
+ input: {},
+ output: {
+ results: Array.from({ length: count }, () => ({
+ documentId: '4a4886d8-9f4b-4f7e-a5a3-3f5c8b6c0e46',
+ name: 'Launch checklist',
+ })),
+ },
+ error: null,
+ },
+ { name: 'ListSkills' }
+ )}
+ />
+ ));
+ expect(rendered.queryByTestId('macro-tool')).toBeNull();
+ expect(rendered.getByTestId('trailing').textContent).toBe(
+ `${count} ${count === 1 ? 'result' : 'results'}`
+ );
+ }
+ );
+
+ it('does not infer a result count from an invalid Macro response', () => {
+ const rendered = render(() => (
+ <ToolCallPart
+ part={toolUse(
+ {
+ kind: 'macro',
+ input: { name: 'launch checklist' },
+ output: { results: ['a', 'b', 'c'] },
+ error: null,
+ },
+ { name: 'SearchSkills' }
+ )}
+ />
+ ));
+ expect(rendered.getByTestId('trailing').textContent).toBe('');
+ });
+});
diff --git a/apps/web/src/features/block-agent/component/parts/ToolCallPart.tsx b/apps/web/src/features/block-agent/component/parts/ToolCallPart.tsx
index 5688f55780..171d3d08a5 100644
--- a/apps/web/src/features/block-agent/component/parts/ToolCallPart.tsx
+++ b/apps/web/src/features/block-agent/component/parts/ToolCallPart.tsx
@@ -4,14 +4,16 @@
*
* The fold has already decided what every call is: a coding-harness tool by
* kind (terminal, edit, read, ...), a Macro tool by name, a user tool the
- * user finishes, or a delegated subagent. This is a pure match over that
- * closed vocabulary — nothing here reads ACP, parses raw JSON, or guesses a
- * tool from its title.
+ * user finishes, or a delegated subagent. Generic calls explicitly addressed
+ * to Macro's MCP server may also use a registered renderer, after that renderer
+ * validates the payload. External servers never select Macro UI by name alone.
*/
-import type { JSX } from 'solid-js';
-import { match } from 'ts-pattern';
+import { hasToolRenderer } from '@core/component/AI/component/tool/handler';
+import { type JSX, Match, Show, Switch } from 'solid-js';
+import { rendersOwnView } from '../../state/tool-groups';
import { settledToolStatus } from '../../ui';
+import { DisplayResultsToolCall } from './DisplayResultsToolCall';
import { EditToolCall } from './EditToolCall';
import { ExchangeToolCall } from './ExchangeToolCall';
import { MacroToolCall } from './MacroToolCall';
@@ -48,44 +50,107 @@ export function ToolCallPart(props: {
server: toolServer(props.part.name),
status: status(),
muted: failed(),
- trailing: failed() ? <span class="text-ink">Failed</span> : undefined,
+ trailing: failed()
+ ? 'Failed'
+ : (props.part.status === 'pending' || props.part.status === 'running') &&
+ status() === 'completed'
+ ? 'Stopped'
+ : undefined,
});
- return match(props.part.detail)
- .with({ kind: 'terminal' }, (detail) => (
- <TerminalToolCall detail={detail} common={common()} />
- ))
- .with({ kind: 'edit' }, (detail) => (
- <EditToolCall detail={detail} common={common()} />
- ))
- .with({ kind: 'read' }, { kind: 'delete' }, { kind: 'move' }, (detail) => (
- <PathsToolCall detail={detail} common={common()} />
- ))
- .with({ kind: 'search' }, (detail) => (
- <SearchToolCall detail={detail} common={common()} />
- ))
- .with({ kind: 'fetch' }, { kind: 'think' }, (detail) => (
- <OutputToolCall detail={detail} common={common()} />
- ))
- .with({ kind: 'other' }, (detail) => (
- <ExchangeToolCall detail={detail} common={common()} />
- ))
- .with({ kind: 'macro' }, (detail) => (
- <MacroToolCall
- detail={detail}
- common={common()}
- context={props.context}
- />
- ))
- .with({ kind: 'user_tool' }, (detail) => (
- <UserToolCall detail={detail} common={common()} context={props.context} />
- ))
- .with({ kind: 'subagent' }, (detail) => (
- <SubagentToolCall
- detail={detail}
- common={common()}
- context={props.context}
- />
- ))
- .exhaustive();
+ // Non-keyed matches preserve the disclosure when a streamed update replaces
+ // its detail object; each child receives the current detail through an accessor.
+ return (
+ <Switch>
+ <Match when={rendersOwnView(props.part)}>
+ <DisplayResultsToolCall
+ input={
+ 'input' in props.part.detail ? props.part.detail.input : undefined
+ }
+ error={
+ 'error' in props.part.detail ? props.part.detail.error : undefined
+ }
+ common={common()}
+ />
+ </Match>
+ <Match when={props.part.detail.kind === 'terminal' && props.part.detail}>
+ {(detail) => <TerminalToolCall detail={detail()} common={common()} />}
+ </Match>
+ <Match when={props.part.detail.kind === 'edit' && props.part.detail}>
+ {(detail) => <EditToolCall detail={detail()} common={common()} />}
+ </Match>
+ <Match
+ when={
+ (props.part.detail.kind === 'read' ||
+ props.part.detail.kind === 'delete' ||
+ props.part.detail.kind === 'move') &&
+ props.part.detail
+ }
+ >
+ {(detail) => <PathsToolCall detail={detail()} common={common()} />}
+ </Match>
+ <Match when={props.part.detail.kind === 'search' && props.part.detail}>
+ {(detail) => <SearchToolCall detail={detail()} common={common()} />}
+ </Match>
+ <Match
+ when={
+ (props.part.detail.kind === 'fetch' ||
+ props.part.detail.kind === 'think') &&
+ props.part.detail
+ }
+ >
+ {(detail) => <OutputToolCall detail={detail()} common={common()} />}
+ </Match>
+ <Match when={props.part.detail.kind === 'other' && props.part.detail}>
+ {(detail) => (
+ <Show
+ when={
+ props.part.name.kind === 'mcp' &&
+ props.part.name.server === 'macro' &&
+ hasToolRenderer(props.part.name.tool)
+ }
+ fallback={<ExchangeToolCall detail={detail()} common={common()} />}
+ >
+ <MacroToolCall
+ detail={{
+ kind: 'macro',
+ input: detail().input,
+ output: detail().result ?? detail().output,
+ error: detail().error,
+ }}
+ common={common()}
+ context={props.context}
+ />
+ </Show>
+ )}
+ </Match>
+ <Match when={props.part.detail.kind === 'macro' && props.part.detail}>
+ {(detail) => (
+ <MacroToolCall
+ detail={detail()}
+ common={common()}
+ context={props.context}
+ />
+ )}
+ </Match>
+ <Match when={props.part.detail.kind === 'user_tool' && props.part.detail}>
+ {(detail) => (
+ <UserToolCall
+ detail={detail()}
+ common={common()}
+ context={props.context}
+ />
+ )}
+ </Match>
+ <Match when={props.part.detail.kind === 'subagent' && props.part.detail}>
+ {(detail) => (
+ <SubagentToolCall
+ detail={detail()}
+ common={common()}
+ context={props.context}
+ />
+ )}
+ </Match>
+ </Switch>
+ );
}
diff --git a/apps/web/src/features/block-agent/component/parts/UserToolCall.tsx b/apps/web/src/features/block-agent/component/parts/UserToolCall.tsx
index 301e1c8756..3ff1231c46 100644
--- a/apps/web/src/features/block-agent/component/parts/UserToolCall.tsx
+++ b/apps/web/src/features/block-agent/component/parts/UserToolCall.tsx
@@ -11,6 +11,8 @@
*/
import { ItemPreview } from '@core/component/ItemPreview';
+import CalendarIcon from '@phosphor/calendar-blank.svg';
+import EmailIcon from '@phosphor/envelope.svg';
import type {
ToolDetail,
UserToolOutcome,
@@ -26,7 +28,15 @@ import type {
EventTimeInput,
SendEmail,
} from '@service-cognition/generated/tools/types';
-import { createMemo, For, type JSX, Match, Show, Switch } from 'solid-js';
+import {
+ createMemo,
+ For,
+ type JSX,
+ Match,
+ Show,
+ Suspense,
+ Switch,
+} from 'solid-js';
import { match } from 'ts-pattern';
import { FoldedOutput, ToolCard } from '../../ui';
import type { ToolCallCommon, ToolCallContext } from './shared';
@@ -49,9 +59,8 @@ function outcomeLabel(outcome: UserToolOutcome): string {
}
/**
- * The draft, typed by the tool's own schema, when the input fits it. A
- * draft that does not - a tool this block has no view for, or arguments the
- * schema rejects - shows as JSON instead.
+ * The draft, typed by the tool's own schema, when the input fits it.
+ * Unsupported tools and rejected arguments remain summary-only rows.
*/
function typedDraft(
common: ToolCallCommon,
@@ -83,34 +92,41 @@ export function UserToolCall(props: {
return (
<ToolCard
+ icon={
+ props.common.label === 'CreateCalendarEvent' ? (
+ <CalendarIcon class="size-4" />
+ ) : (
+ <EmailIcon class="size-4" />
+ )
+ }
title={props.common.label}
status={props.common.status}
subtitle={draft() && draftSubtitle(draft()!)}
muted={props.common.muted || failure() !== undefined}
- trailing={
- props.common.trailing ?? <OutcomeTrailing outcome={outcome()} />
- }
+ trailing={props.common.trailing ?? outcomeLabel(outcome())}
+ hasContent={draft() !== undefined}
>
- <Switch
- fallback={
- <FoldedOutput text={JSON.stringify(props.detail.input, null, 2)} />
- }
- >
- <Match when={failure()}>
- {(message) => <FoldedOutput text={message()} />}
- </Match>
- <Match when={draft()?.name === 'SendEmail' && draft()}>
- {(tool) => (
- <EmailDraft
- email={tool().data as SendEmail}
- inFlight={props.context?.inFlight ?? false}
- />
- )}
- </Match>
- <Match when={draft()?.name === 'CreateCalendarEvent' && draft()}>
- {(tool) => <EventDraft event={tool().data as CreateCalendarEvent} />}
- </Match>
- </Switch>
+ <Show when={draft()}>
+ <Switch>
+ <Match when={failure()}>
+ {(message) => <FoldedOutput text={message()} />}
+ </Match>
+ <Match when={draft()?.name === 'SendEmail' && draft()}>
+ {(tool) => (
+ <EmailDraft
+ email={tool().data as SendEmail}
+ inFlight={props.context?.inFlight ?? false}
+ />
+ )}
+ </Match>
+ <Match when={draft()?.name === 'CreateCalendarEvent' && draft()}>
+ {(tool) => (
+ <EventDraft event={tool().data as CreateCalendarEvent} />
+ )}
+ </Match>
+ </Switch>
+ <OutcomeLink outcome={outcome()} />
+ </Show>
</ToolCard>
);
}
@@ -130,19 +146,20 @@ function draftSubtitle(
* The outcome, and for an email that went somewhere, a link to where: the
* thread it was sent into, or the thread its draft belongs to.
*/
-function OutcomeTrailing(props: { outcome: UserToolOutcome }): JSX.Element {
+function OutcomeLink(props: { outcome: UserToolOutcome }): JSX.Element {
const threadId = () =>
match(props.outcome)
.with({ kind: 'sent' }, (sent) => sent.threadId)
.with({ kind: 'draft' }, (draft) => draft.threadId ?? undefined)
.otherwise(() => undefined);
return (
- <span class="flex items-center gap-2">
- <span class="text-ink">{outcomeLabel(props.outcome)}</span>
- <Show when={threadId()}>
- {(id) => <ItemPreview id={id()} type="email" class="ring-0" />}
- </Show>
- </span>
+ <Show when={threadId()}>
+ {(id) => (
+ <Suspense>
+ <ItemPreview id={id()} type="email" class="mt-2 ring-0" />
+ </Suspense>
+ )}
+ </Show>
);
}
diff --git a/apps/web/src/features/block-agent/debug/Gallery.tsx b/apps/web/src/features/block-agent/debug/Gallery.tsx
index 8b0be09eb5..1ff47b3db2 100644
--- a/apps/web/src/features/block-agent/debug/Gallery.tsx
+++ b/apps/web/src/features/block-agent/debug/Gallery.tsx
@@ -8,9 +8,14 @@ import { StaticMarkdownContext } from '@core/component/LexicalMarkdown/component
import { MagicChipView } from '@core/component/LexicalMarkdown/component/decorator/MagicChip/MagicChipView';
import type { MagicChipPresentation } from '@core/component/LexicalMarkdown/component/decorator/MagicChip/presentation';
import { useUserId } from '@core/context/user';
+import FileText from '@phosphor/file-text.svg';
+import MagnifyingGlass from '@phosphor/magnifying-glass.svg';
+import PencilSimple from '@phosphor/pencil-simple.svg';
+import Terminal from '@phosphor/terminal.svg';
import type {
ElicitationSchema,
FoldedMessage,
+ MessagePart,
ModelOption,
PendingElicitation,
ToolStatus,
@@ -193,6 +198,237 @@ const FIXTURE_DIFF = {
'fn fold(log: &[Frame]) -> Vec<Message> {\n let mut machine = FoldMachine::default();\n for frame in log {\n machine.push(frame);\n }\n machine.finish()\n}\n',
};
+const TOOL_REPLAY_PARTS: MessagePart[] = [
+ {
+ kind: 'tool_use',
+ id: 'replay-search',
+ name: { kind: 'mcp', server: 'macro', tool: 'SearchSkills' },
+ status: 'completed',
+ detail: {
+ kind: 'macro',
+ input: { name: 'launch checklist' },
+ output: {
+ results: [
+ {
+ documentId: '4a4886d8-9f4b-4f7e-a5a3-3f5c8b6c0e46',
+ name: 'Launch checklist',
+ updatedAt: null,
+ },
+ {
+ documentId: '4a4886d8-9f4b-4f7e-a5a3-3f5c8b6c0e47',
+ name: 'Launch timeline',
+ updatedAt: null,
+ },
+ {
+ documentId: '4a4886d8-9f4b-4f7e-a5a3-3f5c8b6c0e48',
+ name: 'Release notes',
+ updatedAt: null,
+ },
+ ],
+ },
+ error: null,
+ },
+ },
+ {
+ kind: 'tool_use',
+ id: 'replay-read',
+ name: { kind: 'native', name: 'Read' },
+ status: 'completed',
+ detail: { kind: 'read', paths: ['Launch checklist'] },
+ },
+ {
+ kind: 'tool_use',
+ id: 'replay-fetch',
+ name: { kind: 'native', name: 'Fetch' },
+ status: 'failed',
+ detail: {
+ kind: 'fetch',
+ output: 'Could not reach status.macro.com/api: connection refused.',
+ },
+ },
+ {
+ kind: 'tool_use',
+ id: 'replay-edit',
+ name: { kind: 'native', name: 'Edit' },
+ status: 'completed',
+ detail: {
+ kind: 'edit',
+ diffs: [{ ...FIXTURE_DIFF, path: 'docs/launch.md' }],
+ },
+ },
+ {
+ kind: 'tool_use',
+ id: 'replay-agent',
+ name: { kind: 'native', name: 'Agent' },
+ status: 'completed',
+ detail: {
+ kind: 'subagent',
+ title: 'Verify changes',
+ description: 'Verify the launch checklist',
+ agentType: 'subagent',
+ prompt: 'Verify changes to docs/launch.md',
+ background: false,
+ children: [],
+ result: {
+ text: 'The launch checklist is consistent.',
+ error: null,
+ agentId: 'replay-review',
+ model: null,
+ durationMs: 3485,
+ tokens: null,
+ toolUses: 1,
+ stats: null,
+ },
+ },
+ },
+ {
+ kind: 'tool_use',
+ id: 'replay-shell',
+ name: { kind: 'native', name: 'Shell' },
+ status: 'completed',
+ detail: {
+ kind: 'terminal',
+ command: 'bun run check',
+ output: 'All checks passed.',
+ exitCode: 0,
+ },
+ },
+];
+
+/** Exercises the production message renderer with both paced and batched calls. */
+function ToolReplayDemo() {
+ const [count, setCount] = createSignal(TOOL_REPLAY_PARTS.length);
+ const [inFlight, setInFlight] = createSignal(false);
+ let timer: ReturnType<typeof setInterval> | undefined;
+ const finish = () => {
+ clearInterval(timer);
+ timer = undefined;
+ setInFlight(false);
+ };
+ const replay = (interval: number) => {
+ finish();
+ setCount(1);
+ setInFlight(true);
+ timer = setInterval(() => {
+ if (count() === TOOL_REPLAY_PARTS.length) finish();
+ else setCount((value) => value + 1);
+ }, interval);
+ };
+ onCleanup(() => clearInterval(timer));
+ const message = (): FoldedMessage => ({
+ agentSessionId: 'tool-replay',
+ requestId: null,
+ pending: false,
+ turn: 0,
+ author: { kind: 'agent' },
+ stop: inFlight() ? null : { kind: 'end_turn' },
+ parts: TOOL_REPLAY_PARTS.slice(0, count()).map((part, index) =>
+ part.kind === 'tool_use' && inFlight() && index === count() - 1
+ ? { ...part, status: 'running' }
+ : part
+ ),
+ });
+ return (
+ <div class="flex flex-col gap-4" data-testid="tool-replay">
+ <div class="flex flex-wrap gap-3 text-xs text-ink-muted">
+ <button
+ type="button"
+ class="rounded border border-edge-muted px-2 py-1"
+ onClick={() => replay(1000)}
+ >
+ Replay tool calls
+ </button>
+ <button
+ type="button"
+ class="rounded border border-edge-muted px-2 py-1"
+ onClick={() => replay(80)}
+ >
+ Replay fast batch
+ </button>
+ <button
+ type="button"
+ class="rounded border border-edge-muted px-2 py-1 disabled:opacity-40"
+ disabled={!inFlight()}
+ onClick={finish}
+ >
+ Finish tool calls
+ </button>
+ </div>
+ <Message message={message()} inFlight={inFlight()} />
+ </div>
+ );
+}
+
+/** A generated view stays visible between collapsed runs, even before a result. */
+function DisplayResultsDemo() {
+ const [pending, setPending] = createSignal(false);
+ const message = (): FoldedMessage => ({
+ agentSessionId: 'display-results-demo',
+ requestId: null,
+ pending: false,
+ turn: 0,
+ author: { kind: 'agent' },
+ stop: pending() ? null : { kind: 'end_turn' },
+ parts: [
+ ...TOOL_REPLAY_PARTS.slice(0, 2),
+ {
+ kind: 'tool_use',
+ id: 'display-results-demo',
+ name: { kind: 'mcp', server: 'macro', tool: 'DisplayResults' },
+ status: pending() ? 'running' : 'completed',
+ detail: {
+ kind: 'macro',
+ input: {
+ view: {
+ title: 'Launch overview',
+ widgets: [
+ {
+ type: 'md',
+ markdown:
+ 'The checklist is ready. **Two steps remain before launch.**',
+ },
+ {
+ type: 'timeline',
+ events: [
+ {
+ time: 'Today',
+ title: 'Review launch checklist',
+ description:
+ 'Confirm the release notes and rollout plan.',
+ },
+ {
+ time: 'Tomorrow',
+ title: 'Launch',
+ description: 'Publish the release after checks pass.',
+ future: true,
+ },
+ ],
+ },
+ ],
+ },
+ },
+ output: null,
+ error: null,
+ },
+ },
+ ...(pending() ? [] : TOOL_REPLAY_PARTS.slice(4)),
+ ],
+ });
+ return (
+ <div class="flex flex-col gap-3" data-testid="display-results-demo">
+ <label class="flex items-center gap-2 text-xs text-ink-muted">
+ <input
+ type="checkbox"
+ checked={pending()}
+ onChange={(event) => setPending(event.currentTarget.checked)}
+ />
+ DisplayResults in progress
+ </label>
+ <Message message={message()} inFlight={pending()} />
+ </div>
+ );
+}
+
const FIXTURE_MESSAGE: FoldedMessage = {
agentSessionId: 'demo',
requestId: null,
@@ -306,8 +542,8 @@ const FIXTURE_MESSAGE: FoldedMessage = {
error: null,
},
},
- // An MCP call the fold has no model for - a Cursor session reaching
- // Macro's server, whose exchange is the request and response JSON.
+ // A Macro MCP call whose payload does not fit the registered renderer:
+ // keep its summary visible without exposing the raw exchange.
{
kind: 'tool_use',
id: 'demo-mcp-macro',
@@ -732,6 +968,13 @@ export default function AgentUiGallery() {
<StaticMarkdownContext>
<div class="size-full overflow-auto">
<div class="mx-auto flex max-w-3xl flex-col gap-8 px-6 py-8">
+ <Item label="Tool calls (live replay)">
+ <ToolReplayDemo />
+ </Item>
+
+ <Item label="DisplayResults (inline between groups)">
+ <DisplayResultsDemo />
+ </Item>
<Item label="ElicitationForm (live validation)">
<ElicitationFormDemo />
</Item>
@@ -823,57 +1066,59 @@ export default function AgentUiGallery() {
<Item label="ToolCard">
<ToolCard
- title="Bash"
+ title="Shell"
+ icon={<Terminal />}
subtitle="cargo test -p agent_fold"
status={status()}
/>
<ToolCard
title="Read"
+ icon={<FileText />}
subtitle="crates/agent_fold/src/domain/fold.rs"
args={{ limit: '200' }}
status="completed"
/>
<ToolCard
title="Edit"
+ icon={<PencilSimple />}
subtitle={FIXTURE_DIFF.path}
trailing={<DiffChanges additions={4} deletions={3} />}
status="completed"
- defaultOpen
>
<PierreDiff diffs={[FIXTURE_DIFF]} />
</ToolCard>
</Item>
<Item label="ToolGroup (active / settled)">
- <ToolGroup
- count={3}
- active={pulse()}
- latest={{ label: 'Bash', detail: 'cargo test -p agent_fold' }}
- >
+ <ToolGroup count={3} active={pulse()}>
<ToolCard
title="Read"
+ icon={<FileText />}
subtitle="crates/agent_fold/src/domain/fold.rs"
status="completed"
/>
<ToolCard
title="Edit"
+ icon={<PencilSimple />}
subtitle={FIXTURE_DIFF.path}
status="completed"
/>
<ToolCard
- title="Bash"
+ title="Shell"
+ icon={<Terminal />}
subtitle="cargo test -p agent_fold"
status={pulse() ? 'running' : 'completed'}
/>
</ToolGroup>
- <ToolGroup
- count={2}
- active={false}
- latest={{ label: 'ReadContent' }}
- defaultOpen
- >
- <ToolCard title="NameSearch" subtitle="fold" status="completed" />
- <ToolCard title="ReadContent" status="completed" />
+ <ToolGroup count={2} active={false} defaultOpen>
+ <ToolCard
+ title="Search"
+ icon={<MagnifyingGlass />}
+ subtitle="fold"
+ status="completed"
+ trailing="3 results"
+ />
+ <ToolCard title="Read" icon={<FileText />} status="completed" />
</ToolGroup>
</Item>
diff --git a/apps/web/src/features/block-agent/state/tool-groups.test.ts b/apps/web/src/features/block-agent/state/tool-groups.test.ts
index 305a30cd66..c413651741 100644
--- a/apps/web/src/features/block-agent/state/tool-groups.test.ts
+++ b/apps/web/src/features/block-agent/state/tool-groups.test.ts
@@ -1,14 +1,21 @@
-import type { MessagePart } from '@service-agent-fold/generated/types';
+import type {
+ MessagePart,
+ ToolDetail,
+ ToolName,
+} from '@service-agent-fold/generated/types';
import { describe, expect, it } from 'vitest';
import { rendersOwnView, segmentParts } from './tool-groups';
const text = (): MessagePart => ({ kind: 'text', text: 'hi' });
-const tool = (): MessagePart => ({
+const tool = (
+ overrides?: Partial<Extract<MessagePart, { kind: 'tool_use' }>>
+): MessagePart => ({
kind: 'tool_use',
id: 'call',
name: { kind: 'native', name: 'Read' },
status: 'completed',
detail: { kind: 'read', paths: ['a.rs'] },
+ ...overrides,
});
const thought = (): MessagePart => ({ kind: 'thought', text: 'thinking...' });
/**
@@ -70,6 +77,59 @@ describe('segmentParts', () => {
]);
});
+ describe.each([
+ {
+ label: 'native',
+ name: { kind: 'native', name: 'DisplayResults' } satisfies ToolName,
+ },
+ {
+ label: 'MCP',
+ name: {
+ kind: 'mcp',
+ server: 'macro',
+ tool: 'DisplayResults',
+ } satisfies ToolName,
+ },
+ ])('DisplayResults called through $label', ({ name }) => {
+ it.each(['pending', 'running', 'completed'] as const)(
+ 'breaks tool groups before and after a %s call',
+ (status) => {
+ const details: ToolDetail[] = [
+ { kind: 'macro', input: null, output: null, error: null },
+ {
+ kind: 'other',
+ acpKind: 'other',
+ input: null,
+ output: null,
+ result: null,
+ error: null,
+ },
+ ];
+ for (const detail of details) {
+ if (name.kind === 'native' && detail.kind === 'other') continue;
+ const display = tool({ name, status, detail });
+ expect(
+ segmentParts([tool(), tool(), display, tool(), tool()])
+ ).toEqual([
+ { kind: 'tools', start: 0, end: 2 },
+ { kind: 'part', start: 2, end: 3 },
+ { kind: 'tools', start: 3, end: 5 },
+ ]);
+ }
+ }
+ );
+ });
+
+ it('keeps adjacent thoughts in their own runs around inline results', () => {
+ expect(
+ segmentParts([tool(), thought(), displayResults(), thought(), tool()])
+ ).toEqual([
+ { kind: 'tools', start: 0, end: 2 },
+ { kind: 'part', start: 2, end: 3 },
+ { kind: 'tools', start: 3, end: 5 },
+ ]);
+ });
+
it('groups a run that closes the message', () => {
expect(segmentParts([text(), tool(), tool()])).toEqual([
{ kind: 'part', start: 0, end: 1 },
@@ -98,13 +158,20 @@ describe('segmentParts', () => {
]);
});
- it('leaves a trailing thought out of a tool run', () => {
+ it('leaves a trailing thought out of a run that closes the message', () => {
expect(segmentParts([thought(), tool(), thought()])).toEqual([
{ kind: 'tools', start: 0, end: 2 },
{ kind: 'part', start: 2, end: 3 },
]);
});
+ it('keeps a trailing thought in a run that prose follows', () => {
+ expect(segmentParts([tool(), tool(), thought(), text()])).toEqual([
+ { kind: 'tools', start: 0, end: 3 },
+ { kind: 'part', start: 3, end: 4 },
+ ]);
+ });
+
it('leaves a thought after a single tool as its own part', () => {
expect(segmentParts([tool(), thought()])).toEqual([
{ kind: 'part', start: 0, end: 1 },
@@ -163,18 +230,35 @@ describe('segmentParts', () => {
]);
});
- it('keeps the last thought and the dashboard visible after grouped tools', () => {
+ it('keeps a thought before the dashboard in the preceding tool group', () => {
expect(
segmentParts([thought(), tool(), thought(), displayResults()])
).toEqual([
- { kind: 'tools', start: 0, end: 2 },
- { kind: 'part', start: 2, end: 3 },
+ { kind: 'tools', start: 0, end: 3 },
{ kind: 'part', start: 3, end: 4 },
]);
});
});
describe('rendersOwnView', () => {
+ it('does not treat a same-named external MCP tool as a dashboard', () => {
+ const part = tool({
+ name: { kind: 'mcp', server: 'external', tool: 'DisplayResults' },
+ detail: {
+ kind: 'other',
+ acpKind: 'other',
+ input: { view: { widgets: [] } },
+ output: null,
+ result: null,
+ error: null,
+ },
+ });
+ expect(rendersOwnView(part)).toBe(false);
+ expect(segmentParts([tool(), part, tool()])).toEqual([
+ { kind: 'tools', start: 0, end: 3 },
+ ]);
+ });
+
it('is true for a Macro displayResults call', () => {
expect(rendersOwnView(displayResults())).toBe(true);
});
diff --git a/apps/web/src/features/block-agent/state/tool-groups.ts b/apps/web/src/features/block-agent/state/tool-groups.ts
index 066ead2750..80448f9e90 100644
--- a/apps/web/src/features/block-agent/state/tool-groups.ts
+++ b/apps/web/src/features/block-agent/state/tool-groups.ts
@@ -3,11 +3,14 @@
* tool calls and thinking blocks reads as one collapsed row (`ui/ToolGroup`),
* everything else as itself. A lone call stays a card of its own — a group of
* one would hide the call behind a count that says nothing the card did not.
+ * DisplayResults is inline answer content and always breaks the run, including
+ * while its arguments are still arriving.
*
- * A thought at the tail of a run stays out of the group. That row is the
- * current (or last) reasoning, and burying it in "Called N tools" is what
- * made a live Cursor turn look finished — or, once expanded, like every
- * earlier thought was still happening.
+ * A thought at the tail of a run stays out of the group only when the run
+ * closes the message: that row is the current (or last) reasoning, and
+ * burying it in "Called N tools" is what made a live Cursor turn look
+ * finished. Mid-message, a trailing thought belongs to its run — prose
+ * follows it, so nothing live is being hidden.
*
* Segments are half-open index ranges into the parts array, so a grouped call
* keeps its position for the tool render context.
@@ -39,7 +42,13 @@ const SELF_RENDERING_TOOLS: ReadonlySet<string> = new Set(['DisplayResults']);
* them, and the chat component library is what renders them.
*/
export function rendersOwnView(part: MessagePart | undefined): boolean {
- if (part?.kind !== 'tool_use' || part.detail.kind !== 'macro') return false;
+ if (part?.kind !== 'tool_use') return false;
+ const macroTool =
+ part.detail.kind === 'macro' ||
+ (part.detail.kind === 'other' &&
+ part.name.kind === 'mcp' &&
+ part.name.server === 'macro');
+ if (!macroTool) return false;
// The tool's own name, without the MCP server namespace the fold already
// separated out (mirrors `toolLabel` in `component/parts/shared.ts`).
const name = part.name.kind === 'mcp' ? part.name.tool : part.name.name;
@@ -61,7 +70,11 @@ export function segmentParts(parts: readonly MessagePart[]): PartSegment[] {
let end = start + 1;
if (isGroupable(parts[start])) {
while (isGroupable(parts[end])) end += 1;
- if (end - start >= 2 && parts[end - 1]?.kind === 'thought') {
+ if (
+ end - start >= 2 &&
+ end === parts.length &&
+ parts[end - 1]?.kind === 'thought'
+ ) {
end -= 1;
}
}
diff --git a/apps/web/src/features/block-agent/ui/FoldedExchange.test.tsx b/apps/web/src/features/block-agent/ui/FoldedExchange.test.tsx
deleted file mode 100644
index 13edf2cfc3..0000000000
--- a/apps/web/src/features/block-agent/ui/FoldedExchange.test.tsx
+++ /dev/null
@@ -1,127 +0,0 @@
-/** @vitest-environment jsdom */
-
-import { cleanup, render, waitFor } from '@solidjs/testing-library';
-import { afterEach, describe, expect, it, vi } from 'vitest';
-import { exchangeText, FoldedExchange } from './FoldedExchange';
-
-vi.mock('@phosphor/copy.svg', () => ({ default: () => <svg /> }));
-vi.mock('@phosphor/check.svg', () => ({ default: () => <svg /> }));
-
-afterEach(cleanup);
-
-const section = (view: ReturnType<typeof render>, label: string) =>
- view.container.querySelector<HTMLElement>(
- `[data-exchange-section="${label}"]`
- );
-
-describe('FoldedExchange', () => {
- it('shows the request and a JSON response as labelled, pretty-printed sections', () => {
- const view = render(() => (
- <FoldedExchange
- request={{ documentId: 'doc-1', limit: 5 }}
- response={{ content: { text: 'Q3 plan' }, ok: true, count: null }}
- />
- ));
- const request = section(view, 'request');
- expect(request?.textContent).toContain('Request');
- expect(request?.querySelector('pre')?.textContent).toBe(
- JSON.stringify({ documentId: 'doc-1', limit: 5 }, null, 2)
- );
- const response = section(view, 'response');
- expect(response?.querySelector('pre')?.textContent).toBe(
- JSON.stringify(
- { content: { text: 'Q3 plan' }, ok: true, count: null },
- null,
- 2
- )
- );
- expect(section(view, 'error')).toBeNull();
- });
-
- it('lights JSON by token kind', () => {
- const view = render(() => (
- <FoldedExchange request={{ name: 'x', n: 1, on: true, none: null }} />
- ));
- const pre = section(view, 'request')?.querySelector('pre');
- const classes = (selector: string) =>
- [...(pre?.querySelectorAll(selector) ?? [])].map((el) => el.textContent);
- expect(classes('.text-cyan')).toEqual(['"name"', '"n"', '"on"', '"none"']);
- expect(classes('.text-green')).toEqual(['"x"']);
- expect(classes('.text-orange')).toEqual(['1', 'true', 'null']);
- });
-
- it('shows a string response as its text, unquoted and unlit', () => {
- const view = render(() => (
- <FoldedExchange response="Launching skill: hexagonal-architecture" />
- ));
- const pre = section(view, 'response')?.querySelector('pre');
- expect(pre?.textContent).toBe('Launching skill: hexagonal-architecture');
- expect(pre?.querySelector('span')).toBeNull();
- });
-
- it('falls back to reported text when there is no structured response', () => {
- const view = render(() => (
- <FoldedExchange responseText="1 match in src/a.rs" />
- ));
- expect(section(view, 'response')?.querySelector('pre')?.textContent).toBe(
- '1 match in src/a.rs'
- );
- expect(section(view, 'request')).toBeNull();
- });
-
- it('shows nothing for slots the call did not report', () => {
- const view = render(() => (
- <FoldedExchange request={null} response={null} responseText={null} />
- ));
- expect(view.container.querySelectorAll('section')).toHaveLength(0);
- });
-
- it('shows an error in its own section, read as a failure', () => {
- const view = render(() => (
- <FoldedExchange request={{}} error="permission denied" />
- ));
- const error = section(view, 'error');
- expect(error?.querySelector('pre')?.textContent).toBe('permission denied');
- expect(
- error?.querySelector('pre')?.classList.contains('text-failure')
- ).toBe(true);
- // A tool that takes nothing still made a request.
- expect(section(view, 'request')?.querySelector('pre')?.textContent).toBe(
- '{}'
- );
- });
-
- it('copies a section whole', async () => {
- const writeText = vi.fn(() => Promise.resolve());
- Object.defineProperty(navigator, 'clipboard', {
- value: { writeText },
- configurable: true,
- });
- const view = render(() => (
- <FoldedExchange response={{ answer: 42, nested: { deep: [1, 2] } }} />
- ));
- view.getByRole('button', { name: 'Copy response' }).click();
- expect(writeText).toHaveBeenCalledWith(
- JSON.stringify({ answer: 42, nested: { deep: [1, 2] } }, null, 2)
- );
- // The button says so for a moment, then offers to copy again.
- await waitFor(() =>
- expect(view.getByRole('button', { name: 'Copied' })).toBeTruthy()
- );
- await waitFor(
- () =>
- expect(
- view.getByRole('button', { name: 'Copy response' })
- ).toBeTruthy(),
- { timeout: 3000 }
- );
- });
-});
-
-describe('exchangeText', () => {
- it('pretty-prints JSON and leaves strings alone', () => {
- expect(exchangeText({ a: 1 })).toBe('{\n "a": 1\n}');
- expect(exchangeText('plain')).toBe('plain');
- expect(exchangeText([1, 'two'])).toBe('[\n 1,\n "two"\n]');
- });
-});
diff --git a/apps/web/src/features/block-agent/ui/FoldedExchange.tsx b/apps/web/src/features/block-agent/ui/FoldedExchange.tsx
deleted file mode 100644
index 04a7231de5..0000000000
--- a/apps/web/src/features/block-agent/ui/FoldedExchange.tsx
+++ /dev/null
@@ -1,198 +0,0 @@
-/**
- * The exchange a tool call was: the request the agent made and the response
- * it got, each labelled, as JSON lit the way the code gallery lights its
- * snippets, with a copy button per section. The body for a call the fold has
- * no special rendering for - a tool on an MCP server, a harness tool this
- * block does not model - where the chat block would show raw JSON.
- */
-
-import { jsonLanguage } from '@codemirror/lang-json';
-import { highlightCode, tagHighlighter, tags } from '@lezer/highlight';
-import Check from '@phosphor/check.svg';
-import Copy from '@phosphor/copy.svg';
-import { Button } from '@ui';
-import {
- createMemo,
- createSignal,
- For,
- type JSX,
- onCleanup,
- Show,
-} from 'solid-js';
-
-export interface FoldedExchangeProps {
- /** The tool's arguments; `null` or `undefined` when the call reported none. */
- request?: unknown;
- /** The tool's result, when it reported one as JSON. */
- response?: unknown;
- /** The text the tool reported, for a call whose result is not JSON. */
- responseText?: string | null;
- /** Why the call failed, when it did. */
- error?: string | null;
-}
-
-/**
- * Above this many characters a payload is shown plain: lighting it would
- * mean a span per token of something nobody reads token by token.
- */
-const HIGHLIGHT_LIMIT = 100_000;
-
-type Token = { text: string; class: string };
-
-const highlighter = tagHighlighter([
- { tag: tags.propertyName, class: 'text-cyan' },
- { tag: tags.string, class: 'text-green' },
- { tag: [tags.number, tags.bool, tags.null], class: 'text-orange' },
- {
- tag: [tags.punctuation, tags.bracket, tags.separator],
- class: 'text-ink-extra-muted',
- },
-]);
-
-/** The text split into lines of lit tokens, or plain lines past the limit. */
-function tokenizeJson(code: string): Token[][] {
- if (code.length > HIGHLIGHT_LIMIT) {
- return code.split('\n').map((line) => [{ text: line, class: '' }]);
- }
- const lines: Token[][] = [[]];
- highlightCode(
- code,
- jsonLanguage.parser.parse(code),
- highlighter,
- (text, classes) => lines[lines.length - 1]!.push({ text, class: classes }),
- () => lines.push([])
- );
- return lines;
-}
-
-/**
- * A payload as the text to show and copy: pretty-printed JSON, or - for a
- * result that is one string, which is how a tool reporting prose arrives -
- * the string itself.
- */
-export function exchangeText(value: unknown): string {
- return typeof value === 'string' ? value : JSON.stringify(value, null, 2);
-}
-
-/** Whether a payload slot carries anything to show. */
-function present(value: unknown): boolean {
- return value !== undefined && value !== null;
-}
-
-export function FoldedExchange(props: FoldedExchangeProps): JSX.Element {
- const responseText = () =>
- present(props.response)
- ? exchangeText(props.response)
- : (props.responseText ?? undefined);
- return (
- <div class="flex flex-col gap-2">
- <Show when={present(props.request)}>
- <Section
- label="Request"
- text={exchangeText(props.request)}
- json={typeof props.request !== 'string'}
- />
- </Show>
- <Show when={responseText()}>
- {(text) => (
- <Section
- label="Response"
- text={text()}
- json={present(props.response) && typeof props.response !== 'string'}
- />
- )}
- </Show>
- <Show when={props.error}>
- {(error) => <Section label="Error" text={error()} failed />}
- </Show>
- </div>
- );
-}
-
-function Section(props: {
- label: string;
- text: string;
- /** Light the text as JSON; plain otherwise. */
- json?: boolean;
- /** Read as a failure. */
- failed?: boolean;
-}): JSX.Element {
- const lines = createMemo(() => (props.json ? tokenizeJson(props.text) : []));
- return (
- <section
- class="flex min-w-0 flex-col gap-1"
- aria-label={props.label}
- data-exchange-section={props.label.toLowerCase()}
- >
- <div class="flex items-center justify-between gap-2">
- <span class="text-[10px] font-medium tracking-wide text-ink-extra-muted uppercase">
- {props.label}
- </span>
- <CopyButton
- text={props.text}
- label={`Copy ${props.label.toLowerCase()}`}
- />
- </div>
- <pre
- class="max-h-96 overflow-auto rounded bg-surface p-2 font-mono text-xs whitespace-pre-wrap wrap-break-word"
- classList={{
- 'text-failure': props.failed,
- 'text-ink-muted': !props.failed,
- }}
- >
- <Show when={props.json} fallback={props.text}>
- <For each={lines()}>
- {(tokens, index) => (
- <>
- <Show when={index() > 0}>{'\n'}</Show>
- <For each={tokens}>
- {(token) => (
- <span class={token.class || undefined}>{token.text}</span>
- )}
- </For>
- </>
- )}
- </For>
- </Show>
- </pre>
- </section>
- );
-}
-
-function CopyButton(props: { text: string; label: string }): JSX.Element {
- const [copied, setCopied] = createSignal(false);
- let timer: ReturnType<typeof setTimeout> | undefined;
- onCleanup(() => clearTimeout(timer));
-
- const copy = async () => {
- try {
- await navigator.clipboard.writeText(props.text);
- } catch (error) {
- console.error('Failed to copy to clipboard', error);
- return;
- }
- setCopied(true);
- clearTimeout(timer);
- timer = setTimeout(() => setCopied(false), 2000);
- };
-
- return (
- <Button
- type="button"
- variant="ghost"
- size="icon-xs"
- noTouchResize
- class="shrink-0 text-ink-extra-muted hover:text-ink-muted"
- label={copied() ? 'Copied' : props.label}
- onMouseDown={(event) => event.preventDefault()}
- onClick={(event) => {
- event.stopPropagation();
- void copy();
- }}
- >
- <Show when={copied()} fallback={<Copy />}>
- <Check class="text-success" />
- </Show>
- </Button>
- );
-}
diff --git a/apps/web/src/features/block-agent/ui/Thought.tsx b/apps/web/src/features/block-agent/ui/Thought.tsx
index a1efa2d567..220da45984 100644
--- a/apps/web/src/features/block-agent/ui/Thought.tsx
+++ b/apps/web/src/features/block-agent/ui/Thought.tsx
@@ -25,11 +25,12 @@ export function Thought(props: ThoughtProps) {
<div class="relative text-xs leading-5 text-ink-extra-muted">
<button
type="button"
+ aria-expanded={expanded()}
class="flex min-h-7 items-center gap-1 py-1 text-left text-ink-extra-muted hover:text-ink-muted"
onClick={() => setExpanded((prev) => !prev)}
>
<CaretRight
- class="size-4 shrink-0 transition-transform motion-reduce:transition-none"
+ class="size-4 shrink-0"
classList={{ 'rotate-90': expanded() }}
/>
<TextShimmer
diff --git a/apps/web/src/features/block-agent/ui/ToolCard.test.tsx b/apps/web/src/features/block-agent/ui/ToolCard.test.tsx
index 4b4ffed1f3..05fa7195c5 100644
--- a/apps/web/src/features/block-agent/ui/ToolCard.test.tsx
+++ b/apps/web/src/features/block-agent/ui/ToolCard.test.tsx
@@ -10,6 +10,34 @@ vi.mock('@phosphor/caret-right.svg', () => ({ default: () => <svg /> }));
afterEach(cleanup);
describe('ToolCard', () => {
+ it('shows a result summary and only shimmers while the tool is active', async () => {
+ const [status, setStatus] = createSignal<
+ 'running' | 'completed' | 'failed'
+ >('running');
+ const view = render(() => (
+ <ToolCard
+ title="Search"
+ status={status()}
+ icon={<svg data-testid="search-icon" />}
+ >
+ Search results
+ </ToolCard>
+ ));
+ expect(view.getByTestId('search-icon')).toBeTruthy();
+ expect(view.queryByText('Succeeded')).toBeNull();
+ expect(view.container.querySelector('.magic-chip-shimmer')).toBeTruthy();
+ setStatus('completed');
+ expect(view.getByText('Succeeded')).toBeTruthy();
+ await waitFor(() =>
+ expect(view.container.querySelector('.magic-chip-shimmer')).toBeNull()
+ );
+ setStatus('failed');
+ expect(view.getByText('Failed')).toBeTruthy();
+ expect(view.getByRole('button').getAttribute('aria-expanded')).toBe(
+ 'false'
+ );
+ });
+
it('constructs expensive content only on expansion and disposes it on close', async () => {
const mounted = vi.fn();
const disposed = vi.fn();
diff --git a/apps/web/src/features/block-agent/ui/ToolCard.tsx b/apps/web/src/features/block-agent/ui/ToolCard.tsx
index 621984225c..41a26ab0a1 100644
--- a/apps/web/src/features/block-agent/ui/ToolCard.tsx
+++ b/apps/web/src/features/block-agent/ui/ToolCard.tsx
@@ -1,6 +1,5 @@
/**
- * The universal collapsible tool card: one row per tool call, with an optional
- * expandable body.
+ * A bare tool row with an icon, a compact result, and lazy result disclosure.
*
* Ported from opencode's
* `packages/session-ui/src/v2/components/basic-tool-v2.tsx`
@@ -10,15 +9,18 @@
import { Collapsible } from '@kobalte/core/collapsible';
import CaretRight from '@phosphor/caret-right.svg';
+import Wrench from '@phosphor/wrench.svg';
+import { Tooltip } from '@ui/components/Tooltip';
import { createSignal, For, type JSX, Show } from 'solid-js';
import { TextShimmer } from './TextShimmer';
import { isToolActive, type ToolStatus } from './types';
export interface ToolCardProps {
+ icon?: JSX.Element;
title: JSX.Element | string;
/** Mono, truncated detail next to the title (a path, a command, ...). */
subtitle?: string;
- /** Small `key=value` chips after the subtitle. */
+ /** Compact `key=value` details after the subtitle. */
args?: Record<string, string>;
/** Right-aligned slot before the chevron (status text, counts, ...). */
trailing?: JSX.Element;
@@ -35,9 +37,6 @@ export interface ToolCardProps {
children?: JSX.Element;
}
-const ROW_CLASS =
- 'flex min-h-9 w-full items-center gap-2 px-3 py-2 text-left text-xs leading-5';
-
export function ToolCard(props: ToolCardProps) {
const active = () => isToolActive(props.status);
const [uncontrolledOpen, setUncontrolledOpen] = createSignal(
@@ -51,13 +50,32 @@ export function ToolCard(props: ToolCardProps) {
// Reading children to inspect them mounts expensive bodies even while closed.
// Conditional callers supply presence separately; Kobalte mounts the body.
const hasChildren = () => props.hasContent ?? 'children' in props;
+ const summary = () =>
+ props.trailing ??
+ (props.status === 'failed'
+ ? 'Failed'
+ : props.status === 'completed'
+ ? 'Succeeded'
+ : undefined);
const row = (expandable: boolean) => (
<>
+ <span
+ aria-hidden="true"
+ class="flex size-4 shrink-0 items-center justify-center text-ink-extra-muted [&>svg]:size-4"
+ >
+ {props.icon ?? <Wrench />}
+ </span>
<span class="flex min-w-0 flex-1 items-center gap-1.5 overflow-hidden">
- <span class="shrink-0 text-ink">
+ <span class="min-w-0 truncate text-ink-muted">
{typeof props.title === 'string' ? (
- <TextShimmer text={props.title} active={active()} />
+ <Tooltip
+ label={props.title}
+ as="span"
+ class="min-w-0 max-w-full truncate"
+ >
+ <TextShimmer text={props.title} active={active()} />
+ </Tooltip>
) : (
props.title
)}
@@ -68,25 +86,27 @@ export function ToolCard(props: ToolCardProps) {
<span aria-hidden="true" class="shrink-0 text-ink-placeholder">
·
</span>
- <span class="min-w-0 truncate font-mono">{subtitle()}</span>
+ <Tooltip label={subtitle()} as="span" class="min-w-0 truncate">
+ <span class="truncate font-mono">{subtitle()}</span>
+ </Tooltip>
</>
)}
</Show>
<For each={Object.entries(props.args ?? {})}>
{([key, value]) => (
- <span class="shrink-0 rounded bg-hover px-1 font-mono text-ink-extra-muted">
+ <span class="min-w-0 truncate font-mono text-ink-extra-muted">
{key}={value}
</span>
)}
</For>
</span>
- <Show when={props.trailing || expandable}>
- <span class="flex shrink-0 items-center gap-1.5 whitespace-nowrap">
- {props.trailing}
+ <Show when={summary() || expandable}>
+ <span class="ml-auto flex shrink-0 items-center gap-2 whitespace-nowrap text-xs tabular-nums text-ink-extra-muted">
+ {summary()}
<Show when={expandable}>
<CaretRight
aria-hidden="true"
- class="size-3 shrink-0 text-ink-extra-muted transition-transform group-data-expanded:rotate-90 motion-reduce:transition-none"
+ class="size-3.5 shrink-0 text-ink-extra-muted group-data-expanded:rotate-90"
/>
</Show>
</span>
@@ -96,20 +116,28 @@ export function ToolCard(props: ToolCardProps) {
return (
<div
- class="overflow-hidden rounded-lg bg-surface text-ink-extra-muted"
- classList={{ 'opacity-50': props.muted }}
+ class="min-w-0 text-ink-extra-muted"
+ data-tool-row
+ data-tool-status={props.status}
+ classList={{ 'opacity-75': props.muted }}
>
<Show
when={hasChildren()}
- fallback={<div class={ROW_CLASS}>{row(false)}</div>}
+ fallback={
+ <div class="flex min-h-8 w-full min-w-0 items-center gap-2 py-1 text-left text-sm leading-6">
+ {row(false)}
+ </div>
+ }
>
<Collapsible open={open()} onOpenChange={setOpen}>
- <Collapsible.Trigger class={`group hover:bg-hover ${ROW_CLASS}`}>
+ <Collapsible.Trigger class="group flex min-h-8 w-full min-w-0 items-center gap-2 py-1 text-left text-sm leading-6 outline-offset-2 hover:text-ink focus-visible:outline-2 focus-visible:outline-accent">
{row(true)}
</Collapsible.Trigger>
<Collapsible.Content class="data-closed:hidden">
<Show when={open()}>
- <div class="min-w-0 px-3 pb-2">{props.children}</div>
+ <div class="min-w-0 pb-2 pl-6 text-xs leading-5">
+ {props.children}
+ </div>
</Show>
</Collapsible.Content>
</Collapsible>
diff --git a/apps/web/src/features/block-agent/ui/ToolErrorCard.tsx b/apps/web/src/features/block-agent/ui/ToolErrorCard.tsx
index 72e1d57313..f10b48912c 100644
--- a/apps/web/src/features/block-agent/ui/ToolErrorCard.tsx
+++ b/apps/web/src/features/block-agent/ui/ToolErrorCard.tsx
@@ -1,5 +1,5 @@
/**
- * Error card for a failed tool call: a red-edged collapsible row whose header
+ * Error details for a failed tool call: a compact collapsible row whose header
* is "Tool · Subtitle" and whose body is the rest of the error, with a
* copy-error button.
*
@@ -8,13 +8,12 @@
* tokens and Tailwind.
*/
-import { Collapsible } from '@kobalte/core/collapsible';
-import CaretRight from '@phosphor/caret-right.svg';
import Check from '@phosphor/check.svg';
import Copy from '@phosphor/copy.svg';
import Prohibit from '@phosphor/prohibit.svg';
import { Button } from '@ui';
import { createMemo, createSignal, Show } from 'solid-js';
+import { ToolCard } from './ToolCard';
/** Display names for well-known tool ids (from opencode's v1 card). */
const TOOL_NAMES: Record<string, string> = {
@@ -89,47 +88,37 @@ export function ToolErrorCard(props: ToolErrorCardProps) {
};
return (
- <Collapsible
+ <ToolCard
+ title={title()}
+ subtitle={subtitle() === 'Failed' ? undefined : subtitle()}
+ icon={<Prohibit />}
+ status="failed"
open={props.open}
defaultOpen={props.defaultOpen}
onOpenChange={props.onOpenChange}
- class="flex w-full min-w-0 flex-col border-l-2 border-failure pl-2.5 text-xs leading-5"
>
- <Collapsible.Trigger class="group flex min-h-6 w-full min-w-0 items-center gap-2 rounded-xs py-0.5 text-left">
- <Prohibit class="size-4 shrink-0 text-failure" />
- <div class="flex min-w-0 items-center gap-1.5 overflow-hidden">
- <span class="shrink-0 font-medium text-ink">{title()}</span>
- <span class="shrink-0 text-ink-placeholder" aria-hidden="true">
- ·
- </span>
- <span class="min-w-0 truncate text-ink-muted">{subtitle()}</span>
- <CaretRight class="size-3.5 shrink-0 text-ink-extra-muted transition-transform group-data-expanded:rotate-90" />
+ <div class="flex items-start gap-2 pt-1">
+ <div class="min-w-0 flex-1 whitespace-pre-wrap wrap-break-word text-ink-extra-muted">
+ {body()}
</div>
- </Collapsible.Trigger>
- <Collapsible.Content class="min-w-0 data-closed:hidden">
- <div class="flex items-start gap-2 pt-1 pl-6">
- <div class="min-w-0 flex-1 whitespace-pre-wrap wrap-break-word text-ink-extra-muted">
- {body()}
- </div>
- <Button
- type="button"
- variant="ghost"
- size="sm"
- noTouchResize
- class="shrink-0 px-1 text-ink-extra-muted hover:text-ink-muted"
- aria-label={copied() ? 'Copied' : 'Copy error'}
- onMouseDown={(event) => event.preventDefault()}
- onClick={(event) => {
- event.stopPropagation();
- void copy();
- }}
- >
- <Show when={copied()} fallback={<Copy class="size-3.5" />}>
- <Check class="size-3.5 text-success" />
- </Show>
- </Button>
- </div>
- </Collapsible.Content>
- </Collapsible>
+ <Button
+ type="button"
+ variant="ghost"
+ size="sm"
+ noTouchResize
+ class="shrink-0 px-1 text-ink-extra-muted hover:text-ink-muted"
+ aria-label={copied() ? 'Copied' : 'Copy error'}
+ onMouseDown={(event) => event.preventDefault()}
+ onClick={(event) => {
+ event.stopPropagation();
+ void copy();
+ }}
+ >
+ <Show when={copied()} fallback={<Copy class="size-3.5" />}>
+ <Check class="size-3.5 text-success" />
+ </Show>
+ </Button>
+ </div>
+ </ToolCard>
);
}
diff --git a/apps/web/src/features/block-agent/ui/ToolGroup.test.tsx b/apps/web/src/features/block-agent/ui/ToolGroup.test.tsx
index c132648fd1..eac7d51612 100644
--- a/apps/web/src/features/block-agent/ui/ToolGroup.test.tsx
+++ b/apps/web/src/features/block-agent/ui/ToolGroup.test.tsx
@@ -1,61 +1,168 @@
/** @vitest-environment jsdom */
import { cleanup, render } from '@solidjs/testing-library';
-import { afterEach, describe, expect, it, vi } from 'vitest';
+import { createSignal, Index } from 'solid-js';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { ToolGroup } from './ToolGroup';
vi.mock('@phosphor/caret-right.svg', () => ({
default: () => <svg data-testid="caret" />,
}));
-afterEach(cleanup);
+let animationDefaults: HTMLStyleElement;
-function mount(overrides?: { active?: boolean; defaultOpen?: boolean }) {
- return render(() => (
+beforeEach(() => {
+ vi.useFakeTimers();
+ // jsdom's absent CSS reports an empty animation name. Browser styles report
+ // "none" when animation is disabled; Kobalte uses it to finish presence.
+ animationDefaults = document.createElement('style');
+ animationDefaults.textContent = '* { animation-name: none; }';
+ document.head.append(animationDefaults);
+});
+
+afterEach(() => {
+ cleanup();
+ animationDefaults.remove();
+ vi.useRealTimers();
+});
+
+function mount(overrides?: {
+ active?: boolean;
+ live?: boolean;
+ defaultOpen?: boolean;
+}) {
+ const [active, setActive] = createSignal(overrides?.active ?? false);
+ const [live, setLive] = createSignal(overrides?.live);
+ const [calls, setCalls] = createSignal(['Read', 'Edit', 'Shell']);
+ const view = render(() => (
<ToolGroup
- count={3}
- active={overrides?.active ?? false}
+ count={calls().length}
+ active={active()}
+ live={live()}
defaultOpen={overrides?.defaultOpen}
- latest={{ label: 'Bash', detail: 'cargo test -p agent_fold' }}
>
- <div data-testid="call">Read</div>
- <div data-testid="call">Edit</div>
- <div data-testid="call">Bash</div>
+ <Index each={calls()}>
+ {(call) => <div data-testid="call">{call()}</div>}
+ </Index>
</ToolGroup>
));
+ return { ...view, setActive, setLive, setCalls };
}
describe('ToolGroup', () => {
- it('starts closed, counting the calls and naming the latest one', () => {
+ it('starts historical groups collapsed with just the count', () => {
const view = mount();
expect(view.getByRole('button').textContent).toContain('Called 3 tools');
expect(view.getByRole('button').getAttribute('aria-expanded')).toBe(
'false'
);
- expect(view.container.textContent).toContain('Bash');
- expect(view.container.textContent).toContain('cargo test -p agent_fold');
+ expect(view.queryAllByTestId('call')).toHaveLength(0);
+ vi.advanceTimersByTime(2000);
expect(view.queryAllByTestId('call')).toHaveLength(0);
});
- it('opens on click, swapping the latest line for the calls', () => {
+ it('keeps manual expansion of historical groups until the reader closes them', () => {
const view = mount();
view.getByRole('button').click();
expect(view.getByRole('button').getAttribute('aria-expanded')).toBe('true');
expect(view.getAllByTestId('call')).toHaveLength(3);
- expect(view.container.textContent).not.toContain(
- 'cargo test -p agent_fold'
- );
+ vi.advanceTimersByTime(2000);
+ expect(view.getAllByTestId('call')).toHaveLength(3);
view.getByRole('button').click();
expect(view.queryAllByTestId('call')).toHaveLength(0);
});
- it('reads as in progress while a call is still running', () => {
+ it('starts an active group open and collects arriving calls in place', () => {
const view = mount({ active: true });
+ const first = view.getAllByTestId('call')[0];
expect(view.getByRole('button').textContent).toContain('Calling 3 tools');
+ expect(view.getByRole('button').getAttribute('aria-expanded')).toBe('true');
+ view.setCalls((calls) => [...calls, 'Search']);
+ expect(view.getAllByTestId('call')).toHaveLength(4);
+ expect(view.getAllByTestId('call')[0]).toBe(first);
+ vi.advanceTimersByTime(2000);
+ expect(view.getAllByTestId('call')).toHaveLength(4);
+ });
+
+ it('settles the shimmer immediately and collapses after a readable pause', () => {
+ const view = mount({ active: true });
+ view.setActive(false);
+ expect(view.getByRole('button').textContent).toContain('Called 3 tools');
+ expect(view.getByRole('button').getAttribute('aria-expanded')).toBe('true');
+ vi.advanceTimersByTime(699);
+ expect(view.getByRole('button').getAttribute('aria-expanded')).toBe('true');
+ vi.advanceTimersByTime(1);
+ expect(view.getByRole('button').getAttribute('aria-expanded')).toBe(
+ 'false'
+ );
+ expect(view.queryAllByTestId('call')).toHaveLength(0);
+ });
+
+ it('bridges quick gaps between calls and cancels the earlier collapse', () => {
+ const view = mount({ active: true });
+ const first = view.getAllByTestId('call')[0];
+ view.setActive(false);
+ vi.advanceTimersByTime(500);
+ view.setCalls((calls) => [...calls, 'Search']);
+ view.setActive(true);
+ vi.advanceTimersByTime(500);
+ expect(view.getAllByTestId('call')[0]).toBe(first);
+ view.setActive(false);
+ vi.advanceTimersByTime(699);
+ expect(view.getByRole('button').getAttribute('aria-expanded')).toBe('true');
+ vi.advanceTimersByTime(1);
+ expect(view.getByRole('button').getAttribute('aria-expanded')).toBe(
+ 'false'
+ );
});
- it('can start open', () => {
+ it('briefly reveals completed calls arriving in a live batch', () => {
+ const view = mount({ live: true });
+ expect(view.getAllByTestId('call')).toHaveLength(3);
+ expect(view.getByRole('button').textContent).toContain('Called 3 tools');
+ vi.advanceTimersByTime(700);
+ expect(view.queryAllByTestId('call')).toHaveLength(0);
+ view.setCalls((calls) => [...calls, 'Search', 'Read']);
+ expect(view.getAllByTestId('call')).toHaveLength(5);
+ vi.advanceTimersByTime(700);
+ expect(view.queryAllByTestId('call')).toHaveLength(0);
+ });
+
+ it('preserves manually reopened results after automatic collapse', () => {
+ const view = mount({ active: true });
+ view.setActive(false);
+ vi.advanceTimersByTime(700);
+ view.getByRole('button').click();
+ vi.advanceTimersByTime(2000);
+ expect(view.getAllByTestId('call')).toHaveLength(3);
+ });
+
+ it('supports an initially expanded static example', () => {
const view = mount({ defaultOpen: true });
+ vi.advanceTimersByTime(2000);
expect(view.getAllByTestId('call')).toHaveLength(3);
});
+
+ it('does not construct results for a historical collapsed group', () => {
+ const bodyMounted = vi.fn();
+ function Body() {
+ bodyMounted();
+ return <div>Expensive result</div>;
+ }
+ const view = render(() => (
+ <ToolGroup count={2} active={false}>
+ <Body />
+ </ToolGroup>
+ ));
+ expect(bodyMounted).not.toHaveBeenCalled();
+ view.getByRole('button').click();
+ expect(bodyMounted).toHaveBeenCalledOnce();
+ });
+
+ it('clears pending collapse work on unmount', () => {
+ const view = mount({ active: true });
+ view.setActive(false);
+ view.unmount();
+ expect(vi.getTimerCount()).toBe(0);
+ });
});
diff --git a/apps/web/src/features/block-agent/ui/ToolGroup.tsx b/apps/web/src/features/block-agent/ui/ToolGroup.tsx
index caba18aeac..08929a6b62 100644
--- a/apps/web/src/features/block-agent/ui/ToolGroup.tsx
+++ b/apps/web/src/features/block-agent/ui/ToolGroup.tsx
@@ -1,66 +1,62 @@
-/**
- * A run of consecutive tool calls folded to one row: how many, and — while
- * closed — the latest one in a quiet line beneath, so a reader following a
- * long stretch of tool use sees what the agent is on without a card per call.
- *
- * Shaped like `Thought` rather than `ToolCard`: a bare caret row, no surface,
- * because the cards themselves appear once it opens.
- */
+/** Consecutive calls collect in an open group while live, then fold to one row. */
+import { Collapsible } from '@kobalte/core/collapsible';
import CaretRight from '@phosphor/caret-right.svg';
-import { createSignal, type JSX, Show } from 'solid-js';
+import { createWritableMemo } from '@solid-primitives/memo';
+import { createScheduled, debounce } from '@solid-primitives/scheduled';
+import { createMemo, type JSX, on, Show } from 'solid-js';
import { TextShimmer } from './TextShimmer';
+/** Let a fast result remain readable and bridge brief gaps between calls. */
+const SETTLE_DELAY_MS = 700;
+
export interface ToolGroupProps {
count: number;
/** A call in the run is still in flight: reads "Calling" and shimmers. */
active: boolean;
- /** The most recent call: its label and, when it has one, what it touched. */
- latest: { label: string; detail?: string };
+ /** The live tail can receive calls already completed in the same batch. */
+ live?: boolean;
defaultOpen?: boolean;
- /** The calls themselves, shown in place of the latest line once open. */
children: JSX.Element;
}
export function ToolGroup(props: ToolGroupProps) {
- const [expanded, setExpanded] = createSignal(props.defaultOpen ?? false);
+ const settled = createScheduled((callback) =>
+ debounce(callback, SETTLE_DELAY_MS)
+ );
+ const automaticOpen = createMemo((wasOpen: boolean) => {
+ const active = props.active;
+ // Each new call extends the grace period, including completed batches.
+ const live = (props.live ?? active) && props.count > 0;
+ const readyToClose = settled();
+ return active || (!readyToClose && (live || wasOpen));
+ }, false);
+ const [expanded, setExpanded] = createWritableMemo<boolean>(
+ on(automaticOpen, (open, previous) =>
+ previous === undefined ? (props.defaultOpen ?? open) : open
+ )
+ );
const title = () =>
- `${props.active ? 'Calling' : 'Called'} ${props.count} tools`;
+ `${props.active ? 'Calling' : 'Called'} ${props.count} ${props.count === 1 ? 'tool' : 'tools'}`;
return (
- <div class="min-w-0 text-xs leading-5 text-ink-extra-muted">
- <button
- type="button"
- aria-expanded={expanded()}
- class="flex min-h-7 items-center gap-1 py-1 text-left text-ink-extra-muted hover:text-ink-muted"
- onClick={() => setExpanded((prev) => !prev)}
- >
+ <Collapsible
+ open={expanded()}
+ onOpenChange={setExpanded}
+ class="min-w-0 text-sm leading-6 text-ink-extra-muted"
+ >
+ <Collapsible.Trigger class="group flex min-h-8 items-center gap-2 py-1 text-left text-ink-extra-muted hover:text-ink-muted">
+ <TextShimmer text={title()} active={props.active} />
<CaretRight
- class="size-4 shrink-0 transition-transform motion-reduce:transition-none"
- classList={{ 'rotate-90': expanded() }}
+ aria-hidden="true"
+ class="size-4 shrink-0 opacity-0 group-data-expanded:rotate-90 group-hover:opacity-100 group-focus-visible:opacity-100"
/>
- <TextShimmer text={title()} active={props.active} />
- </button>
- <Show
- when={expanded()}
- fallback={
- <div class="flex min-w-0 items-center gap-1.5 pl-5 text-ink-placeholder">
- <span class="shrink-0">{props.latest.label}</span>
- <Show when={props.latest.detail}>
- {(detail) => (
- <>
- <span aria-hidden="true" class="shrink-0">
- ·
- </span>
- <span class="min-w-0 truncate font-mono">{detail()}</span>
- </>
- )}
- </Show>
- </div>
- }
- >
- <div class="flex min-w-0 flex-col gap-1 pl-5">{props.children}</div>
- </Show>
- </div>
+ </Collapsible.Trigger>
+ <Collapsible.Content class="data-closed:hidden">
+ <Show when={expanded()}>
+ <div class="flex min-w-0 flex-col pl-6">{props.children}</div>
+ </Show>
+ </Collapsible.Content>
+ </Collapsible>
);
}
diff --git a/apps/web/src/features/block-agent/ui/index.ts b/apps/web/src/features/block-agent/ui/index.ts
index 89df49277e..36bccabdb1 100644
--- a/apps/web/src/features/block-agent/ui/index.ts
+++ b/apps/web/src/features/block-agent/ui/index.ts
@@ -26,11 +26,6 @@ export {
type ElicitationFormProps,
} from './ElicitationForm';
export { FoldedAnsiText } from './FoldedAnsiText';
-export {
- exchangeText,
- FoldedExchange,
- type FoldedExchangeProps,
-} from './FoldedExchange';
export { FoldedOutput } from './FoldedOutput';
export { FoldedPathList } from './FoldedPathList';
export { FoldedTerminal } from './FoldedTerminal';
diff --git a/apps/web/src/lib/core/component/AI/component/tool/BaseTool.tsx b/apps/web/src/lib/core/component/AI/component/tool/BaseTool.tsx
index 3cb8b9548e..7a738740c9 100644
--- a/apps/web/src/lib/core/component/AI/component/tool/BaseTool.tsx
+++ b/apps/web/src/lib/core/component/AI/component/tool/BaseTool.tsx
@@ -25,6 +25,7 @@ function BaseToolCall(props: ToolCallProps) {
<Tool.Root grouped={grouped()} muted={!!error}>
<Tool.Row
align={props.align}
+ grouped={grouped()}
icon={props.icon}
trailing={error ? <span class="text-ink">Failed</span> : undefined}
>
@@ -39,7 +40,7 @@ function BaseToolCall(props: ToolCallProps) {
function BaseToolResponse(props: ToolResponseProps) {
return (
- <Tool.Root>
+ <Tool.Root grouped={props.renderContext.grouped}>
<div class="px-3 py-2">{props.children && props.children}</div>
</Tool.Root>
);
diff --git a/apps/web/src/lib/core/component/AI/component/tool/BashCodeExecution.tsx b/apps/web/src/lib/core/component/AI/component/tool/BashCodeExecution.tsx
index c4530ec481..5709e78cd0 100644
--- a/apps/web/src/lib/core/component/AI/component/tool/BashCodeExecution.tsx
+++ b/apps/web/src/lib/core/component/AI/component/tool/BashCodeExecution.tsx
@@ -42,6 +42,8 @@ function CodeFence(props: {
<Show when={isCollapsible() && needsTruncation()}>
<button
type="button"
+ aria-label="Command output"
+ aria-expanded={expanded()}
class="text-ink-extra-muted hover:text-ink-muted absolute top-1 right-1 p-1"
onClick={() => setExpanded(!expanded())}
>
diff --git a/apps/web/src/lib/core/component/AI/component/tool/SendEmail.tsx b/apps/web/src/lib/core/component/AI/component/tool/SendEmail.tsx
index 39c25c2e1b..5ee76f1294 100644
--- a/apps/web/src/lib/core/component/AI/component/tool/SendEmail.tsx
+++ b/apps/web/src/lib/core/component/AI/component/tool/SendEmail.tsx
@@ -143,12 +143,7 @@ function SentEmailResponse(props: {
</Suspense>
</div>
<span class="shrink-0 text-ink-muted">
- <CaretRight
- class={cn(
- 'size-4 transition-transform',
- 'group-open:rotate-90'
- )}
- />
+ <CaretRight class={cn('size-4', 'group-open:rotate-90')} />
</span>
</div>
</BaseTool>
diff --git a/apps/web/src/lib/core/component/AI/component/tool/Tool.tsx b/apps/web/src/lib/core/component/AI/component/tool/Tool.tsx
index 23c6c81d77..941b51069e 100644
--- a/apps/web/src/lib/core/component/AI/component/tool/Tool.tsx
+++ b/apps/web/src/lib/core/component/AI/component/tool/Tool.tsx
@@ -5,6 +5,7 @@ import { Show } from 'solid-js';
type ToolRowProps = {
align?: 'center' | 'start';
+ grouped?: boolean;
children: JSX.Element;
icon: Component<JSX.SvgSVGAttributes<SVGSVGElement>>;
trailing?: JSX.Element;
@@ -65,8 +66,10 @@ function Row(props: ToolRowProps) {
return (
<div
- class="flex min-h-9 w-full gap-2 px-3 py-2"
+ class="flex w-full gap-2"
classList={{
+ 'min-h-8 py-1 text-sm leading-6': props.grouped,
+ 'min-h-9 px-3 py-2': !props.grouped,
'items-center': !alignStart(),
'items-start': alignStart(),
}}
@@ -118,7 +121,7 @@ function ResultToggle(props: ToolResultToggleProps) {
<span>{props.status}</span>
</Show>
<CaretRight
- class="transition-transform"
+ aria-hidden="true"
classList={{
'rotate-90': props.expanded,
}}
diff --git a/apps/web/src/lib/core/component/AI/component/tool/handler.tsx b/apps/web/src/lib/core/component/AI/component/tool/handler.tsx
index 75ed9db872..f311122dac 100644
--- a/apps/web/src/lib/core/component/AI/component/tool/handler.tsx
+++ b/apps/web/src/lib/core/component/AI/component/tool/handler.tsx
@@ -205,6 +205,11 @@ type TriggerToolArgs = Omit<
type: 'call' | 'response' | 'error';
};
+/** Schema support alone does not guarantee that this surface has a renderer. */
+export function hasToolRenderer(name: string): boolean {
+ return Object.hasOwn(toolHandlers, name);
+}
+
export function RenderTool(props: ToolProps) {
const maybeTool = deserializeToolCall({
id: props.tool_id,
diff --git a/docs/AGENT_GUIDE/ai-chat.md b/docs/AGENT_GUIDE/ai-chat.md
index a281836f8d..23c7e67358 100644
--- a/docs/AGENT_GUIDE/ai-chat.md
+++ b/docs/AGENT_GUIDE/ai-chat.md
@@ -396,31 +396,59 @@ to open the PR entity in a split; until GitHub has synced the entity the
chip is a GitHub link instead. The icon and status word follow open /
merged / closed.
-Tool groups and individual tool cards start collapsed. Expand a group to see
-its calls, then expand an edit card to view its file diffs. Diff bodies load
-only when their card opens; syntax highlighting may appear after the diff text.
-Opening a session or expanding a group should leave the app responsive, even
-when the session contains many file edits.
+Individual tools appear as bare rows with an icon, tool name, optional detail,
+and a right-aligned result summary. The caret on the right opens the results;
+it points right when collapsed and down when expanded. Individual results start
+collapsed. Existing rich result views retain their own content and controls;
+when a result view provides its own disclosure, use that control rather than
+adding a second nested disclosure. Counts come from structured responses,
+edits show additions/deletions, and other tools show their outcome. A call cut
+off when its turn ends reads **Stopped**.
+
+Only tools with a supported result view can expand. Unknown tools, unsupported
+drafts, and payloads that do not fit their renderer stay as summary rows with
+no caret. Tool arguments and results never fall back to raw JSON.
+
+Consecutive calls collect under an expanded **Calling N tools** group while
+running. Rows appear as calls arrive; after the calls finish, the group briefly
+settles and collapses to **Called N tools**. Group growth and collapse happen
+immediately, without animation, including fast batches. Completed groups in
+history start collapsed and can be reopened. The group caret sits immediately
+after its label and appears on hover or keyboard focus. Expand an edit row to
+view its diffs. Result bodies load only when their row opens; syntax highlighting
+may appear after the diff text. Opening a session or expanding a group should
+leave the app responsive, even when the session contains many file edits.
+
+`DisplayResults` renders its dynamic view directly in the reply and stays visible
+without opening a tool row. It breaks tool groups before and after itself,
+including while pending; later calls start a separate group.
+Its dashboard supports markdown, timelines, entity lists, and channel messages,
+using the same full-width view as AI chat. Incomplete arguments stay hidden while
+streaming; a valid view updates as arguments arrive. Malformed completed views
+show **Couldn't render dashboard**; failed calls show a **Failed** summary row
+without a disclosure. Macro's built-in agents receive the complete view schema
+with the tool definition. External coding agents connected through Macro's MCP
+server do not currently receive this tool.
+
+The development gallery at `/app/component/agent-ui` includes **Replay tool
+calls** and **Replay fast batch**, both using the message renderer. Check that
+rows accumulate, completed calls stop shimmering, the group collapses after
+completion without height animation, and its carets still expand the results.
+Check that rich result controls still work and `DisplayResults` stays visible
+between surrounding groups. In **AgentMessage (end-to-end)**, expand the group
+and confirm unknown tools have no individual disclosure or JSON payload. Repeat
+at a narrow viewport width.
A thought row reads **Thinking** and shimmers only while it is the last part
of the turn the session is working on. Earlier thoughts settle to **Thought**
as soon as a tool or answer follows, including during long Cursor turns. A
-trailing thought stays outside the tool group so the live reasoning row stays
-visible. Only the newest turn can be live: once the composer stops showing the
+trailing thought at the end of a message stays outside the tool group so live
+reasoning stays visible; thoughts followed by prose stay inside the group.
+Only the newest turn can be live: once the composer stops showing the
agent as working, every Thinking label, **Calling N tools** row, shimmering
tool title, and working row settles — earlier turns never shimmer, even ones
-the runtime cut off mid-call. At most one shimmering row is ever expected.
-
-A `displayResults` call is the exception: it renders the dynamic-UI view the
-model composed — the same dashboard (markdown, timelines, entity lists, channel
-messages) that AI chat shows — full width in the transcript, and never folded
-into a tool group or behind a card. Expect the view itself, not a `DisplayResults`
-row. Incomplete arguments stay hidden while streaming, and a valid view updates
-as its arguments change. A completed call whose JSON does not match the schema
-shows `Couldn't render dashboard`; a failed call keeps its error card.
-Macro's built-in agents receive the complete view schema with the tool definition.
-External coding agents connected through Macro's MCP server do not currently
-receive this tool.
+the runtime cut off mid-call. Shimmer identifies current activity: an active
+tool and its containing group can shimmer together; completed rows stay still.
### Sharing a session