Skip to content

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

bugfix: Show cancelled reason and error messages for turn in chat (#1004)

harshil-20961513e912262d
diff --git a/.changeset/chat-cancelled-reason.md b/.changeset/chat-cancelled-reason.md
new file mode 100644
index 000000000..96704ef0d
--- /dev/null
+++ b/.changeset/chat-cancelled-reason.md
@@ -0,0 +1,6 @@
+---
+'@truefoundry/trueforge-assistant-ui-runtime': patch
+'@truefoundry/trueforge-ui': patch
+---
+
+Show cancelled turn reasons in chat and session detail via an orange cancelled banner, projecting the wire reason on message metadata from turn.done (including live commits).
diff --git a/packages/assistant-ui-runtime/src/convertTurnMessages.ts b/packages/assistant-ui-runtime/src/convertTurnMessages.ts
index 93dc9e459..1c87f6d84 100644
--- a/packages/assistant-ui-runtime/src/convertTurnMessages.ts
+++ b/packages/assistant-ui-runtime/src/convertTurnMessages.ts
@@ -30,6 +30,7 @@ import {
} from './foldPeerThreads.js';
import { drainListPages } from './listPages.js';
import { buildMcpAuthTextParts, mcpAuthAssistantStatus, mcpAuthMessageCustom } from './mcpAuth.js';
+import { CANCELLATION_REASON_CUSTOM_KEY } from './messageCustomMetadata.js';
import type { AssistantContentPart } from './modelMessageContent.js';
import { extractImageUrlFromUserContentItem, imageUrlToAttachment } from './modelMessageImageContent.js';
import {
@@ -68,6 +69,8 @@ import {
import { appendMcpAuthToTurnContent, appendToolApprovalToTurnContent } from './turnEventHelpers.js';
import type { TurnStreamUpdate } from './turnStreamUpdate.js';
+export { CANCELLATION_REASON_CUSTOM_KEY } from './messageCustomMetadata.js';
+
/**
* Turn / event → assistant-ui normalization
*
@@ -719,6 +722,32 @@ function assistantStatusFromTurnState(state: Turn['state']): MessageStatus {
}
}
+/**
+ * Cancelled-turn UI flow (chat + session detail share this projection):
+ *
+ * Example: turn.done { status: "cancelled", reason: "abandoned" } with no model
+ * text. Without special handling the chat would show only the user bubble.
+ *
+ * 1. Live SSE — streamTurnEvents yields status cancelled +
+ * metadata.cancellationReason = "abandoned" (no synthetic text part).
+ * 2. Commit — commitActiveStream reads that key, stores TurnStateCancelled on
+ * the turn record (not a fake "done"), then clears activeStream.
+ * 3. History / reload — projectHistoryTurns sees state.cancelled, puts the wire
+ * reason on metadata.custom, and always emits an assistant row even when the
+ * fold has no model.message parts. trueforge-ui renders the orange banner.
+ *
+ * assistant-ui MessageStatus only knows reason: "cancelled" (no wire reason),
+ * so the human-readable reason lives on metadata.custom.cancellationReason.
+ */
+
+/**
+ * Normal turns only get an assistant bubble when the model produced content.
+ * Cancelled/error turns still need a bubble so the banner/error chrome can show.
+ */
+function shouldEmitTerminalAssistant(state: Turn['state'], content: readonly AssistantContentPart[]): boolean {
+ return content.length > 0 || state.status === 'cancelled' || state.status === 'error';
+}
+
function resolveCreatedAt(
messageId: string,
fallback: Date,
@@ -1198,6 +1227,7 @@ function projectHistoryTurns(snapshot: SessionSnapshot, options?: ProjectSession
...baseCustom,
turnId: record.id,
...(sandboxId != null ? { sandboxId } : {}),
+ ...(record.state.status === 'cancelled' ? { [CANCELLATION_REASON_CUSTOM_KEY]: record.state.reason } : {}),
};
const assistantCreatedAt = record.state.status === 'running' ? record.createdAt : record.state.completedAt;
const replaceAssistantCreatedAt = record.state.status !== 'running';
@@ -1222,7 +1252,8 @@ function projectHistoryTurns(snapshot: SessionSnapshot, options?: ProjectSession
break;
}
- if (content.length > 0) {
+ // Includes empty cancelled/error turns so the terminal state is visible.
+ if (shouldEmitTerminalAssistant(record.state, content)) {
messages.push(
buildAssistantMessage(
record.id,
@@ -1235,8 +1266,12 @@ function projectHistoryTurns(snapshot: SessionSnapshot, options?: ProjectSession
),
);
lastAssistantIndex = messages.length - 1;
+ } else {
+ // New user group with no assistant of its own — do not let a later empty
+ // cancelled/error continuation fold into a prior group's assistant.
+ lastAssistantIndex = undefined;
}
- } else if (content.length > 0 && lastAssistantIndex != null) {
+ } else if (shouldEmitTerminalAssistant(record.state, content) && lastAssistantIndex != null) {
if (record.state.status === 'running') {
break;
}
@@ -1701,6 +1736,20 @@ export async function* streamTurnEvents(
if (event.state.status === 'error') {
throw new TurnFailedError(event.state.message);
}
+ // Live cancel: stash wire reason for commit + UI banner. Return so
+ // sandbox/MCP/approval post-loop yields cannot overwrite this update.
+ if (event.state.status === 'cancelled') {
+ const ids =
+ 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 } },
+ });
+ return;
+ }
// The turn is logically complete once `turn.done` is observed. The
// resumed-turn transport (`subscribeToTurn`) is a reconnectable live
// tail and is not guaranteed to close its SSE body right after this
diff --git a/packages/assistant-ui-runtime/src/index.ts b/packages/assistant-ui-runtime/src/index.ts
index b77c27c22..79c341516 100644
--- a/packages/assistant-ui-runtime/src/index.ts
+++ b/packages/assistant-ui-runtime/src/index.ts
@@ -39,7 +39,7 @@ export {
useTrueForgeTurnId,
useTrueForgeUpdateAgentSpec,
} from './hooks.js';
-export { isMcpServerAuthInfoList } from './messageCustomMetadata.js';
+export { CANCELLATION_REASON_CUSTOM_KEY, isMcpServerAuthInfoList } from './messageCustomMetadata.js';
export type {
McpAuthMessageCustomMetadata,
SandboxMessageCustomMetadata,
diff --git a/packages/assistant-ui-runtime/src/messageCustomMetadata.ts b/packages/assistant-ui-runtime/src/messageCustomMetadata.ts
index d31dcd2c9..48cfdc028 100644
--- a/packages/assistant-ui-runtime/src/messageCustomMetadata.ts
+++ b/packages/assistant-ui-runtime/src/messageCustomMetadata.ts
@@ -4,6 +4,9 @@ import type { SubAgentCustomMetadata } from './foldPeerThreads.js';
import { TOOL_APPROVAL_THREAD_ID_CUSTOM_KEY } from './toolApproval.js';
import { TOOL_RESPONSE_THREAD_ID_CUSTOM_KEY } from './toolResponse.js';
+/** Wire cancel reason from `turn.done` — UI reads this for the cancelled banner. */
+export const CANCELLATION_REASON_CUSTOM_KEY = 'cancellationReason';
+
/** Keys written to `ThreadMessage.metadata.custom` by this runtime adapter. */
export interface TrueForgeMessageCustomMetadata {
subAgent?: SubAgentCustomMetadata;
@@ -12,6 +15,7 @@ export interface TrueForgeMessageCustomMetadata {
sandboxId?: string;
/** Turn that produced this message. Scopes artifact downloads to their own turn. */
turnId?: string;
+ [CANCELLATION_REASON_CUSTOM_KEY]?: string;
[TOOL_APPROVAL_THREAD_ID_CUSTOM_KEY]?: string;
[TOOL_RESPONSE_THREAD_ID_CUSTOM_KEY]?: string;
}
diff --git a/packages/assistant-ui-runtime/src/useTrueForgeAgentMessages.ts b/packages/assistant-ui-runtime/src/useTrueForgeAgentMessages.ts
index 27a6730c8..1978f7bf9 100644
--- a/packages/assistant-ui-runtime/src/useTrueForgeAgentMessages.ts
+++ b/packages/assistant-ui-runtime/src/useTrueForgeAgentMessages.ts
@@ -16,6 +16,7 @@ import { ROOT_THREAD_ID } from './constants.js';
import {
buildEditedUserMessageContent,
buildSnapshotThroughTurn,
+ CANCELLATION_REASON_CUSTOM_KEY,
computeGroupRootBaseline,
extractTurnUserMessageContent,
prependOlderSessionHistory,
@@ -104,14 +105,40 @@ function buildCompletedTurnState(
};
}
-function buildCancelledTurnState(completedAt: string): TurnStateCancelled {
+function buildCancelledTurnState({
+ completedAt,
+ reason = 'Superseded by a later message',
+}: {
+ completedAt: string;
+ reason?: string;
+}): TurnStateCancelled {
return {
status: 'cancelled',
- reason: 'Superseded by a later message',
+ reason,
completedAt,
};
}
+/**
+ * Map the last stream update onto the turn record's terminal state.
+ * Prefer the wire cancellationReason from streamTurnEvents (e.g. "abandoned");
+ * otherwise treat a clean stream end as done.
+ */
+function committedStateFromActiveStream(
+ update: TurnStreamUpdate,
+ completedAt: string,
+): TurnStateDone | TurnStateCancelled {
+ const cancelReason = update.metadata?.custom?.[CANCELLATION_REASON_CUSTOM_KEY];
+ const status = update.status;
+ if ((status?.type === 'incomplete' && status.reason === 'cancelled') || typeof cancelReason === 'string') {
+ return buildCancelledTurnState({
+ completedAt,
+ reason: typeof cancelReason === 'string' ? cancelReason : 'client-cancelled',
+ });
+ }
+ return buildCompletedTurnState(completedAt, requiredActionsFromActiveUpdate(update));
+}
+
/**
* Custom stream adapters may yield projected content without fold events.
* Materialize that content so a cancelled commit still projects after
@@ -171,7 +198,7 @@ function abandonInFlightClientTurn(snapshot: SessionSnapshot): SessionSnapshot {
}
const completedAt = new Date().toISOString();
- const cancelledState = buildCancelledTurnState(completedAt);
+ const cancelledState = buildCancelledTurnState({ completedAt });
if (active != null && active.streamComplete !== true) {
const activeSandboxIdValue = active.update.metadata?.custom?.['sandboxId'];
@@ -333,12 +360,21 @@ function commitActiveStream(snapshot: SessionSnapshot, continuationInputs?: Requ
const activeSandboxIdValue = active.update.metadata?.custom?.['sandboxId'];
const activeSandboxId = typeof activeSandboxIdValue === 'string' ? activeSandboxIdValue : undefined;
- const completedState = buildCompletedTurnState(
- new Date().toISOString(),
- requiredActionsFromActiveUpdate(active.update),
- );
+ const completedState = committedStateFromActiveStream(active.update, new Date().toISOString());
const baseline = snapshot.groupRootBaseline ?? computeGroupRootBaseline(snapshot.turns);
- const rootModelMessageIds = rootModelMessageIdsSinceBaseline(snapshot.fold, baseline);
+ let rootModelMessageIds = rootModelMessageIdsSinceBaseline(snapshot.fold, baseline);
+ // Cancelled commits clear activeStream so history rebuilds from turn.state (banner).
+ // Custom adapters may have only update.content — materialize into the fold first
+ // so clearing activeStream does not drop streamed parts.
+ if (completedState.status === 'cancelled' && rootModelMessageIds.length === 0) {
+ rootModelMessageIds = materializeAbandonedStreamRootIds({
+ fold: snapshot.fold,
+ turnId: active.turnId,
+ content: active.update.content,
+ existingRootIds: rootModelMessageIds,
+ });
+ }
+ const clearActiveStream = rootModelMessageIds.length > 0 || completedState.status === 'cancelled';
const lastTurn = snapshot.turns.at(-1);
if (lastTurn?.id === active.turnId) {
@@ -355,9 +391,9 @@ function commitActiveStream(snapshot: SessionSnapshot, continuationInputs?: Requ
: turn,
),
pendingUser: undefined,
- // Custom stream adapters may yield projected content without fold events.
- // Keep that completed projection until the next stream replaces it.
- ...(rootModelMessageIds.length > 0 ? { activeStream: undefined } : {}),
+ // Non-cancel completes with an empty fold keep activeStream so custom adapters
+ // that only yielded update.content stay visible until the next stream.
+ ...(clearActiveStream ? { activeStream: undefined } : {}),
});
}
@@ -377,7 +413,7 @@ function commitActiveStream(snapshot: SessionSnapshot, continuationInputs?: Requ
return replaceSessionSnapshot(snapshot, {
turns: [...snapshot.turns, record],
pendingUser: undefined,
- ...(rootModelMessageIds.length > 0 ? { activeStream: undefined } : {}),
+ ...(clearActiveStream ? { activeStream: undefined } : {}),
});
}
diff --git a/packages/assistant-ui-runtime/test/convertTurnMessages.test.ts b/packages/assistant-ui-runtime/test/convertTurnMessages.test.ts
index d0978b6c7..1b8a1f9ba 100644
--- a/packages/assistant-ui-runtime/test/convertTurnMessages.test.ts
+++ b/packages/assistant-ui-runtime/test/convertTurnMessages.test.ts
@@ -619,6 +619,81 @@ describe('convertTurnMessages', () => {
expect(result.runningTurn).toBeUndefined();
});
+ it('emits an assistant row with cancellationReason for an empty cancelled turn', async () => {
+ const result = await convertTurnsToThreadMessages(
+ mockServerWithTurns([
+ mockTurn({
+ id: 'turn-abandoned',
+ createdAt,
+ input: [{ type: 'user.message', content: 'give me a pdf' }],
+ state: { status: 'cancelled', reason: 'abandoned', completedAt: createdAt },
+ events: [],
+ }),
+ ]),
+ SESSION_ID,
+ );
+
+ expect(result.messages).toHaveLength(2);
+ expect(result.messages[1]).toMatchObject({
+ id: 'turn-abandoned-assistant',
+ role: 'assistant',
+ content: [],
+ status: { type: 'incomplete', reason: 'cancelled' },
+ metadata: { custom: { cancellationReason: 'abandoned', turnId: 'turn-abandoned' } },
+ });
+ });
+
+ it('keeps model text and stamps cancellationReason on cancelled turns', async () => {
+ const result = await convertTurnsToThreadMessages(
+ mockServerWithTurns([
+ mockTurn({
+ id: 'turn-cancel',
+ createdAt,
+ input: [{ type: 'user.message', content: 'hello' }],
+ state: { status: 'cancelled', reason: 'client-cancelled', completedAt: createdAt },
+ events: [
+ modelMessage({
+ id: 'm1',
+ threadId: ROOT_THREAD_ID,
+ content: 'partial reply',
+ }),
+ ],
+ }),
+ ]),
+ SESSION_ID,
+ );
+
+ expect(result.messages[1]).toMatchObject({
+ role: 'assistant',
+ content: [{ type: 'text', text: 'partial reply' }],
+ status: { type: 'incomplete', reason: 'cancelled' },
+ metadata: { custom: { cancellationReason: 'client-cancelled', turnId: 'turn-cancel' } },
+ });
+ });
+
+ it('emits an assistant row for an empty error turn', async () => {
+ const result = await convertTurnsToThreadMessages(
+ mockServerWithTurns([
+ mockTurn({
+ id: 'turn-error',
+ createdAt,
+ input: [{ type: 'user.message', content: 'hello' }],
+ state: { status: 'error', message: 'model failed', completedAt: createdAt },
+ events: [],
+ }),
+ ]),
+ SESSION_ID,
+ );
+
+ expect(result.messages).toHaveLength(2);
+ expect(result.messages[1]).toMatchObject({
+ id: 'turn-error-assistant',
+ role: 'assistant',
+ content: [],
+ status: { type: 'incomplete', reason: 'error', error: 'model failed' },
+ });
+ });
+
it('carries sandboxId from a historical sandbox.created event onto the assistant message', async () => {
const result = await convertTurnsToThreadMessages(
mockServerWithTurns([
@@ -1480,6 +1555,57 @@ describe('convertTurnMessages', () => {
expect(updates).toEqual([{ content: [{ type: 'text', text: 'streaming' }], sequenceNumber: 1 }]);
});
+ it('yields Cancelled: reason and cancellationReason on cancelled turn.done', async () => {
+ const foldState = new PeerThreadFoldState();
+ const updates = await collectStream(
+ streamTurnEvents(
+ streamFrom([
+ {
+ type: 'turn.done',
+ id: 'turn-done-cancel',
+ createdAt,
+ state: { status: 'cancelled', reason: 'abandoned', completedAt: createdAt },
+ },
+ ]),
+ foldState,
+ ),
+ );
+
+ expect(updates).toEqual([
+ {
+ content: [],
+ status: { type: 'incomplete', reason: 'cancelled' },
+ metadata: { custom: { cancellationReason: 'abandoned' } },
+ sequenceNumber: 1,
+ },
+ ]);
+ });
+
+ it('does not let a post-loop sandbox flush overwrite a cancelled turn.done', async () => {
+ const foldState = new PeerThreadFoldState();
+ const updates = await collectStream(
+ streamTurnEvents(
+ streamFrom([
+ sandboxCreated({ id: 'sbx-evt', sandboxId: 'sbx-1' }),
+ {
+ type: 'turn.done',
+ id: 'turn-done-cancel',
+ createdAt,
+ state: { status: 'cancelled', reason: 'abandoned', completedAt: createdAt },
+ },
+ ]),
+ foldState,
+ ),
+ );
+
+ expect(updates).toHaveLength(1);
+ expect(updates[0]).toMatchObject({
+ content: [],
+ status: { type: 'incomplete', reason: 'cancelled' },
+ metadata: { custom: { cancellationReason: 'abandoned' } },
+ });
+ });
+
it('reports every stream sequence including events that do not yield UI', async () => {
const foldState = new PeerThreadFoldState();
const sequences: number[] = [];
diff --git a/packages/trueforge-ui/src/atoms/AssistantMessageBubble.tsx b/packages/trueforge-ui/src/atoms/AssistantMessageBubble.tsx
index e339c836a..7344a9e50 100644
--- a/packages/trueforge-ui/src/atoms/AssistantMessageBubble.tsx
+++ b/packages/trueforge-ui/src/atoms/AssistantMessageBubble.tsx
@@ -5,11 +5,19 @@ import { cn } from './lib/cn.js';
export type AssistantMessageBubbleProps = {
children: ReactNode;
error?: ReactNode;
+ /** Terminal status chrome (e.g. cancelled banner); rendered under message parts. */
+ statusBanner?: ReactNode;
actionBar?: ReactNode;
className?: string;
};
-export function AssistantMessageBubble({ children, error, actionBar, className }: AssistantMessageBubbleProps) {
+export function AssistantMessageBubble({
+ children,
+ error,
+ statusBanner,
+ actionBar,
+ className,
+}: AssistantMessageBubbleProps) {
return (
<div
data-slot="aui_assistant-message-root"
@@ -20,6 +28,7 @@ export function AssistantMessageBubble({ children, error, actionBar, className }
>
<div className="min-w-0 max-w-full">
{children}
+ {statusBanner}
{error && <div className="mt-2 text-sm text-failure-bg">{error}</div>}
</div>
{actionBar && <div className="mt-1">{actionBar}</div>}
diff --git a/packages/trueforge-ui/src/atoms/MessageCancelledBanner.tsx b/packages/trueforge-ui/src/atoms/MessageCancelledBanner.tsx
new file mode 100644
index 000000000..48441d661
--- /dev/null
+++ b/packages/trueforge-ui/src/atoms/MessageCancelledBanner.tsx
@@ -0,0 +1,30 @@
+import { Icon } from '../icons/Icon.js';
+import { cn } from './lib/cn.js';
+
+export type MessageCancelledBannerProps = {
+ /** Wire cancel reason as-is, e.g. "client-cancelled". */
+ message: string;
+ className?: string;
+};
+
+/** Orange warning banner for cancelled turns (Figma Agents cancelled status). */
+export function MessageCancelledBanner({ message, className }: MessageCancelledBannerProps) {
+ return (
+ <div
+ role="status"
+ className={cn(
+ 'aui-message-cancelled-root border-warning-bg bg-warning-bg/10 text-warning-bg mt-2 inline-flex w-fit max-w-full items-center gap-3 rounded-xl border px-3 py-1.5 text-sm font-medium leading-[1.4]',
+ className,
+ )}
+ >
+ <Icon name="circle-exclamation" size="1rem" className="text-warning-bg shrink-0" aria-hidden />
+ <span className="aui-message-cancelled-message min-w-0 break-words">{message}</span>
+ </div>
+ );
+}
+
+declare module '../theme/SlotsProvider.js' {
+ interface AtomSlots {
+ MessageCancelledBanner: typeof MessageCancelledBanner;
+ }
+}
diff --git a/packages/trueforge-ui/src/containers/AgentSessionTimelineContainer.tsx b/packages/trueforge-ui/src/containers/AgentSessionTimelineContainer.tsx
index b7cd00c6f..c7a60b829 100644
--- a/packages/trueforge-ui/src/containers/AgentSessionTimelineContainer.tsx
+++ b/packages/trueforge-ui/src/containers/AgentSessionTimelineContainer.tsx
@@ -109,47 +109,6 @@ function buildProjectionEvents(items: SessionEventItem[], turns: SessionTurnView
});
}
-function appendTerminalText(content: ThreadMessageLike['content'], text: string): ThreadMessageLike['content'] {
- const terminalPart: { type: 'text'; text: string } = { type: 'text', text };
- return typeof content === 'string' ? [{ type: 'text', text: content }, terminalPart] : [...content, terminalPart];
-}
-
-function applyTerminalState(messages: ThreadMessageLike[], turn: SessionTurnView): ThreadMessageLike[] {
- const state = turn.done?.state;
- if (state?.status !== 'error' && state?.status !== 'cancelled') return messages;
-
- // failures need an assistant row so the terminal state is visible.
- const assistantIndex = messages.findIndex(message => message.role === 'assistant');
- const assistant = assistantIndex < 0 ? undefined : messages[assistantIndex];
- const createdAt = new Date(state.completedAt ?? turn.done?.createdAt ?? turn.created.createdAt);
- const terminal: ThreadMessageLike =
- state.status === 'error'
- ? {
- ...(assistant ?? {
- id: `${turn.turnId}-assistant`,
- role: 'assistant',
- content: [],
- createdAt,
- metadata: { custom: { turnId: turn.turnId } },
- }),
- status: { type: 'incomplete', reason: 'error', error: state.message },
- }
- : {
- ...(assistant ?? {
- id: `${turn.turnId}-assistant`,
- role: 'assistant',
- content: [],
- createdAt,
- metadata: { custom: { turnId: turn.turnId } },
- }),
- content: appendTerminalText(assistant?.content ?? [], `Cancelled: ${state.reason}`),
- status: { type: 'incomplete', reason: 'cancelled' },
- };
-
- if (assistantIndex < 0) return [...messages, terminal];
- return messages.map((message, index) => (index === assistantIndex ? terminal : message));
-}
-
/** Retrieves MCP servers requiring OAuth in this turn from done actions or turn events. */
function findTurnMcpServers(turn: SessionTurnView) {
const actions = turn.done?.state.status === 'done' ? turn.done.state.requiredActions : undefined;
@@ -205,8 +164,7 @@ function applyMcpAuthState(messages: ThreadMessageLike[], turn: SessionTurnView)
function messagesForTurn(messages: ThreadMessageLike[], turn: SessionTurnView): ThreadMessageLike[] {
const matched = messages.filter(message => turnIdFromMessage(message) === turn.turnId);
- const withMcpAuth = applyMcpAuthState(matched, turn);
- return applyTerminalState(withMcpAuth, turn);
+ return applyMcpAuthState(matched, turn);
}
export type AgentSessionTimelineContainerProps = {
diff --git a/packages/trueforge-ui/src/containers/AssistantMessageContainer.tsx b/packages/trueforge-ui/src/containers/AssistantMessageContainer.tsx
index c17a96251..17473265c 100644
--- a/packages/trueforge-ui/src/containers/AssistantMessageContainer.tsx
+++ b/packages/trueforge-ui/src/containers/AssistantMessageContainer.tsx
@@ -2,7 +2,10 @@
import { useActionBarCopy, useMessageError, useThreadIsRunning, type PartState } from '@assistant-ui/core/react';
import { MessagePrimitive, useAuiState, type EnrichedPartState, type GroupByContext } from '@assistant-ui/react';
-import { useTrueForgeResumeUnavailable } from '@truefoundry/trueforge-assistant-ui-runtime';
+import {
+ CANCELLATION_REASON_CUSTOM_KEY,
+ useTrueForgeResumeUnavailable,
+} from '@truefoundry/trueforge-assistant-ui-runtime';
import { useTrackAnalytics } from '../analytics/AnalyticsProvider.js';
import { AnalyticsEvents } from '../analytics/events.js';
@@ -39,6 +42,7 @@ export function AssistantMessageContainer() {
const AssistantMessageBubble = useSlot('AssistantMessageBubble');
const MessageActionBar = useSlot('MessageActionBar');
const MessageErrorBanner = useSlot('MessageErrorBanner');
+ const MessageCancelledBanner = useSlot('MessageCancelledBanner');
const MessageIndicator = useSlot('MessageIndicator');
const isThreadRunning = useThreadIsRunning();
const resumeUnavailable = useTrueForgeResumeUnavailable();
@@ -46,6 +50,11 @@ export function AssistantMessageContainer() {
const createdAt = useAuiState(s => s.message.createdAt);
const sessionId = useAuiState(s => s.threadListItem.remoteId);
const isMessageRunning = useAuiState(s => s.message.status?.type === 'running');
+ const messageStatus = useAuiState(s => s.message.status);
+ const cancellationReason = useAuiState(s => {
+ const value = s.message.metadata?.custom?.[CANCELLATION_REASON_CUSTOM_KEY];
+ return typeof value === 'string' ? value : undefined;
+ });
const track = useTrackAnalytics();
const shell = useOptionalShellMode();
const shellAgent =
@@ -59,6 +68,10 @@ export function AssistantMessageContainer() {
};
const parts = useAuiState(s => s.message.parts);
+ const cancelledBanner =
+ messageStatus?.type === 'incomplete' && messageStatus.reason === 'cancelled'
+ ? (cancellationReason ?? 'cancelled')
+ : undefined;
const { cutIndex, hasFinal, toolCount, thinkingCount } = computeAgentStepsSplit(parts, isMessageRunning);
@@ -84,6 +97,7 @@ export function AssistantMessageContainer() {
<MessagePrimitive.Root data-role="assistant">
<AssistantMessageBubble
error={error !== undefined ? <MessageErrorBanner message={String(error)} /> : undefined}
+ statusBanner={cancelledBanner !== undefined ? <MessageCancelledBanner message={cancelledBanner} /> : undefined}
actionBar={
!isThreadRunning ? <MessageActionBar isCopied={isCopied} onCopy={onCopy} createdAt={createdAt} /> : undefined
}
diff --git a/packages/trueforge-ui/src/index.ts b/packages/trueforge-ui/src/index.ts
index 8a801f0c3..c0b6f86c4 100644
--- a/packages/trueforge-ui/src/index.ts
+++ b/packages/trueforge-ui/src/index.ts
@@ -108,6 +108,8 @@ export { Markdown, preloadMarkdownOpenUI } from './atoms/Markdown.js';
export type { MarkdownProps } from './atoms/Markdown.js';
export { MessageActionBar } from './atoms/MessageActionBar.js';
export type { MessageActionBarProps } from './atoms/MessageActionBar.js';
+export { MessageCancelledBanner } from './atoms/MessageCancelledBanner.js';
+export type { MessageCancelledBannerProps } from './atoms/MessageCancelledBanner.js';
export { MessageErrorBanner } from './atoms/MessageErrorBanner.js';
export type { MessageErrorBannerProps } from './atoms/MessageErrorBanner.js';
export { MessageIndicator } from './atoms/MessageIndicator.js';
diff --git a/packages/trueforge-ui/src/theme/defaultSlots.ts b/packages/trueforge-ui/src/theme/defaultSlots.ts
index c802e68fd..a627cf7ed 100644
--- a/packages/trueforge-ui/src/theme/defaultSlots.ts
+++ b/packages/trueforge-ui/src/theme/defaultSlots.ts
@@ -68,6 +68,7 @@ import { FilePreviewPanel } from '../atoms/FilePreviewPanel.js';
import { HistoryLoader } from '../atoms/HistoryLoader.js';
import { Markdown } from '../atoms/Markdown.js';
import { MessageActionBar } from '../atoms/MessageActionBar.js';
+import { MessageCancelledBanner } from '../atoms/MessageCancelledBanner.js';
import { MessageErrorBanner } from '../atoms/MessageErrorBanner.js';
import { MessageIndicator } from '../atoms/MessageIndicator.js';
import { MessageTimestamp } from '../atoms/MessageTimestamp.js';
@@ -189,6 +190,7 @@ export const defaultSlots = {
UserMessageEdit,
UserMessageActionBar,
MessageActionBar,
+ MessageCancelledBanner,
MessageErrorBanner,
MessageIndicator,
MessageTimestamp,
diff --git a/packages/trueforge-ui/test/atoms/MessageCancelledBanner.test.tsx b/packages/trueforge-ui/test/atoms/MessageCancelledBanner.test.tsx
new file mode 100644
index 000000000..96ab2d6fb
--- /dev/null
+++ b/packages/trueforge-ui/test/atoms/MessageCancelledBanner.test.tsx
@@ -0,0 +1,20 @@
+import { render, screen } from '@testing-library/react';
+import { describe, expect, it } from 'vitest';
+
+import { MessageCancelledBanner } from '@/atoms/MessageCancelledBanner.js';
+
+describe('MessageCancelledBanner', () => {
+ it('announces the cancelled message with warning styling', () => {
+ render(<MessageCancelledBanner message="client-cancelled" className="host-cancelled" />);
+
+ const banner = screen.getByRole('status');
+ expect(banner).toHaveTextContent('client-cancelled');
+ expect(banner).toHaveClass(
+ 'aui-message-cancelled-root',
+ 'host-cancelled',
+ 'border-warning-bg',
+ 'text-warning-bg',
+ 'w-fit',
+ );
+ });
+});
diff --git a/packages/trueforge-ui/test/containers/AgentSessionTimelineContainer.test.tsx b/packages/trueforge-ui/test/containers/AgentSessionTimelineContainer.test.tsx
index 8840cd7ac..6b02bf97b 100644
--- a/packages/trueforge-ui/test/containers/AgentSessionTimelineContainer.test.tsx
+++ b/packages/trueforge-ui/test/containers/AgentSessionTimelineContainer.test.tsx
@@ -221,7 +221,7 @@ describe('AgentSessionTimelineContainer', () => {
expect(within(turn1).queryByText('turn two response')).not.toBeInTheDocument();
expect(within(turn2).getByText('continue')).toBeInTheDocument();
expect(within(turn2).getByText('turn two response')).toBeInTheDocument();
- expect(within(turn3).getByText('Cancelled: client-cancelled')).toBeInTheDocument();
+ expect(within(turn3).getByText('client-cancelled')).toBeInTheDocument();
expect(within(turn4).getByText('model failed')).toBeInTheDocument();
});
diff --git a/packages/trueforge-ui/test/publicUiExports.test.ts b/packages/trueforge-ui/test/publicUiExports.test.ts
index 9cd132649..766560518 100644
--- a/packages/trueforge-ui/test/publicUiExports.test.ts
+++ b/packages/trueforge-ui/test/publicUiExports.test.ts
@@ -99,6 +99,7 @@ const expectedRuntimeExports: Array<keyof typeof sdk> = [
'McpAuthContainer',
'MessageActionBar',
'MessageAttachmentsContainer',
+ 'MessageCancelledBanner',
'MessageErrorBanner',
'MessageGroup',
'MessageIndicator',