feat(chat): show provider thinking traces (#11784)

Co-authored-by: maria-rcks <[email protected]>
Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
Co-authored-by: Cursor <[email protected]>
This commit is contained in:
authored and GitHub committed 2026-09-16 15:32:02 -03:00
1 parent f4ef5155fb
commit 052c7ae53e
32 files changed
+1923 -117

No files matched your search

@@ -1907,6 +1907,118 @@ describe("deriveMessagesTimelineRows", () => {
expect(rows.map((row) => row.id)).toEqual(["turn-fold:turn-1", "assistant-final-entry"]);
});
const reasoningEntry = (id: string, at: string, turnId: string | null) => ({
id,
kind: "message" as const,
createdAt: at,
message: {
id: id as never,
role: "reasoning" as const,
text: "weighing it up",
turnId: turnId as never,
createdAt: at,
updatedAt: at,
streaming: false,
},
});
const answerEntry = (id: string, at: string, turnId: string) => ({
id,
kind: "message" as const,
createdAt: at,
message: {
id: id as never,
role: "assistant" as const,
text: "the answer",
turnId: turnId as never,
createdAt: at,
updatedAt: at,
streaming: false,
},
});
const toolEntry = (id: string, at: string, turnId: string) => ({
id,
kind: "work" as const,
createdAt: at,
entry: {
id,
createdAt: at,
turnId: turnId as never,
label: "Ran a command",
tone: "tool" as const,
},
});
it("keeps a thought-only turn out of the work fold", () => {
const rows = deriveMessagesTimelineRows({
timelineEntries: [
reasoningEntry("reasoning-entry", "2026-01-01T00:00:01Z", "turn-1"),
answerEntry("assistant-entry", "2026-01-01T00:00:02Z", "turn-1"),
],
isWorking: false,
activeTurnStartedAt: null,
turnDiffSummaries: [],
supportsConversationRollback: false,
});
expect(rows.some((row) => row.kind === "turn-fold")).toBe(false);
expect(rows.map((row) => row.id)).toContain("reasoning-entry");
});
it("folds a thinking block away with the tool work beside it", () => {
const rows = deriveMessagesTimelineRows({
timelineEntries: [
reasoningEntry("reasoning-entry", "2026-01-01T00:00:01Z", "turn-1"),
toolEntry("tool-entry", "2026-01-01T00:00:02Z", "turn-1"),
answerEntry("assistant-entry", "2026-01-01T00:00:03Z", "turn-1"),
],
isWorking: false,
activeTurnStartedAt: null,
turnDiffSummaries: [],
supportsConversationRollback: false,
});
expect(rows.some((row) => row.kind === "turn-fold")).toBe(true);
expect(rows.map((row) => row.id)).not.toContain("reasoning-entry");
});
it("still folds a lone trailing tool call when a thought follows the answer", () => {
const rows = deriveMessagesTimelineRows({
timelineEntries: [
toolEntry("tool-before", "2026-01-01T00:00:01Z", "turn-1"),
answerEntry("assistant-entry", "2026-01-01T00:00:02Z", "turn-1"),
reasoningEntry("reasoning-after", "2026-01-01T00:00:03Z", "turn-1"),
toolEntry("tool-after", "2026-01-01T00:00:04Z", "turn-1"),
],
isWorking: false,
activeTurnStartedAt: null,
turnDiffSummaries: [],
supportsConversationRollback: false,
});
const ids = rows.map((row) => row.id);
expect(ids).not.toContain("tool-after");
expect(ids).not.toContain("reasoning-after");
});
it("does not let a stranded streaming thought hold a settled turn open", () => {
const stranded = reasoningEntry("reasoning-stranded", "2026-01-01T00:00:01Z", "turn-1");
const rows = deriveMessagesTimelineRows({
timelineEntries: [
{ ...stranded, message: { ...stranded.message, streaming: true } },
toolEntry("tool-entry", "2026-01-01T00:00:02Z", "turn-1"),
answerEntry("assistant-entry", "2026-01-01T00:00:03Z", "turn-1"),
],
isWorking: false,
activeTurnStartedAt: null,
turnDiffSummaries: [],
supportsConversationRollback: false,
});
expect(rows.some((row) => row.kind === "turn-fold")).toBe(true);
});
it("derives a sane duration for a steer-superseded turn with one instant commentary message", () => {
// A steer ends the previous turn early: its only message completes the
// instant it is created, and trailing work entries land after it. The
@@ -299,7 +299,7 @@ function maxIsoTimestamp(a: string | null, b: string | null): string | null {
export interface TimelineDurationMessage {
id: string;
role: "user" | "assistant" | "system";
role: ChatMessage["role"];
createdAt: string;
updatedAt: string;
streaming: boolean;
@@ -524,7 +524,7 @@ interface TurnFold {
* user sends a message, the previous turn is still the "active" one until the
* server creates the new turn, and folding must not flicker through that window.
*/
function deriveUnsettledTurnId(
export function deriveUnsettledTurnId(
latestTurn: TimelineLatestTurn | null,
runningTurnId: TurnId | null,
): TurnId | null {
@@ -546,7 +546,9 @@ function lastUserMessageIndex(timelineEntries: ReadonlyArray<TimelineEntry>): nu
function timelineEntryTurnId(entry: TimelineEntry): TurnId | null {
if (entry.kind === "message") {
return entry.message.role === "assistant" ? (entry.message.turnId ?? null) : null;
return entry.message.role === "assistant" || entry.message.role === "reasoning"
? (entry.message.turnId ?? null)
: null;
}
if (entry.kind === "proposed-plan") {
return entry.proposedPlan.turnId;
@@ -624,8 +626,13 @@ function deriveTurnFolds(input: {
pendingUserBoundary = entry.message.createdAt;
continue;
}
// Thinking is work, so it folds with the rest of it. A provider that
// interleaves a block with every tool call would otherwise leave dozens of
// "Thought" rows standing beside the "Worked for ..." summary.
// Nothing folds while the turn is live, which is when traces are watched.
const turnId =
entry.kind === "message" && entry.message.role === "assistant"
entry.kind === "message" &&
(entry.message.role === "assistant" || entry.message.role === "reasoning")
? (entry.message.turnId ?? null)
: entry.kind === "work"
? (entry.entry.turnId ?? null)
@@ -652,7 +659,10 @@ function deriveTurnFolds(input: {
if (input.terminalAssistantMessageIds.has(entry.message.id)) {
group.terminalEntry = entry;
}
if (entry.message.streaming) {
// A live turn is already excluded above, so only an answer still being
// written may hold a fold open. A thinking block stranded by a crashed
// provider keeps its streaming flag forever and must not.
if (entry.message.streaming && entry.message.role !== "reasoning") {
group.hasStreamingMessage = true;
}
}
@@ -670,6 +680,15 @@ function deriveTurnFolds(input: {
const terminalEntryIndex = group.terminalEntry
? group.entries.findIndex((entry) => entry.id === group.terminalEntry?.id)
: group.entries.length;
// Thinking blocks do not count toward "one trailing activity": a block can
// follow the answer, and it must not stop that lone tool call from folding
// the way it did before traces existed. Loop-invariant, so it is counted
// once: a long turn re-derives these rows on every work-log change.
const trailingEntryCount = group.entries.filter(
(candidate, candidateIndex) =>
candidateIndex > terminalEntryIndex &&
!(candidate.kind === "message" && candidate.message.role === "reasoning"),
).length;
for (const [index, entry] of group.entries.entries()) {
if (entry.id === group.terminalEntry?.id) {
continue;
@@ -677,10 +696,18 @@ function deriveTurnFolds(input: {
const isCompaction =
entry.kind === "work" && entry.entry.sourceActivityKind === "context-compaction";
const isSingleTrailingActivity =
group.entries.length === terminalEntryIndex + 2 &&
trailingEntryCount === 1 &&
entry.kind === "work" &&
!workEntryDisplayIndicatesToolFailure(entry.entry);
if (!isCompaction && index > terminalEntryIndex && !isSingleTrailingActivity) {
// A thinking block after the answer folds with its turn rather than
// trailing under it, which is what mobile already does.
const isReasoning = entry.kind === "message" && entry.message.role === "reasoning";
if (
!isCompaction &&
!isReasoning &&
index > terminalEntryIndex &&
!isSingleTrailingActivity
) {
continue;
}
// User input and subagent batches stay visible after their turn settles.
@@ -696,13 +723,16 @@ function deriveTurnFolds(input: {
continue;
}
// A lone compaction row stays visible on its own; it only folds away as
// part of a turn that already folds other work.
const hidesNonCompactionWork = group.entries.some(
// part of a turn that already folds other work. Thinking is the same: a
// question answered by thought alone keeps its "Thought" row
// rather than collapsing behind a "Worked for ..." that hides nothing else.
const hidesFoldableWork = group.entries.some(
(entry) =>
hiddenEntryIds.has(entry.id) &&
!(entry.kind === "work" && entry.entry.sourceActivityKind === "context-compaction"),
!(entry.kind === "work" && entry.entry.sourceActivityKind === "context-compaction") &&
!(entry.kind === "message" && entry.message.role === "reasoning"),
);
if (!hidesNonCompactionWork) {
if (!hidesFoldableWork) {
continue;
}
@@ -778,7 +808,15 @@ function attachTrailingToolGroupsToAssistant(
let hasTrailingToolGroup = false;
for (let index = messageIndex + 1; index < rows.length; index += 1) {
const candidate = rows[index];
if (!candidate || candidate.kind === "message") {
if (!candidate) {
break;
}
// A thinking block can follow the answer (the next one starts before its
// tool call); it is not another message in the conversation.
if (candidate.kind === "message" && candidate.message.role === "reasoning") {
continue;
}
if (candidate.kind === "message") {
break;
}
if (candidate.kind === "work-toggle" && candidate.turnId === turnId) {
@@ -1326,6 +1364,16 @@ export function deriveMessagesTimelineRows(input: {
);
}
}
// A live thinking block is the real version of the placeholder below, so it
// suppresses it rather than sitting under a second "Thinking" row.
const hasStreamingReasoningRow = nextRows.some(
(row) =>
row.kind === "message" &&
row.message.role === "reasoning" &&
row.message.streaming &&
row.message.turnId !== null &&
row.message.turnId === unsettledTurnId,
);
// A running setup owns the working slot above its card and shows no
// activity row of its own; every other state gets the usual tail.
@@ -1333,7 +1381,12 @@ export function deriveMessagesTimelineRows(input: {
if (input.isWorking && !hasWorkingRow && activeTurnHeaderIndex === input.timelineEntries.length) {
appendWorkingRow();
}
if (input.isWorking && !setupRunning && (!hasActivityRow || latestToolFailed)) {
if (
input.isWorking &&
!setupRunning &&
!hasStreamingReasoningRow &&
(!hasActivityRow || latestToolFailed)
) {
nextRows.push({
kind: "thinking",
id: LIVE_ACTIVITY_ROW_ID,
@@ -167,6 +167,7 @@ import { useAssistantCitationTarget, type CitationHistoryPage } from "./useAssis
import {
computeStableMessagesTimelineRows,
deriveMessagesTimelineRowsWithState,
deriveUnsettledTurnId,
type MessagesTimelineRowsProjection,
liveWorkEntryLabel,
resolveAssistantMessageCopyState,
@@ -280,6 +281,8 @@ interface TimelineRowSharedState {
onToggleWorkGroup: (groupId: string, anchorKey: string) => void;
onToggleWorkEntry: (anchorKey: string, collapsed: boolean) => void;
onToggleSpawnRow: (entryId: string, expanded: boolean) => void;
onToggleReasoning: (messageId: string, expanded: boolean) => void;
expandedReasoningMessageIds: ReadonlySet<string>;
workGroupViewState: WorkGroupViewState;
agentPanelModel: AgentPanelModel;
expandedSpawnEntryIds: ReadonlySet<string>;
@@ -298,6 +301,7 @@ interface TimelineRowActivityState {
isCompacting: boolean;
isRevertingCheckpoint: boolean;
latestTurnId: TurnId | null;
unsettledTurnId: TurnId | null;
/**
* A worktree setup whose script is still running after the agent took
* over. The working header shows it as a chip with a popover; the stage
@@ -516,6 +520,9 @@ export const MessagesTimeline = memo(function MessagesTimeline({
const [expandedSpawnEntryIds, setExpandedSpawnEntryIds] = useState<ReadonlySet<string>>(
new Set(),
);
const [expandedReasoningMessageIds, setExpandedReasoningMessageIds] = useState<
ReadonlySet<string>
>(new Set());
const listIdentityKey = displayThreadKey ?? routeThreadKey;
const prefersReducedMotion = useMediaQuery("(prefers-reduced-motion: reduce)");
const listIdentityRef = useRef(listIdentityKey);
@@ -526,6 +533,7 @@ export const MessagesTimeline = memo(function MessagesTimeline({
let paintedExpandedTurnIds = expandedTurnIds;
let paintedExpandedWorkGroupIds = expandedWorkGroupIds;
let paintedExpandedSpawnEntryIds = expandedSpawnEntryIds;
let paintedExpandedReasoningMessageIds = expandedReasoningMessageIds;
if (listIdentityRef.current !== listIdentityKey) {
listIdentityRef.current = listIdentityKey;
previousLatestTurnRef.current = latestTurn;
@@ -533,9 +541,11 @@ export const MessagesTimeline = memo(function MessagesTimeline({
paintedExpandedTurnIds = new Set();
paintedExpandedWorkGroupIds = new Set();
paintedExpandedSpawnEntryIds = new Set();
paintedExpandedReasoningMessageIds = new Set();
setExpandedTurnIds(paintedExpandedTurnIds);
setExpandedWorkGroupIds(paintedExpandedWorkGroupIds);
setExpandedSpawnEntryIds(paintedExpandedSpawnEntryIds);
setExpandedReasoningMessageIds(paintedExpandedReasoningMessageIds);
}
const onToggleSpawnRow = useCallback((entryId: string, expanded: boolean) => {
setExpandedSpawnEntryIds((current) => {
@@ -660,6 +670,21 @@ export const MessagesTimeline = memo(function MessagesTimeline({
},
[expandedWorkGroupIds, suspendEndScrollMaintenanceForDisclosure],
);
const onToggleReasoning = useCallback(
(messageId: string, expanded: boolean) => {
// The anchor must be the timeline row id, which for a message row is the
// message id, or position restoration is skipped for every row.
suspendEndScrollMaintenanceForDisclosure(messageId, !expanded);
setExpandedReasoningMessageIds((current) => {
if (current.has(messageId) === expanded) return current;
const next = new Set(current);
if (expanded) next.add(messageId);
else next.delete(messageId);
return next;
});
},
[suspendEndScrollMaintenanceForDisclosure],
);
// An in-session interrupt leaves its turn expanded so the user keeps their
// place; the next turn (or a reload, since this is local state) folds it.
@@ -944,6 +969,8 @@ export const MessagesTimeline = memo(function MessagesTimeline({
onToggleWorkGroup,
onToggleWorkEntry: suspendEndScrollMaintenanceForDisclosure,
onToggleSpawnRow,
onToggleReasoning,
expandedReasoningMessageIds: paintedExpandedReasoningMessageIds,
workGroupViewState,
agentPanelModel: agentPanelModel ?? EMPTY_AGENT_PANEL_MODEL,
expandedSpawnEntryIds: paintedExpandedSpawnEntryIds,
@@ -977,6 +1004,8 @@ export const MessagesTimeline = memo(function MessagesTimeline({
onToggleWorkGroup,
suspendEndScrollMaintenanceForDisclosure,
onToggleSpawnRow,
onToggleReasoning,
paintedExpandedReasoningMessageIds,
workGroupViewState,
agentPanelModel,
paintedExpandedSpawnEntryIds,
@@ -1003,6 +1032,9 @@ export const MessagesTimeline = memo(function MessagesTimeline({
isCompacting,
isRevertingCheckpoint,
latestTurnId: latestTurn?.turnId ?? null,
// The same value the row-derivation uses, so a block and the placeholder
// beside it can never disagree about whether a turn is still live.
unsettledTurnId: deriveUnsettledTurnId(latestTurn ?? null, runningTurnId),
backgroundWorktreeSetup,
}),
[
@@ -1011,7 +1043,12 @@ export const MessagesTimeline = memo(function MessagesTimeline({
isRevertingCheckpoint,
isWorking,
isPreparingWorktree,
// Deliberately the fields `deriveUnsettledTurnId` reads, not the object:
// its identity changes on every thread-shell patch.
latestTurn?.turnId,
latestTurn?.state,
latestTurn?.completedAt,
runningTurnId,
],
);
@@ -1453,6 +1490,7 @@ const TimelineRowContent = memo(function TimelineRowContent({ row }: { row: Time
: (row.kind === "message" &&
row.message.role === "assistant" &&
!row.showAssistantMeta) ||
(row.kind === "message" && row.message.role === "reasoning") ||
row.kind === "work" ||
row.kind === "work-live" ||
row.kind === "work-toggle" ||
@@ -1488,6 +1526,9 @@ const TimelineRowContent = memo(function TimelineRowContent({ row }: { row: Time
{row.kind === "message" && row.message.role === "assistant" ? (
<AssistantTimelineRow row={row} />
) : null}
{row.kind === "message" && row.message.role === "reasoning" ? (
<ReasoningTimelineRow row={row} />
) : null}
{row.kind === "assistant-meta" ? <AssistantMetaTimelineRow row={row} /> : null}
{row.kind === "proposed-plan" ? <ProposedPlanTimelineRow row={row} /> : null}
{row.kind === "working" ? <WorkingTimelineRow row={row} /> : null}
@@ -2363,6 +2404,86 @@ function ThinkingTimelineRow() {
);
}
/**
* A provider's thinking trace. Collapsed by default: reasoning is context for
* the answer, not the answer. The open/closed flag lives on the list so it
* survives row recycling in the virtualizer.
*/
const ReasoningTimelineRow = memo(function ReasoningTimelineRow({
row,
}: {
row: Extract<TimelineRow, { kind: "message" }>;
}) {
const ctx = use(TimelineRowCtx);
const { isWorking, unsettledTurnId } = use(TimelineRowActivityCtx);
const { message } = row;
// A block left open by a crashed provider or a restarted server never gets
// its completion. Only the live turn may claim to still be thinking, so a
// settled turn cannot shimmer "Thinking" at the user forever.
const streaming =
Boolean(message.streaming) &&
isWorking &&
message.turnId !== null &&
message.turnId === unsettledTurnId;
const expanded = ctx.expandedReasoningMessageIds.has(message.id);
const { onToggleReasoning } = ctx;
const toggle = useCallback(() => {
onToggleReasoning(message.id, !expanded);
}, [expanded, message.id, onToggleReasoning]);
const label = streaming ? "Thinking" : "Thought";
if (message.text.trim().length === 0 && !streaming) {
return null;
}
return (
<div className={cn("flex flex-col", expanded && "mb-1")}>
<button
type="button"
aria-expanded={expanded}
onClick={toggle}
className="flex cursor-pointer select-none items-center gap-1.5 rounded-md px-0.5 py-0.5 text-start transition-colors hover:bg-accent/20 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring/70"
>
<span className="flex size-6 shrink-0 items-center justify-center text-icon-muted">
<BrainIcon aria-hidden className="block size-4 shrink-0 stroke-[1.8] opacity-70" />
</span>
<span className="flex min-w-0 flex-1 items-center gap-1.5">
<span
ref={streaming ? observeVisibleAnimation : undefined}
className="relative min-w-0 flex-1 truncate text-secondary-label text-sm leading-relaxed"
>
{label}
{streaming ? <ActivityShimmerOverlay>{label}</ActivityShimmerOverlay> : null}
</span>
<span className="flex size-4 shrink-0 items-center justify-center" aria-hidden>
<ChevronRightIcon
className={cn(
"size-3 shrink-0 text-icon-muted opacity-70 transition-transform duration-200",
expanded && "rotate-90",
)}
/>
</span>
</span>
</button>
{expanded ? (
<div className="mt-1 ms-7 max-h-96 overflow-auto rounded-md bg-muted/40 px-3 py-2 text-secondary-label select-text">
<ChatMarkdown
text={message.text}
cwd={ctx.markdownCwd}
threadRef={ctx.threadRef ?? undefined}
isStreaming={streaming}
lineBreaks
skills={ctx.skills}
headingLevelOffset={MESSAGE_HEADING_LEVEL}
onUseArtifactTemplate={ctx.onUseArtifactTemplate}
onImageExpand={ctx.onImageExpand}
/>
</div>
) : null}
</div>
);
});
function CompactingLabel() {
return (
<span className="inline-flex items-center gap-1.5">
@@ -187,7 +187,8 @@ const RESPONSE_STREAMING_MODE_LABELS: Record<ResponseStreamingMode, string> = {
const RESPONSE_STREAMING_MODE_DESCRIPTIONS: Record<ResponseStreamingMode, string> = {
turn: "Text appears once the agent finishes its turn.",
paragraph: "Each paragraph or code block appears as soon as it is complete.",
token: "Every token repaints the message as it arrives. Slower and harder to read.",
token:
"Every token repaints the answer as it arrives. Slower and harder to read. Thinking traces still arrive a paragraph at a time.",
};
const TIMESTAMP_FORMAT_LABELS = {
+4 -2
View File
@@ -65,8 +65,10 @@ const StoredShellSnapshotJson = Schema.fromJsonString(StoredShellSnapshot);
// exists for rollback safety: a pre-pagination client would decode a windowed
// v2 record, silently drop the unknown `page` field, and treat the partial
// thread as complete forever. Older entries fail to decode → cold cache.
// v4 reloads pre-thinking caches: their fallback system roles cannot recover
// settled reasoning messages by resuming afterSequence.
const StoredThreadSnapshot = Schema.Struct({
schemaVersion: Schema.Literal(3),
schemaVersion: Schema.Literal(4),
environmentId: EnvironmentId,
threadId: ThreadId,
snapshot: OrchestrationThreadDetailSnapshot,
@@ -679,7 +681,7 @@ export const connectionStorageLayer = Layer.effectContext(
saveThread: (environmentId, snapshot) =>
Effect.gen(function* () {
const encoded = yield* encodeStoredThreadSnapshot({
schemaVersion: 3,
schemaVersion: 4,
environmentId,
threadId: snapshot.thread.id,
snapshot,
+5 -3
View File
@@ -1613,11 +1613,13 @@ export function createMessageAttachmentPreviewProjector() {
};
}
/** Text and update time do not change a streaming assistant message's timeline structure. */
const streamsText = (role: ChatMessage["role"]) => role === "assistant" || role === "reasoning";
/** Text and update time do not change a streaming message's timeline structure. */
export function isStreamingMessageTextUpdate(previous: ChatMessage, next: ChatMessage): boolean {
if (
previous.role !== "assistant" ||
next.role !== "assistant" ||
!streamsText(previous.role) ||
previous.role !== next.role ||
!previous.streaming ||
!next.streaming
) {