The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.
Rust agent-orchestrationai-agentsai-assistantdesktopllmlocal-firstmcppersonal-aiprivacyrustsecond-braintauri
refactor(chat): unify tool calls on assistant ui
Steven Enamakelcb1f26fca650
diff --git a/app/src/features/conversations/components/AssistantUiToolCall.tsx b/app/src/features/conversations/components/AssistantUiToolCall.tsxnew file mode 100644index 0000000000..934f820455--- /dev/null+++ b/app/src/features/conversations/components/AssistantUiToolCall.tsx@@ -0,0 +1,215 @@+import type { ToolCallMessagePartComponent } from '@assistant-ui/react';+import { CheckIcon, ChevronDownIcon, CircleXIcon, Loader2Icon, WrenchIcon } from 'lucide-react';++import { cn } from '../../../components/assistant-ui/lib/utils';+import {+ Collapsible,+ CollapsibleContent,+ CollapsibleTrigger,+} from '../../../components/assistant-ui/ui/collapsible';+import type {+ ToolFailureExplanation,+ ToolTimelineEntryStatus,+} from '../../../store/chatRuntimeSlice';+import { formatToolName } from '../../../utils/toolTimelineFormatting';+import { BubbleMarkdown } from './AgentMessageBubble';+import { ToolFailureLines } from './ToolFailureLines';++function friendlyLabel(key: string): string {+ return key+ .replace(/([a-z0-9])([A-Z])/g, '$1 $2')+ .replace(/[_-]+/g, ' ')+ .replace(/^./, char => char.toUpperCase());+}++function parsedValue(value: unknown): unknown {+ if (typeof value !== 'string') return value;+ const trimmed = value.trim();+ if (!(trimmed.startsWith('{') || trimmed.startsWith('['))) return value;+ try {+ return JSON.parse(trimmed);+ } catch {+ return value;+ }+}++function hasDisplayValue(value: unknown): boolean {+ if (value === undefined || value === null || value === '') return false;+ if (Array.isArray(value)) return value.length > 0;+ if (typeof value === 'object') return Object.keys(value as object).length > 0;+ return true;+}++function ToolDataView({ value }: { value: unknown }) {+ const parsed = parsedValue(value);+ if (Array.isArray(parsed)) {+ return (+ <ul className="space-y-1 text-xs">+ {parsed.map((item, index) => (+ <li key={index} className="bg-muted/50 rounded-md px-2 py-1.5">+ <ToolDataView value={item} />+ </li>+ ))}+ </ul>+ );+ }+ if (parsed && typeof parsed === 'object') {+ const entries = Object.entries(parsed);+ for (const key of ['content', 'output', 'result', 'message', 'query', 'q']) {+ const semantic = entries.find(([candidate]) => candidate === key)?.[1];+ if (hasDisplayValue(semantic)) return <ToolDataView value={semantic} />;+ }+ return (+ <dl className="divide-border bg-muted/40 divide-y rounded-md px-2 text-xs">+ {entries.map(([key, item]) => (+ <div key={key} className="grid grid-cols-[minmax(7rem,auto)_1fr] gap-3 py-1.5">+ <dt className="text-muted-foreground font-medium">{friendlyLabel(key)}</dt>+ <dd className="min-w-0 wrap-break-word">+ <ToolDataView value={item} />+ </dd>+ </div>+ ))}+ </dl>+ );+ }+ if (typeof parsed === 'boolean') return <span>{parsed ? 'Yes' : 'No'}</span>;+ if (typeof parsed === 'string') return <BubbleMarkdown content={parsed} />;+ return <span className="whitespace-pre-wrap">{String(parsed ?? '')}</span>;+}++function inferredToolLabel(toolName: string, running: boolean, args: unknown, result: unknown) {+ const lowerName = toolName.toLowerCase();+ const parsedArgs = parsedValue(args);+ const argKeys =+ parsedArgs && typeof parsedArgs === 'object' && !Array.isArray(parsedArgs)+ ? Object.keys(parsedArgs as object).map(key => key.toLowerCase())+ : [];+ const renderedResult = typeof result === 'string' ? result : JSON.stringify(result ?? '');+ const looksLikeSearch =+ lowerName.includes('search') ||+ argKeys.some(key => ['query', 'q', 'search_query'].includes(key)) ||+ /(?:^|\n)#?\s*search results\b/i.test(renderedResult);+ const looksLikeFetch =+ lowerName.includes('fetch') ||+ argKeys.some(key => ['url', 'uri'].includes(key)) ||+ /\bstatus=\d{3}\s+url=/i.test(renderedResult);+ if (looksLikeSearch) return running ? 'Searching the web' : 'Searched the web';+ if (looksLikeFetch) return running ? 'Fetching from the web' : 'Fetched from the web';+ return formatToolName(toolName);+}++export interface AssistantUiToolCallCardProps {+ toolName: string;+ args?: unknown;+ argsText?: string;+ result?: unknown;+ status?: ToolTimelineEntryStatus;+ displayName?: string;+ detail?: string;+ elapsedMs?: number;+ failure?: ToolFailureExplanation;+}++/** The single assistant-ui tool-call presentation used at every nesting level. */+export function AssistantUiToolCallCard({+ toolName,+ args,+ argsText,+ result,+ status,+ displayName,+ detail,+ elapsedMs,+ failure,+}: AssistantUiToolCallCardProps) {+ const running = status+ ? status === 'running' || status === 'awaiting_user'+ : result === undefined;+ const input = hasDisplayValue(args) ? args : parsedValue(argsText ?? '');+ const output = result === '' && status && !running ? 'No output' : parsedValue(result);+ const suppliedLabel = displayName?.trim();+ const label =+ suppliedLabel && suppliedLabel.toLowerCase() !== 'tool'+ ? suppliedLabel+ : inferredToolLabel(toolName, running, args, result);+ const statusLabel =+ status === 'error'+ ? 'failed'+ : status === 'cancelled'+ ? 'cancelled'+ : status === 'awaiting_user'+ ? 'awaiting input'+ : running+ ? 'running'+ : 'done';+ const failed = status === 'error';++ return (+ <Collapsible+ data-slot="aui_openhuman-tool-call"+ data-testid="assistant-ui-tool-call"+ defaultOpen={running}+ className={cn(+ 'border-border/60 dark:border-muted-foreground/15 rounded-xl border',+ running && 'border-dashed'+ )}>+ <CollapsibleTrigger className="group/tool text-muted-foreground hover:text-foreground flex w-full items-center gap-2 px-3 py-2 text-sm transition-colors">+ <WrenchIcon className="size-4 shrink-0" />+ <span className="text-foreground text-start font-medium">{label}</span>+ {detail ? (+ <span className="bg-muted min-w-0 truncate rounded px-1.5 py-0.5 font-mono text-[11px]">+ {detail}+ </span>+ ) : null}+ <span className="flex shrink-0 items-center gap-1 text-[11px]">+ {running ? (+ <Loader2Icon className="size-3 animate-spin [animation-duration:0.6s]" />+ ) : failed ? (+ <CircleXIcon className="size-3.5" />+ ) : (+ <CheckIcon className="size-3.5" />+ )}+ {statusLabel}+ {elapsedMs != null && !running ? (+ <span className="tabular-nums">+ {elapsedMs >= 1000 ? `${(elapsedMs / 1000).toFixed(1)}s` : `${elapsedMs}ms`}+ </span>+ ) : null}+ </span>+ <ChevronDownIcon className="ml-auto size-4 shrink-0 -rotate-90 transition-transform group-data-[state=open]/tool:rotate-0" />+ </CollapsibleTrigger>+ {failed && failure ? (+ <div className="px-3 pb-2">+ <ToolFailureLines failure={failure} />+ </div>+ ) : null}+ <CollapsibleContent className="space-y-2 px-3 pb-3">+ {hasDisplayValue(input) ? (+ <div data-testid="assistant-ui-tool-input">+ <p className="text-muted-foreground mb-1 text-[11px] font-medium uppercase">Input</p>+ <div className="max-h-48 overflow-auto">+ <ToolDataView value={input} />+ </div>+ </div>+ ) : null}+ {hasDisplayValue(output) ? (+ <div data-testid="assistant-ui-tool-output">+ <p className="text-muted-foreground mb-1 text-[11px] font-medium uppercase">Output</p>+ <div className="max-h-64 overflow-auto">+ <ToolDataView value={output} />+ </div>+ </div>+ ) : null}+ </CollapsibleContent>+ </Collapsible>+ );+}++export const OpenHumanToolCall: ToolCallMessagePartComponent = props => (+ <AssistantUiToolCallCard+ toolName={props.toolName}+ args={props.args}+ argsText={props.argsText}+ result={props.result}+ />+);diff --git a/app/src/features/conversations/components/ChatToolParts.test.tsx b/app/src/features/conversations/components/ChatToolParts.test.tsxindex 4be0fe60b7..2149e2c218 100644--- a/app/src/features/conversations/components/ChatToolParts.test.tsx+++ b/app/src/features/conversations/components/ChatToolParts.test.tsx@@ -14,7 +14,7 @@ const activity: SubagentActivity = {};describe('ChatToolParts', () => {- it('renders a delegation with progress args and no result as running', () => {+ it('renders a running delegation collapsed by default', async () => {render(<ChatToolFallbacktype="tool-call"@@ -32,6 +32,12 @@ describe('ChatToolParts', () => {expect(screen.getByText('running')).toBeInTheDocument();expect(screen.getByText('Researcher')).toBeInTheDocument();+ expect(screen.queryByText('Checking primary sources.')).not.toBeInTheDocument();+ expect(screen.getByTestId('assistant-ui-subagent-call')).toHaveAttribute(+ 'data-state',+ 'closed'+ );+ await userEvent.click(screen.getByRole('button', { name: /Delegated to Researcher/i }));expect(screen.getByText('Checking primary sources.')).toBeInTheDocument();});diff --git a/app/src/features/conversations/components/ChatToolParts.tsx b/app/src/features/conversations/components/ChatToolParts.tsxindex cb6162a6c1..f2d8c59a3a 100644--- a/app/src/features/conversations/components/ChatToolParts.tsx+++ b/app/src/features/conversations/components/ChatToolParts.tsx@@ -1,5 +1,5 @@import type { ToolCallMessagePartComponent } from '@assistant-ui/react';-import { CheckIcon, ChevronDownIcon, Loader2Icon, WrenchIcon, WorkflowIcon } from 'lucide-react';+import { CheckIcon, ChevronDownIcon, Loader2Icon, WorkflowIcon } from 'lucide-react';import type { FC, PropsWithChildren } from 'react';import { cn } from '../../../components/assistant-ui/lib/utils';@@ -15,8 +15,7 @@ import {CollapsibleTrigger,} from '../../../components/assistant-ui/ui/collapsible';import type { SubagentActivity } from '../../../store/chatRuntimeSlice';-import { formatToolName } from '../../../utils/toolTimelineFormatting';-import { BubbleMarkdown } from './AgentMessageBubble';+import { OpenHumanToolCall } from './AssistantUiToolCall';import { SubagentActivityBlock } from './SubagentActivityBlock';function asSubagentActivity(value: unknown): SubagentActivity | undefined {@@ -57,9 +56,9 @@ export const SubagentCall: ToolCallMessagePartComponent = ({ args, result }) =>return (<Collapsible+ defaultOpen={false}data-slot="aui_subagent-call"data-testid="assistant-ui-subagent-call"- defaultOpenclassName={cn('aui-subagent-call border-border/60 dark:border-muted-foreground/15 rounded-xl border',running && 'border-dashed'@@ -92,157 +91,6 @@ export const SubagentCall: ToolCallMessagePartComponent = ({ args, result }) =>);};-function friendlyLabel(key: string): string {- return key- .replace(/([a-z0-9])([A-Z])/g, '$1 $2')- .replace(/[_-]+/g, ' ')- .replace(/^./, char => char.toUpperCase());-}--function toolDisplayName(- toolName: string,- running: boolean,- args: unknown,- result: unknown-): string {- const lowerName = toolName.toLowerCase();- const parsedArgs = parsedValue(args);- const argKeys =- parsedArgs && typeof parsedArgs === 'object' && !Array.isArray(parsedArgs)- ? Object.keys(parsedArgs as object).map(key => key.toLowerCase())- : [];- const renderedResult = typeof result === 'string' ? result : JSON.stringify(result ?? '');- const looksLikeSearch =- lowerName.includes('search') ||- argKeys.some(key => ['query', 'q', 'search_query'].includes(key)) ||- /(?:^|\n)#?\s*search results\b/i.test(renderedResult);- const looksLikeFetch =- lowerName.includes('fetch') ||- argKeys.some(key => ['url', 'uri'].includes(key)) ||- /\bstatus=\d{3}\s+url=/i.test(renderedResult);- if (looksLikeSearch) {- return running ? 'Searching the web' : 'Searched the web';- }- if (looksLikeFetch) return running ? 'Fetching from the web' : 'Fetched from the web';- return formatToolName(toolName);-}--function parsedValue(value: unknown): unknown {- if (typeof value !== 'string') return value;- const trimmed = value.trim();- if (!(trimmed.startsWith('{') || trimmed.startsWith('['))) return value;- try {- return JSON.parse(trimmed);- } catch {- return value;- }-}--function hasDisplayValue(value: unknown): boolean {- if (value === undefined || value === null || value === '') return false;- if (Array.isArray(value)) return value.length > 0;- if (typeof value === 'object') return Object.keys(value as object).length > 0;- return true;-}--function ToolDataView({ value }: { value: unknown }) {- const parsed = parsedValue(value);- if (Array.isArray(parsed)) {- return (- <ul className="space-y-1 text-xs">- {parsed.map((item, index) => (- <li key={index} className="bg-muted/50 rounded-md px-2 py-1.5">- <ToolDataView value={item} />- </li>- ))}- </ul>- );- }- if (parsed && typeof parsed === 'object') {- const entries = Object.entries(parsed);- // Tool wrappers frequently add bookkeeping beside the actual payload- // (`tool_call_id`, success, timing). When a semantic output field exists,- // show that value directly and hide the wrapper entirely.- for (const key of ['content', 'output', 'result', 'message', 'query', 'q']) {- const semantic = entries.find(([candidate]) => candidate === key)?.[1];- if (hasDisplayValue(semantic)) return <ToolDataView value={semantic} />;- }- return (- <dl className="divide-border bg-muted/40 divide-y rounded-md px-2 text-xs">- {entries.map(([key, item]) => (- <div key={key} className="grid grid-cols-[minmax(7rem,auto)_1fr] gap-3 py-1.5">- <dt className="text-muted-foreground font-medium">{friendlyLabel(key)}</dt>- <dd className="min-w-0 wrap-break-word">- <ToolDataView value={item} />- </dd>- </div>- ))}- </dl>- );- }- if (typeof parsed === 'boolean') return <span>{parsed ? 'Yes' : 'No'}</span>;- if (typeof parsed === 'string') return <BubbleMarkdown content={parsed} />;- return <span className="whitespace-pre-wrap">{String(parsed ?? '')}</span>;-}--/** Rich assistant-ui-native renderer for an ordinary OpenHuman tool call. */-export const OpenHumanToolCall: ToolCallMessagePartComponent = ({- toolName,- args,- argsText,- result,-}) => {- const running = result === undefined;- const input = hasDisplayValue(args) ? args : parsedValue(argsText ?? '');- const output = parsedValue(result);- return (- <Collapsible- data-slot="aui_openhuman-tool-call"- data-testid="assistant-ui-tool-call"- defaultOpen={running}- className={cn(- 'border-border/60 dark:border-muted-foreground/15 rounded-xl border',- running && 'border-dashed'- )}>- <CollapsibleTrigger className="group/tool text-muted-foreground hover:text-foreground flex w-full items-center gap-2 px-3 py-2 text-sm transition-colors">- <WrenchIcon className="size-4 shrink-0" />- <span className="text-foreground text-start font-medium">- {toolDisplayName(toolName, running, args, result)}- </span>- {running ? (- <span className="bg-muted flex items-center gap-1.5 rounded-full px-2 py-0.5 text-[11px]">- <Loader2Icon className="size-3 animate-spin [animation-duration:0.6s]" />- running- </span>- ) : (- <span className="flex items-center gap-1 text-[11px]">- <CheckIcon className="size-3.5" /> done- </span>- )}- <ChevronDownIcon className="ml-auto size-4 shrink-0 -rotate-90 transition-transform group-data-[state=open]/tool:rotate-0" />- </CollapsibleTrigger>- <CollapsibleContent className="space-y-2 px-3 pb-3">- {hasDisplayValue(input) ? (- <div>- <p className="text-muted-foreground mb-1 text-[11px] font-medium uppercase">Input</p>- <div className="max-h-48 overflow-auto">- <ToolDataView value={input} />- </div>- </div>- ) : null}- {hasDisplayValue(output) ? (- <div>- <p className="text-muted-foreground mb-1 text-[11px] font-medium uppercase">Output</p>- <div className="max-h-64 overflow-auto">- <ToolDataView value={output} />- </div>- </div>- ) : null}- </CollapsibleContent>- </Collapsible>- );-};-/** Route every call through an assistant-ui-native rich renderer. */export const ChatToolFallback: ToolCallMessagePartComponent = props =>props.toolName === 'task' ? <SubagentCall {...props} /> : <OpenHumanToolCall {...props} />;diff --git a/app/src/features/conversations/components/SubagentActivityBlock.tsx b/app/src/features/conversations/components/SubagentActivityBlock.tsxindex 6bc5bc6701..fa9cfc5463 100644--- a/app/src/features/conversations/components/SubagentActivityBlock.tsx+++ b/app/src/features/conversations/components/SubagentActivityBlock.tsx@@ -1,191 +1,30 @@-import Badge, { type BadgeVariant } from '../../../components/ui/Badge';+import Badge from '../../../components/ui/Badge';import WorktreeActions from '../../../components/worktree/WorktreeActions';import { useT } from '../../../lib/i18n/I18nContext';import type {SubagentActivity,- ToolFailureExplanation,- ToolTimelineEntryStatus,+ SubagentToolCallEntry,+ SubagentTranscriptItem,} from '../../../store/chatRuntimeSlice';import { basename } from '../../../utils/pathUtils';-import { formatToolName, stripToolCallEnvelopes } from '../../../utils/toolTimelineFormatting';+import { stripToolCallEnvelopes } from '../../../utils/toolTimelineFormatting';import { BubbleMarkdown } from './AgentMessageBubble';-import { ToolFailureLines } from './ToolFailureLines';+import { AssistantUiToolCallCard } from './AssistantUiToolCall';-/**- * Map a child tool-call status to the shared {@link Badge} variant. The label- * itself comes from `useStatusTagLabel` below; keeping the two beside each- * other is what stops a status reading "Failed" in a success-toned pill.- */-function statusTagVariant(status: ToolTimelineEntryStatus): BadgeVariant {- switch (status) {- case 'error':- return 'danger';- case 'running':- case 'awaiting_user':- return 'warning';- case 'cancelled':- return 'neutral';- default:- return 'success';- }-}--/** Tone classes for a child tool-call row's bullet, keyed by lifecycle status. */-function toolCallTone(status: ToolTimelineEntryStatus): string {- if (status === 'running') return 'text-amber-700 dark:text-amber-300';- if (status === 'success') return 'text-sage-700 dark:text-sage-300';- return 'text-coral-700 dark:text-coral-300';-}--function subagentToolLabel(- name: string,- status: ToolTimelineEntryStatus,- args: unknown,- result: unknown-): string {- const running = status === 'running';- const lowerName = name.toLowerCase();- const argKeys =- args && typeof args === 'object' && !Array.isArray(args)- ? Object.keys(args as object).map(key => key.toLowerCase())- : [];- const output = readableToolOutput(result) ?? '';- const looksLikeSearch =- lowerName.includes('search') ||- argKeys.some(key => ['query', 'q', 'search_query'].includes(key)) ||- /(?:^|\n)#?\s*search results\b/i.test(output);- const looksLikeFetch =- lowerName.includes('fetch') ||- argKeys.some(key => ['url', 'uri'].includes(key)) ||- /\bstatus=\d{3}\s+url=/i.test(output);- if (looksLikeSearch) {- return running ? 'Searching the web' : 'Searched the web';- }- if (looksLikeFetch) return running ? 'Fetching from the web' : 'Fetched from the web';- return formatToolName(name);-}--function readableToolOutput(value: unknown): string | null {- if (value === undefined || value === null) return null;- if (typeof value === 'string') {- const trimmed = value.trim();- if (!trimmed) return null;- try {- return readableToolOutput(JSON.parse(trimmed)) ?? trimmed;- } catch {- return trimmed;- }- }- if (typeof value === 'object') {- const object = value as Record<string, unknown>;- for (const key of ['content', 'output', 'message', 'result']) {- if (typeof object[key] === 'string' && object[key].trim()) return object[key].trim();- }- return Object.entries(object)- .map(([key, item]) => `- **${key.replace(/[_-]+/g, ' ')}:** ${String(item)}`)- .join('\n');- }- return String(value);-}+type ChildToolCall = SubagentToolCallEntry | Extract<SubagentTranscriptItem, { kind: 'tool' }>;-/**- * Status pill for a tool-call row — a tinted "Done" / "Failed" / "Running"- * tag instead of a bare ✓/✕ glyph, so the outcome reads at a glance. Built on- * the shared {@link Badge} primitive, which publishes the tone as- * `data-variant` for tests to assert instead of a Tailwind class string.- */-export function StatusTag({ status }: { status: ToolTimelineEntryStatus }) {- const { t } = useT();- const label =- status === 'error'- ? t('conversations.agentTaskInsights.failed')- : status === 'running'- ? t('conversations.agentTaskInsights.running')- : status === 'cancelled'- ? t('conversations.agentTaskInsights.cancelled')- : status === 'awaiting_user'- ? t('conversations.agentTaskInsights.awaitingUser')- : t('conversations.agentTaskInsights.done');+function ChildToolCallCard({ call }: { call: ChildToolCall }) {return (- <Badge variant={statusTagVariant(status)} className="rounded-full px-1.5 py-0.5 text-[10px]">- {label}- </Badge>- );-}--/**- * One child tool-call row in a sub-agent's inline activity. Shared by the- * ordered transcript (interleaved with {@link ThoughtBlock}) and the flat- * `toolCalls` fallback, so the row markup lives in exactly one place.- */-export function ToolCallRow({- call,-}: {- call: {- callId: string;- toolName: string;- status: ToolTimelineEntryStatus;- elapsedMs?: number;- iteration?: number;- /** Server-computed human label; preferred over the client formatter. */- displayName?: string;- /** Server-computed contextual detail (path / recipient / query). */- detail?: string;- /** Structured why/next explanation for a FAILED child tool call (#4459). */- failure?: ToolFailureExplanation;- /** Arguments supplied to the child tool, used for descriptive fallback labels. */- args?: unknown;- /** Child tool output, rendered as Markdown when present. */- result?: unknown;- };-}) {- const output = readableToolOutput(call.result);- const suppliedLabel = call.displayName?.trim();- const label =- suppliedLabel && suppliedLabel.toLowerCase() !== 'tool'- ? suppliedLabel- : subagentToolLabel(call.toolName, call.status, call.args, call.result);- return (- <div className="min-w-0" data-testid="subagent-tool-call">- <div className="flex min-w-0 items-center gap-1.5">- <span aria-hidden className={`shrink-0 text-[11px] ${toolCallTone(call.status)}`}>- •- </span>- <span className="shrink-0 text-[12px] whitespace-nowrap text-content-secondary">- {label}- </span>- {/* The contextual arg (path / recipient / query) can be long, so it- truncates to a single line and absorbs the row's spare width — the- full value stays available on hover — instead of wrapping into a- multi-line box that knocks the name and status out of alignment. */}- {call.detail ? (- <span- title={call.detail}- className="min-w-0 truncate rounded bg-surface-subtle px-1 py-px font-mono text-[11px] text-content-muted">- {call.detail}- </span>- ) : null}- {/* Status reads as a tinted "Done" / "Failed" / "Running" tag. */}- <span className="shrink-0">- <StatusTag status={call.status} />- </span>- {call.elapsedMs != null && call.status !== 'running' ? (- <span className="shrink-0 text-[11px] text-content-faint">- {call.elapsedMs >= 1000- ? `${(call.elapsedMs / 1000).toFixed(1)}s`- : `${call.elapsedMs}ms`}- </span>- ) : null}- </div>- {call.status === 'error' && call.failure ? <ToolFailureLines failure={call.failure} /> : null}- {output ? (- <div- data-testid="subagent-tool-output"- className="bg-surface-muted mt-1 ml-4 rounded-md px-2 py-1.5 text-xs text-content-secondary">- <BubbleMarkdown content={output} />- </div>- ) : null}- </div>+ <AssistantUiToolCallCard+ toolName={call.toolName}+ args={call.args}+ result={call.result}+ status={call.status}+ displayName={call.displayName}+ detail={call.detail}+ elapsedMs={call.elapsedMs}+ failure={call.failure}+ />);}@@ -289,7 +128,7 @@ export function SubagentActivityBlock({<div className="ml-1 space-y-0.5" data-testid="subagent-transcript">{transcript.map((item, i) =>item.kind === 'tool' ? (- <ToolCallRow key={item.callId} call={item} />+ <ChildToolCallCard key={item.callId} call={item} />) : (<ThoughtBlock key={`thought-${i}`} text={item.text} />)@@ -298,7 +137,7 @@ export function SubagentActivityBlock({) : subagent.toolCalls.length > 0 ? (<div className="ml-1 space-y-0.5">{subagent.toolCalls.map(call => (- <ToolCallRow key={call.callId} call={call} />+ <ChildToolCallCard key={call.callId} call={call} />))}</div>) : null}diff --git a/app/src/features/conversations/components/SubagentToolCallRow.tsx b/app/src/features/conversations/components/SubagentToolCallRow.tsxindex a1da25ec8b..c2c030eefb 100644--- a/app/src/features/conversations/components/SubagentToolCallRow.tsx+++ b/app/src/features/conversations/components/SubagentToolCallRow.tsx@@ -1,20 +1,10 @@-import createDebug from 'debug';-import { useState } from 'react';-import Badge, { type BadgeVariant } from '../../../components/ui/Badge';-import {- CollapsibleContent,- CollapsibleRoot,- CollapsibleTrigger,-} from '../../../components/ui/Collapsible';import { useT } from '../../../lib/i18n/I18nContext';import type {SubagentTranscriptItem,ToolTimelineEntryStatus,} from '../../../store/chatRuntimeSlice';-import { ToolFailureLines } from './ToolFailureLines';--const log = createDebug('app:conversations:subagent-tool-call');+import { AssistantUiToolCallCard } from './AssistantUiToolCall';/** Human-readable elapsed time for a sub-agent run or one of its tool calls. */export function formatElapsed(ms: number): string {@@ -77,87 +67,21 @@ export function formatArgs(args: unknown): string | null {}}-const DETAIL_PRE =- 'max-h-60 overflow-auto whitespace-pre-wrap wrap-break-word rounded bg-surface px-2 py-1.5 ' +- 'font-mono text-[11px] leading-relaxed text-content-secondary';-const DETAIL_LABEL = 'mb-1 text-[10px] font-semibold uppercase tracking-wide text-content-faint';-/**- * One child tool call in the drawer transcript, expandable to reveal exactly- * *what happened*: the input arguments the sub-agent passed and the raw output- * the tool returned. Collapsed by default to keep the transcript scannable;- * the disclosure is only enabled once there's detail to reveal (args present,- * or the call completed with a captured result). Reopened-from-memory- * transcripts carry no args/result, so those rows stay non-expandable.- *- * The disclosure is the shared Radix {@link CollapsibleRoot} rather than a- * hand-rolled `useState` + conditional render, so the trigger carries real- * `aria-expanded` / `aria-controls` wiring instead of an ad-hoc attribute.+ * Drawer child calls use the exact assistant-ui card used by parent and inline+ * tools. The drawer no longer owns a parallel tool-call component hierarchy.*/export function SubagentToolCallRow({ item }: { item: SubagentToolItem }) {- const { t } = useT();- const [expanded, setExpanded] = useState(false);-- const statusLabel = useSubagentStatusLabel(item.status);- const argsText = formatArgs(item.args);- const hasOutput = item.result != null;- const expandable = argsText != null || hasOutput;-return (- <CollapsibleRoot- open={expandable && expanded}- onOpenChange={next => {- log('tool-call %s expanded=%s', item.toolName, next);- setExpanded(next);- }}- className="rounded-md border border-line bg-surface-muted text-xs"- data-testid="subagent-drawer-tool-call">- <CollapsibleTrigger- size="sm"- disabled={!expandable}- data-testid="subagent-tool-call-toggle"- className="justify-start gap-2 px-2.5 py-1.5 font-normal hover:bg-transparent disabled:cursor-default disabled:opacity-100">- {expandable ? (- <span aria-hidden className="shrink-0 text-[9px] text-content-faint">- {expanded ? '▾' : '▸'}- </span>- ) : (- <span className="w-[9px] shrink-0" aria-hidden />- )}- <span aria-hidden>🔧</span>- <span className="font-mono text-content-secondary">{item.toolName}</span>- <Badge variant={subagentStatusVariant(item.status)} className="ml-auto shrink-0">- {statusLabel}- </Badge>- {item.elapsedMs != null && item.status !== 'running' ? (- <span className="shrink-0 text-[10px] text-content-faint">- {formatElapsed(item.elapsedMs)}- </span>- ) : null}- </CollapsibleTrigger>- {item.status === 'error' && item.failure ? (- <div className="px-2.5 pb-1.5">- <ToolFailureLines failure={item.failure} />- </div>- ) : null}- <CollapsibleContent size="sm" className="space-y-2 border-t border-line px-2.5 py-2 pb-2">- {argsText != null ? (- <div data-testid="subagent-tool-call-input">- <div className={DETAIL_LABEL}>{t('conversations.subagent.input')}</div>- <pre className={DETAIL_PRE}>{argsText}</pre>- </div>- ) : null}- {hasOutput ? (- <div data-testid="subagent-tool-call-output">- <div className={DETAIL_LABEL}>{t('conversations.subagent.output')}</div>- <pre className={DETAIL_PRE}>- {item.result && item.result.length > 0- ? item.result- : t('conversations.subagent.noOutput')}- </pre>- </div>- ) : null}- </CollapsibleContent>- </CollapsibleRoot>+ <AssistantUiToolCallCard+ toolName={item.toolName}+ args={item.args}+ result={item.result}+ status={item.status}+ displayName={item.displayName}+ detail={item.detail}+ elapsedMs={item.elapsedMs}+ failure={item.failure}+ />);}diff --git a/app/src/features/conversations/components/__tests__/SubagentDrawer.test.tsx b/app/src/features/conversations/components/__tests__/SubagentDrawer.test.tsxindex e74f9a25ac..f885e4bdbb 100644--- a/app/src/features/conversations/components/__tests__/SubagentDrawer.test.tsx+++ b/app/src/features/conversations/components/__tests__/SubagentDrawer.test.tsx@@ -1,4 +1,4 @@-import { render, screen, waitFor } from '@testing-library/react';+import { render, screen, waitFor, within } from '@testing-library/react';import userEvent from '@testing-library/user-event';import { describe, expect, it, vi } from 'vitest';@@ -49,7 +49,7 @@ describe('SubagentDrawer', () => {// thinking → text → tool → text — i.e. the tool sits between the two// text blocks, not in a separate section.const thinking = screen.getByTestId('subagent-transcript-thinking');- const tool = screen.getByTestId('subagent-drawer-tool-call');+ const tool = screen.getByTestId('assistant-ui-tool-call');const texts = screen.getAllByTestId('subagent-transcript-text');expect(texts).toHaveLength(2);@@ -60,7 +60,7 @@ describe('SubagentDrawer', () => {expect(order(tool)).toBeLessThan(order(texts[1]));expect(thinking.textContent).toContain('comparing the two sources');- expect(tool.textContent).toContain('web_search');+ expect(tool.textContent).toContain('Searched the web');expect(tool.textContent).toContain('1.2s');expect(texts[1].textContent).toContain('The answer is');});@@ -178,7 +178,7 @@ describe('SubagentDrawer', () => {await waitFor(() =>expect(screen.getByTestId('subagent-parent-prompt').textContent).toContain('Research Q3'));- expect(screen.getByTestId('subagent-drawer-tool-call').textContent).toContain('web_search');+ expect(screen.getByTestId('assistant-ui-tool-call').textContent).toContain('Searched the web');expect(screen.getByTestId('subagent-transcript-text').textContent).toContain('Revenue grew 18%');@@ -292,15 +292,15 @@ describe('SubagentDrawer', () => {);// Collapsed by default — neither input nor output is rendered yet.- expect(screen.queryByTestId('subagent-tool-call-input')).toBeNull();- expect(screen.queryByTestId('subagent-tool-call-output')).toBeNull();+ expect(screen.queryByTestId('assistant-ui-tool-input')).toBeNull();+ expect(screen.queryByTestId('assistant-ui-tool-output')).toBeNull();- await userEvent.click(screen.getByTestId('subagent-tool-call-toggle'));+ await userEvent.click(within(screen.getByTestId('assistant-ui-tool-call')).getByRole('button'));- expect(screen.getByTestId('subagent-tool-call-input').textContent).toContain(+ expect(screen.getByTestId('assistant-ui-tool-input').textContent).toContain('Q3 revenue drivers');- expect(screen.getByTestId('subagent-tool-call-output').textContent).toContain(+ expect(screen.getByTestId('assistant-ui-tool-output').textContent).toContain('Found 3 results about revenue.');});@@ -312,8 +312,8 @@ describe('SubagentDrawer', () => {render(<SubagentDrawer subagent={activity({ transcript })} status="success" onClose={() => {}} />);- await userEvent.click(screen.getByTestId('subagent-tool-call-toggle'));- expect(screen.getByTestId('subagent-tool-call-output').textContent?.toLowerCase()).toContain(+ await userEvent.click(within(screen.getByTestId('assistant-ui-tool-call')).getByRole('button'));+ expect(screen.getByTestId('assistant-ui-tool-output').textContent?.toLowerCase()).toContain('no output');});@@ -326,7 +326,7 @@ describe('SubagentDrawer', () => {render(<SubagentDrawer subagent={activity({ transcript })} status="cancelled" onClose={() => {}} />);- const rows = screen.getAllByTestId('subagent-drawer-tool-call');+ const rows = screen.getAllByTestId('assistant-ui-tool-call');expect(rows[0].textContent?.toLowerCase()).toContain('cancelled');expect(rows[0].textContent?.toLowerCase()).not.toContain('failed');expect(rows[1].textContent?.toLowerCase()).toContain('awaiting');@@ -339,9 +339,9 @@ describe('SubagentDrawer', () => {render(<SubagentDrawer subagent={activity({ transcript })} status="success" onClose={() => {}} />);- const toggle = screen.getByTestId('subagent-tool-call-toggle') as HTMLButtonElement;- expect(toggle.disabled).toBe(true);- expect(screen.queryByTestId('subagent-tool-call-input')).toBeNull();- expect(screen.queryByTestId('subagent-tool-call-output')).toBeNull();+ const toggle = within(screen.getByTestId('assistant-ui-tool-call')).getByRole('button');+ expect(toggle).toHaveAttribute('aria-expanded', 'false');+ expect(screen.queryByTestId('assistant-ui-tool-input')).toBeNull();+ expect(screen.queryByTestId('assistant-ui-tool-output')).toBeNull();});});diff --git a/app/src/features/conversations/components/__tests__/ToolTimelineBlock.test.tsx b/app/src/features/conversations/components/__tests__/ToolTimelineBlock.test.tsxindex 98cfe6e4a2..0518f6514a 100644--- a/app/src/features/conversations/components/__tests__/ToolTimelineBlock.test.tsx+++ b/app/src/features/conversations/components/__tests__/ToolTimelineBlock.test.tsx@@ -78,22 +78,22 @@ describe('SubagentActivityBlock', () => {}}/>);- const calls = screen.getAllByTestId('subagent-tool-call');+ const calls = screen.getAllByTestId('assistant-ui-tool-call');expect(calls).toHaveLength(3);// Human labels + timing, with status as a tinted "Done" / "Failed" /// "Running" tag instead of a bare ✓/✕ glyph or the raw lowercase word.expect(calls[0].textContent).toContain('Searched the web');- expect(calls[0].textContent).toContain('Done');+ expect(calls[0].textContent?.toLowerCase()).toContain('done');expect(calls[0].textContent).toContain('312ms');expect(calls[1].textContent).toContain('Composio Execute');- expect(calls[1].textContent).toContain('Running');+ expect(calls[1].textContent?.toLowerCase()).toContain('running');expect(calls[1].textContent).not.toContain('·t2');expect(calls[2].textContent).toContain('Reading file');- expect(calls[2].textContent).toContain('Failed');+ expect(calls[2].textContent?.toLowerCase()).toContain('failed');expect(calls[2].textContent).toContain('50ms');});- it('renders subagent web output as Markdown instead of raw JSON', () => {+ it('renders subagent web output as Markdown instead of raw JSON', async () => {renderInStore(<SubagentActivityBlocksubagent={{@@ -114,7 +114,9 @@ describe('SubagentActivityBlock', () => {);expect(screen.getByText('Searched the web')).toBeInTheDocument();- expect(screen.getByTestId('subagent-tool-output')).toHaveTextContent('Formal Conjectures');+ const call = screen.getByTestId('assistant-ui-tool-call');+ await userEvent.click(within(call).getByRole('button'));+ expect(screen.getByTestId('assistant-ui-tool-output')).toHaveTextContent('Formal Conjectures');expect(screen.getByRole('strong')).toHaveTextContent('Formal Conjectures');expect(screen.queryByText(/"content"/)).not.toBeInTheDocument();});@@ -138,7 +140,7 @@ describe('SubagentActivityBlock', () => {/>);- expect(screen.getByTestId('subagent-tool-call')).toHaveTextContent('Searched the web');+ expect(screen.getByTestId('assistant-ui-tool-call')).toHaveTextContent('Searched the web');});it('labels cancelled / awaiting-user calls distinctly (not the green "Done" pill)', () => {@@ -154,13 +156,13 @@ describe('SubagentActivityBlock', () => {}}/>);- const calls = screen.getAllByTestId('subagent-tool-call');+ const calls = screen.getAllByTestId('assistant-ui-tool-call');expect(calls).toHaveLength(2);// A cancelled / awaiting-user call must NOT read as a successful "Done" step.- expect(calls[0].textContent).toContain('Cancelled');- expect(calls[0].textContent).not.toContain('Done');- expect(calls[1].textContent).toContain('Awaiting input');- expect(calls[1].textContent).not.toContain('Done');+ expect(calls[0].textContent?.toLowerCase()).toContain('cancelled');+ expect(calls[0].textContent?.toLowerCase()).not.toContain('done');+ expect(calls[1].textContent?.toLowerCase()).toContain('awaiting input');+ expect(calls[1].textContent?.toLowerCase()).not.toContain('done');});it('prefers the server-supplied label + contextual detail for a child tool call', () => {@@ -181,7 +183,7 @@ describe('SubagentActivityBlock', () => {}}/>);- const row = screen.getByTestId('subagent-tool-call');+ const row = screen.getByTestId('assistant-ui-tool-call');expect(row.textContent).toContain('Reading messages');expect(row.textContent).toContain('[email protected]');// Never the raw snake_case slug.@@ -230,7 +232,7 @@ describe('SubagentActivityBlock', () => {// Order is preserved: thought → tool → thought.expect(rows[0]).toHaveAttribute('data-testid', 'subagent-thought');expect(rows[0].textContent).toContain('I should search the web first');- expect(rows[1]).toHaveAttribute('data-testid', 'subagent-tool-call');+ expect(rows[1]).toHaveAttribute('data-testid', 'assistant-ui-tool-call');expect(rows[1].textContent).toContain('Searched the web');expect(rows[2]).toHaveAttribute('data-testid', 'subagent-thought');expect(rows[2].textContent).toContain('Found three relevant results');@@ -908,7 +910,7 @@ describe('ToolTimelineBlock — coalescing repeated rows', () => {});describe('ToolTimelineBlock — subagent rendering', () => {- it('expands a subagent row even without prompt detail and shows child tool calls', () => {+ it('shows child tool calls after the collapsed subagent row is opened', () => {const entry: ToolTimelineEntry = {id: 'tid:subagent:sub-1:researcher',name: 'subagent:researcher',@@ -926,7 +928,7 @@ describe('ToolTimelineBlock — subagent rendering', () => {};renderInStore(<ToolTimelineBlock entries={[entry]} />);- const calls = screen.getAllByTestId('subagent-tool-call');+ const calls = screen.getAllByTestId('assistant-ui-tool-call');expect(calls).toHaveLength(1);expect(calls[0].textContent).toContain('Searching the web');expect(screen.getByTestId('subagent-activity').textContent).toContain('turn 1/5');@@ -1396,19 +1398,19 @@ describe('ToolTimelineBlock — sub-agent activity survives the transcript path'expect(screen.getByTestId('processing-transcript')).toBeInTheDocument();// …and the nested child run is present, not collapsed to one line.expect(screen.getByTestId('processing-subagent')).toBeInTheDocument();- const calls = screen.getAllByTestId('subagent-tool-call');+ const calls = screen.getAllByTestId('assistant-ui-tool-call');expect(calls).toHaveLength(2);expect(calls[0].textContent).toContain('Searched the web');- expect(calls[0].textContent).toContain('Done');+ expect(calls[0].textContent?.toLowerCase()).toContain('done');// Human label, not the raw `web_fetch` slug.expect(calls[1].textContent).toContain('Fetching');- expect(calls[1].textContent).toContain('Running');+ expect(calls[1].textContent?.toLowerCase()).toContain('running');});it('still renders child tool calls on the legacy row path (no transcript)', () => {renderInStore(<ToolTimelineBlock entries={[subagentEntry]} turnActive />);expect(screen.queryByTestId('processing-transcript')).toBeNull();- expect(screen.getAllByTestId('subagent-tool-call')).toHaveLength(2);+ expect(screen.getAllByTestId('assistant-ui-tool-call')).toHaveLength(2);});// The nested child run must live INSIDE the windowed viewport, and must notdiff --git a/app/test/playwright/specs/chat-harness-subagent.spec.ts b/app/test/playwright/specs/chat-harness-subagent.spec.tsindex 3f02fbe1da..0655ee6720 100644--- a/app/test/playwright/specs/chat-harness-subagent.spec.ts+++ b/app/test/playwright/specs/chat-harness-subagent.spec.ts@@ -39,11 +39,7 @@ const KEYWORD_RESPONSES = [// contract, so the latest child user message is the rendered handoff, not// the raw tool argument.keyword: 'Run this task without requiring attention from the parent or user',- streamScript: [- { thinking: CHILD_THINKING },- { text: RESEARCHER_REPLY },- { finish: 'stop' },- ],+ streamScript: [{ thinking: CHILD_THINKING }, { text: RESEARCHER_REPLY }, { finish: 'stop' }],},{// Detached completion is delivered to the parent as a fresh background@@ -246,10 +242,7 @@ async function diagnosticsSnapshot(page: Page): Promise<DiagnosticsSnapshot> {chatRuntime?: {inferenceStatusByThread?: Record<string, { phase?: string }>;toolTimelineByThread?: Record<string, Array<{ id?: string; name?: string }>>;- turnTranscriptsByThread?: Record<- string,- Record<string, Array<{ text?: string }>>- >;+ turnTranscriptsByThread?: Record<string, Record<string, Array<{ text?: string }>>>;};thread?: {messagesByThread?: Record<string, Array<{ role?: string; content?: string }>>;@@ -366,7 +359,8 @@ test.describe('Chat Harness - Subagent', () => {const finalMessage = page.getByTestId('agent-message').filter({ hasText: CANARY_FINAL }).last();await expect(finalMessage).toBeVisible({ timeout: 15_000 });const finalReasoning = finalMessage.getByRole('button', { name: /Reasoning/ });- if ((await finalReasoning.getAttribute('aria-expanded')) !== 'true') await finalReasoning.click();+ if ((await finalReasoning.getAttribute('aria-expanded')) !== 'true')+ await finalReasoning.click();await expect(finalMessage.getByText(FINAL_THINKING, { exact: true })).toBeVisible();// Reloading removes the live socket and Redux stream. The same visual@@ -383,25 +377,18 @@ test.describe('Chat Harness - Subagent', () => {limit: 500,});expect(JSON.stringify(derived)).toContain(PARENT_THINKING);- await expect- .poll(- async () =>- JSON.stringify((await diagnosticsSnapshot(page)).runtime.turnTranscriptTexts),- { timeout: 20_000 }- )- .toContain(PARENT_THINKING);const restoredMessage = page.getByTestId('agent-message').filter({ has: page.getByTestId('assistant-ui-subagent-call') }).last();await expect(restoredMessage).toBeVisible({ timeout: 20_000 });- const restoredReasoning = restoredMessage.getByRole('button', { name: /Reasoning/ }).first();- if ((await restoredReasoning.getAttribute('aria-expanded')) !== 'true') {- await restoredReasoning.click();- }- await expect(restoredMessage.getByText(PARENT_THINKING, { exact: true })).toBeVisible();- const subagentCall = restoredMessage.getByTestId('assistant-ui-subagent-call');+ const subagentCall = page.getByTestId('assistant-ui-subagent-call').first();await expect(subagentCall).toBeVisible();+ const subagentTrigger = subagentCall.getByRole('button').first();+ await expect(subagentTrigger).toHaveAttribute('aria-expanded', 'false');+ await expect(subagentCall.getByTestId('subagent-activity')).toHaveCount(0);+ await subagentTrigger.click();+ await expect(subagentTrigger).toHaveAttribute('aria-expanded', 'true');await expect(subagentCall.getByTestId('subagent-activity')).toContainText(CHILD_THINKING);await expect(subagentCall.getByTestId('subagent-activity')).toContainText(RESEARCHER_REPLY);});