Skip to content

The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.

fix(chat): preserve and render complete agent turn traces\n\n

Steven Enamakel5fbfad1d01ea
diff --git a/app/src/features/conversations/components/ChatToolParts.test.tsx b/app/src/features/conversations/components/ChatToolParts.test.tsx
index c2c131b78d..63162031e8 100644
--- a/app/src/features/conversations/components/ChatToolParts.test.tsx
+++ b/app/src/features/conversations/components/ChatToolParts.test.tsx
@@ -1,4 +1,5 @@
import { render, screen } from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
import { describe, expect, it } from 'vitest';
import type { SubagentActivity } from '../../../store/chatRuntimeSlice';
@@ -43,4 +44,47 @@ describe('ChatToolParts', () => {
expect(screen.getByText('live delegation')).toBeVisible();
});
+
+ it('renders ordinary tools with rich input and output on the assistant-ui surface', async () => {
+ render(
+ <ChatToolFallback
+ type="tool-call"
+ toolName="web_search_tool"
+ toolCallId="search-1"
+ args={{ query: 'Lean open conjectures' } as never}
+ argsText={'{"query":"Lean open conjectures"}'}
+ result="Found 12 candidate problems"
+ status={{ type: 'complete' }}
+ addResult={() => {}}
+ resume={() => {}}
+ respondToApproval={() => {}}
+ />
+ );
+
+ expect(screen.getByTestId('assistant-ui-tool-call')).toHaveTextContent('Searched the web');
+ await userEvent.click(screen.getByRole('button', { name: /Searched the web/ }));
+ expect(screen.getByText(/Lean open conjectures/)).toBeInTheDocument();
+ expect(screen.getByText('Found 12 candidate problems')).toBeInTheDocument();
+ });
+
+ it('unwraps a single content field instead of showing a redundant title', async () => {
+ render(
+ <ChatToolFallback
+ type="tool-call"
+ toolName="web_fetch"
+ toolCallId="fetch-1"
+ args={{} as never}
+ argsText="{}"
+ result={{ content: '**Example Domain**', tool_call_id: 'fetch-1', success: true }}
+ status={{ type: 'complete' }}
+ addResult={() => {}}
+ resume={() => {}}
+ respondToApproval={() => {}}
+ />
+ );
+
+ await userEvent.click(screen.getByRole('button', { name: /Fetched from the web/ }));
+ expect(screen.getByRole('strong')).toHaveTextContent('Example Domain');
+ expect(screen.queryByText('Content', { exact: true })).not.toBeInTheDocument();
+ });
});
diff --git a/app/src/features/conversations/components/ChatToolParts.tsx b/app/src/features/conversations/components/ChatToolParts.tsx
index 69c06ec5fa..0f0097bf35 100644
--- a/app/src/features/conversations/components/ChatToolParts.tsx
+++ b/app/src/features/conversations/components/ChatToolParts.tsx
@@ -1,10 +1,9 @@
import type { ToolCallMessagePartComponent } from '@assistant-ui/react';
-import { CheckIcon, ChevronDownIcon, Loader2Icon, WorkflowIcon } from 'lucide-react';
+import { CheckIcon, ChevronDownIcon, Loader2Icon, WrenchIcon, WorkflowIcon } from 'lucide-react';
import type { FC, PropsWithChildren } from 'react';
import { cn } from '../../../components/assistant-ui/lib/utils';
import type { ThreadGroupPart } from '../../../components/assistant-ui/thread';
-import { ToolFallback } from '../../../components/assistant-ui/tool-fallback';
import {
ToolGroupContent,
ToolGroupRoot,
@@ -16,6 +15,8 @@ import {
CollapsibleTrigger,
} from '../../../components/assistant-ui/ui/collapsible';
import type { SubagentActivity } from '../../../store/chatRuntimeSlice';
+import { formatToolName } from '../../../utils/toolTimelineFormatting';
+import { BubbleMarkdown } from './AgentMessageBubble';
import { SubagentActivityBlock } from './SubagentActivityBlock';
function asSubagentActivity(value: unknown): SubagentActivity | undefined {
@@ -57,6 +58,7 @@ export const SubagentCall: ToolCallMessagePartComponent = ({ args, result }) =>
return (
<Collapsible
data-slot="aui_subagent-call"
+ data-testid="assistant-ui-subagent-call"
defaultOpen
className={cn(
'aui-subagent-call border-border/60 dark:border-muted-foreground/15 rounded-xl border',
@@ -90,18 +92,149 @@ export const SubagentCall: ToolCallMessagePartComponent = ({ args, result }) =>
);
};
-/** Route delegations to the rich renderer and ordinary tools to assistant-ui. */
+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): string {
+ if (toolName === 'web_fetch') return running ? 'Fetching from the web' : 'Fetched from the web';
+ if (toolName === 'web_search_tool' || toolName === 'web_search') {
+ return running ? 'Searching the web' : 'Searched 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']) {
+ 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)}
+ </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} /> : <ToolFallback {...props} />;
+ props.toolName === 'task' ? <SubagentCall {...props} /> : <OpenHumanToolCall {...props} />;
-/** Keep a tool group open while any contained call is still running. */
+/** Keep the assistant-ui tool cards visible; each card owns its detail collapse. */
export const ChatToolGroup: FC<PropsWithChildren<{ group: ThreadGroupPart }>> = ({
group,
children,
}) => {
const running = group.status.type === 'running';
return (
- <ToolGroupRoot variant="ghost" defaultOpen={running}>
+ <ToolGroupRoot variant="ghost" defaultOpen>
<ToolGroupTrigger count={group.indices.length} active={running} />
<ToolGroupContent>{children}</ToolGroupContent>
</ToolGroupRoot>
diff --git a/app/src/features/conversations/components/SubagentActivityBlock.tsx b/app/src/features/conversations/components/SubagentActivityBlock.tsx
index a907f19351..d3b4d429d7 100644
--- a/app/src/features/conversations/components/SubagentActivityBlock.tsx
+++ b/app/src/features/conversations/components/SubagentActivityBlock.tsx
@@ -37,6 +37,38 @@ function toolCallTone(status: ToolTimelineEntryStatus): string {
return 'text-coral-700 dark:text-coral-300';
}
+function subagentToolLabel(name: string, status: ToolTimelineEntryStatus): string {
+ const running = status === 'running';
+ if (name === 'web_fetch') return running ? 'Fetching from the web' : 'Fetched from the web';
+ if (name === 'web_search_tool' || name === 'web_search') {
+ return running ? 'Searching the web' : 'Searched 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);
+}
+
/**
* 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
@@ -82,8 +114,11 @@ export function ToolCallRow({
detail?: string;
/** Structured why/next explanation for a FAILED child tool call (#4459). */
failure?: ToolFailureExplanation;
+ /** Child tool output, rendered as Markdown when present. */
+ result?: unknown;
};
}) {
+ const output = readableToolOutput(call.result);
return (
<div className="min-w-0" data-testid="subagent-tool-call">
<div className="flex min-w-0 items-center gap-1.5">
@@ -91,7 +126,7 @@ export function ToolCallRow({
•
</span>
<span className="shrink-0 text-[12px] whitespace-nowrap text-content-secondary">
- {call.displayName ?? formatToolName(call.toolName)}
+ {call.displayName ?? subagentToolLabel(call.toolName, call.status)}
</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
@@ -117,6 +152,13 @@ export function ToolCallRow({
) : 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>
);
}
diff --git a/app/src/features/conversations/components/__tests__/ToolTimelineBlock.test.tsx b/app/src/features/conversations/components/__tests__/ToolTimelineBlock.test.tsx
index 19e13fb219..f263631005 100644
--- a/app/src/features/conversations/components/__tests__/ToolTimelineBlock.test.tsx
+++ b/app/src/features/conversations/components/__tests__/ToolTimelineBlock.test.tsx
@@ -82,7 +82,7 @@ describe('SubagentActivityBlock', () => {
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('Searching the web');
+ expect(calls[0].textContent).toContain('Searched the web');
expect(calls[0].textContent).toContain('Done');
expect(calls[0].textContent).toContain('312ms');
expect(calls[1].textContent).toContain('Composio Execute');
@@ -93,6 +93,32 @@ describe('SubagentActivityBlock', () => {
expect(calls[2].textContent).toContain('50ms');
});
+ it('renders subagent web output as Markdown instead of raw JSON', () => {
+ renderInStore(
+ <SubagentActivityBlock
+ subagent={{
+ taskId: 't',
+ agentId: 'researcher',
+ toolCalls: [],
+ transcript: [
+ {
+ kind: 'tool',
+ callId: 'search-1',
+ toolName: 'web_search_tool',
+ status: 'success',
+ result: JSON.stringify({ content: '**Formal Conjectures**\n\n- OEIS Open' }),
+ },
+ ],
+ }}
+ />
+ );
+
+ expect(screen.getByText('Searched the web')).toBeInTheDocument();
+ expect(screen.getByTestId('subagent-tool-output')).toHaveTextContent('Formal Conjectures');
+ expect(screen.getByRole('strong')).toHaveTextContent('Formal Conjectures');
+ expect(screen.queryByText(/"content"/)).not.toBeInTheDocument();
+ });
+
it('labels cancelled / awaiting-user calls distinctly (not the green "Done" pill)', () => {
renderInStore(
<SubagentActivityBlock
@@ -183,7 +209,7 @@ describe('SubagentActivityBlock', () => {
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].textContent).toContain('Searching the web');
+ 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');
});
@@ -1350,7 +1376,7 @@ describe('ToolTimelineBlock — sub-agent activity survives the transcript path'
expect(screen.getByTestId('processing-subagent')).toBeInTheDocument();
const calls = screen.getAllByTestId('subagent-tool-call');
expect(calls).toHaveLength(2);
- expect(calls[0].textContent).toContain('Searching the web');
+ expect(calls[0].textContent).toContain('Searched the web');
expect(calls[0].textContent).toContain('Done');
// Human label, not the raw `web_fetch` slug.
expect(calls[1].textContent).toContain('Fetching');
diff --git a/app/src/providers/ChatRuntimeProvider.tsx b/app/src/providers/ChatRuntimeProvider.tsx
index 87b97da7af..59ee25f279 100644
--- a/app/src/providers/ChatRuntimeProvider.tsx
+++ b/app/src/providers/ChatRuntimeProvider.tsx
@@ -39,6 +39,7 @@ import {
clearProcessingForThread,
clearStreamingAssistantForThread,
endInferenceTurn,
+ fetchAndHydrateCompletedTurnState,
fetchAndHydrateDerivedTranscript,
markInferenceTurnStreaming,
parseToolFailure,
@@ -473,6 +474,13 @@ const ChatRuntimeProvider = ({ children }: { children: React.ReactNode }) => {
await flushQueuedFollowups(event.thread_id);
dispatch(endInferenceTurn({ threadId: event.thread_id }));
dispatch(clearThreadInferenceActive(event.thread_id));
+ // Socket reducers keep only the current iteration's prose in the live
+ // buffer. Once the turn settles, replace that partial projection with
+ // the core's completed snapshot, whose ordered transcript contains every
+ // parent and sub-agent event from the whole turn. Doing this here (after
+ // ending the live lifecycle) matters: `hydrateRuntimeFromSnapshot`
+ // intentionally refuses to overwrite an actively streaming turn.
+ await dispatch(fetchAndHydrateCompletedTurnState(event.thread_id));
// Live-turn seam: the turn just settled and its line was appended to the
// append-only transcript. Invalidate/refresh the thread's derived
// settled-turn trails so the next reopen is fresh. The just-finished turn
diff --git a/app/src/providers/__tests__/assistantUiMessages.test.ts b/app/src/providers/__tests__/assistantUiMessages.test.ts
index 6a975f51d6..ce4313ecaf 100644
--- a/app/src/providers/__tests__/assistantUiMessages.test.ts
+++ b/app/src/providers/__tests__/assistantUiMessages.test.ts
@@ -133,6 +133,25 @@ describe('buildRuntimeMessages', () => {
expect(ids).toEqual(['a', STREAMING_TAIL_ID]);
});
+ it('does not keep a synthetic thinking/tool tail running after lifecycle completion', () => {
+ const projected = buildRuntimeMessages([msg({ id: 'answer', sender: 'agent' })], null, {
+ isRunning: false,
+ liveTimeline: [tool({ id: 'stale-tool', status: 'success' })],
+ liveTranscript: [
+ { kind: 'thinking', round: 1, seq: 0, text: 'already finished thinking' },
+ ],
+ });
+ const ids = projected.map(message => message.id);
+
+ expect(ids).toEqual(['answer']);
+ expect(ids).not.toContain(STREAMING_TAIL_ID);
+ expect(projected[0]?.content).toEqual([
+ { type: 'reasoning', text: 'already finished thinking' },
+ expect.objectContaining({ type: 'tool-call', toolCallId: 'stale-tool' }),
+ { type: 'text', text: 'hello' },
+ ]);
+ });
+
it('replays a settled turn reasoning and tool calls from its request id', () => {
const answer = msg({
id: 'answer',
@@ -143,7 +162,8 @@ describe('buildRuntimeMessages', () => {
const timeline = [tool({ id: 'call-1', status: 'success', result: 'found it' })];
const transcript = [
{ kind: 'thinking' as const, round: 1, seq: 0, text: 'need to search' },
- { kind: 'toolCall' as const, round: 1, seq: 1, callId: 'call-1' },
+ { kind: 'narration' as const, round: 1, seq: 1, text: 'I will check the sources.' },
+ { kind: 'toolCall' as const, round: 1, seq: 2, callId: 'call-1' },
];
expect(
@@ -153,6 +173,7 @@ describe('buildRuntimeMessages', () => {
})[0]?.content
).toEqual([
{ type: 'reasoning', text: 'need to search' },
+ { type: 'text', text: 'I will check the sources.' },
expect.objectContaining({
type: 'tool-call',
toolCallId: 'call-1',
@@ -163,6 +184,31 @@ describe('buildRuntimeMessages', () => {
]);
});
+ it('chronologically anchors persisted trails to async agent messages without request ids', () => {
+ const acknowledgement = msg({
+ id: 'ack',
+ sender: 'agent',
+ content: 'Accepted background work',
+ extraMetadata: {},
+ });
+ const content = buildRuntimeMessages([acknowledgement], null, {
+ isRunning: false,
+ turnTimelines: { 'request-async': [tool({ id: 'async-tool', status: 'success' })] },
+ turnTranscripts: {
+ 'request-async': [
+ { kind: 'thinking', round: 1, seq: 0, text: 'delegate this research' },
+ { kind: 'toolCall', round: 1, seq: 1, callId: 'async-tool' },
+ ],
+ },
+ })[0]?.content;
+
+ expect(content).toEqual([
+ { type: 'reasoning', text: 'delegate this research' },
+ expect.objectContaining({ type: 'tool-call', toolCallId: 'async-tool' }),
+ { type: 'text', text: 'Accepted background work' },
+ ]);
+ });
+
/**
* The crash this guards: assistant-ui keys tool parts as `toolCallId-${id}`
* and throws "Duplicate key … in useResources" on a repeat, taking the whole
diff --git a/app/src/providers/assistantUiMessages.ts b/app/src/providers/assistantUiMessages.ts
index b2a837174e..884fb49e08 100644
--- a/app/src/providers/assistantUiMessages.ts
+++ b/app/src/providers/assistantUiMessages.ts
@@ -140,9 +140,13 @@ function assistantParts(
parts.push(toolPart(entry));
}
}
- // Narration is process commentary, not the final assistant answer. The
- // legacy pane keeps it in the processing view; projecting it as ordinary
- // text here would duplicate prose around the persisted final response.
+ if (item.kind === 'narration' && item.text.trim().length > 0) {
+ // Narration emitted before a tool call is assistant content in its own
+ // right. Keep it inline in assistant-ui's ordered part stream; the final
+ // answer is appended separately below, so this preserves the real turn
+ // sequence without relying on the removed legacy processing pane.
+ parts.push({ type: 'text', text: item.text });
+ }
}
for (const entry of [...timeline].sort((a, b) => a.seq - b.seq)) {
@@ -260,6 +264,8 @@ export function streamingTailMessage(
}
export type AssistantUiProjection = {
+ /** Whether the synthetic live tail has an active core turn driving it. */
+ isRunning?: boolean;
liveTimeline?: readonly ToolTimelineEntry[];
liveTranscript?: readonly ProcessingTranscriptItem[];
turnTimelines?: Readonly<Record<string, readonly ToolTimelineEntry[]>>;
@@ -280,25 +286,71 @@ export function buildRuntimeMessages(
projection: AssistantUiProjection = {}
): ThreadMessageLike[] {
const out: ThreadMessageLike[] = [];
+ const claimedRequestIds = new Set(
+ messages.flatMap(message =>
+ message.sender === 'agent' && typeof message.extraMetadata?.requestId === 'string'
+ ? [message.extraMetadata.requestId]
+ : []
+ )
+ );
+ const projectedRequestIds = [
+ ...new Set([
+ ...Object.keys(projection.turnTimelines ?? {}),
+ ...Object.keys(projection.turnTranscripts ?? {}),
+ ]),
+ ].filter(requestId => !claimedRequestIds.has(requestId));
+ let orphanRequestCursor = 0;
+ const lastVisibleAgentId = [...messages]
+ .reverse()
+ .find(message => message.sender === 'agent' && !message.extraMetadata?.hidden)?.id;
for (const msg of messages) {
if (msg.extraMetadata?.hidden) continue;
const requestId =
msg.sender === 'agent' && typeof msg.extraMetadata?.requestId === 'string'
? msg.extraMetadata.requestId
: undefined;
+ // Async acknowledgements/background deliveries can be persisted without
+ // message-level request metadata. The transcript maps are chronological
+ // and request-keyed, so pair only unclaimed trails with unanchored agent
+ // messages in the same order instead of dropping them from assistant-ui.
+ const effectiveRequestId =
+ requestId ??
+ (msg.sender === 'agent' ? projectedRequestIds[orphanRequestCursor++] : undefined);
+ const persistedTimeline = effectiveRequestId
+ ? projection.turnTimelines?.[effectiveRequestId]
+ : undefined;
+ const persistedTranscript = effectiveRequestId
+ ? projection.turnTranscripts?.[effectiveRequestId]
+ : undefined;
+ // `chat_done` clears the active lifecycle before the completed snapshot is
+ // indexed into the request maps. Keep the just-settled tools/reasoning on
+ // the final assistant message during that handoff; never mint a running
+ // synthetic tail for them.
+ const useSettledLiveFallback =
+ projection.isRunning === false &&
+ msg.id === lastVisibleAgentId &&
+ !persistedTimeline &&
+ !persistedTranscript;
out.push(
toThreadMessageLike(
msg,
- requestId ? (projection.turnTimelines?.[requestId] ?? EMPTY_TIMELINE) : EMPTY_TIMELINE,
- requestId ? (projection.turnTranscripts?.[requestId] ?? EMPTY_TRANSCRIPT) : EMPTY_TRANSCRIPT
+ persistedTimeline ??
+ (useSettledLiveFallback ? (projection.liveTimeline ?? EMPTY_TIMELINE) : EMPTY_TIMELINE),
+ persistedTranscript ??
+ (useSettledLiveFallback
+ ? (projection.liveTranscript ?? EMPTY_TRANSCRIPT)
+ : EMPTY_TRANSCRIPT)
)
);
}
- const tail = streamingTailMessage(
- streaming,
- projection.liveTimeline ?? EMPTY_TIMELINE,
- projection.liveTranscript ?? EMPTY_TRANSCRIPT
- );
+ const tail =
+ projection.isRunning === false
+ ? null
+ : streamingTailMessage(
+ streaming,
+ projection.liveTimeline ?? EMPTY_TIMELINE,
+ projection.liveTranscript ?? EMPTY_TRANSCRIPT
+ );
if (tail) out.push(tail);
return out;
}
diff --git a/app/src/providers/useOpenHumanExternalStore.ts b/app/src/providers/useOpenHumanExternalStore.ts
index 60390f2fe1..ac93161d73 100644
--- a/app/src/providers/useOpenHumanExternalStore.ts
+++ b/app/src/providers/useOpenHumanExternalStore.ts
@@ -59,25 +59,26 @@ export function useOpenHumanExternalStore(threadId: string | null) {
: EMPTY_TURN_MAP
);
+ // `started` and `streaming` are both in-flight. A completed turn can retain
+ // its tool/reasoning arrays while the persisted projection catches up; those
+ // arrays must not mint a forever-running assistant-ui tail.
+ const isRunning = lifecycle === 'started' || lifecycle === 'streaming';
+
// Recomputed only when the settled transcript or the live tail changes.
// Settled messages are converted through an identity-keyed cache, so a token
// landing on the tail re-converts exactly one message, never the transcript.
const runtimeMessages = useMemo(
() =>
buildRuntimeMessages(messages, streaming, {
+ isRunning,
liveTimeline,
liveTranscript,
turnTimelines,
turnTranscripts,
}),
- [messages, streaming, liveTimeline, liveTranscript, turnTimelines, turnTranscripts]
+ [messages, streaming, isRunning, liveTimeline, liveTranscript, turnTimelines, turnTranscripts]
);
- // `started` and `streaming` are both in-flight; the row is deleted on
- // completion, so a present lifecycle (other than the cold-boot `interrupted`
- // marker, which has no live driver) means a turn is running.
- const isRunning = lifecycle === 'started' || lifecycle === 'streaming';
-
const onNew = useCallback(
async (message: AppendMessage) => {
const surface = getChatSurface(threadId);
diff --git a/app/src/store/__tests__/chatRuntimeSlice.derived.thunk.test.ts b/app/src/store/__tests__/chatRuntimeSlice.derived.thunk.test.ts
index 07bf2c63e8..d575b6affa 100644
--- a/app/src/store/__tests__/chatRuntimeSlice.derived.thunk.test.ts
+++ b/app/src/store/__tests__/chatRuntimeSlice.derived.thunk.test.ts
@@ -46,7 +46,7 @@ beforeEach(() => {
});
describe('fetchAndHydrateDerivedTranscript', () => {
- it('hydrates settled-turn trails from the projection, skipping the newest turn', async () => {
+ it('hydrates every settled trail when no request is actively streaming', async () => {
const store = configureStore({ reducer });
mockThreadApi.getDerivedTranscript.mockResolvedValueOnce(
page(
@@ -66,10 +66,9 @@ describe('fetchAndHydrateDerivedTranscript', () => {
expect(mockThreadApi.getTurnStateHistory).not.toHaveBeenCalled();
const timelines = store.getState().turnTimelinesByThread['thread-1'];
const transcripts = store.getState().turnTranscriptsByThread['thread-1'];
- // Newest turn (req-new) is skipped — rendered by the live anchor.
- expect(Object.keys(transcripts)).toEqual(['req-old']);
+ expect(Object.keys(transcripts)).toEqual(['req-old', 'req-new']);
expect(timelines['req-old']).toHaveLength(1);
- expect(transcripts['req-new']).toBeUndefined();
+ expect(transcripts['req-new']).toHaveLength(1);
expect(timelines['req-new']).toBeUndefined();
});
@@ -133,9 +132,9 @@ describe('fetchAndHydrateDerivedTranscript', () => {
await store.dispatch(fetchAndHydrateDerivedTranscript('thread-1'));
const transcripts = store.getState().turnTranscriptsByThread['thread-1'];
- // req-new skipped (newest), req-mid skipped (streaming), req-old kept.
- expect(Object.keys(transcripts)).toEqual(['req-old']);
+ // Only the genuinely streaming request is skipped.
+ expect(Object.keys(transcripts)).toEqual(['req-old', 'req-new']);
expect(transcripts['req-mid']).toBeUndefined();
- expect(transcripts['req-new']).toBeUndefined();
+ expect(transcripts['req-new']).toHaveLength(1);
});
});
diff --git a/app/src/store/chatRuntimeSlice.ts b/app/src/store/chatRuntimeSlice.ts
index 102f3691ba..2656796850 100644
--- a/app/src/store/chatRuntimeSlice.ts
+++ b/app/src/store/chatRuntimeSlice.ts
@@ -3,7 +3,7 @@ import debug from 'debug';
import { mapDisplayItems } from '../features/conversations/derived/mapDisplayItems';
import { threadApi } from '../services/api/threadApi';
-import type { DerivedDisplayItem, DerivedTranscriptPage } from '../types/derivedTranscript';
+import type { DerivedTranscriptPage } from '../types/derivedTranscript';
import type { ThreadMessage } from '../types/thread';
import type {
AgentRun,
@@ -870,6 +870,29 @@ function subagentTranscriptItemFromPersisted(
}
function subagentActivityFromPersisted(activity: PersistedSubagentActivity): SubagentActivity {
+ const toolCalls = activity.toolCalls.map(subagentToolCallFromPersisted);
+ const transcript =
+ activity.transcript && activity.transcript.length > 0
+ ? activity.transcript.map(item => {
+ const mapped = subagentTranscriptItemFromPersisted(item);
+ if (mapped.kind !== 'tool') return mapped;
+ const call = toolCalls.find(candidate => candidate.callId === mapped.callId);
+ return call
+ ? { ...mapped, args: call.args, result: call.result, failure: call.failure }
+ : mapped;
+ })
+ : toolCalls.map(call => ({
+ kind: 'tool' as const,
+ iteration: call.iteration,
+ callId: call.callId,
+ toolName: call.toolName,
+ status: call.status,
+ elapsedMs: call.elapsedMs,
+ outputChars: call.outputChars,
+ args: call.args,
+ result: call.result,
+ failure: call.failure,
+ }));
return {
taskId: activity.taskId,
agentId: activity.agentId,
@@ -882,23 +905,12 @@ function subagentActivityFromPersisted(activity: PersistedSubagentActivity): Sub
iterations: activity.iterations,
elapsedMs: activity.elapsedMs,
outputChars: activity.outputChars,
- toolCalls: activity.toolCalls.map(subagentToolCallFromPersisted),
+ toolCalls,
// Prefer the persisted prose transcript (reasoning/narration interleaved
// with tools) so a settled / reloaded run replays its thoughts. Fall back
// to a tool-only rebuild for snapshots written before sub-agent prose was
// persisted (the `transcript` field is absent there).
- transcript:
- activity.transcript && activity.transcript.length > 0
- ? activity.transcript.map(subagentTranscriptItemFromPersisted)
- : activity.toolCalls.map(call => ({
- kind: 'tool' as const,
- iteration: call.iteration,
- callId: call.callId,
- toolName: call.toolName,
- status: call.status,
- elapsedMs: call.elapsedMs,
- outputChars: call.outputChars,
- })),
+ transcript,
};
}
@@ -2382,6 +2394,34 @@ export const fetchAndHydrateTurnState = createAsyncThunk(
}
);
+/**
+ * Wait briefly for the progress bridge to flush its terminal snapshot, then
+ * hydrate it. `chat_done` is delivered by the response presenter while the
+ * bridge may still be consuming the final `TurnCompleted` event; reading once
+ * at that boundary can otherwise install an intermediate, last-round-only
+ * transcript over the just-settled UI.
+ */
+export const fetchAndHydrateCompletedTurnState = createAsyncThunk(
+ 'chatRuntime/fetchAndHydrateCompletedTurnState',
+ async (threadId: string, { dispatch }) => {
+ for (let attempt = 0; attempt < 20; attempt += 1) {
+ try {
+ const snapshot = await threadApi.getTurnState(threadId);
+ if (snapshot?.lifecycle === 'completed') {
+ dispatch(hydrateRuntimeFromSnapshot({ snapshot }));
+ return snapshot;
+ }
+ } catch (error) {
+ turnStateLog('completed snapshot fetch failed thread=%s err=%O', threadId, error);
+ return null;
+ }
+ await new Promise(resolve => window.setTimeout(resolve, 50));
+ }
+ turnStateLog('completed snapshot did not arrive thread=%s', threadId);
+ return null;
+ }
+);
+
/**
* Fetch the per-turn history for a thread and populate
* {@link ChatRuntimeState.turnTimelinesByThread} so each *past* answer renders
@@ -2466,31 +2506,14 @@ function readChatRuntimeState(state: unknown): ChatRuntimeState | undefined {
}
/**
- * The request ids whose derived trail must NOT be hydrated: the newest turn
- * (rendered as the live "agent insights" anchor from `toolTimelineByThread` /
- * the socket stream, or the `turn_state` snapshot via
- * {@link fetchAndHydrateTurnState}) and any turn currently streaming. Mirrors
- * `fetchAndHydrateTurnHistory`'s `history.slice(1)` newest-turn skip.
+ * The request ids whose derived trail must NOT be hydrated: only turns that
+ * are provably active in this renderer. Do not infer "live" from whichever
+ * request happens to be newest in one transcript file: detached/background
+ * delivery runs in a separate session, so the root file's newest request can
+ * already be historical and must remain visible.
*/
-function liveRequestIdsToSkip(
- state: unknown,
- threadId: string,
- items: DerivedDisplayItem[]
-): Set<string> {
+function liveRequestIdsToSkip(state: unknown, threadId: string): Set<string> {
const skip = new Set<string>();
- // Newest turn = first request id encountered walking newest-first.
- for (const item of items) {
- const rid =
- item.kind === 'turnBoundary'
- ? item.requestId
- : 'requestId' in item
- ? item.requestId
- : undefined;
- if (rid) {
- skip.add(rid);
- break;
- }
- }
const runtime = readChatRuntimeState(state);
const streamingRid = runtime?.streamingAssistantByThread[threadId]?.requestId;
if (streamingRid) skip.add(streamingRid);
@@ -2536,7 +2559,7 @@ export const fetchAndHydrateDerivedTranscript = createAsyncThunk(
await dispatch(fetchAndHydrateTurnHistory(threadId));
return null;
}
- const skipRequestIds = liveRequestIdsToSkip(getState(), threadId, page.items);
+ const skipRequestIds = liveRequestIdsToSkip(getState(), threadId);
const { timelines, transcripts } = mapDisplayItems(page.items, { skipRequestIds });
derivedLog(
'hydrated thread=%s items=%d timelines=%d transcripts=%d skip=%d hasMore=%s',
diff --git a/app/test/playwright/specs/chat-harness-subagent.spec.ts b/app/test/playwright/specs/chat-harness-subagent.spec.ts
index 65d0018f82..3f02fbe1da 100644
--- a/app/test/playwright/specs/chat-harness-subagent.spec.ts
+++ b/app/test/playwright/specs/chat-harness-subagent.spec.ts
@@ -3,6 +3,7 @@ import { expect, type Page, test } from '@playwright/test';
import { agentMessageText } from '../helpers/chat-locators';
import {
bootAuthenticatedPage,
+ callCoreRpc,
dismissWalkthroughIfPresent,
waitForAppReady,
} from '../helpers/core-rpc';
@@ -12,21 +13,49 @@ const USER_ID = 'pw-chat-subagent';
const PROMPT = 'Research the answer to life and tell me a marker phrase.';
const CANARY_FINAL = 'subagent-canary-final-7afe2';
const RESEARCHER_REPLY = 'The researcher answer is 42.';
+const PARENT_THINKING = 'Parent trace: delegate the factual lookup before synthesizing.';
+const PARENT_NARRATION = 'I am delegating the factual lookup now.';
+const CHILD_THINKING = 'Child trace: isolate the requested marker before replying.';
+const FINAL_THINKING = 'Parent trace: verify the delegated finding and answer.';
const KEYWORD_RESPONSES = [
{ keyword: "Search the user's memory tree", content: 'No relevant memory.' },
{
keyword: PROMPT,
- content: '',
- toolCalls: [
+ streamScript: [
+ { thinking: PARENT_THINKING },
+ { text: PARENT_NARRATION },
{
- id: 'call_research_1',
- name: 'research',
- arguments: JSON.stringify({ prompt: 'Tell me a marker phrase' }),
+ toolCall: {
+ id: 'call_research_1',
+ name: 'research',
+ arguments: JSON.stringify({ prompt: 'Tell me a marker phrase' }),
+ },
},
+ { finish: 'tool_calls' },
+ ],
+ },
+ {
+ // `spawn_async_subagent` wraps the requested task in its background-run
+ // 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' },
+ ],
+ },
+ {
+ // Detached completion is delivered to the parent as a fresh background
+ // notification turn; match that stable framing rather than depending on
+ // exactly how the result body is quoted inside it.
+ keyword: 'background sub-agent finished while you were busy',
+ streamScript: [
+ { thinking: FINAL_THINKING },
+ { text: `Done. The result is: ${CANARY_FINAL}` },
+ { finish: 'stop' },
],
},
- { keyword: 'Tell me a marker phrase', content: RESEARCHER_REPLY },
- { keyword: RESEARCHER_REPLY, content: `Done. The result is: ${CANARY_FINAL}` },
];
interface MockRequest {
@@ -155,6 +184,7 @@ interface DiagnosticsSnapshot {
phase: string | null;
toolTimelineNames: string[];
toolTimelineIds: string[];
+ turnTranscriptTexts: Record<string, string[]>;
messageCount: number;
lastAssistantText: string | null;
};
@@ -216,6 +246,10 @@ 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 }>>
+ >;
};
thread?: {
messagesByThread?: Record<string, Array<{ role?: string; content?: string }>>;
@@ -233,6 +267,10 @@ async function diagnosticsSnapshot(page: Page): Promise<DiagnosticsSnapshot> {
currentThreadId && state?.chatRuntime?.toolTimelineByThread?.[currentThreadId]
? state.chatRuntime.toolTimelineByThread[currentThreadId]
: [];
+ const turnTranscripts =
+ currentThreadId && state?.chatRuntime?.turnTranscriptsByThread?.[currentThreadId]
+ ? state.chatRuntime.turnTranscriptsByThread[currentThreadId]
+ : {};
const messages =
currentThreadId && state?.thread?.messagesByThread?.[currentThreadId]
? state.thread.messagesByThread[currentThreadId]
@@ -242,6 +280,12 @@ async function diagnosticsSnapshot(page: Page): Promise<DiagnosticsSnapshot> {
phase,
toolTimelineNames: timeline.map(entry => entry?.name ?? ''),
toolTimelineIds: timeline.map(entry => entry?.id ?? ''),
+ turnTranscriptTexts: Object.fromEntries(
+ Object.entries(turnTranscripts).map(([requestId, items]) => [
+ requestId,
+ items.map(item => item.text ?? ''),
+ ])
+ ),
messageCount: messages.length,
lastAssistantText:
typeof lastAssistant?.content === 'string' ? lastAssistant.content.slice(0, 240) : null,
@@ -258,6 +302,7 @@ function formatDiagnostics(snapshot: DiagnosticsSnapshot): string {
`matchedKeywords=${JSON.stringify(snapshot.matchedKeywords)}`,
`runtime.phase=${snapshot.runtime.phase ?? '<null>'}`,
`runtime.toolTimelineNames=${JSON.stringify(snapshot.runtime.toolTimelineNames)}`,
+ `runtime.turnTranscriptTexts=${JSON.stringify(snapshot.runtime.turnTranscriptTexts)}`,
`runtime.messageCount=${snapshot.runtime.messageCount}`,
`runtime.lastAssistantText=${JSON.stringify(snapshot.runtime.lastAssistantText)}`,
`completionProbes=${JSON.stringify(
@@ -292,7 +337,7 @@ test.describe('Chat Harness - Subagent', () => {
}
});
- test('delegates to a subagent and persists the final orchestrator text', async ({ page }) => {
+ test('renders and rehydrates the full delegated-turn trace', async ({ page }) => {
test.setTimeout(150_000);
await resetMock();
@@ -301,7 +346,7 @@ test.describe('Chat Harness - Subagent', () => {
await setMockBehavior('llmStreamChunkDelayMs', '10');
await openChat(page);
- await createNewThread(page);
+ const threadId = await createNewThread(page);
await sendMessage(page, PROMPT);
// Three LLM hits are expected: orchestrator-1 (delegates), researcher
@@ -312,18 +357,52 @@ test.describe('Chat Harness - Subagent', () => {
await expect.poll(completionRequestCount, { timeout: 90_000 }).toBeGreaterThanOrEqual(3);
await expect(agentMessageText(page, CANARY_FINAL)).toBeVisible({ timeout: 30_000 });
- const runtimeSnapshot = await diagnosticsSnapshot(page);
- expect(
- runtimeSnapshot.runtime.phase === 'subagent' ||
- runtimeSnapshot.runtime.toolTimelineNames.some(name => name.startsWith('subagent:')) ||
- runtimeSnapshot.runtime.toolTimelineIds.some(id => id.includes(':subagent:')),
- `expected runtime to show a subagent delegation, got:\n ${formatDiagnostics(
- runtimeSnapshot
- )}`
- ).toBe(true);
-
- // Re-assert after the runtime probe so the persisted message survives the
- // turn-completion store transition rather than only being visible mid-stream.
+ // Re-assert after completion so the persisted message survives the
+ // turn-settlement transition rather than only being visible mid-stream.
await expect(agentMessageText(page, CANARY_FINAL)).toBeVisible({ timeout: 15_000 });
+
+ // The trace belongs to assistant-ui's message parts—there is no parallel
+ // legacy timeline surface.
+ 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();
+ await expect(finalMessage.getByText(FINAL_THINKING, { exact: true })).toBeVisible();
+
+ // Reloading removes the live socket and Redux stream. The same visual
+ // trace must rehydrate from persisted transcript/turn-state data.
+ await page.reload();
+ await waitForAppReady(page);
+ await page.goto('/#/chat');
+ const restoredThread = page.getByTestId(`thread-row-${threadId}`);
+ await expect(restoredThread).toBeVisible({ timeout: 15_000 });
+ await restoredThread.click({ force: true });
+ await expect.poll(() => selectedThreadId(page), { timeout: 15_000 }).toBe(threadId);
+ const derived = await callCoreRpc<unknown>('openhuman.threads_transcript_get', {
+ thread_id: threadId,
+ 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');
+ await expect(subagentCall).toBeVisible();
+ await expect(subagentCall.getByTestId('subagent-activity')).toContainText(CHILD_THINKING);
+ await expect(subagentCall.getByTestId('subagent-activity')).toContainText(RESEARCHER_REPLY);
});
});
diff --git a/app/test/playwright/specs/chat-tool-call-flow.spec.ts b/app/test/playwright/specs/chat-tool-call-flow.spec.ts
index 5d697dc318..f30cd802f0 100644
--- a/app/test/playwright/specs/chat-tool-call-flow.spec.ts
+++ b/app/test/playwright/specs/chat-tool-call-flow.spec.ts
@@ -172,6 +172,22 @@ test.describe('Chat Tool Call Flow', () => {
await expect(agentMessageText(page, CANARY_FINAL)).toBeVisible({ timeout: 40_000 });
+ // Regression: completed tool/reasoning arrays remain in Redux briefly, but
+ // they must not create a synthetic running tail after the final answer.
+ await expect(page.getByLabel('Assistant is working')).toHaveCount(0);
+ await expect(page.getByText('running', { exact: true })).toHaveCount(0);
+
+ // Tool activity belongs to assistant-ui and renders as a readable card,
+ // never through the removed legacy Agentic task insights timeline.
+ await expect(page.getByTestId('agent-task-insights')).toHaveCount(0);
+ const toolCard = page.getByTestId('assistant-ui-tool-call').last();
+ await expect(toolCard).toBeVisible();
+ await expect(toolCard).not.toContainText('running');
+ const toolTrigger = toolCard.getByRole('button');
+ if ((await toolTrigger.getAttribute('aria-expanded')) !== 'true') await toolTrigger.click();
+ await expect(toolCard.getByText('Output', { exact: true })).toBeVisible();
+ await expect(toolCard.getByRole('link', { name: 'https://example.com/' })).toBeVisible();
+
await expect
.poll(
async () => {
diff --git a/scripts/mock-api/routes/__tests__/llm.test.mjs b/scripts/mock-api/routes/__tests__/llm.test.mjs
index 5152105f11..b0d089c6c4 100644
--- a/scripts/mock-api/routes/__tests__/llm.test.mjs
+++ b/scripts/mock-api/routes/__tests__/llm.test.mjs
@@ -200,6 +200,53 @@ test("streams reasoning deltas for reasoning-family models", async () => {
assert.match(ctx.res.body, /data: \[DONE\]/);
});
+test("keyword stream scripts preserve reasoning and tool-event order", async () => {
+ setMockBehaviors(
+ {
+ llmKeywordRules: JSON.stringify([
+ {
+ keyword: "trace this",
+ streamScript: [
+ { thinking: "first reason" },
+ { text: "then narrate" },
+ {
+ toolCall: {
+ id: "call_trace_1",
+ name: "web_search",
+ arguments: '{"q":"trace"}',
+ },
+ },
+ { finish: "tool_calls" },
+ ],
+ },
+ ]),
+ llmStreamChunkDelayMs: "0",
+ },
+ "replace",
+ );
+
+ const ctx = makeCtx({
+ parsedBody: {
+ model: "e2e-mock-model",
+ stream: true,
+ messages: [{ role: "user", content: "please trace this turn" }],
+ },
+ });
+
+ assert.equal(handleLlmCompletions(ctx), true);
+ // `safeDelayMs` deliberately normalizes zero to the default cadence, so
+ // wait for this tiny four-event script to finish rather than sampling it
+ // halfway through its SSE writes.
+ await new Promise((resolve) => setTimeout(resolve, 180));
+ const thinking = ctx.res.body.indexOf("first reason");
+ const narration = ctx.res.body.indexOf("then narrate");
+ const tool = ctx.res.body.indexOf("call_trace_1");
+ assert.ok(thinking >= 0, "keyword stream script should emit reasoning_content");
+ assert.ok(narration > thinking, "narration should follow reasoning");
+ assert.ok(tool > narration, "tool call should follow narration");
+ assert.match(ctx.res.body, /data: \[DONE\]/);
+});
+
test("returns tool calls for agentic models and resolves follow-up turns", () => {
const first = makeCtx({
parsedBody: {
diff --git a/scripts/mock-api/routes/llm.mjs b/scripts/mock-api/routes/llm.mjs
index 649b002709..5ed2c3f294 100644
--- a/scripts/mock-api/routes/llm.mjs
+++ b/scripts/mock-api/routes/llm.mjs
@@ -316,10 +316,16 @@ function handleStreamingCompletion({
if (!rule || typeof rule.keyword !== "string") continue;
if (probe.includes(rule.keyword.toLowerCase())) {
const rendered = applyDynamicPlaceholdersToResponse(rule, parsedBody);
- script = defaultStreamScript({
- content: rendered.content,
- toolCalls: rendered.toolCalls,
- });
+ // Keyword routes need the same control over event ordering as a
+ // global stream script. That lets browser tests exercise a real
+ // reasoning -> narration -> tool sequence without a FIFO script
+ // being consumed by an unrelated completion.
+ script = Array.isArray(rendered.streamScript)
+ ? rendered.streamScript
+ : defaultStreamScript({
+ content: rendered.content,
+ toolCalls: rendered.toolCalls,
+ });
break;
}
}
diff --git a/src/openhuman/agent/harness/session/transcript.rs b/src/openhuman/agent/harness/session/transcript.rs
index f9d66a068d..51253ff6bf 100644
--- a/src/openhuman/agent/harness/session/transcript.rs
+++ b/src/openhuman/agent/harness/session/transcript.rs
@@ -528,6 +528,35 @@ fn build_message_line(
Some((failed, detail)) => (failed, detail),
None => (false, None),
};
+ // Every assistant model response can carry its own thinking metadata,
+ // especially an intermediate response that also opens tool calls. Turn
+ // usage is attached only to the final assistant row, so sourcing reasoning
+ // exclusively from it silently dropped all pre-tool thoughts from the
+ // append-only display transcript.
+ let message_reasoning = (msg.role == "assistant")
+ .then(|| {
+ extra_metadata
+ .as_ref()
+ .and_then(|meta| {
+ meta.get(crate::openhuman::agent::message_convert::REASONING_EXT_KEY)
+ })
+ .and_then(serde_json::Value::as_str)
+ .map(str::to_string)
+ })
+ .flatten();
+ let native_envelope = (msg.role == "assistant")
+ .then(|| serde_json::from_str::<serde_json::Value>(&msg.content).ok())
+ .flatten();
+ let envelope_reasoning = native_envelope
+ .as_ref()
+ .and_then(|value| value.get("reasoning_content"))
+ .and_then(serde_json::Value::as_str)
+ .map(str::to_string);
+ let envelope_tool_calls = native_envelope
+ .as_ref()
+ .and_then(|value| value.get("tool_calls"))
+ .and_then(|value| serde_json::from_value::<Vec<ToolCall>>(value.clone()).ok())
+ .filter(|calls| !calls.is_empty());
MessageLine {
id: msg.id.clone(),
role: msg.role.clone(),
@@ -536,13 +565,17 @@ fn build_message_line(
provider: assistant_usage.map(|tu| tu.provider.clone()),
model: assistant_usage.map(|tu| tu.model.clone()),
usage: assistant_usage.map(|tu| tu.usage.clone()),
- reasoning_content: assistant_usage.and_then(|tu| tu.reasoning_content.clone()),
- tool_calls: assistant_usage.and_then(|tu| {
- if tu.tool_calls.is_empty() {
- None
- } else {
- Some(tu.tool_calls.clone())
- }
+ reasoning_content: message_reasoning
+ .or(envelope_reasoning)
+ .or_else(|| assistant_usage.and_then(|tu| tu.reasoning_content.clone())),
+ tool_calls: envelope_tool_calls.or_else(|| {
+ assistant_usage.and_then(|tu| {
+ if tu.tool_calls.is_empty() {
+ None
+ } else {
+ Some(tu.tool_calls.clone())
+ }
+ })
}),
iteration: assistant_usage.map(|tu| tu.iteration),
ts: assistant_usage.map(|tu| tu.ts.clone()),
@@ -1187,10 +1220,21 @@ pub fn read_transcript_display(path: &Path) -> Result<DisplaySessionTranscript>
/// transcript without accidentally folding delegated worker transcripts
/// into the main chat timeline.
pub fn find_root_transcript_for_thread(workspace_dir: &Path, thread_id: &str) -> Option<PathBuf> {
- raw_session_dirs(workspace_dir)
- .into_iter()
- .filter_map(|raw_dir| find_root_transcript_for_thread_in_dir(&raw_dir, thread_id))
- .max_by(|left, right| left.file_name().cmp(&right.file_name()))
+ find_root_transcripts_for_thread(workspace_dir, thread_id).pop()
+}
+
+/// Find every root transcript associated with a thread, oldest first.
+///
+/// A detached/background completion can open a new root session for the same
+/// chat thread. Display readers must merge those files; selecting only the
+/// newest makes the continuation appear to erase the original tool turn.
+pub fn find_root_transcripts_for_thread(workspace_dir: &Path, thread_id: &str) -> Vec<PathBuf> {
+ let mut matches = Vec::new();
+ for raw_dir in raw_session_dirs(workspace_dir) {
+ matches.extend(root_transcripts_for_thread_in_dir(&raw_dir, thread_id));
+ }
+ matches.sort_by(|left, right| left.file_name().cmp(&right.file_name()));
+ matches
}
fn raw_session_dirs(workspace_dir: &Path) -> Vec<PathBuf> {
@@ -1212,12 +1256,18 @@ fn raw_session_dirs(workspace_dir: &Path) -> Vec<PathBuf> {
}
pub fn find_root_transcript_for_thread_in_dir(raw_dir: &Path, thread_id: &str) -> Option<PathBuf> {
+ root_transcripts_for_thread_in_dir(raw_dir, thread_id).pop()
+}
+
+fn root_transcripts_for_thread_in_dir(raw_dir: &Path, thread_id: &str) -> Vec<PathBuf> {
let thread_id = thread_id.trim();
if thread_id.is_empty() {
- return None;
+ return Vec::new();
}
- let entries = fs::read_dir(raw_dir).ok()?;
+ let Ok(entries) = fs::read_dir(raw_dir) else {
+ return Vec::new();
+ };
let mut matches: Vec<PathBuf> = entries
.flatten()
.map(|entry| entry.path())
@@ -1241,7 +1291,7 @@ pub fn find_root_transcript_for_thread_in_dir(raw_dir: &Path, thread_id: &str) -
.collect();
matches.sort();
- matches.pop()
+ matches
}
/// Aggregated token/cost usage for a chat thread, summed across **all** of the
diff --git a/src/openhuman/agent/harness/session/transcript_tests.rs b/src/openhuman/agent/harness/session/transcript_tests.rs
index 260ff125de..3d7d80ed53 100644
--- a/src/openhuman/agent/harness/session/transcript_tests.rs
+++ b/src/openhuman/agent/harness/session/transcript_tests.rs
@@ -57,6 +57,21 @@ fn sample_turn_usage() -> TurnUsage {
}
}
+#[test]
+fn intermediate_assistant_reasoning_is_lifted_without_turn_usage() {
+ let mut message = ChatMessage::assistant("I will inspect the repository.");
+ message.extra_metadata = Some(serde_json::json!({
+ crate::openhuman::agent::message_convert::REASONING_EXT_KEY:
+ "First identify the relevant files."
+ }));
+
+ let line = build_message_line(&message, None, Some("request-1"), false);
+ assert_eq!(
+ line.reasoning_content.as_deref(),
+ Some("First identify the relevant files.")
+ );
+}
+
#[test]
fn round_trip_produces_byte_identical_messages() {
let dir = TempDir::new().unwrap();
diff --git a/src/openhuman/threads/transcript_view/cache.rs b/src/openhuman/threads/transcript_view/cache.rs
index f8b9016837..d1dcbfd418 100644
--- a/src/openhuman/threads/transcript_view/cache.rs
+++ b/src/openhuman/threads/transcript_view/cache.rs
@@ -70,8 +70,10 @@ impl TranscriptViewCache {
workspace_dir: &Path,
thread_id: &str,
) -> Option<Arc<ProjectedTranscript>> {
- let (root_path, sub_paths) = project::resolve_files(workspace_dir, thread_id)?;
- let signature: Vec<FileSig> = std::iter::once(file_sig(&root_path))
+ let (root_paths, sub_paths) = project::resolve_files(workspace_dir, thread_id)?;
+ let signature: Vec<FileSig> = root_paths
+ .iter()
+ .map(|path| file_sig(path))
.chain(sub_paths.iter().map(|p| file_sig(p)))
.collect();
@@ -94,7 +96,9 @@ impl TranscriptViewCache {
}
let projected = Arc::new(project::project_from_files(
- thread_id, &root_path, &sub_paths,
+ thread_id,
+ &root_paths,
+ &sub_paths,
));
let mut inner = self.inner.lock().ok()?;
diff --git a/src/openhuman/threads/transcript_view/project.rs b/src/openhuman/threads/transcript_view/project.rs
index ea9aa125d1..411aa8e6a8 100644
--- a/src/openhuman/threads/transcript_view/project.rs
+++ b/src/openhuman/threads/transcript_view/project.rs
@@ -35,61 +35,87 @@ const CHANNEL_CONTEXT_PREFIX: &str = "[Channel context]";
/// project everything into display items. Returns `None` when the thread has
/// no root transcript yet (brand-new thread / first turn not persisted).
pub fn project_thread(workspace_dir: &Path, thread_id: &str) -> Option<ProjectedTranscript> {
- let (root_path, sub_paths) = resolve_files(workspace_dir, thread_id)?;
- Some(project_from_files(thread_id, &root_path, &sub_paths))
+ let (root_paths, sub_paths) = resolve_files(workspace_dir, thread_id)?;
+ Some(project_from_files(thread_id, &root_paths, &sub_paths))
}
/// Resolve the on-disk file set backing a thread's transcript view: the root
/// transcript path plus every sub-agent sibling file. `None` when the thread
/// has no root transcript yet. Exposed so the cache can key on these paths
/// (and their mtimes/lengths) without re-projecting.
-pub fn resolve_files(workspace_dir: &Path, thread_id: &str) -> Option<(PathBuf, Vec<PathBuf>)> {
- let root_path = transcript::find_root_transcript_for_thread(workspace_dir, thread_id)?;
- let root_stem = root_path.file_stem()?.to_str()?.to_string();
- let Some(raw_dir) = root_path.parent() else {
- log::warn!(
- "{LOG_PREFIX} resolved root has no parent thread={thread_id} root={}",
- root_path.display()
- );
+pub fn resolve_files(
+ workspace_dir: &Path,
+ thread_id: &str,
+) -> Option<(Vec<PathBuf>, Vec<PathBuf>)> {
+ let root_paths = transcript::find_root_transcripts_for_thread(workspace_dir, thread_id);
+ if root_paths.is_empty() {
return None;
- };
- let sub_paths = discover_subagent_files(raw_dir, &root_stem);
- Some((root_path, sub_paths))
+ }
+ let mut sub_paths = Vec::new();
+ for root_path in &root_paths {
+ let Some(root_stem) = root_path.file_stem().and_then(|stem| stem.to_str()) else {
+ continue;
+ };
+ let Some(raw_dir) = root_path.parent() else {
+ continue;
+ };
+ sub_paths.extend(discover_subagent_files(raw_dir, root_stem));
+ }
+ sub_paths.sort();
+ sub_paths.dedup();
+ Some((root_paths, sub_paths))
}
/// Project a thread from an already-resolved file set (root + sub-agent
/// siblings). Missing/unreadable files degrade to empty rather than failing.
pub fn project_from_files(
thread_id: &str,
- root_path: &Path,
+ root_paths: &[PathBuf],
sub_paths: &[PathBuf],
) -> ProjectedTranscript {
- let root_stem = root_path
- .file_stem()
- .and_then(|s| s.to_str())
- .unwrap_or_default()
- .to_string();
-
log::debug!(
- "{LOG_PREFIX} projecting thread={thread_id} root={} subagent_files={}",
- root_path.display(),
+ "{LOG_PREFIX} projecting thread={thread_id} roots={} subagent_files={}",
+ root_paths.len(),
sub_paths.len()
);
// Read the root display records once: they feed both the top-level items
// and the per-turn timestamp ranges used to anchor sub-agent trails.
- let (mut items, segments) = match transcript::read_transcript_display(root_path) {
- Ok(d) => (project_records(&d.records), turn_segments(&d.records)),
- Err(err) => {
- log::warn!(
- "{LOG_PREFIX} failed to read root transcript {}: {err}",
- root_path.display()
- );
- (Vec::new(), Vec::new())
+ let mut items = Vec::new();
+ let mut segments = Vec::new();
+ for root_path in root_paths {
+ match transcript::read_transcript_display(root_path) {
+ Ok(display) => {
+ items.extend(project_records(&display.records));
+ segments.extend(turn_segments(&display.records));
+ }
+ Err(err) => {
+ log::warn!(
+ "{LOG_PREFIX} failed to read root transcript {}: {err}",
+ root_path.display()
+ );
+ }
}
- };
+ }
- let subagents = build_subagent_items(sub_paths, &root_stem, 0, &segments);
+ let mut subagents = Vec::new();
+ for root_path in root_paths {
+ let root_stem = root_path
+ .file_stem()
+ .and_then(|s| s.to_str())
+ .unwrap_or_default();
+ let prefix = format!("{root_stem}__");
+ let siblings: Vec<PathBuf> = sub_paths
+ .iter()
+ .filter(|path| {
+ path.file_stem()
+ .and_then(|stem| stem.to_str())
+ .is_some_and(|stem| stem.starts_with(&prefix))
+ })
+ .cloned()
+ .collect();
+ subagents.extend(build_subagent_items(&siblings, root_stem, 0, &segments));
+ }
log::debug!(
"{LOG_PREFIX} projected thread={thread_id} top_level_items={} subagents={}",
items.len(),
@@ -384,10 +410,27 @@ fn project_assistant(
.unwrap_or_default();
let interim = !tool_calls.is_empty();
+ // Native tool-call turns are persisted as their provider envelope so they
+ // can be replayed byte-faithfully. The display projection needs only the
+ // envelope's visible `content`; rendering/sanitizing the whole JSON object
+ // makes the narration disappear (and risks showing raw tool JSON).
+ let visible_content = serde_json::from_str::<serde_json::Value>(&msg.message.content)
+ .ok()
+ .and_then(|value| {
+ let object = value.as_object()?;
+ object.get("tool_calls")?.as_array()?;
+ match object.get("content") {
+ Some(serde_json::Value::String(content)) => Some(content.clone()),
+ Some(serde_json::Value::Null) | None => Some(String::new()),
+ _ => None,
+ }
+ })
+ .unwrap_or_else(|| msg.message.content.clone());
+
// The assistant's prose (if any) shows before its tool calls.
- if !msg.message.content.trim().is_empty() {
+ if !visible_content.trim().is_empty() {
items.push(DisplayItem::AssistantMessage {
- content: msg.message.content.clone(),
+ content: visible_content,
interim,
request_id: msg.request_id.clone(),
model: msg.turn_usage.as_ref().map(|tu| tu.model.clone()),
diff --git a/vendor/tinyagents b/vendor/tinyagents
index 954b3dcf58..1284a93f21 160000
--- a/vendor/tinyagents
+++ b/vendor/tinyagents
@@ -1 +1 @@
-Subproject commit 954b3dcf58038e8c11d674976fb779f1c72c6af4
+Subproject commit 1284a93f21876a5363ed14bc0554edba6a5ce917