The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.
Rust agent-orchestrationai-agentsai-assistantdesktopllmlocal-firstmcppersonal-aiprivacyrustsecond-braintauri
fix(chat): report terminal tool and delegation states faithfully\n\nAddresses the review threads on #5885. Six defects, all in the direction of\nreporting a failure as a success — which matters more here than elsewhere,\nbecause this PR's whole subject is rendering a turn faithfully.\n\n- Sub-agent lifecycle was collapsed to a boolean in three places, producing\n opposite errors from the same cause: `AssistantUiSubagentCall`'s\n `running = false` default rendered a failed delegation with a success check,\n while `ToolTimelineBlock`'s `status !== 'completed'` gave the same row an\n endless spinner. `isActiveSubagentStatus` is now the single question all\n three call sites ask, and a failed or cancelled delegation renders with the\n `CircleXIcon` the tool card already uses for the same state.\n- A terminal tool status never reached the assistant-ui adapter: the part has\n no status field, so `OpenHumanToolCall` fell back to `result !== undefined`\n and labelled a failed tool "done". `toolPart` now carries the status for a\n failed or cancelled entry and the adapter unwraps it. The success path is\n byte-identical on purpose.\n- `recoverTimelineToolNames` advanced its cursor on every timeline entry even\n though `recoveredNames` only holds names for the generic rows, so a named row\n consumed the first recovered name and the last generic row kept `tool`.\n- Narration already contained in the merged final answer rendered twice, since\n `mergedAssistantText` prefers the longest text when it contains every segment\n and the guard tested equality rather than containment.\n- Root transcripts were ordered by file name. Modern `{unix_ts}_{agent}` stems\n sort the same either way, but a legacy `{agent}_{index}` root encodes no time\n and, digits sorting before letters, landed after every modern one regardless\n of age — reordering the view and able to attach a sub-agent trail to the\n wrong turn. Ordering is now by `meta.created`, with the path as tiebreak.\n- `ChatThreadView` read `content.length` behind a guard that only covered the\n message, though `TranscriptRow` already treats content as nullish.\n\nTest hygiene from the same review: two Playwright locators that could not fail\n(`Loading conversation…` never matches the rendered label, which has no\nellipsis; `getByRole('button')` throws on strict mode if the card grows a\nsecond button), a `querySelector('button')!` that failed with an opaque\nTypeError at the click, and a single-microtask flush that could let a scheduled\n`logout` slip past a not-called assertion.\n\nEvery new test was checked by reverting its fix and confirming it fails.\n
M3gA-Mindc61d40b50530
diff --git a/app/src/features/conversations/components/AssistantUiSubagentCall.tsx b/app/src/features/conversations/components/AssistantUiSubagentCall.tsxindex 783ee93fd3..fc0b29b3f7 100644--- a/app/src/features/conversations/components/AssistantUiSubagentCall.tsx+++ b/app/src/features/conversations/components/AssistantUiSubagentCall.tsx@@ -1,4 +1,4 @@-import { CheckIcon, ChevronDownIcon, Loader2Icon, WorkflowIcon } from 'lucide-react';+import { CheckIcon, ChevronDownIcon, CircleXIcon, Loader2Icon, WorkflowIcon } from 'lucide-react';import { cn } from '../../../components/assistant-ui/lib/utils';import {@@ -150,9 +150,27 @@ function SubagentDetails({);}+/**+ * Statuses that mean the delegation is still in flight.+ *+ * `SubagentActivity.status` carries `running` | `awaiting_user` | `completed` |+ * `failed`, and collapsing that to a boolean is what produced two opposite+ * rendering bugs: a caller that omitted `running` showed a *failed* delegation+ * with a success check, while `status !== 'completed'` gave the same row an+ * endless spinner. Both call sites now ask this one question.+ */+export function isActiveSubagentStatus(status: string | undefined): boolean {+ return status === 'running' || status === 'awaiting_user';+}++/** Statuses that mean the delegation stopped without succeeding. */+function isFailedSubagentStatus(status: string | undefined): boolean {+ return status === 'failed' || status === 'cancelled';+}+export function AssistantUiSubagentCall({activity,- running = false,+ running,description,onView,defaultOpen = false,@@ -164,27 +182,35 @@ export function AssistantUiSubagentCall({defaultOpen?: boolean;}) {const name = activity.displayName ?? activity.agentId ?? 'subagent';+ // Default to the activity's own lifecycle rather than `false`: most call+ // sites pass no `running` prop at all, and treating every non-running+ // activity as finished-successfully is what rendered a failed delegation+ // with a success check.+ const active = running ?? isActiveSubagentStatus(activity.status);+ const failed = !active && isFailedSubagentStatus(activity.status);return (<CollapsibledefaultOpen={defaultOpen}data-slot="aui_subagent-call"data-testid="assistant-ui-subagent-call"+ data-status={activity.status ?? (active ? 'running' : 'completed')}className={cn('aui-subagent-call border-border/60 dark:border-muted-foreground/15 rounded-xl border',- running && 'border-dashed'+ active && 'border-dashed')}><CollapsibleTrigger className="group/subagent text-muted-foreground hover:text-foreground flex w-full items-center gap-2 px-3 py-2 text-sm transition-colors"><WorkflowIcon className="size-4 shrink-0" /><span className="text-start leading-none">Delegated to <b className="text-foreground">{name}</b></span>- {running ? (+ {active ? (<span className="bg-muted text-muted-foreground flex shrink-0 items-center gap-1.5 rounded-full px-2 py-0.5 text-[11px] leading-none"><Loader2Icon className="size-3 animate-spin [animation-duration:0.6s]" /> running</span>) : (<span className="text-muted-foreground flex shrink-0 items-center gap-1.5 text-[11px] leading-none">- <CheckIcon className="size-3.5" />+ {failed ? <CircleXIcon className="size-3.5" /> : <CheckIcon className="size-3.5" />}+ {failed ? <span>{activity.status}</span> : null}{activity.elapsedMs != null ? (<span className="tabular-nums">{(activity.elapsedMs / 1000).toFixed(1)}s</span>) : null}diff --git a/app/src/features/conversations/components/AssistantUiToolCall.tsx b/app/src/features/conversations/components/AssistantUiToolCall.tsxindex 934f820455..dd0dfb19bd 100644--- a/app/src/features/conversations/components/AssistantUiToolCall.tsx+++ b/app/src/features/conversations/components/AssistantUiToolCall.tsx@@ -205,11 +205,41 @@ export function AssistantUiToolCallCard({);}-export const OpenHumanToolCall: ToolCallMessagePartComponent = props => (- <AssistantUiToolCallCard- toolName={props.toolName}- args={props.args}- argsText={props.argsText}- result={props.result}- />-);+/**+ * Terminal status carried inside a settled tool part's `result`.+ *+ * assistant-ui's tool-call part has no status field, so `toolPart` puts the+ * status there for a tool that failed or was cancelled (`value` holds the real+ * output when there was one). Without unwrapping it here the card fell back to+ * `result !== undefined`, which reads as success — a failed tool rendered+ * "done" with a check.+ */+function toolStatusEnvelope(+ result: unknown+):+ | { status: ToolTimelineEntryStatus; failure?: ToolFailureExplanation; value?: unknown }+ | undefined {+ if (!result || typeof result !== 'object' || Array.isArray(result)) return undefined;+ const candidate = result as { status?: unknown; failure?: unknown; value?: unknown };+ return candidate.status === 'error' || candidate.status === 'cancelled'+ ? {+ status: candidate.status as ToolTimelineEntryStatus,+ failure: candidate.failure as ToolFailureExplanation | undefined,+ ...('value' in candidate ? { value: candidate.value } : {}),+ }+ : undefined;+}++export const OpenHumanToolCall: ToolCallMessagePartComponent = props => {+ const envelope = toolStatusEnvelope(props.result);+ return (+ <AssistantUiToolCallCard+ toolName={props.toolName}+ args={props.args}+ argsText={props.argsText}+ result={envelope ? envelope.value : props.result}+ status={envelope?.status}+ failure={envelope?.failure}+ />+ );+};diff --git a/app/src/features/conversations/components/ChatThreadView.tsx b/app/src/features/conversations/components/ChatThreadView.tsxindex 003c384a0a..e186bda89e 100644--- a/app/src/features/conversations/components/ChatThreadView.tsx+++ b/app/src/features/conversations/components/ChatThreadView.tsx@@ -344,7 +344,7 @@ export const ChatThreadView = forwardRef<ChatThreadViewHandle, ChatThreadViewPro// own collapsed process trail above it. The latest turn is excluded upstream// (it renders as the live "agent insights" anchor), so there is no double// render. Empty for legacy messages without a `requestId`.- const settledRevision = `${messages.at(-1)?.id ?? ''}:${messages.at(-1)?.content.length ?? 0}`;+ const settledRevision = `${messages.at(-1)?.id ?? ''}:${messages.at(-1)?.content?.length ?? 0}`;const coreTranscript = useCoreTranscriptProjection(threadId,settledRevision,diff --git a/app/src/features/conversations/components/ChatToolParts.test.tsx b/app/src/features/conversations/components/ChatToolParts.test.tsxindex 2149e2c218..9fba803e40 100644--- a/app/src/features/conversations/components/ChatToolParts.test.tsx+++ b/app/src/features/conversations/components/ChatToolParts.test.tsx@@ -41,6 +41,78 @@ describe('ChatToolParts', () => {expect(screen.getByText('Checking primary sources.')).toBeInTheDocument();});+ it('renders a failed delegation as failed, not as a completed one', () => {+ // `SubagentActivity.status` carries `failed`, but a settled part was read+ // as `running: false` and rendered with a success check — the transcript+ // reported a failure as a success.+ render(+ <ChatToolFallback+ type="tool-call"+ toolName="task"+ toolCallId="sub-1"+ args={{} as never}+ argsText="{}"+ result={{ ...activity, status: 'failed' } as never}+ status={{ type: 'complete' }}+ addResult={() => {}}+ resume={() => {}}+ respondToApproval={() => {}}+ />+ );++ expect(screen.getByTestId('assistant-ui-subagent-call')).toHaveAttribute(+ 'data-status',+ 'failed'+ );+ expect(screen.getByText('failed')).toBeInTheDocument();+ expect(screen.queryByText('running')).not.toBeInTheDocument();+ });++ it('keeps a completed delegation reading as completed', () => {+ render(+ <ChatToolFallback+ type="tool-call"+ toolName="task"+ toolCallId="sub-1"+ args={{} as never}+ argsText="{}"+ result={{ ...activity, status: 'completed' } as never}+ status={{ type: 'complete' }}+ addResult={() => {}}+ resume={() => {}}+ respondToApproval={() => {}}+ />+ );++ expect(screen.getByTestId('assistant-ui-subagent-call')).toHaveAttribute(+ 'data-status',+ 'completed'+ );+ expect(screen.queryByText('failed')).not.toBeInTheDocument();+ });++ it('keeps a still-running delegation running when the part has already settled', () => {+ // The tool-call status and the delegation status are separate fields, so a+ // settled part can still carry an in-flight activity. Hard-coding+ // `running: false` for any settled part froze that row into a success.+ render(+ <ChatToolFallback+ type="tool-call"+ toolName="task"+ toolCallId="sub-1"+ args={{} as never}+ argsText="{}"+ result={{ ...activity, status: 'running' } as never}+ status={{ type: 'complete' }}+ addResult={() => {}}+ resume={() => {}}+ respondToApproval={() => {}}+ />+ );++ expect(screen.getByText('running')).toBeInTheDocument();+ });+it('opens a group containing in-flight work on mount', () => {render(<ChatToolGroup group={{ type: 'group-tool-call', status: { type: 'running' }, indices: [0] }}>diff --git a/app/src/features/conversations/components/ChatToolParts.tsx b/app/src/features/conversations/components/ChatToolParts.tsxindex 606abd8490..1069e6477d 100644--- a/app/src/features/conversations/components/ChatToolParts.tsx+++ b/app/src/features/conversations/components/ChatToolParts.tsx@@ -8,7 +8,7 @@ import {ToolGroupTrigger,} from '../../../components/assistant-ui/tool-group';import type { SubagentActivity } from '../../../store/chatRuntimeSlice';-import { AssistantUiSubagentCall } from './AssistantUiSubagentCall';+import { AssistantUiSubagentCall, isActiveSubagentStatus } from './AssistantUiSubagentCall';import { OpenHumanToolCall } from './AssistantUiToolCall';function asSubagentActivity(value: unknown): SubagentActivity | undefined {@@ -29,7 +29,10 @@ function readSubagentState(result: unknown): { activity: SubagentActivity | undefined; running: boolean } {const completed = asSubagentActivity(result);- if (completed) return { activity: completed, running: false };+ // A settled part carries the activity, but "settled" is not "succeeded":+ // ask the activity's own status so a `failed` delegation is not rendered as+ // a completed one.+ if (completed) return { activity: completed, running: isActiveSubagentStatus(completed.status) };const progress =args && typeof args === 'object'? asSubagentActivity((args as { progress?: unknown }).progress)diff --git a/app/src/features/conversations/components/ToolTimelineBlock.tsx b/app/src/features/conversations/components/ToolTimelineBlock.tsxindex 345356c7b3..4975148cc4 100644--- a/app/src/features/conversations/components/ToolTimelineBlock.tsx+++ b/app/src/features/conversations/components/ToolTimelineBlock.tsx@@ -15,7 +15,7 @@ import type {import { formatTimelineEntry, stripToolCallEnvelopes } from '../../../utils/toolTimelineFormatting';import { parseWorkerThreadRef } from '../utils/workerThreadRef';import { agentNameTone, AgentTimelineRail } from './AgentTimelineRail';-import { AssistantUiSubagentCall } from './AssistantUiSubagentCall';+import { AssistantUiSubagentCall, isActiveSubagentStatus } from './AssistantUiSubagentCall';import { ProcessingTranscriptView } from './ProcessingTranscriptView';import {coalesceTimelineEntries,@@ -421,7 +421,7 @@ export function ToolTimelineBlock({renderSubagent={subagent => (<AssistantUiSubagentCallactivity={subagent}- running={subagent.status !== 'completed'}+ running={isActiveSubagentStatus(subagent.status)}onView={onViewSubagent ? () => onViewSubagent(subagent) : undefined}/>)}diff --git a/app/src/features/conversations/components/__tests__/ToolTimelineBlock.test.tsx b/app/src/features/conversations/components/__tests__/ToolTimelineBlock.test.tsxindex 6939bacb0b..4c68fa44cd 100644--- a/app/src/features/conversations/components/__tests__/ToolTimelineBlock.test.tsx+++ b/app/src/features/conversations/components/__tests__/ToolTimelineBlock.test.tsx@@ -27,6 +27,34 @@ function renderInStore(ui: React.ReactNode) {}describe('SubagentActivityBlock', () => {+ it('derives its lifecycle from the activity when no running prop is passed', () => {+ // Most call sites (AgentProcessSourcePanel, PastTurnInsights, this block)+ // pass no `running` prop at all. The old `running = false` default reported+ // an in-flight delegation as finished, with a success check.+ renderInStore(+ <SubagentActivityBlock+ subagent={{ taskId: 't', agentId: 'researcher', status: 'running', toolCalls: [] }}+ />+ );++ expect(screen.getByText('running')).toBeInTheDocument();+ });++ it('marks a failed delegation as failed rather than complete', () => {+ renderInStore(+ <SubagentActivityBlock+ subagent={{ taskId: 't', agentId: 'researcher', status: 'failed', toolCalls: [] }}+ />+ );++ expect(screen.getByTestId('assistant-ui-subagent-call')).toHaveAttribute(+ 'data-status',+ 'failed'+ );+ expect(screen.getByText('failed')).toBeInTheDocument();+ expect(screen.queryByText('running')).not.toBeInTheDocument();+ });+it('renders mode + dedicated-thread + child-turn pills', () => {renderInStore(<SubagentActivityBlockdiff --git a/app/src/features/conversations/derived/derivedRestore.render.test.tsx b/app/src/features/conversations/derived/derivedRestore.render.test.tsxindex af7a457a91..1d7a6e1009 100644--- a/app/src/features/conversations/derived/derivedRestore.render.test.tsx+++ b/app/src/features/conversations/derived/derivedRestore.render.test.tsx@@ -73,7 +73,14 @@ describe('derived transcript restore (mapper → PastTurnInsights)', () => {expect(screen.getAllByTestId('processing-tool-row').length).toBeGreaterThan(0);// The sub-agent's own reasoning trail renders beneath.const subagents = screen.getByTestId('past-turn-subagents');- fireEvent.click(screen.getByTestId('assistant-ui-subagent-call').querySelector('button')!);+ // Assert the trigger before clicking: a bare `querySelector('button')!`+ // throws an opaque TypeError at the click, pointing the stack at the click+ // rather than at the element that was never rendered.+ const subagentTrigger = screen+ .getByTestId('assistant-ui-subagent-call')+ .querySelector('button');+ expect(subagentTrigger).not.toBeNull();+ fireEvent.click(subagentTrigger as HTMLElement);expect(subagents.textContent).toContain('child reasoning trail');});});diff --git a/app/src/providers/__tests__/CoreStateProvider.test.tsx b/app/src/providers/__tests__/CoreStateProvider.test.tsxindex c48f850ed3..9204fb0162 100644--- a/app/src/providers/__tests__/CoreStateProvider.test.tsx+++ b/app/src/providers/__tests__/CoreStateProvider.test.tsx@@ -567,7 +567,10 @@ describe('CoreStateProvider — identity-change cache clearing', () => {},}));- await Promise.resolve();+ // Drain past the microtask queue: the handler may `await` before it can+ // reach `logout`, and a single `Promise.resolve()` tick would let this+ // assertion pass without that path having had a chance to run.+ await new Promise(resolve => setTimeout(resolve, 0));});expect(vi.mocked(tauriCommands.logout)).not.toHaveBeenCalled();diff --git a/app/src/providers/__tests__/assistantUiMessages.test.ts b/app/src/providers/__tests__/assistantUiMessages.test.tsindex a8b891c8ed..0d0974b1ec 100644--- a/app/src/providers/__tests__/assistantUiMessages.test.ts+++ b/app/src/providers/__tests__/assistantUiMessages.test.ts@@ -353,3 +353,71 @@ describe('buildRuntimeMessages', () => {parse.mockRestore();});});++describe('recovered tool names', () => {+ it('does not consume a recovered name on an entry it does not rename', () => {+ // `recoveredNames` comes from tool-call envelopes, so it only ever holds+ // names for the *generic* rows. Advancing the cursor on every entry made a+ // named row eat the first recovered name: the first generic row then took+ // the second name and the last one kept the placeholder.+ const converted = toThreadMessageLike(+ msg({+ id: 'a',+ sender: 'agent',+ content: 'done',+ extraMetadata: { assistantUiToolNames: ['web_search', 'web_fetch'] },+ }),+ [+ tool({ id: 'c1', name: 'read_file', seq: 0, status: 'ok' }),+ tool({ id: 'c2', name: 'tool', seq: 1, status: 'ok' }),+ tool({ id: 'c3', name: 'tool', seq: 2, status: 'ok' }),+ ]+ );+ const names = (converted.content as { type: string; toolName?: string }[])+ .filter(part => part.type === 'tool-call')+ .map(part => part.toolName);+ expect(names).toEqual(['read_file', 'web_search', 'web_fetch']);+ });+});++describe('terminal tool status', () => {+ it('carries a failed tool status through to the rendered part', () => {+ // assistant-ui's tool-call part has no status field, so a failed tool that+ // produced output used to arrive as a bare result and read as success.+ const converted = toThreadMessageLike(msg({ id: 'a', sender: 'agent', content: 'done' }), [+ tool({ id: 'c1', name: 'web_search', seq: 0, status: 'error', result: 'boom' }),+ ]);+ const part = (converted.content as { type: string; result?: unknown }[]).find(+ candidate => candidate.type === 'tool-call'+ );+ expect(part?.result).toMatchObject({ status: 'error', value: 'boom' });+ });++ it('leaves a successful tool result untouched', () => {+ const converted = toThreadMessageLike(msg({ id: 'a', sender: 'agent', content: 'done' }), [+ tool({ id: 'c1', name: 'web_search', seq: 0, status: 'ok', result: 'the answer' }),+ ]);+ const part = (converted.content as { type: string; result?: unknown }[]).find(+ candidate => candidate.type === 'tool-call'+ );+ expect(part?.result).toBe('the answer');+ });+});++describe('narration merged into the final answer', () => {+ it('does not render narration that the final text already contains', () => {+ // `mergedAssistantText` prefers the longest text when it *contains* every+ // segment, so the duplicate is a substring rather than an exact match and+ // the old equality guard let it through twice.+ const finalText = 'I will check the sources. Here is what I found.';+ const converted = toThreadMessageLike(+ msg({ id: 'a', sender: 'agent', content: finalText }),+ [],+ [{ kind: 'narration', round: 1, seq: 0, text: 'I will check the sources.' }]+ );+ const texts = (converted.content as { type: string; text?: string }[])+ .filter(part => part.type === 'text')+ .map(part => part.text);+ expect(texts).toEqual([finalText]);+ });+});diff --git a/app/src/providers/assistantUiMessages.ts b/app/src/providers/assistantUiMessages.tsindex 31a0dd7551..ad39165b82 100644--- a/app/src/providers/assistantUiMessages.ts+++ b/app/src/providers/assistantUiMessages.ts@@ -78,6 +78,30 @@ function toolArgs(entry: ToolTimelineEntry): Record<string, never> {}}+/**+ * The `result` payload for a settled non-sub-agent tool part.+ *+ * assistant-ui's tool-call part has no status field, so a terminal status has+ * to travel inside `result` or not at all. It did not travel: the adapter fell+ * back to `result !== undefined`, which reads as success, and a failed or+ * cancelled tool rendered with a "done" label and a check.+ *+ * A tool that produced no output already reported `{ status, failure }` here,+ * so only the failed-*with*-output case needed a shape — `value` carries the+ * real output beside the status, and {@link isToolStatusEnvelope} unwraps it.+ * The success path is byte-identical to before, deliberately: every reader of+ * a successful result keeps seeing exactly what it saw.+ */+function toolResultPayload(entry: ToolTimelineEntry): unknown {+ const terminalFailure = entry.status === 'error' || entry.status === 'cancelled';+ if (!terminalFailure) return entry.result ?? { status: entry.status, failure: entry.failure };+ return {+ status: entry.status,+ failure: entry.failure,+ ...(entry.result !== undefined ? { value: entry.result } : {}),+ };+}+function toolPart(entry: ToolTimelineEntry): ThreadAssistantMessagePart {const running = entry.status === 'running' || entry.status === 'awaiting_user';const isSubagent = entry.name.startsWith('subagent:') || entry.subagent !== undefined;@@ -99,7 +123,7 @@ function toolPart(entry: ToolTimelineEntry): ThreadAssistantMessagePart {? {result: isSubagent? (entry.subagent ?? { status: entry.status })- : (entry.result ?? { status: entry.status, failure: entry.failure }),+ : toolResultPayload(entry),}: {}),};@@ -145,12 +169,15 @@ function assistantParts(if (item.kind === 'narration' &&item.text.trim().length > 0 &&- item.text.trim() !== text.trim()+ !text.trim().includes(item.text.trim())) {// 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. A final-round narration is the- // same streamed bytes as that answer and must not render twice.+ // same streamed bytes as that answer and must not render twice —+ // `includes`, not equality, because `mergedAssistantText` prefers the+ // longest text when it *contains* every segment, so the duplicate is a+ // substring rather than an exact match.parts.push({ type: 'text', text: item.text });}}@@ -186,11 +213,18 @@ function recoverTimelineToolNames(if (recoveredNames.length === 0 || !timeline.some(entry => isGenericToolName(entry.name))) {return timeline;}+ // Advance only when a name is actually consumed. `recoveredNames` comes from+ // tool-call envelopes, so it is not positionally aligned with the whole+ // timeline: incrementing on every entry made `[read_file, tool, tool]` ++ // `[web_search, web_fetch]` mis-assign `web_fetch` to the first generic row+ // and leave the second one named `tool`.let recoveredIndex = 0;return timeline.map(entry => {+ if (!isGenericToolName(entry.name)) return entry;const recovered = recoveredNames[recoveredIndex];+ if (!recovered) return entry;recoveredIndex += 1;- return recovered && isGenericToolName(entry.name) ? { ...entry, name: recovered } : entry;+ return { ...entry, name: recovered };});}diff --git a/app/test/playwright/specs/chat-scroll-stability.spec.ts b/app/test/playwright/specs/chat-scroll-stability.spec.tsindex 4195bbf9d4..9f0a2bda7b 100644--- a/app/test/playwright/specs/chat-scroll-stability.spec.ts+++ b/app/test/playwright/specs/chat-scroll-stability.spec.ts@@ -88,7 +88,10 @@ test.describe('Chat scroll paint stability', () => {};}, fraction);expect(metrics).toEqual(initial);- await expect(page.getByText('Loading conversation…')).toHaveCount(0);+ // The surface renders `Loading conversation` with no ellipsis; the old+ // locator matched nothing, so `toHaveCount(0)` passed without ever+ // checking the loading element.+ await expect(page.getByText('Loading conversation')).toHaveCount(0);}expect(transcriptRpcCount).toBe(rpcCountBeforeScroll);});diff --git a/app/test/playwright/specs/chat-tool-call-flow.spec.ts b/app/test/playwright/specs/chat-tool-call-flow.spec.tsindex f5c1d96411..5cec18ff95 100644--- a/app/test/playwright/specs/chat-tool-call-flow.spec.ts+++ b/app/test/playwright/specs/chat-tool-call-flow.spec.ts@@ -191,7 +191,7 @@ test.describe('Chat Tool Call Flow', () => {await expect(toolCard).toBeVisible();await expect(toolCard).toContainText('Fetched from the web');await expect(toolCard).not.toContainText('running');- const toolTrigger = toolCard.getByRole('button');+ const toolTrigger = toolCard.getByRole('button').first();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();diff --git a/src/openhuman/agent/harness/session/transcript_part_02.rs b/src/openhuman/agent/harness/session/transcript_part_02.rsindex 2066c4c278..8737aab9b2 100644--- a/src/openhuman/agent/harness/session/transcript_part_02.rs+++ b/src/openhuman/agent/harness/session/transcript_part_02.rs@@ -464,7 +464,16 @@ pub fn find_root_transcripts_for_thread(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()));+ // Already chronological within each directory (see+ // `root_transcripts_for_thread_in_dir`); re-key across directories on the+ // same `created` stamp rather than the file name.+ matches.sort_by_cached_key(|path| {+ let created = read_transcript(path)+ .ok()+ .map(|transcript| transcript.meta.created)+ .unwrap_or_default();+ (created, path.clone())+ });matches}@@ -499,7 +508,14 @@ fn root_transcripts_for_thread_in_dir(raw_dir: &Path, thread_id: &str) -> Vec<Palet Ok(entries) = fs::read_dir(raw_dir) else {return Vec::new();};- let mut matches: Vec<PathBuf> = entries+ // Keyed by `meta.created` so the order is chronological rather than+ // lexicographic. Modern stems are `{unix_ts}_{agent_id}` and sort the same+ // either way, but a legacy `{agent}_{index}` root encodes no time at all —+ // and because digits sort before letters, every legacy root sorted *after*+ // every modern one regardless of when it was written. `project_from_files`+ // concatenates these in order, so that reordered the rendered view and+ // could attach a sub-agent trail to the wrong turn.+ let mut matches: Vec<(String, PathBuf)> = entries.flatten().map(|entry| entry.path()).filter(|path| {@@ -509,20 +525,25 @@ fn root_transcripts_for_thread_in_dir(raw_dir: &Path, thread_id: &str) -> Vec<Pa.and_then(|s| s.to_str()).is_some_and(|stem| !stem.contains("__"))})- .filter(|path| match read_transcript(path) {- Ok(transcript) => transcript.meta.thread_id.as_deref() == Some(thread_id),+ .filter_map(|path| match read_transcript(&path) {+ Ok(transcript) if transcript.meta.thread_id.as_deref() == Some(thread_id) => {+ Some((transcript.meta.created.clone(), path))+ }+ Ok(_) => None,Err(err) => {log::warn!("[transcript] skipping unreadable root transcript candidate {}: {err}",path.display());- false+ None}}).collect();- matches.sort();- matches+ // Path is the tiebreak so the order stays total and deterministic when two+ // transcripts share a `created` stamp.+ matches.sort_by(|left, right| left.0.cmp(&right.0).then_with(|| left.1.cmp(&right.1)));+ matches.into_iter().map(|(_, path)| path).collect()}/// Aggregated token/cost usage for a chat thread, summed across **all** of thediff --git a/src/openhuman/agent/harness/session/transcript_tests_part_03_tests.rs b/src/openhuman/agent/harness/session/transcript_tests_part_03_tests.rsindex 5baf739b9e..96f80b02a6 100644--- a/src/openhuman/agent/harness/session/transcript_tests_part_03_tests.rs+++ b/src/openhuman/agent/harness/session/transcript_tests_part_03_tests.rs@@ -53,3 +53,58 @@ fn meta_version_stamped_and_optional() {"append writer must stamp the schema version on the meta header");}++/// Root transcripts must come back in the order they were written, not in+/// filename order.+///+/// Modern stems are `{unix_ts}_{agent}` and sort identically either way, but a+/// legacy `{agent}_{index}` root encodes no time at all — and because digits+/// sort before letters, every legacy root sorted *after* every modern one no+/// matter when it was written. `project_from_files` concatenates these in+/// order, so a mis-ordered list reorders the rendered view and can attach a+/// sub-agent trail to the wrong turn.+#[test]+fn root_transcripts_are_ordered_by_creation_not_file_name() {+ let dir = TempDir::new().unwrap();+ let raw = dir.path().join("session_raw");+ std::fs::create_dir_all(&raw).unwrap();++ let write_root = |stem: &str, created: &str| {+ let mut meta = sample_meta();+ meta.thread_id = Some("thread-order".into());+ meta.created = created.into();+ write_transcript(+ &raw.join(format!("{stem}.jsonl")),+ &sample_messages(),+ &meta,+ None,+ )+ .unwrap();+ };++ // The legacy root is the OLDEST, but `orchestrator_1` sorts after any+ // digit-led stem, so a filename sort puts it last.+ write_root("orchestrator_1", "2026-04-10T09:00:00Z");+ write_root("1776211200_orchestrator", "2026-04-11T09:00:00Z");+ write_root("1776297600_orchestrator", "2026-04-12T09:00:00Z");++ let ordered: Vec<String> = find_root_transcripts_for_thread(dir.path(), "thread-order")+ .into_iter()+ .map(|path| {+ path.file_stem()+ .and_then(|stem| stem.to_str())+ .unwrap_or_default()+ .to_string()+ })+ .collect();++ assert_eq!(+ ordered,+ vec![+ "orchestrator_1".to_string(),+ "1776211200_orchestrator".to_string(),+ "1776297600_orchestrator".to_string(),+ ],+ "roots must be chronological; a filename sort would put the legacy root last"+ );+}