Add Codex multi-agent timeline support (#588)

* checkpoint codex multiagent UI state

* fix codex multiagent event scoping

* fix: stabilize codex subagent timeline

* chore: remove codex subagent nesting prompt

* test(web): stabilize tool result rendering tests

* fix: collapse codex agent trace rows by default

* fix(web): keep chat scrolled to bottom

* fix(web): backfill agent-run-heavy message loads

* fix(codex): fail stuck subagent spawns

* fix(codex): preserve wrapped child event scope

* fix(codex): surface agent tool completions
This commit is contained in:
SmallSpider
2026-05-07 10:46:16 +08:00
committed by GitHub
parent 0006d04f9e
commit 841b7cc035
31 changed files with 5745 additions and 152 deletions
+13 -5
View File
@@ -31,13 +31,14 @@ function ElapsedView(props: { from: number; active: boolean }) {
useEffect(() => {
if (!props.active) return
setNow(Date.now())
const id = setInterval(() => setNow(Date.now()), ELAPSED_INTERVAL_MS)
return () => clearInterval(id)
}, [props.active])
}, [props.active, props.from])
if (!props.active) return null
const elapsed = (now - props.from) / 1000
const elapsed = Math.max(0, now - props.from) / 1000
if (!Number.isFinite(elapsed)) return null
return (
@@ -296,6 +297,7 @@ function ToolCardInner(props: ToolCardProps) {
const isAskUserQuestion = isAskUserQuestionToolName(toolName)
const isRequestUserInput = isRequestUserInputToolName(toolName)
const isQuestionTool = isAskUserQuestion || isRequestUserInput
const isCodexAgentCard = toolName === 'CodexAgent'
const showsPermissionFooter = Boolean(permission && (
permission.status === 'pending'
|| ((permission.status === 'denied' || permission.status === 'canceled') && Boolean(permission.reason))
@@ -306,18 +308,24 @@ function ToolCardInner(props: ToolCardProps) {
const header = (
<div className="flex items-center justify-between gap-3">
<div className="min-w-0 flex flex-col gap-1">
<div className="min-w-0 flex flex-1 flex-col gap-1">
<div className="min-w-0 flex items-center gap-2">
<div className="shrink-0 flex h-3.5 w-3.5 items-center justify-center text-[var(--app-tool-card-accent)] leading-none">
{presentation.icon}
</div>
<CardTitle className="min-w-0 text-sm font-medium leading-tight break-words text-[var(--app-fg)]">
<CardTitle className={cn(
'min-w-0 text-sm font-medium leading-tight text-[var(--app-fg)]',
isCodexAgentCard ? 'truncate whitespace-nowrap' : 'break-words'
)}>
{toolTitle}
</CardTitle>
</div>
{subtitle ? (
<CardDescription className="font-mono text-xs break-all text-[var(--app-tool-card-subtitle)]">
<CardDescription className={cn(
'font-mono text-xs text-[var(--app-tool-card-subtitle)]',
isCodexAgentCard ? 'truncate whitespace-nowrap' : 'break-all'
)}>
{truncate(subtitle, 160)}
</CardDescription>
) : null}
+336
View File
@@ -0,0 +1,336 @@
import { isObject, safeStringify } from '@hapi/protocol'
import { getInputStringAny, truncate } from '@/lib/toolInputUtils'
export const codexAgentToolNames = [
'spawn_agent',
'send_input',
'resume_agent',
'wait_agent',
'close_agent'
] as const
export type CodexAgentToolName = typeof codexAgentToolNames[number]
export function isCodexAgentToolName(toolName: string): toolName is CodexAgentToolName {
return (codexAgentToolNames as readonly string[]).includes(toolName)
}
export function parseMaybeJsonObject(value: unknown): Record<string, unknown> | null {
if (isObject(value)) return value
if (typeof value !== 'string') return null
const trimmed = value.trim()
if (!trimmed.startsWith('{') || !trimmed.endsWith('}')) return null
try {
const parsed = JSON.parse(trimmed) as unknown
return isObject(parsed) ? parsed : null
} catch {
return null
}
}
function asNonEmptyString(value: unknown): string | null {
return typeof value === 'string' && value.trim().length > 0 ? value : null
}
function asBooleanLabel(value: unknown): string | null {
return typeof value === 'boolean' ? (value ? 'true' : 'false') : null
}
function compactText(text: string): string {
return text.replace(/\s+/g, ' ').trim()
}
function cleanAgentPromptForSummary(prompt: string): string {
const withoutTags = prompt
.replace(/<[^>\n]+>/g, ' ')
.replace(/\r/g, '\n')
const noisePatterns = [
/not alone in the codebase/i,
/do not revert/i,
/don't revert/i,
/list the file paths/i,
/changed files/i,
/final answer/i,
/avoid merge conflicts/i,
/accommodate the changes/i
]
const lines = withoutTags
.split('\n')
.map((line) => line.trim().replace(/^[-*]\s+/, '').replace(/^#{1,6}\s+/, ''))
.filter((line) => line.length > 0)
.filter((line) => !noisePatterns.some((pattern) => pattern.test(line)))
const candidate = lines.length > 0 ? lines.join(' ') : withoutTags
return compactText(candidate)
.replace(/^(task|your task|request|prompt)\s*[::]\s*/i, '')
.trim()
}
export function getCodexAgentPrompt(input: unknown): string | null {
const direct = getInputStringAny(input, ['message', 'prompt'])
if (direct) return direct
if (!isObject(input) || !Array.isArray(input.items)) return null
const textParts = input.items
.map((item) => isObject(item) && typeof item.text === 'string' ? item.text.trim() : '')
.filter((text) => text.length > 0)
return textParts.length > 0 ? textParts.join('\n\n') : null
}
export function summarizeCodexAgentPrompt(prompt: string, maxLength = 80): string | null {
const cleaned = cleanAgentPromptForSummary(prompt)
if (!cleaned) return null
return truncate(cleaned, maxLength)
}
export function getCodexAgentSummary(input: unknown): string | null {
const explicit = getInputStringAny(input, ['summary', 'title', 'description'])
if (explicit) return truncate(compactText(explicit), 80)
const prompt = getCodexAgentPrompt(input)
if (prompt) {
const summary = summarizeCodexAgentPrompt(prompt)
if (summary) return summary
}
const agentType = getCodexAgentType(input)
return agentType ? `${agentType} agent` : null
}
function getCodexAgentStatus(input: unknown): string | null {
const status = getInputStringAny(input, ['agentStatus', 'status', 'state'])
return status ? status.trim().toLowerCase() : null
}
function isTerminalCodexAgentStatus(status: string | null): boolean {
return status === 'completed'
|| status === 'failed'
|| status === 'error'
|| status === 'canceled'
|| status === 'cancelled'
}
function normalizeNonTerminalCodexAgentActivity(activity: string): string {
const replacements: Array<[RegExp, string]> = [
[/^Command completed\b/i, 'Command finished'],
[/^Tool completed\b/i, 'Tool finished'],
[/^Completed\s*:\s*/i, 'Output ready: '],
[/^Completed$/i, 'Running']
]
for (const [pattern, replacement] of replacements) {
if (pattern.test(activity)) {
return activity.replace(pattern, replacement)
}
}
return activity
}
export function getCodexAgentActivity(input: unknown): string | null {
const activity = getInputStringAny(input, ['activity', 'statusText', 'status_text', 'agentStatus'])
if (!activity) return null
const status = getCodexAgentStatus(input)
return isTerminalCodexAgentStatus(status)
? activity
: normalizeNonTerminalCodexAgentActivity(activity)
}
export function getCodexAgentReasoningEffort(input: unknown): string | null {
return getInputStringAny(input, ['reasoning_effort', 'reasoningEffort'])
}
export function formatCodexAgentReasoningEffort(effort: string): string {
const normalized = effort.trim().toLowerCase()
if (!normalized || normalized === 'default') return 'reasoning default'
return `reasoning ${normalized}`
}
export function getCodexAgentReasoningEffortLabel(input: unknown): string | null {
const effort = getCodexAgentReasoningEffort(input)
return effort ? formatCodexAgentReasoningEffort(effort) : null
}
export function getCodexAgentType(input: unknown): string | null {
return getInputStringAny(input, ['agent_type', 'subagent_type', 'type'])
}
export function getCodexAgentTargets(input: unknown): string[] {
if (!isObject(input)) return []
const targets = Array.isArray(input.targets)
? input.targets.filter((target): target is string => typeof target === 'string' && target.length > 0)
: []
if (targets.length > 0) return targets
const direct = [input.target, input.id, input.agent_id, input.agentId]
.filter((target): target is string => typeof target === 'string' && target.length > 0)
return direct
}
export function getCodexAgentFieldRows(toolName: string, input: unknown): Array<{ label: string; value: string }> {
const rows: Array<{ label: string; value: string }> = []
const agentId = isObject(input)
? asNonEmptyString(input.agentId) ?? asNonEmptyString(input.agent_id)
: null
if (agentId) rows.push({ label: 'Agent', value: agentId })
const statusText = getCodexAgentActivity(input)
if (statusText) rows.push({ label: 'Status', value: statusText })
const summary = getCodexAgentSummary(input)
if (summary) rows.push({ label: 'Work', value: summary })
const agentType = getCodexAgentType(input)
if (agentType) rows.push({ label: 'Type', value: agentType })
const model = getInputStringAny(input, ['model'])
if (model) rows.push({ label: 'Model', value: model })
const effort = getCodexAgentReasoningEffort(input)
if (effort) rows.push({ label: 'Reasoning', value: effort })
if (isObject(input)) {
const forkContext = asBooleanLabel(input.fork_context)
if (forkContext) rows.push({ label: 'Fork context', value: forkContext })
const timeout = typeof input.timeout_ms === 'number' ? `${input.timeout_ms} ms` : null
if (timeout) rows.push({ label: 'Timeout', value: timeout })
}
const targets = getCodexAgentTargets(input)
if (targets.length > 0) {
rows.push({
label: targets.length === 1 ? (toolName === 'resume_agent' ? 'Agent' : 'Target') : 'Targets',
value: targets.join(', ')
})
}
return rows
}
export type CodexSpawnAgentResult = {
agentId: string | null
nickname: string | null
}
export function parseCodexSpawnAgentResult(result: unknown): CodexSpawnAgentResult | null {
const obj = parseMaybeJsonObject(result)
if (!obj) return null
const agentId = asNonEmptyString(obj.agent_id) ?? asNonEmptyString(obj.agentId) ?? asNonEmptyString(obj.id)
const nickname = asNonEmptyString(obj.nickname) ?? asNonEmptyString(obj.name)
if (!agentId && !nickname) return null
return { agentId, nickname }
}
export type CodexAgentStatus = {
agentId: string
state: string
text: string | null
}
function extractStatusText(value: unknown): string | null {
if (typeof value === 'string') return value
if (!isObject(value)) return null
const candidates = ['completed', 'failed', 'error', 'message', 'output', 'text', 'reason']
for (const key of candidates) {
const candidate = value[key]
if (typeof candidate === 'string') return candidate
}
return safeStringify(value)
}
function extractStatusState(value: unknown): string {
if (!isObject(value)) return 'completed'
const states = ['completed', 'failed', 'error', 'canceled', 'cancelled', 'killed', 'running', 'pending']
for (const state of states) {
if (state in value) return state === 'cancelled' ? 'canceled' : state
}
const status = asNonEmptyString(value.status) ?? asNonEmptyString(value.state)
return status ?? 'completed'
}
export function parseCodexWaitAgentResult(result: unknown): { statuses: CodexAgentStatus[]; timedOut: boolean | null } | null {
const obj = parseMaybeJsonObject(result)
if (!obj) return null
const statusObj = isObject(obj.status) ? obj.status : null
const statuses: CodexAgentStatus[] = []
if (statusObj) {
for (const [agentId, statusValue] of Object.entries(statusObj)) {
statuses.push({
agentId,
state: extractStatusState(statusValue),
text: extractStatusText(statusValue)
})
}
}
const timedOut = typeof obj.timed_out === 'boolean'
? obj.timed_out
: typeof obj.timedOut === 'boolean'
? obj.timedOut
: null
if (statuses.length === 0 && timedOut === null) return null
return { statuses, timedOut }
}
export function parseCodexCloseAgentResult(result: unknown): CodexAgentStatus | null {
const obj = parseMaybeJsonObject(result)
if (!obj) return null
const previousStatus = isObject(obj.previous_status) ? obj.previous_status
: isObject(obj.previousStatus) ? obj.previousStatus
: null
if (!previousStatus) return null
return {
agentId: '',
state: extractStatusState(previousStatus),
text: extractStatusText(previousStatus)
}
}
export function summarizeCodexAgentResult(toolName: string, result: unknown): string | null {
if (toolName === 'spawn_agent') {
const parsed = parseCodexSpawnAgentResult(result)
if (!parsed) return null
const label = parsed.nickname && parsed.agentId
? `${parsed.nickname} (${parsed.agentId})`
: parsed.nickname ?? parsed.agentId
return label ? `Launched ${label}` : 'Agent launched'
}
if (toolName === 'wait_agent') {
const parsed = parseCodexWaitAgentResult(result)
if (!parsed) return null
if (parsed.statuses.length === 0 && parsed.timedOut) return 'Timed out'
const completed = parsed.statuses.filter((status) => status.state === 'completed').length
const failed = parsed.statuses.filter((status) => status.state !== 'completed').length
const parts = []
if (completed > 0) parts.push(`${completed} completed`)
if (failed > 0) parts.push(`${failed} non-completed`)
if (parsed.timedOut) parts.push('timed out')
return parts.length > 0 ? parts.join(', ') : 'No agent status yet'
}
if (toolName === 'close_agent') {
const parsed = parseCodexCloseAgentResult(result)
if (!parsed) return null
return `Closed (${parsed.state})`
}
return null
}
@@ -72,3 +72,132 @@ describe('getToolPresentation — unknown tool semantic title + subtitle dedup',
expect(presentation.subtitle).toBeNull()
})
})
describe('getToolPresentation — Codex agent tools', () => {
it('titles CodexAgent cards from work summary instead of agent id', () => {
const presentation = getToolPresentation({
toolName: 'CodexAgent',
input: {
agentId: 'agent-1234567890',
summary: '检查 Hub Web README',
activity: 'Reading file: README.md',
reasoning_effort: 'medium'
},
result: null,
childrenCount: 0,
description: null,
metadata: null,
})
expect(presentation.title).toBe('Agent: 检查 Hub Web README')
expect(presentation.title).not.toContain('agent-1234567890')
expect(presentation.subtitle).toBe('reasoning medium · Reading file: README.md')
expect(presentation.minimal).toBe(true)
})
it('shows Codex auto-selected effort on CodexAgent cards even before activity is available', () => {
const presentation = getToolPresentation({
toolName: 'CodexAgent',
input: {
summary: 'Inspect package metadata',
reasoning_effort: 'low'
},
result: null,
childrenCount: 0,
description: null,
metadata: null,
})
expect(presentation.title).toBe('Agent: Inspect package metadata')
expect(presentation.subtitle).toBe('reasoning low')
})
it('does not present sub-operation completion as final agent completion while still running', () => {
const presentation = getToolPresentation({
toolName: 'CodexAgent',
input: {
summary: 'Inspect package metadata',
agentStatus: 'running',
activity: 'Command completed: bun test',
reasoning_effort: 'low'
},
result: null,
childrenCount: 0,
description: null,
metadata: null,
})
expect(presentation.subtitle).toBe('reasoning low · Command finished: bun test')
})
it('falls back to prompt-derived CodexAgent titles without exposing agent id', () => {
const presentation = getToolPresentation({
toolName: 'CodexAgent',
input: {
agentId: 'agent-1234567890',
message: 'Fix the reducer for live agent cards.\nDo not revert other changes.'
},
result: null,
childrenCount: 0,
description: null,
metadata: null,
})
expect(presentation.title).toBe('Agent: Fix the reducer for live agent cards.')
expect(presentation.title).not.toContain('agent-1234567890')
})
it('summarizes spawn_agent with the spawned agent id', () => {
const presentation = getToolPresentation({
toolName: 'spawn_agent',
input: {
agent_type: 'worker',
message: 'Implement the parser'
},
result: '{"agent_id":"agent-123","nickname":"Raman"}',
childrenCount: 0,
description: null,
metadata: null,
})
expect(presentation.title).toBe('Spawn worker agent')
expect(presentation.subtitle).toBe('Launched Raman (agent-123)')
expect(presentation.minimal).toBe(true)
})
it('summarizes wait_agent status counts', () => {
const presentation = getToolPresentation({
toolName: 'wait_agent',
input: {
targets: ['a', 'b'],
timeout_ms: 30000
},
result: '{"status":{"a":{"completed":"done"},"b":{"failed":"boom"}},"timed_out":false}',
childrenCount: 0,
description: null,
metadata: null,
})
expect(presentation.title).toBe('Wait for 2 agents')
expect(presentation.subtitle).toBe('1 completed, 1 non-completed')
expect(presentation.minimal).toBe(true)
})
it('does not expose close_agent previous output in the collapsed subtitle', () => {
const presentation = getToolPresentation({
toolName: 'close_agent',
input: {
target: 'agent-123'
},
result: '{"previous_status":{"completed":"hidden child output"}}',
childrenCount: 0,
description: null,
metadata: null,
})
expect(presentation.title).toBe('Close agent')
expect(presentation.subtitle).toBe('Closed (completed)')
expect(presentation.subtitle).not.toContain('hidden child output')
expect(presentation.minimal).toBe(true)
})
})
@@ -6,6 +6,15 @@ import type { ChecklistItem } from '@/components/ToolCard/checklist'
import { extractTodoChecklist, extractUpdatePlanChecklist } from '@/components/ToolCard/checklist'
import { basename, resolveDisplayPath } from '@/utils/path'
import { getInputStringAny, truncate } from '@/lib/toolInputUtils'
import {
getCodexAgentActivity,
getCodexAgentPrompt,
getCodexAgentReasoningEffortLabel,
getCodexAgentSummary,
getCodexAgentTargets,
getCodexAgentType,
summarizeCodexAgentResult
} from '@/components/ToolCard/codexAgents'
const DEFAULT_ICON_CLASS = 'h-3.5 w-3.5'
// Tool presentation registry for `hapi/web` (aligned with `hapi-app`).
@@ -175,6 +184,24 @@ export const knownTools: Record<string, {
subtitle: (opts) => getInputStringAny(opts.input, ['message', 'command']) ?? null,
minimal: true
},
CodexAgent: {
icon: () => <RocketIcon className={DEFAULT_ICON_CLASS} />,
title: (opts) => {
const summary = getCodexAgentSummary(opts.input)
if (summary) return `Agent: ${summary}`
return 'Agent'
},
subtitle: (opts) => {
const activity = getCodexAgentActivity(opts.input)
const result = summarizeCodexAgentResult('wait_agent', opts.result)
const prompt = getCodexAgentPrompt(opts.input)
const status = activity ?? result ?? (prompt ? truncate(prompt, 120) : null)
const effort = getCodexAgentReasoningEffortLabel(opts.input)
if (effort && status) return `${effort} · ${status}`
return effort ?? status
},
minimal: true
},
shell_command: {
icon: () => <TerminalIcon className={DEFAULT_ICON_CLASS} />,
title: (opts) => opts.description ?? 'Terminal',
@@ -305,6 +332,63 @@ export const knownTools: Record<string, {
},
minimal: (opts) => opts.childrenCount === 0
},
spawn_agent: {
icon: () => <RocketIcon className={DEFAULT_ICON_CLASS} />,
title: (opts) => {
const agentType = getCodexAgentType(opts.input)
return agentType ? `Spawn ${agentType} agent` : 'Spawn agent'
},
subtitle: (opts) => {
const summary = summarizeCodexAgentResult(opts.toolName, opts.result)
if (summary) return summary
const agentType = getCodexAgentType(opts.input)
return agentType ? `${agentType} agent` : 'Background agent'
},
minimal: true
},
send_input: {
icon: () => <MessageSquareIcon className={DEFAULT_ICON_CLASS} />,
title: () => 'Message agent',
subtitle: (opts) => {
const targets = getCodexAgentTargets(opts.input)
return targets.length > 0 ? targets.join(', ') : 'Background message'
},
minimal: true
},
resume_agent: {
icon: () => <RocketIcon className={DEFAULT_ICON_CLASS} />,
title: () => 'Resume agent',
subtitle: (opts) => {
const targets = getCodexAgentTargets(opts.input)
return targets.length > 0 ? targets.join(', ') : null
},
minimal: true
},
wait_agent: {
icon: () => <RocketIcon className={DEFAULT_ICON_CLASS} />,
title: (opts) => {
const targets = getCodexAgentTargets(opts.input)
return targets.length > 1 ? `Wait for ${targets.length} agents` : 'Wait for agent'
},
subtitle: (opts) => {
const summary = summarizeCodexAgentResult(opts.toolName, opts.result)
if (summary) return summary
const targets = getCodexAgentTargets(opts.input)
return targets.length > 0 ? targets.join(', ') : null
},
minimal: true
},
close_agent: {
icon: () => <RocketIcon className={DEFAULT_ICON_CLASS} />,
title: () => 'Close agent',
subtitle: (opts) => {
const summary = summarizeCodexAgentResult(opts.toolName, opts.result)
if (summary) return summary
const targets = getCodexAgentTargets(opts.input)
return targets.length > 0 ? targets.join(', ') : null
},
minimal: true
},
CodexReasoning: {
icon: () => <BulbIcon className={DEFAULT_ICON_CLASS} />,
title: (opts) => getInputStringAny(opts.input, ['title']) ?? 'Reasoning',
@@ -95,6 +95,31 @@ function makeTaskBlock(
}
}
function makeCodexAgentBlock(
children: ToolCallBlock[],
state: ToolCallBlock['tool']['state'] = 'completed',
result: unknown = 'done',
): ToolCallBlock {
return {
kind: 'tool-call',
id: 'agent-1',
localId: null,
createdAt: 1000,
tool: {
id: 'agent-1',
name: 'CodexAgent',
state,
input: { message: 'inspect repo', agentId: 'subagent-1' },
createdAt: 1000,
startedAt: 1000,
completedAt: 2000,
description: null,
result,
},
children,
}
}
function makeAgentBlock(
children: ToolCallBlock[],
state: ToolCallBlock['tool']['state'] = 'completed',
@@ -309,6 +334,26 @@ describe('TraceSection', () => {
expect(screen.getByText('Result')).toBeInTheDocument()
})
it('opens CodexAgent trace by default but leaves child rows collapsed', () => {
const block = makeCodexAgentBlock([makeChild('c1', 'Bash'), makeChild('c2', 'Read')], 'completed')
const { container } = render(<TraceSection block={block} metadata={null} />)
expect(container.querySelector('button[aria-expanded="true"]')).not.toBeNull()
expect(container.querySelector('.border-l')).toBeNull()
expect(container.textContent).toContain('Terminal')
expect(container.textContent).toContain('file-c2.ts')
expect(container.textContent).not.toContain('Input')
expect(container.textContent).not.toContain('Result')
const childButtons = Array.from(container.querySelectorAll('button'))
.filter((button) => button.getAttribute('aria-expanded') === null)
expect(childButtons).toHaveLength(2)
fireEvent.click(childButtons[0])
expect(container.textContent).toContain('Input')
expect(container.textContent).toContain('Result')
})
// Agent tool name — same Trace UX as Task
it('renders Trace header for Agent blocks', () => {
const block = makeAgentBlock([makeChild('c1', 'Glob'), makeChild('c2', 'Grep')])
+125 -21
View File
@@ -4,12 +4,14 @@
*/
import { useState } from 'react'
import { isObject, safeStringify } from '@hapi/protocol'
import type { ToolCallBlock } from '@/chat/types'
import type { ChatBlock, ToolCallBlock } from '@/chat/types'
import type { SessionMetadataSummary } from '@/types/api'
import { getToolFullViewComponent } from '@/components/ToolCard/views/_all'
import { getToolResultViewComponent } from '@/components/ToolCard/views/_results'
import { formatTaskChildLabel, TaskStateIcon } from '@/components/ToolCard/helpers'
import { CodeBlock } from '@/components/CodeBlock'
import { MarkdownRenderer } from '@/components/MarkdownRenderer'
import { getEventPresentation } from '@/chat/presentation'
import { useTranslation } from '@/lib/use-translation'
import { isSubagentToolName } from '@/chat/subagentTool'
@@ -57,6 +59,13 @@ export function getTaskTraceChildren(block: ToolCallBlock): ToolCallBlock[] | nu
return children.length === 0 ? null : children
}
function getTraceChildren(block: ToolCallBlock): ChatBlock[] | null {
if (block.tool.name === 'CodexAgent') {
return block.children.length === 0 ? null : block.children
}
return getTaskTraceChildren(block)
}
/**
* Formats the summary line shown in the Trace header.
* Falls back gracefully when token / duration data is unavailable.
@@ -93,11 +102,14 @@ type TraceSectionProps = {
export function TraceSection({ block, metadata }: TraceSectionProps) {
const { t } = useTranslation()
const children = getTaskTraceChildren(block)
const children = getTraceChildren(block)
if (!children) return null
const state = block.tool.state
const defaultOpen = state === 'running' || state === 'error' || state === 'pending'
const isCodexAgentTrace = block.tool.name === 'CodexAgent'
const defaultOpen = isCodexAgentTrace || state === 'running' || state === 'error' || state === 'pending'
const fixedHeight = isCodexAgentTrace
const mode = isCodexAgentTrace ? 'session' : 'trace'
// Extract summary metadata from result using typed helper
const { totalTokens, totalDurationMs, totalToolUseCount } = readSummaryFields(block.tool.result)
@@ -111,6 +123,8 @@ export function TraceSection({ block, metadata }: TraceSectionProps) {
metadata={metadata}
defaultOpen={defaultOpen}
summaryText={summaryText}
fixedHeight={fixedHeight}
mode={mode}
/>
)
}
@@ -120,10 +134,12 @@ export function TraceSection({ block, metadata }: TraceSectionProps) {
// ---------------------------------------------------------------------------
type TraceSectionInnerProps = {
items: ToolCallBlock[]
items: ChatBlock[]
metadata: SessionMetadataSummary | null
defaultOpen: boolean
summaryText: string
fixedHeight: boolean
mode: 'trace' | 'session'
}
function TraceSectionInner({
@@ -131,6 +147,8 @@ function TraceSectionInner({
metadata,
defaultOpen,
summaryText,
fixedHeight,
mode,
}: TraceSectionInnerProps) {
const { t } = useTranslation()
const [open, setOpen] = useState(defaultOpen)
@@ -149,9 +167,11 @@ function TraceSectionInner({
<span className="font-mono font-normal opacity-70">({summaryText})</span>
</button>
{open && (
<TraceChildList items={items} metadata={metadata} />
)}
{open ? (
<div className={fixedHeight ? 'min-h-[260px] max-h-[45vh] overflow-y-auto pr-1' : undefined}>
<TraceChildList items={items} metadata={metadata} mode={mode} />
</div>
) : null}
</div>
)
}
@@ -161,24 +181,27 @@ function TraceSectionInner({
// ---------------------------------------------------------------------------
type TraceChildListProps = {
items: ToolCallBlock[]
items: ChatBlock[]
metadata: SessionMetadataSummary | null
mode: 'trace' | 'session'
}
function TraceChildList({ items, metadata }: TraceChildListProps) {
function TraceChildList({ items, metadata, mode }: TraceChildListProps) {
const [expandedId, setExpandedId] = useState<string | null>(null)
return (
<div className="flex flex-col gap-1 pl-4 border-l border-[var(--app-border)]">
<div className={mode === 'session'
? 'flex flex-col gap-3'
: 'flex flex-col gap-1 pl-4 border-l border-[var(--app-border)]'
}>
{items.map((child) => (
<TraceChildRow
key={child.id}
child={child}
metadata={metadata}
expanded={expandedId === child.id}
onToggle={() =>
setExpandedId((prev) => (prev === child.id ? null : child.id))
}
onToggle={() => setExpandedId((prev) => (prev === child.id ? null : child.id))}
mode={mode}
/>
))}
</div>
@@ -190,34 +213,115 @@ function TraceChildList({ items, metadata }: TraceChildListProps) {
// ---------------------------------------------------------------------------
type TraceChildRowProps = {
child: ToolCallBlock
child: ChatBlock
metadata: SessionMetadataSummary | null
expanded: boolean
onToggle: () => void
onToggle?: () => void
mode: 'trace' | 'session'
}
function TraceChildRow({ child, metadata, expanded, onToggle }: TraceChildRowProps) {
function TraceChildRow({ child, metadata, expanded, onToggle, mode }: TraceChildRowProps) {
const { t } = useTranslation()
const isSessionMode = mode === 'session'
const rowClassName = isSessionMode
? 'flex flex-col gap-2 rounded-xl border border-[var(--app-border)] bg-[var(--app-subtle-bg)] p-2'
: 'flex flex-col gap-1'
const detailClassName = isSessionMode
? 'rounded-lg border border-[var(--app-border)] bg-[var(--app-bg)] p-2 text-sm'
: 'ml-8 rounded border border-[var(--app-border)] p-2 text-sm'
const detailPlainClassName = isSessionMode ? '' : 'ml-8'
const chevron = onToggle ? (
<span className="w-3 text-center select-none">{expanded ? '▾' : '▸'}</span>
) : (
<span className="w-3 text-center select-none text-[var(--app-hint)]">•</span>
)
if (child.kind === 'agent-text' || child.kind === 'agent-reasoning') {
const label = child.kind === 'agent-reasoning' ? 'Reasoning' : 'Message'
const preview = child.text.trim().split('\n')[0] ?? ''
return (
<div className={rowClassName}>
<button
type="button"
className="flex items-center gap-2 text-left text-xs text-[var(--app-hint)] hover:text-[var(--app-fg)] transition-colors disabled:pointer-events-none"
onClick={onToggle}
disabled={!onToggle}
>
{chevron}
<span className="font-medium">{label}</span>
<span className="min-w-0 truncate">{preview}</span>
</button>
{expanded && (
<div className={detailClassName}>
<MarkdownRenderer content={child.text} />
</div>
)}
</div>
)
}
if (child.kind === 'cli-output') {
return (
<div className={rowClassName}>
<button
type="button"
className="flex items-center gap-2 text-left text-xs text-[var(--app-hint)] hover:text-[var(--app-fg)] transition-colors disabled:pointer-events-none"
onClick={onToggle}
disabled={!onToggle}
>
{chevron}
<span className="font-medium">Output</span>
<span className="min-w-0 truncate">{child.text.trim().split('\n')[0]}</span>
</button>
{expanded && (
<div className={detailPlainClassName}>
<CodeBlock code={child.text} language="text" />
</div>
)}
</div>
)
}
if (child.kind === 'agent-event') {
const presentation = getEventPresentation(child.event)
return (
<div className={isSessionMode
? 'flex items-center gap-2 rounded-xl border border-[var(--app-border)] bg-[var(--app-subtle-bg)] p-2 text-xs text-[var(--app-hint)]'
: 'flex items-center gap-2 text-xs text-[var(--app-hint)]'
}>
<span className="w-3 text-center select-none">•</span>
{presentation.icon ? <span aria-hidden="true">{presentation.icon}</span> : null}
<span>{presentation.text}</span>
</div>
)
}
if (child.kind !== 'tool-call') {
return null
}
const label = formatTaskChildLabel(child, metadata, t)
const FullInputView = getToolFullViewComponent(child.tool.name)
const ResultView = getToolResultViewComponent(child.tool.name)
return (
<div className="flex flex-col gap-1">
<div className={rowClassName}>
<button
type="button"
className="flex items-center gap-2 text-left text-xs text-[var(--app-hint)] hover:text-[var(--app-fg)] transition-colors"
className="flex items-center gap-2 text-left text-xs text-[var(--app-hint)] hover:text-[var(--app-fg)] transition-colors disabled:pointer-events-none"
onClick={onToggle}
disabled={!onToggle}
>
<span className="w-3 text-center select-none">{expanded ? '▾' : '▸'}</span>
{chevron}
<span className="w-4 text-center shrink-0">
<TaskStateIcon state={child.tool.state} />
</span>
<span className="font-mono break-all">{label}</span>
<span className={isSessionMode ? 'min-w-0 truncate font-mono' : 'font-mono break-all'}>{label}</span>
</button>
{expanded && (
<div className="ml-8 flex flex-col gap-2 rounded border border-[var(--app-border)] p-2">
<div className={isSessionMode ? 'flex flex-col gap-2' : 'ml-8 flex flex-col gap-2 rounded border border-[var(--app-border)] p-2'}>
<div>
<div className="mb-1 text-xs font-medium text-[var(--app-hint)]">{t('tool.input')}</div>
{FullInputView ? (
@@ -12,6 +12,11 @@ import { TodoWriteView } from '@/components/ToolCard/views/TodoWriteView'
import { UpdatePlanView } from '@/components/ToolCard/views/UpdatePlanView'
import { WriteView } from '@/components/ToolCard/views/WriteView'
import { getInputStringAny } from '@/lib/toolInputUtils'
import {
getCodexAgentFieldRows,
getCodexAgentPrompt,
summarizeCodexAgentResult
} from '@/components/ToolCard/codexAgents'
export type ToolViewProps = {
block: ToolCallBlock
@@ -30,6 +35,44 @@ const SkillFullView: ToolViewComponent = ({ block }: ToolViewProps) => {
)
}
const CodexAgentView: ToolViewComponent = ({ block, surface }: ToolViewProps) => {
const input = block.tool.input
const rows = getCodexAgentFieldRows(block.tool.name, input)
const prompt = getCodexAgentPrompt(input)
const resultSummary = surface === 'inline'
? summarizeCodexAgentResult(block.tool.name, block.tool.result)
: null
return (
<div className="flex flex-col gap-2 text-sm">
{surface === 'dialog' && prompt ? (
<div className="rounded-xl bg-[var(--app-subtle-bg)] px-3 py-2 text-[var(--app-fg)]">
<div className="mb-1 text-[11px] font-medium uppercase tracking-wide text-[var(--app-hint)]">
Prompt
</div>
<div className="whitespace-pre-wrap break-words">{prompt}</div>
</div>
) : null}
{rows.length > 0 ? (
<div className="flex flex-wrap gap-2">
{rows.map((row) => (
<span
key={`${row.label}:${row.value}`}
className="inline-flex max-w-full items-center gap-1 rounded-full border border-[var(--app-border)] bg-[var(--app-subtle-bg)] px-2 py-0.5 text-xs text-[var(--app-hint)]"
>
<span className="font-medium text-[var(--app-fg)]">{row.label}:</span>
<span className="truncate font-mono">{row.value}</span>
</span>
))}
</div>
) : null}
{resultSummary ? (
<div className="text-xs text-[var(--app-hint)]">{resultSummary}</div>
) : null}
</div>
)
}
export const toolViewRegistry: Record<string, ToolViewComponent> = {
Edit: EditView,
MultiEdit: MultiEditView,
@@ -37,6 +80,12 @@ export const toolViewRegistry: Record<string, ToolViewComponent> = {
TodoWrite: TodoWriteView,
update_plan: UpdatePlanView,
CodexDiff: CodexDiffCompactView,
CodexAgent: CodexAgentView,
spawn_agent: CodexAgentView,
send_input: CodexAgentView,
resume_agent: CodexAgentView,
wait_agent: CodexAgentView,
close_agent: CodexAgentView,
AskUserQuestion: AskUserQuestionView,
ExitPlanMode: ExitPlanModeView,
ask_user_question: AskUserQuestionView,
@@ -50,7 +99,13 @@ export const toolFullViewRegistry: Record<string, ToolViewComponent> = {
Write: WriteView,
CodexDiff: CodexDiffFullView,
CodexPatch: CodexPatchView,
CodexAgent: CodexAgentView,
Skill: SkillFullView,
spawn_agent: CodexAgentView,
send_input: CodexAgentView,
resume_agent: CodexAgentView,
wait_agent: CodexAgentView,
close_agent: CodexAgentView,
AskUserQuestion: AskUserQuestionView,
ExitPlanMode: ExitPlanModeView,
ask_user_question: AskUserQuestionView,
@@ -10,6 +10,17 @@ vi.mock('@/components/MarkdownRenderer', () => ({
)
}))
vi.mock('@/components/CodeBlock', () => ({
CodeBlock: (props: { code: string; language?: string; title?: string; className?: string }) => (
<div className={props.className}>
{props.title ? <div>{props.title}</div> : null}
<pre data-language={props.language ?? 'text'}>
<code>{props.code}</code>
</pre>
</div>
)
}))
describe('extractTextFromResult', () => {
it('returns string directly', () => {
expect(extractTextFromResult('hello')).toBe('hello')
@@ -139,6 +150,11 @@ describe('getToolResultViewComponent registry', () => {
expect(getToolResultViewComponent('CodexBash')).not.toBe(getToolResultViewComponent('SomeUnknownTool'))
})
it('uses a dedicated result view for Codex agent tools', () => {
expect(getToolResultViewComponent('spawn_agent')).not.toBe(getToolResultViewComponent('SomeUnknownTool'))
expect(getToolResultViewComponent('wait_agent')).toBe(getToolResultViewComponent('spawn_agent'))
})
it('Agent falls back to GenericResultView (no dedicated view — view layer must not filter content)', () => {
const agentView = getToolResultViewComponent('Agent')
const genericView = getToolResultViewComponent('SomeUnknownTool')
@@ -199,6 +215,138 @@ describe('dialog result formatting', () => {
})
})
describe('Codex agent result formatting', () => {
function renderToolResult(
toolName: string,
result: unknown,
input: unknown = {},
surface: 'inline' | 'dialog' = 'dialog'
) {
const ResultView = getToolResultViewComponent(toolName)
const block: ToolCallBlock = {
id: 'tool-agent',
localId: null,
createdAt: 0,
kind: 'tool-call',
children: [],
tool: {
id: 'tool-agent',
name: toolName,
state: 'completed',
input,
result,
createdAt: 0,
startedAt: null,
completedAt: 0,
description: null
}
}
return render(
<I18nProvider>
<ResultView block={block} metadata={null} surface={surface} />
</I18nProvider>
)
}
it('renders spawn_agent JSON output as launch metadata', () => {
const { container } = renderToolResult(
'spawn_agent',
'{"agent_id":"agent-123","nickname":"Singer"}'
)
expect(container).toHaveTextContent('Agent launched')
expect(container).toHaveTextContent('Singer')
expect(container).toHaveTextContent('agent-123')
})
it('renders wait_agent completion output per agent', () => {
const { container } = renderToolResult(
'wait_agent',
'{"status":{"agent-123":{"completed":"42。"}},"timed_out":false}',
{ targets: ['agent-123'] }
)
expect(container).toHaveTextContent('1 agent')
expect(container).toHaveTextContent('completed')
expect(container).toHaveTextContent('agent-123')
expect(container).toHaveTextContent('42。')
})
it('hides wait_agent completion text inline', () => {
const { container } = renderToolResult(
'wait_agent',
'{"status":{"agent-123":{"completed":"secret child output"}},"timed_out":false}',
{ targets: ['agent-123'] },
'inline'
)
expect(container).toHaveTextContent('1 agent')
expect(container).toHaveTextContent('1 completed')
expect(container).not.toHaveTextContent('agent-123')
expect(container).not.toHaveTextContent('secret child output')
})
it('renders close_agent previous status', () => {
const { container } = renderToolResult(
'close_agent',
'{"previous_status":{"completed":"done"}}',
{ target: 'agent-123' }
)
expect(container).toHaveTextContent('Agent closed')
expect(container).toHaveTextContent('agent-123')
expect(container).toHaveTextContent('done')
})
it('hides close_agent previous status text inline', () => {
const { container } = renderToolResult(
'close_agent',
'{"previous_status":{"completed":"secret close output"}}',
{ target: 'agent-123' },
'inline'
)
expect(container).toHaveTextContent('Agent closed')
expect(container).toHaveTextContent('agent-123')
expect(container).not.toHaveTextContent('secret close output')
})
it('renders CodexAgent live activity while running without a result', () => {
const ResultView = getToolResultViewComponent('CodexAgent')
const block: ToolCallBlock = {
id: 'tool-agent',
localId: null,
createdAt: 0,
kind: 'tool-call',
children: [],
tool: {
id: 'tool-agent',
name: 'CodexAgent',
state: 'running',
input: {
summary: 'Inspect README',
activity: 'Reading file: README.md'
},
result: null,
createdAt: 0,
startedAt: 0,
completedAt: null,
description: null
}
}
const { container } = render(
<I18nProvider>
<ResultView block={block} metadata={null} surface="inline" />
</I18nProvider>
)
expect(container).toHaveTextContent('Reading file: README.md')
expect(container).not.toHaveTextContent('Running…')
})
})
describe('read file result formatting', () => {
function renderToolResult(toolName: string, result: unknown, input: unknown = {}) {
const ResultView = getToolResultViewComponent(toolName)
@@ -6,6 +6,13 @@ import { MarkdownRenderer } from '@/components/MarkdownRenderer'
import { ChecklistList, extractTodoChecklist } from '@/components/ToolCard/checklist'
import { basename, resolveDisplayPath } from '@/utils/path'
import { getInputStringAny } from '@/lib/toolInputUtils'
import {
getCodexAgentActivity,
getCodexAgentTargets,
parseCodexCloseAgentResult,
parseCodexSpawnAgentResult,
parseCodexWaitAgentResult
} from '@/components/ToolCard/codexAgents'
function parseToolUseError(message: string): { isToolUseError: boolean; errorMessage: string | null } {
const regex = /<tool_use_error>(.*?)<\/tool_use_error>/s
@@ -751,6 +758,127 @@ const TodoWriteResultView: ToolViewComponent = (props: ToolViewProps) => {
return <ChecklistList items={todos} />
}
function AgentIdPill(props: { label: string; value: string }) {
return (
<ResultMetaPill>
<span className="font-sans">{props.label}: </span>
<span>{props.value}</span>
</ResultMetaPill>
)
}
const CodexAgentResultView: ToolViewComponent = (props: ToolViewProps) => {
const { name, state, result, input } = props.block.tool
const showDetails = props.surface === 'dialog'
if (result === undefined || result === null) {
return <ResultStatusPill text={getCodexAgentActivity(input) ?? placeholderForState(state)} />
}
if (state === 'error') {
const text = extractTextFromResult(result)
return (
<div className="text-sm text-red-600">
{text?.trim() ? text : 'Agent tool failed'}
</div>
)
}
if (name === 'spawn_agent') {
const parsed = parseCodexSpawnAgentResult(result)
if (parsed) {
return (
<div className="flex flex-wrap gap-2">
<ResultStatusPill text="Agent launched" />
{parsed.nickname ? <AgentIdPill label="Name" value={parsed.nickname} /> : null}
{parsed.agentId ? <AgentIdPill label="ID" value={parsed.agentId} /> : null}
{showDetails ? <RawJsonDevOnly value={result} surface={props.surface} /> : null}
</div>
)
}
}
if (name === 'wait_agent') {
const parsed = parseCodexWaitAgentResult(result)
if (parsed) {
if (parsed.statuses.length === 0) {
return <ResultStatusPill text={parsed.timedOut ? 'Timed out' : 'No status'} />
}
return (
<div className="flex flex-col gap-3">
<div className="flex flex-wrap gap-2">
{parsed.timedOut ? <ResultStatusPill text="Timed out" /> : null}
<ResultStatusPill text={`${parsed.statuses.length} agent${parsed.statuses.length === 1 ? '' : 's'}`} />
{Object.entries(parsed.statuses.reduce<Record<string, number>>((counts, status) => {
counts[status.state] = (counts[status.state] ?? 0) + 1
return counts
}, {})).map(([status, count]) => (
<ResultStatusPill key={status} text={`${count} ${status}`} />
))}
</div>
{showDetails ? (
<div className="flex flex-col gap-2">
{parsed.statuses.map((status) => (
<div key={status.agentId} className="rounded-xl border border-[var(--app-border)] bg-[var(--app-subtle-bg)] px-3 py-2">
<div className="mb-1 flex flex-wrap items-center gap-2 text-xs text-[var(--app-hint)]">
<ResultStatusPill text={status.state} />
<span className="font-mono break-all">{status.agentId}</span>
</div>
{status.text ? (
<div className="text-sm text-[var(--app-fg)]">
{renderText(status.text, { mode: 'auto', collapseLongContent: props.surface === 'inline', surface: props.surface })}
</div>
) : null}
</div>
))}
</div>
) : null}
{showDetails ? <RawJsonDevOnly value={result} surface={props.surface} /> : null}
</div>
)
}
}
if (name === 'close_agent') {
const parsed = parseCodexCloseAgentResult(result)
if (parsed) {
const targets = getCodexAgentTargets(input)
return (
<div className="flex flex-col gap-2">
<div className="flex flex-wrap gap-2">
<ResultStatusPill text="Agent closed" />
{targets[0] ? <AgentIdPill label="ID" value={targets[0]} /> : null}
<ResultStatusPill text={parsed.state} />
</div>
{showDetails && parsed.text ? (
<div className="text-sm text-[var(--app-fg)]">
{renderText(parsed.text, { mode: 'auto', collapseLongContent: props.surface === 'inline', surface: props.surface })}
</div>
) : null}
{showDetails ? <RawJsonDevOnly value={result} surface={props.surface} /> : null}
</div>
)
}
}
const text = extractTextFromResult(result)
if (text) {
if (!showDetails) {
return <ResultStatusPill text={state === 'completed' ? 'Done' : placeholderForState(state)} />
}
return (
<>
{renderText(text, { mode: 'auto', collapseLongContent: props.surface === 'inline', surface: props.surface })}
{typeof result === 'object' ? <RawJsonDevOnly value={result} surface={props.surface} /> : null}
</>
)
}
return <ResultStatusPill text={state === 'completed' ? 'Done' : placeholderForState(state)} />
}
const SkillResultView: ToolViewComponent = (props: ToolViewProps) => {
const { state, result, input } = props.block.tool
@@ -848,7 +976,13 @@ export const toolResultViewRegistry: Record<string, ToolViewComponent> = {
CodexReasoning: CodexReasoningResultView,
CodexPatch: CodexPatchResultView,
CodexDiff: CodexDiffResultView,
CodexAgent: CodexAgentResultView,
Skill: SkillResultView,
spawn_agent: CodexAgentResultView,
send_input: CodexAgentResultView,
resume_agent: CodexAgentResultView,
wait_agent: CodexAgentResultView,
close_agent: CodexAgentResultView,
AskUserQuestion: AskUserQuestionResultView,
ExitPlanMode: MarkdownResultView,
ask_user_question: AskUserQuestionResultView,