Skip to content

The open-source agent harness - the runtime layer that turns an LLM into a working agent.

bugfix: surface cancel and sub-agent failure on session timeline (#1054)

harshil-2096e4caefb9a611
diff --git a/.changeset/session-timeline-cancel-subagent.md b/.changeset/session-timeline-cancel-subagent.md
new file mode 100644
index 000000000..e0985ab68
--- /dev/null
+++ b/.changeset/session-timeline-cancel-subagent.md
@@ -0,0 +1,6 @@
+---
+'@truefoundry/trueforge-assistant-ui-runtime': patch
+'@truefoundry/trueforge-ui': patch
+---
+
+Surface cancelled turn reasons and failed sub-agents on the Agent Sessions timeline and metrics; project unfinished nested sub-agents as cancelled when the parent turn is already terminal, remap abort-shaped child thread.done errors (e.g. LLM stream aborted) to cancelled on cancelled turns, and close unfinished sub-agent chart bars at turn.done when thread.done is missing.
diff --git a/packages/assistant-ui-runtime/src/convertTurnMessages.ts b/packages/assistant-ui-runtime/src/convertTurnMessages.ts
index 1c87f6d84..1a500aff9 100644
--- a/packages/assistant-ui-runtime/src/convertTurnMessages.ts
+++ b/packages/assistant-ui-runtime/src/convertTurnMessages.ts
@@ -351,6 +351,8 @@ function cloneThreadBucket(bucket: ThreadBucket): ThreadBucket {
approvalDecisions: new Map(bucket.approvalDecisions),
pendingResponses: new Map(bucket.pendingResponses),
done: bucket.done,
+ // Keep sub-agent failure text so a cloned bucket still shows as failed.
+ ...(bucket.error != null ? { error: bucket.error } : {}),
...(bucket.title != null ? { title: bucket.title } : {}),
...(bucket.agentInfo != null ? { agentInfo: bucket.agentInfo } : {}),
};
@@ -382,6 +384,10 @@ export function prependFoldState(older: PeerThreadFoldState, newer: PeerThreadFo
approvalDecisions: new Map([...olderBucket.approvalDecisions, ...newerBucket.approvalDecisions]),
pendingResponses: new Map([...olderBucket.pendingResponses, ...newerBucket.pendingResponses]),
done: newerBucket.done || olderBucket.done,
+ // Prefer the newer failure text; if only the older turn failed, keep that.
+ ...(newerBucket.error != null || olderBucket.error != null
+ ? { error: newerBucket.error ?? olderBucket.error }
+ : {}),
...(newerBucket.title != null || olderBucket.title != null
? { title: newerBucket.title ?? olderBucket.title }
: {}),
@@ -972,11 +978,26 @@ function buildTurnUpdateFromFold(
turn: Pick<Turn, 'state'>,
rootModelMessageIds: readonly string[],
): TurnStreamUpdate {
- const content = buildRootAssistantContentForIds(foldState, rootModelMessageIds);
- let update: TurnStreamUpdate = { content };
- update = appendMcpAuthToTurnContent(update.content, turn);
- update = appendToolApprovalToTurnContent(update, turn);
- return update;
+ // While we build this turn's messages, tell nested sub-agents that the parent
+ // already ended (cancelled/error) so they do not stay stuck as "running".
+ // Restore afterward so the flag does not leak into the next turn.
+ const previousParentTerminal = foldState.parentTerminalStatus;
+ if (turn.state.status === 'cancelled') {
+ foldState.parentTerminalStatus = 'cancelled';
+ } else if (turn.state.status === 'error') {
+ foldState.parentTerminalStatus = 'error';
+ } else {
+ foldState.parentTerminalStatus = undefined;
+ }
+ try {
+ const content = buildRootAssistantContentForIds(foldState, rootModelMessageIds);
+ let update: TurnStreamUpdate = { content };
+ update = appendMcpAuthToTurnContent(update.content, turn);
+ update = appendToolApprovalToTurnContent(update, turn);
+ return update;
+ } finally {
+ foldState.parentTerminalStatus = previousParentTerminal;
+ }
}
function contentHasPendingRequiredActions(content: readonly AssistantContentPart[]): boolean {
@@ -1743,11 +1764,18 @@ export async function* streamTurnEvents(
groupRootBaseline != null
? rootModelMessageIdsSinceBaseline(foldState, groupRootBaseline)
: (foldState.threads.get(ROOT_THREAD_ID)?.modelMessageIds ?? []);
- yield withCursor({
- content: buildRootAssistantContentForIds(foldState, ids),
- status: { type: 'incomplete', reason: 'cancelled' },
- metadata: { custom: { [CANCELLATION_REASON_CUSTOM_KEY]: event.state.reason } },
- });
+ // Same as history: mark parent cancelled so open sub-agents render cancelled too.
+ const previousParentTerminal = foldState.parentTerminalStatus;
+ foldState.parentTerminalStatus = 'cancelled';
+ try {
+ yield withCursor({
+ content: buildRootAssistantContentForIds(foldState, ids),
+ status: { type: 'incomplete', reason: 'cancelled' },
+ metadata: { custom: { [CANCELLATION_REASON_CUSTOM_KEY]: event.state.reason } },
+ });
+ } finally {
+ foldState.parentTerminalStatus = previousParentTerminal;
+ }
return;
}
// The turn is logically complete once `turn.done` is observed. The
diff --git a/packages/assistant-ui-runtime/src/foldPeerThreads.ts b/packages/assistant-ui-runtime/src/foldPeerThreads.ts
index 4fdfc2bbd..9b539ad25 100644
--- a/packages/assistant-ui-runtime/src/foldPeerThreads.ts
+++ b/packages/assistant-ui-runtime/src/foldPeerThreads.ts
@@ -59,10 +59,18 @@ export interface ThreadBucket {
approvalDecisions: Map<string, ApprovalDecisionRef>;
pendingResponses: Map<string, PendingResponseRef>;
done: boolean;
+ /** Failure text from a sub-agent thread that ended in error. */
+ error?: string;
title?: string;
agentInfo?: AgentInfo;
}
+/**
+ * Sticky note on the fold while projecting a finished parent turn.
+ * Unfinished children copy this so they show cancelled/error instead of running.
+ */
+export type ParentTerminalStatus = 'cancelled' | 'error';
+
export interface ThreadParentLink {
parentThreadId: string;
toolCallId: string;
@@ -95,6 +103,8 @@ function assertRootThreadEvent(threadId: string, eventType: string): void {
export class PeerThreadFoldState {
readonly threads = new Map<string, ThreadBucket>();
readonly threadParents = new Map<string, ThreadParentLink>();
+ /** Set only while building content for a cancelled/errored parent turn; cleared after. */
+ parentTerminalStatus: ParentTerminalStatus | undefined;
getOrCreateBucket(threadId: string): ThreadBucket {
let bucket = this.threads.get(threadId);
@@ -114,6 +124,35 @@ export class PeerThreadFoldState {
}
}
+/** Pull the human-readable error off a thread.done error state, or a fallback label. */
+function threadDoneErrorMessage(state: unknown): string | undefined {
+ if (typeof state !== 'object' || state == null) {
+ return undefined;
+ }
+ if (!('status' in state) || state.status !== 'error') {
+ return undefined;
+ }
+ if (!('error' in state)) {
+ return 'Sub-agent failed';
+ }
+ const error = state.error;
+ return typeof error === 'string' && error.length > 0 ? error : 'Sub-agent failed';
+}
+
+/**
+ * Cancel often leaves a noisy "LLM stream aborted" error on the child thread.
+ * That is cancel cleanup, not a real sub-agent failure.
+ */
+export function isAbortShapedThreadError(message: string): boolean {
+ const normalized = message.trim().toLowerCase();
+ return (
+ normalized === 'llm stream aborted' ||
+ normalized === 'aborterror' ||
+ normalized.includes('stream aborted') ||
+ normalized.includes('aborterror')
+ );
+}
+
function isTurnScopedEvent(
message: TurnStreamingEvent,
): message is Extract<TurnStreamingEvent, { type: 'turn.created' | 'turn.done' }> {
@@ -173,6 +212,11 @@ function ingestEventIntoBucket(bucket: ThreadBucket, message: TurnStreamingEvent
if (message.title) {
bucket.title = message.title;
}
+ // Remember the failure message so the UI can show error instead of complete.
+ const errorMessage = threadDoneErrorMessage(message.state);
+ if (errorMessage != null) {
+ bucket.error = errorMessage;
+ }
}
}
@@ -303,15 +347,31 @@ function bucketHasUnresolvedPendingResponses(bucket: ThreadBucket): boolean {
return false;
}
-function bucketAssistantStatus(bucket: ThreadBucket): MessageStatus {
+function bucketAssistantStatus(bucket: ThreadBucket, state: PeerThreadFoldState): MessageStatus {
if (bucket.pendingApprovals.size > 0) {
return toolApprovalStatus();
}
if (bucketHasUnresolvedPendingResponses(bucket)) {
return toolResponseStatus();
}
- if (!bucket.done && bucket.modelMessageIds.length > 0) {
- return { type: 'running' };
+ // Parent was cancelled: unfinished (or abort-noise) children count as cancelled too.
+ if (state.parentTerminalStatus === 'cancelled') {
+ if (!bucket.done || (bucket.error != null && isAbortShapedThreadError(bucket.error))) {
+ return { type: 'incomplete', reason: 'cancelled' };
+ }
+ }
+ // Real sub-agent failure (not abort noise from a cancel).
+ if (bucket.error != null) {
+ return { type: 'incomplete', reason: 'error', error: bucket.error };
+ }
+ if (!bucket.done) {
+ // Parent already failed; child never finished — show parent failure, not "running".
+ if (state.parentTerminalStatus === 'error') {
+ return { type: 'incomplete', reason: 'error', error: 'Parent turn failed' };
+ }
+ if (bucket.modelMessageIds.length > 0) {
+ return { type: 'running' };
+ }
}
return { type: 'complete', reason: 'stop' };
}
@@ -447,7 +507,7 @@ function buildSubThreadMessages(state: PeerThreadFoldState, threadId: string): T
id: `${threadId}-assistant`,
role: 'assistant',
content,
- status: bucketAssistantStatus(bucket),
+ status: bucketAssistantStatus(bucket, state),
createdAt: new Date(),
metadata: {
unstable_state: null,
diff --git a/packages/assistant-ui-runtime/test/convertTurnMessages.test.ts b/packages/assistant-ui-runtime/test/convertTurnMessages.test.ts
index 1b8a1f9ba..8e9dc016b 100644
--- a/packages/assistant-ui-runtime/test/convertTurnMessages.test.ts
+++ b/packages/assistant-ui-runtime/test/convertTurnMessages.test.ts
@@ -694,6 +694,121 @@ describe('convertTurnMessages', () => {
});
});
+ it('marks unfinished nested sub-agent cancelled when parent turn.done is cancelled', async () => {
+ const result = await convertTurnsToThreadMessages(
+ mockServerWithTurns([
+ mockTurn({
+ id: 'turn-cancel-sub',
+ createdAt,
+ input: [{ type: 'user.message', content: 'hunt' }],
+ state: { status: 'cancelled', reason: 'client-cancelled', completedAt: createdAt },
+ events: [
+ modelMessage({
+ id: 'root-msg',
+ threadId: ROOT_THREAD_ID,
+ toolCalls: [
+ {
+ id: 'spawn-1',
+ type: 'function',
+ function: { name: 'create_sub_agent', arguments: '{}' },
+ toolInfo: { type: 'trueforge-system', name: 'create_sub_agent' },
+ },
+ ],
+ }),
+ {
+ type: 'thread.created',
+ id: 't-created',
+ threadId: 'child-1',
+ title: 'finder',
+ createdAt,
+ agentInfo: { type: 'dynamic', name: 'finder', input: 'find' },
+ parent: { threadId: ROOT_THREAD_ID, toolCallId: 'spawn-1' },
+ },
+ modelMessage({
+ id: 'child-msg',
+ threadId: 'child-1',
+ content: 'still working',
+ }),
+ ],
+ }),
+ ]),
+ SESSION_ID,
+ );
+
+ const assistant = result.messages[1];
+ expect(assistant).toMatchObject({
+ role: 'assistant',
+ status: { type: 'incomplete', reason: 'cancelled' },
+ metadata: { custom: { cancellationReason: 'client-cancelled' } },
+ });
+ const spawn =
+ assistant?.role === 'assistant' ? assistant.content.find(part => part.type === 'tool-call') : undefined;
+ expect(spawn?.type).toBe('tool-call');
+ if (spawn?.type !== 'tool-call') return;
+ expect(spawn.messages?.[0]?.status).toEqual({ type: 'incomplete', reason: 'cancelled' });
+ });
+
+ it('marks abort-shaped nested thread.done error as cancelled when parent turn is cancelled', async () => {
+ const result = await convertTurnsToThreadMessages(
+ mockServerWithTurns([
+ mockTurn({
+ id: 'turn-cancel-abort',
+ createdAt,
+ input: [{ type: 'user.message', content: 'hunt' }],
+ state: { status: 'cancelled', reason: 'client-cancelled', completedAt: createdAt },
+ events: [
+ modelMessage({
+ id: 'root-msg',
+ threadId: ROOT_THREAD_ID,
+ toolCalls: [
+ {
+ id: 'spawn-1',
+ type: 'function',
+ function: { name: 'create_sub_agent', arguments: '{}' },
+ toolInfo: { type: 'trueforge-system', name: 'create_sub_agent' },
+ },
+ ],
+ }),
+ {
+ type: 'thread.created',
+ id: 't-created',
+ threadId: 'child-1',
+ title: 'finder',
+ createdAt,
+ agentInfo: { type: 'dynamic', name: 'finder', input: 'find' },
+ parent: { threadId: ROOT_THREAD_ID, toolCallId: 'spawn-1' },
+ },
+ modelMessage({
+ id: 'child-msg',
+ threadId: 'child-1',
+ content: 'still working',
+ }),
+ {
+ type: 'thread.done',
+ id: 't-done',
+ threadId: 'child-1',
+ title: 'finder',
+ createdAt,
+ state: { status: 'error', error: 'LLM stream aborted' },
+ },
+ ],
+ }),
+ ]),
+ SESSION_ID,
+ );
+
+ const assistant = result.messages[1];
+ expect(assistant).toMatchObject({
+ role: 'assistant',
+ status: { type: 'incomplete', reason: 'cancelled' },
+ });
+ const spawn =
+ assistant?.role === 'assistant' ? assistant.content.find(part => part.type === 'tool-call') : undefined;
+ expect(spawn?.type).toBe('tool-call');
+ if (spawn?.type !== 'tool-call') return;
+ expect(spawn.messages?.[0]?.status).toEqual({ type: 'incomplete', reason: 'cancelled' });
+ });
+
it('carries sandboxId from a historical sandbox.created event onto the assistant message', async () => {
const result = await convertTurnsToThreadMessages(
mockServerWithTurns([
@@ -1581,6 +1696,67 @@ describe('convertTurnMessages', () => {
]);
});
+ it('projects abort-shaped nested thread.done as cancelled on live turn.done cancel', async () => {
+ const foldState = new PeerThreadFoldState();
+ const updates = await collectStream(
+ streamTurnEvents(
+ streamFrom([
+ modelMessage({
+ id: 'root-msg',
+ threadId: ROOT_THREAD_ID,
+ toolCalls: [
+ {
+ id: 'spawn-1',
+ type: 'function',
+ function: { name: 'create_sub_agent', arguments: '{}' },
+ toolInfo: { type: 'trueforge-system', name: 'create_sub_agent' },
+ },
+ ],
+ }),
+ {
+ type: 'thread.created',
+ id: 't-created',
+ threadId: 'child-1',
+ title: 'finder',
+ createdAt,
+ agentInfo: { type: 'dynamic', name: 'finder', input: 'find' },
+ parent: { threadId: ROOT_THREAD_ID, toolCallId: 'spawn-1' },
+ },
+ modelMessage({
+ id: 'child-msg',
+ threadId: 'child-1',
+ content: 'working',
+ }),
+ {
+ type: 'thread.done',
+ id: 't-done',
+ threadId: 'child-1',
+ title: 'finder',
+ createdAt,
+ state: { status: 'error', error: 'LLM stream aborted' },
+ },
+ {
+ type: 'turn.done',
+ id: 'turn-done-cancel',
+ createdAt,
+ state: { status: 'cancelled', reason: 'client-cancelled', completedAt: createdAt },
+ },
+ ]),
+ foldState,
+ ),
+ );
+
+ const last = updates[updates.length - 1];
+ expect(last).toMatchObject({
+ status: { type: 'incomplete', reason: 'cancelled' },
+ metadata: { custom: { cancellationReason: 'client-cancelled' } },
+ });
+ const spawn = last?.content.find(part => part.type === 'tool-call');
+ expect(spawn?.type).toBe('tool-call');
+ if (spawn?.type !== 'tool-call') return;
+ expect(spawn.messages?.[0]?.status).toEqual({ type: 'incomplete', reason: 'cancelled' });
+ });
+
it('does not let a post-loop sandbox flush overwrite a cancelled turn.done', async () => {
const foldState = new PeerThreadFoldState();
const updates = await collectStream(
diff --git a/packages/assistant-ui-runtime/test/foldPeerThreads.test.ts b/packages/assistant-ui-runtime/test/foldPeerThreads.test.ts
index 69eae2510..88dd9bde4 100644
--- a/packages/assistant-ui-runtime/test/foldPeerThreads.test.ts
+++ b/packages/assistant-ui-runtime/test/foldPeerThreads.test.ts
@@ -422,4 +422,208 @@ describe('foldPeerThreads', () => {
expect(toolCall.isError).toBe(true);
expect(toolCall.result).toEqual({ error: 'not allowed' });
});
+
+ it('marks nested sub-agent incomplete when thread.done is error', () => {
+ const state = new PeerThreadFoldState();
+
+ ingestTurnEvent(
+ state,
+ modelMessage({
+ id: 'root-msg',
+ threadId: ROOT_THREAD_ID,
+ toolCalls: [
+ {
+ id: 'spawn-1',
+ type: 'function',
+ function: { name: 'create_sub_agent', arguments: '{}' },
+ toolInfo: { type: 'trueforge-system', name: 'create_sub_agent' },
+ },
+ ],
+ }),
+ );
+ ingestTurnEvent(
+ state,
+ threadCreated({
+ id: 't-created',
+ threadId: 'child-1',
+ title: 'Research agent',
+ agentInfo: { type: 'dynamic', name: 'researcher', input: 'do research' },
+ parent: { threadId: ROOT_THREAD_ID, toolCallId: 'spawn-1' },
+ }),
+ );
+ ingestTurnEvent(
+ state,
+ modelMessage({
+ id: 'child-msg',
+ threadId: 'child-1',
+ content: 'working',
+ }),
+ );
+ ingestTurnEvent(state, {
+ type: 'thread.done',
+ id: 't-done',
+ threadId: 'child-1',
+ createdAt,
+ state: { status: 'error', error: 'sub-agent blew up' },
+ });
+
+ const spawn = buildRootAssistantContent(state).find(part => part.type === 'tool-call');
+ expect(spawn?.type).toBe('tool-call');
+ if (spawn?.type !== 'tool-call') return;
+ expect(spawn.messages?.[0]?.status).toEqual({
+ type: 'incomplete',
+ reason: 'error',
+ error: 'sub-agent blew up',
+ });
+ });
+
+ it('marks unfinished nested sub-agent cancelled when parent turn is cancelled', () => {
+ const state = new PeerThreadFoldState();
+
+ ingestTurnEvent(
+ state,
+ modelMessage({
+ id: 'root-msg',
+ threadId: ROOT_THREAD_ID,
+ toolCalls: [
+ {
+ id: 'spawn-1',
+ type: 'function',
+ function: { name: 'create_sub_agent', arguments: '{}' },
+ toolInfo: { type: 'trueforge-system', name: 'create_sub_agent' },
+ },
+ ],
+ }),
+ );
+ ingestTurnEvent(
+ state,
+ threadCreated({
+ id: 't-created',
+ threadId: 'child-1',
+ title: 'Research agent',
+ agentInfo: { type: 'dynamic', name: 'researcher', input: 'do research' },
+ parent: { threadId: ROOT_THREAD_ID, toolCallId: 'spawn-1' },
+ }),
+ );
+ ingestTurnEvent(
+ state,
+ modelMessage({
+ id: 'child-msg',
+ threadId: 'child-1',
+ content: 'working',
+ }),
+ );
+
+ state.parentTerminalStatus = 'cancelled';
+ const spawn = buildRootAssistantContent(state).find(part => part.type === 'tool-call');
+ expect(spawn?.type).toBe('tool-call');
+ if (spawn?.type !== 'tool-call') return;
+ expect(spawn.messages?.[0]?.status).toEqual({ type: 'incomplete', reason: 'cancelled' });
+ });
+
+ it('marks abort-shaped thread.done error as cancelled when parent turn is cancelled', () => {
+ const state = new PeerThreadFoldState();
+
+ ingestTurnEvent(
+ state,
+ modelMessage({
+ id: 'root-msg',
+ threadId: ROOT_THREAD_ID,
+ toolCalls: [
+ {
+ id: 'spawn-1',
+ type: 'function',
+ function: { name: 'create_sub_agent', arguments: '{}' },
+ toolInfo: { type: 'trueforge-system', name: 'create_sub_agent' },
+ },
+ ],
+ }),
+ );
+ ingestTurnEvent(
+ state,
+ threadCreated({
+ id: 't-created',
+ threadId: 'child-1',
+ title: 'Research agent',
+ agentInfo: { type: 'dynamic', name: 'researcher', input: 'do research' },
+ parent: { threadId: ROOT_THREAD_ID, toolCallId: 'spawn-1' },
+ }),
+ );
+ ingestTurnEvent(
+ state,
+ modelMessage({
+ id: 'child-msg',
+ threadId: 'child-1',
+ content: 'working',
+ }),
+ );
+ ingestTurnEvent(state, {
+ type: 'thread.done',
+ id: 't-done',
+ threadId: 'child-1',
+ createdAt,
+ state: { status: 'error', error: 'LLM stream aborted' },
+ });
+
+ state.parentTerminalStatus = 'cancelled';
+ const spawn = buildRootAssistantContent(state).find(part => part.type === 'tool-call');
+ expect(spawn?.type).toBe('tool-call');
+ if (spawn?.type !== 'tool-call') return;
+ expect(spawn.messages?.[0]?.status).toEqual({ type: 'incomplete', reason: 'cancelled' });
+ });
+
+ it('keeps non-abort thread.done error when parent turn is cancelled', () => {
+ const state = new PeerThreadFoldState();
+
+ ingestTurnEvent(
+ state,
+ modelMessage({
+ id: 'root-msg',
+ threadId: ROOT_THREAD_ID,
+ toolCalls: [
+ {
+ id: 'spawn-1',
+ type: 'function',
+ function: { name: 'create_sub_agent', arguments: '{}' },
+ toolInfo: { type: 'trueforge-system', name: 'create_sub_agent' },
+ },
+ ],
+ }),
+ );
+ ingestTurnEvent(
+ state,
+ threadCreated({
+ id: 't-created',
+ threadId: 'child-1',
+ title: 'Research agent',
+ agentInfo: { type: 'dynamic', name: 'researcher', input: 'do research' },
+ parent: { threadId: ROOT_THREAD_ID, toolCallId: 'spawn-1' },
+ }),
+ );
+ ingestTurnEvent(
+ state,
+ modelMessage({
+ id: 'child-msg',
+ threadId: 'child-1',
+ content: 'working',
+ }),
+ );
+ ingestTurnEvent(state, {
+ type: 'thread.done',
+ id: 't-done',
+ threadId: 'child-1',
+ createdAt,
+ state: { status: 'error', error: 'sub-agent blew up' },
+ });
+
+ state.parentTerminalStatus = 'cancelled';
+ const spawn = buildRootAssistantContent(state).find(part => part.type === 'tool-call');
+ expect(spawn?.type).toBe('tool-call');
+ if (spawn?.type !== 'tool-call') return;
+ expect(spawn.messages?.[0]?.status).toEqual({
+ type: 'incomplete',
+ reason: 'error',
+ error: 'sub-agent blew up',
+ });
+ });
});
diff --git a/packages/trueforge-ui/src/containers/AgentSessionTimelineContainer.tsx b/packages/trueforge-ui/src/containers/AgentSessionTimelineContainer.tsx
index c7a60b829..e22bca00e 100644
--- a/packages/trueforge-ui/src/containers/AgentSessionTimelineContainer.tsx
+++ b/packages/trueforge-ui/src/containers/AgentSessionTimelineContainer.tsx
@@ -162,8 +162,16 @@ function applyMcpAuthState(messages: ThreadMessageLike[], turn: SessionTurnView)
return messages.map((message, index) => (index === assistantIndex ? updatedAssistant : message));
}
+function messageBelongsToTurn(message: ThreadMessageLike, turnId: string): boolean {
+ if (turnIdFromMessage(message) === turnId) return true;
+ // Folded continuations keep `${openingTurnId}-assistant` but stamp the cancelling
+ // turn id on metadata.custom.turnId so the banner lands on the right section.
+ const customTurnId = message.metadata?.custom?.['turnId'];
+ return typeof customTurnId === 'string' && customTurnId === turnId;
+}
+
function messagesForTurn(messages: ThreadMessageLike[], turn: SessionTurnView): ThreadMessageLike[] {
- const matched = messages.filter(message => turnIdFromMessage(message) === turn.turnId);
+ const matched = messages.filter(message => messageBelongsToTurn(message, turn.turnId));
return applyMcpAuthState(matched, turn);
}
diff --git a/packages/trueforge-ui/src/utils/buildSessionTimelineSegments.ts b/packages/trueforge-ui/src/utils/buildSessionTimelineSegments.ts
index 756c55e4e..532e79c50 100644
--- a/packages/trueforge-ui/src/utils/buildSessionTimelineSegments.ts
+++ b/packages/trueforge-ui/src/utils/buildSessionTimelineSegments.ts
@@ -9,12 +9,16 @@ import {
getSubAgentDescription,
getTurnInputSummary,
getTurnInputType,
+ isAbortShapedThreadError,
+ isRecord,
parentToolCallId,
parseTimestamp,
readString,
terminalCompletedAt,
terminalMessage,
+ terminalReason,
terminalStatus,
+ terminalThreadError,
toolCallDescription,
toolCallsOf,
type TimelineEvent,
@@ -35,7 +39,8 @@ type SubAgentToolCallRequest = {
* to determine their end:
* - tool calls span from the model event that requested them to `tool.response`,
* or to `tool.response_required` / turn end when still waiting on a human;
- * - sub-agent tracks span from `thread.created` to `thread.done`;
+ * - sub-agent tracks span from `thread.created` to `thread.done`, or to
+ * `turn.done` when the child never emitted done (e.g. client cancel);
* - approval-gated and sub-agent parent calls are excluded from ordinary tool
* bars because they have dedicated visual representations.
*
@@ -318,17 +323,42 @@ function appendEventSegments({
}
const doneEvent = threadDoneEvents.get(threadId);
const doneMs = doneEvent == null ? null : parseTimestamp(eventCreatedAt(doneEvent));
+ // Cancelled unfinished children omit public thread.done; close the bar at turn end
+ // so the chart still allocates a lane for child model/tool segments.
+ const turnEndMs = parseTimestamp(terminalCompletedAt(turn.done?.state)) ?? parseTimestamp(turn.done?.createdAt);
+ const closeMs =
+ doneMs != null && doneMs >= eventMs ? doneMs : turnEndMs != null && turnEndMs >= eventMs ? turnEndMs : eventMs;
segments.push({
id: eventId(event),
type: 'sub_agent',
title: event.type,
description: getSubAgentDescription(event),
startMs: eventMs - originMs,
- endMs: doneMs != null && doneMs >= eventMs ? doneMs - originMs : eventMs - originMs,
+ endMs: closeMs - originMs,
turnIndex,
threadId,
- isMarker: doneMs == null || doneMs < eventMs,
+ isMarker: closeMs <= eventMs,
});
+ const doneState = doneEvent != null && isRecord(doneEvent.state) ? doneEvent.state : undefined;
+ if (doneState != null && terminalStatus(doneState) === 'error') {
+ const errorText = terminalThreadError(doneState);
+ const turnCancelled = terminalStatus(turn.done?.state) === 'cancelled';
+ // Cancel mid-stream can leave abort-shaped thread.done error; do not chart as failure.
+ if (!(turnCancelled && isAbortShapedThreadError(errorText))) {
+ const errorMs = doneMs ?? eventMs;
+ segments.push({
+ id: `${eventId(event)}-error`,
+ type: 'error',
+ title: 'thread.error',
+ description: errorText,
+ startMs: errorMs - originMs,
+ endMs: errorMs - originMs,
+ turnIndex,
+ threadId,
+ isMarker: true,
+ });
+ }
+ }
return;
}
case 'tool.approval_required':
@@ -410,6 +440,22 @@ function appendTerminalSegment({
});
return;
}
+ if (status === 'cancelled') {
+ const cancelledMs = parseTimestamp(terminalCompletedAt(turn.done?.state)) ?? latestMs;
+ const reason = terminalReason(turn.done?.state);
+ segments.push({
+ id: `${turn.turnId}-turn.cancelled`,
+ type: 'system',
+ title: 'turn.cancelled',
+ description: reason.length > 0 ? reason : 'cancelled',
+ startMs: cancelledMs - originMs,
+ endMs: cancelledMs - originMs,
+ turnIndex,
+ threadId: MAIN_THREAD_ID,
+ isMarker: true,
+ });
+ return;
+ }
if (status !== 'done' || !emitDoneMarker) return;
const doneMs = parseTimestamp(terminalCompletedAt(turn.done?.state));
if (doneMs == null) return;
diff --git a/packages/trueforge-ui/src/utils/sessionTimelineEvents.ts b/packages/trueforge-ui/src/utils/sessionTimelineEvents.ts
index 36ff7c55f..3d24c56e8 100644
--- a/packages/trueforge-ui/src/utils/sessionTimelineEvents.ts
+++ b/packages/trueforge-ui/src/utils/sessionTimelineEvents.ts
@@ -74,6 +74,29 @@ export function terminalMessage(state: unknown): string {
return isRecord(state) && typeof state.message === 'string' ? state.message : '';
}
+/** Cancel reason on turn.done (`client-cancelled`, etc.). */
+export function terminalReason(state: unknown): string {
+ return isRecord(state) ? (readString(state, 'reason', 'reason') ?? '') : '';
+}
+
+/** Sub-agent thread.done error text (`ThreadStateError.error`). */
+export function terminalThreadError(state: unknown): string {
+ if (!isRecord(state)) return '';
+ if (typeof state.error === 'string' && state.error.length > 0) return state.error;
+ return terminalMessage(state);
+}
+
+/** Cancel mid-stream can persist thread.done error "LLM stream aborted"; not a real failure. */
+export function isAbortShapedThreadError(message: string): boolean {
+ const normalized = message.trim().toLowerCase();
+ return (
+ normalized === 'llm stream aborted' ||
+ normalized === 'aborterror' ||
+ normalized.includes('stream aborted') ||
+ normalized.includes('aborterror')
+ );
+}
+
export function terminalStatus(state: unknown): string | undefined {
return isRecord(state) && typeof state.status === 'string' ? state.status : undefined;
}
diff --git a/packages/trueforge-ui/test/containers/AgentSessionTimelineContainer.test.tsx b/packages/trueforge-ui/test/containers/AgentSessionTimelineContainer.test.tsx
index 6b02bf97b..92c09d26d 100644
--- a/packages/trueforge-ui/test/containers/AgentSessionTimelineContainer.test.tsx
+++ b/packages/trueforge-ui/test/containers/AgentSessionTimelineContainer.test.tsx
@@ -193,10 +193,14 @@ describe('AgentSessionTimelineContainer', () => {
});
it('keeps responses in their backend turns and renders terminal failures', async () => {
+ let timelineTitles: string[] = [];
render(
<SlotsProvider
overrides={{
- AgentSessionEventTimeline: () => null,
+ AgentSessionEventTimeline: ({ segments }) => {
+ timelineTitles = segments.map(segment => segment.title);
+ return null;
+ },
}}
>
<ServerProvider server={createMockAgentUIServer()}>
@@ -223,6 +227,10 @@ describe('AgentSessionTimelineContainer', () => {
expect(within(turn2).getByText('turn two response')).toBeInTheDocument();
expect(within(turn3).getByText('client-cancelled')).toBeInTheDocument();
expect(within(turn4).getByText('model failed')).toBeInTheDocument();
+ await waitFor(() => {
+ expect(timelineTitles).toContain('turn.cancelled');
+ expect(timelineTitles).toContain('turn.error');
+ });
});
it('disables sandbox artifact downloads in session turns', async () => {
diff --git a/packages/trueforge-ui/test/utils/sessionEventTimeline.test.ts b/packages/trueforge-ui/test/utils/sessionEventTimeline.test.ts
index 049726e6f..b671670bc 100644
--- a/packages/trueforge-ui/test/utils/sessionEventTimeline.test.ts
+++ b/packages/trueforge-ui/test/utils/sessionEventTimeline.test.ts
@@ -55,10 +55,12 @@ function done({
turnId,
createdAt,
status = 'done',
+ reason,
}: {
turnId: string;
createdAt: string;
- status?: 'done' | 'error';
+ status?: 'done' | 'error' | 'cancelled';
+ reason?: string;
}): SessionEventItem {
return {
turnId,
@@ -68,7 +70,13 @@ function done({
state:
status === 'error'
? { status: 'error', message: 'failed', completedAt: createdAt }
- : { status: 'done', completedAt: createdAt, output: null, requiredActions: [] },
+ : status === 'cancelled'
+ ? {
+ status: 'cancelled',
+ reason: reason ?? 'client-cancelled',
+ completedAt: createdAt,
+ }
+ : { status: 'done', completedAt: createdAt, output: null, requiredActions: [] },
createdAt,
threadId: null,
},
@@ -706,6 +714,219 @@ describe('buildSessionMetrics', () => {
assert.equal(metrics.errors, 0);
});
+ it('emits a cancelled marker with reason and does not count it as an error', () => {
+ const turns = buildSessionTurnViews([
+ created({ turnId: 't1', createdAt: '2026-01-01T00:00:00.000Z' }),
+ done({
+ turnId: 't1',
+ createdAt: '2026-01-01T00:00:05.000Z',
+ status: 'cancelled',
+ reason: 'client-cancelled',
+ }),
+ ]);
+ const segments = buildSessionTimelineSegments(turns);
+ const cancelled = segments.find(segment => segment.title === 'turn.cancelled');
+ assert.equal(cancelled?.type, 'system');
+ assert.equal(cancelled?.description, 'client-cancelled');
+ assert.equal(cancelled?.isMarker, true);
+ const metrics = buildSessionMetrics({ turns, segments });
+ assert.equal(metrics.errors, 0);
+ });
+
+ it('emits a thread.error marker for failed sub-agents and counts it in errors', () => {
+ const turns = buildSessionTurnViews([
+ created({ turnId: 't1', createdAt: '2026-01-01T00:00:00.000Z' }),
+ {
+ turnId: 't1',
+ event: {
+ type: 'model.message',
+ id: 'model-1',
+ threadId: 'main',
+ content: 'spawn',
+ createdAt: '2026-01-01T00:00:01.000Z',
+ toolCalls: [
+ {
+ id: 'call-sub',
+ type: 'function',
+ function: { name: 'create_sub_agent', arguments: '{}' },
+ },
+ ],
+ },
+ },
+ {
+ turnId: 't1',
+ event: {
+ type: 'thread.created',
+ id: 'thread-1',
+ threadId: 'child',
+ title: 'Researcher',
+ createdAt: '2026-01-01T00:00:01.100Z',
+ agentInfo: { type: 'dynamic', name: 'researcher', input: 'research' },
+ parent: { threadId: 'main', toolCallId: 'call-sub' },
+ },
+ },
+ {
+ turnId: 't1',
+ event: {
+ type: 'thread.done',
+ id: 'thread-done',
+ threadId: 'child',
+ title: 'Researcher',
+ createdAt: '2026-01-01T00:00:04.000Z',
+ state: { status: 'error', error: 'sub-agent blew up' },
+ },
+ },
+ done({ turnId: 't1', createdAt: '2026-01-01T00:00:05.000Z' }),
+ ]);
+
+ const segments = buildSessionTimelineSegments(turns);
+ const threadError = segments.find(segment => segment.title === 'thread.error');
+ assert.equal(threadError?.type, 'error');
+ assert.equal(threadError?.description, 'sub-agent blew up');
+ assert.equal(threadError?.threadId, 'child');
+ const metrics = buildSessionMetrics({ turns, segments });
+ assert.equal(metrics.errors, 1);
+ });
+
+ it('closes unfinished sub-agent bars at turn.done when thread.done is missing', () => {
+ const turns = buildSessionTurnViews([
+ created({ turnId: 't1', createdAt: '2026-01-01T00:00:00.000Z' }),
+ {
+ turnId: 't1',
+ event: {
+ type: 'model.message',
+ id: 'model-1',
+ threadId: 'main',
+ content: 'spawn',
+ createdAt: '2026-01-01T00:00:01.000Z',
+ toolCalls: [
+ {
+ id: 'call-sub',
+ type: 'function',
+ function: { name: 'create_sub_agent', arguments: '{}' },
+ },
+ ],
+ },
+ },
+ {
+ turnId: 't1',
+ event: {
+ type: 'thread.created',
+ id: 'thread-1',
+ threadId: 'child',
+ title: 'Researcher',
+ createdAt: '2026-01-01T00:00:01.100Z',
+ agentInfo: { type: 'dynamic', name: 'researcher', input: 'research' },
+ parent: { threadId: 'main', toolCallId: 'call-sub' },
+ },
+ },
+ {
+ turnId: 't1',
+ event: {
+ type: 'model.message',
+ id: 'child-model',
+ threadId: 'child',
+ content: 'working',
+ createdAt: '2026-01-01T00:00:02.000Z',
+ toolCalls: [
+ {
+ id: 'call-exec',
+ type: 'function',
+ function: { name: 'exec', arguments: '{}' },
+ },
+ ],
+ },
+ },
+ {
+ turnId: 't1',
+ event: {
+ type: 'tool.response',
+ id: 'tool-1',
+ threadId: 'child',
+ toolCallId: 'call-exec',
+ content: 'ok',
+ createdAt: '2026-01-01T00:00:04.000Z',
+ },
+ },
+ done({
+ turnId: 't1',
+ createdAt: '2026-01-01T00:00:05.000Z',
+ status: 'cancelled',
+ reason: 'client-cancelled',
+ }),
+ ]);
+
+ const segments = buildSessionTimelineSegments(turns);
+ const subAgent = segments.find(segment => segment.type === 'sub_agent');
+ assert.ok(subAgent);
+ assert.equal(subAgent.isMarker, false);
+ assert.equal(subAgent.startMs, 1_100);
+ assert.equal(subAgent.endMs, 5_000);
+ assert.ok(segments.some(segment => segment.threadId === 'child' && segment.type === 'tool_call'));
+ });
+
+ it('suppresses abort-shaped thread.error on cancelled turns and does not count it', () => {
+ const turns = buildSessionTurnViews([
+ created({ turnId: 't1', createdAt: '2026-01-01T00:00:00.000Z' }),
+ {
+ turnId: 't1',
+ event: {
+ type: 'model.message',
+ id: 'model-1',
+ threadId: 'main',
+ content: 'spawn',
+ createdAt: '2026-01-01T00:00:01.000Z',
+ toolCalls: [
+ {
+ id: 'call-sub',
+ type: 'function',
+ function: { name: 'create_sub_agent', arguments: '{}' },
+ },
+ ],
+ },
+ },
+ {
+ turnId: 't1',
+ event: {
+ type: 'thread.created',
+ id: 'thread-1',
+ threadId: 'child',
+ title: 'Researcher',
+ createdAt: '2026-01-01T00:00:01.100Z',
+ agentInfo: { type: 'dynamic', name: 'researcher', input: 'research' },
+ parent: { threadId: 'main', toolCallId: 'call-sub' },
+ },
+ },
+ {
+ turnId: 't1',
+ event: {
+ type: 'thread.done',
+ id: 'thread-done',
+ threadId: 'child',
+ title: 'Researcher',
+ createdAt: '2026-01-01T00:00:04.000Z',
+ state: { status: 'error', error: 'LLM stream aborted' },
+ },
+ },
+ done({
+ turnId: 't1',
+ createdAt: '2026-01-01T00:00:05.000Z',
+ status: 'cancelled',
+ reason: 'client-cancelled',
+ }),
+ ]);
+
+ const segments = buildSessionTimelineSegments(turns);
+ assert.equal(
+ segments.find(segment => segment.title === 'thread.error'),
+ undefined,
+ );
+ const cancelled = segments.find(segment => segment.title === 'turn.cancelled');
+ assert.equal(cancelled?.description, 'client-cancelled');
+ const metrics = buildSessionMetrics({ turns, segments });
+ assert.equal(metrics.errors, 0);
+ });
+
it('keeps aggregate cost undefined when no turn reports cost', () => {
const turns = buildSessionTurnViews([
created({ turnId: 't1', createdAt: '2026-01-01T00:00:00.000Z' }),