From 8c602d10d5877fc7815a719716457b9aff366a01 Mon Sep 17 00:00:00 2001 From: Renfei Zhou Date: Wed, 2 Sep 2026 13:43:18 +0000 Subject: [PATCH] fix(web): fold work before and after a mid-turn user message separately A steered turn used to fold into a single "Worked for" row whose contents sat partly above and partly below the steer. The timeline now closes the segment a steer interrupts and opens a new one below it, so each fold covers only the work under it, and the fold's separator moved onto the final response so it lands below the "Ran N subagents" row. Co-Authored-By: Claude Fable 5.1 --- .../chat/MessagesTimeline.logic.test.ts | 123 +++++++++++++++--- .../components/chat/MessagesTimeline.logic.ts | 60 +++++++-- .../src/components/chat/MessagesTimeline.tsx | 14 +- 3 files changed, 162 insertions(+), 35 deletions(-) diff --git a/apps/web/src/components/chat/MessagesTimeline.logic.test.ts b/apps/web/src/components/chat/MessagesTimeline.logic.test.ts index 2890b68110b3f..234f91868b6e3 100644 --- a/apps/web/src/components/chat/MessagesTimeline.logic.test.ts +++ b/apps/web/src/components/chat/MessagesTimeline.logic.test.ts @@ -546,7 +546,7 @@ describe("deriveMessagesTimelineRows", () => { expect(foldRow?.label).toBe("Worked for 22s"); expect(collapsedRows.map((row) => row.id)).toEqual([ "user-entry", - "turn-fold:turn-1", + "turn-fold:assistant-first-entry", "assistant-final-entry", ]); @@ -561,7 +561,7 @@ describe("deriveMessagesTimelineRows", () => { expect(expandedRows.map((row) => row.id)).toEqual([ "user-entry", - "turn-fold:turn-1", + "turn-fold:assistant-first-entry", "assistant-first-entry", "work-toggle:work-entry-1", "assistant-final-entry", @@ -625,7 +625,10 @@ describe("deriveMessagesTimelineRows", () => { revertTurnCountByUserMessageId: new Map(), }); - expect(rows.map((row) => row.id)).toEqual(["turn-fold:turn-1", "assistant-final-entry"]); + expect(rows.map((row) => row.id)).toEqual([ + "turn-fold:assistant-first-entry", + "assistant-final-entry", + ]); }); it("derives a sane duration for a steer-superseded turn with one instant commentary message", () => { @@ -822,7 +825,7 @@ describe("deriveMessagesTimelineRows", () => { }); expect(rows.map((row) => row.id)).toEqual([ - "turn-fold:turn-1", + "turn-fold:work-entry-1", "assistant-final-entry", "user-followup-entry", "working-indicator-row", @@ -1379,7 +1382,7 @@ describe("deriveMessagesTimelineRows", () => { // turn id that opened the response. expect(rows.map((row) => row.id)).toEqual([ "user-1-entry", - "turn-fold:turn-1", + "turn-fold:work-1-entry", "assistant-final-entry", ]); const foldRow = rows.find( @@ -1411,7 +1414,7 @@ describe("deriveMessagesTimelineRows", () => { expect(rows.some((row) => row.kind === "turn-fold")).toBe(false); }); - it("keeps one fold across a same-turn steer and keeps both user messages visible", () => { + it("folds a same-turn steer as one segment per side of the steer", () => { const timelineEntries = [ userEntry("user-1", "2026-01-01T00:00:00Z"), workEntry("work-1", "2026-01-01T00:00:05Z", "turn-1"), @@ -1425,13 +1428,19 @@ describe("deriveMessagesTimelineRows", () => { latestTurn: { turnId: "turn-1" as never, state: "running", - startedAt: "2026-01-01T00:00:00Z", + // The turn started after its user message waited in the queue. + startedAt: "2026-01-01T00:00:02Z", completedAt: null, }, isWorking: true, - activeTurnStartedAt: "2026-01-01T00:00:00Z", + activeTurnStartedAt: "2026-01-01T00:00:02Z", }); - expect(runningRows.some((row) => row.kind === "turn-fold")).toBe(false); + // Work the steer already interrupted is finished, so it folds even though + // the turn is still running; the live segment stays open. + expect(runningRows.filter((row) => row.kind === "turn-fold")).toEqual([ + expect.objectContaining({ id: "turn-fold:work-1-entry", label: "Worked for 3.0s" }), + ]); + expect(runningRows.map((row) => row.id)).toContain("work-toggle:work-2-entry"); const settledRows = deriveMessagesTimelineRows({ ...baseFoldInput, @@ -1439,16 +1448,23 @@ describe("deriveMessagesTimelineRows", () => { latestTurn: { turnId: "turn-1" as never, state: "completed", - startedAt: "2026-01-01T00:00:00Z", + startedAt: "2026-01-01T00:00:02Z", completedAt: "2026-01-01T00:00:30Z", }, }); expect(settledRows.map((row) => row.id)).toEqual([ "user-1-entry", - "turn-fold:turn-1", + "turn-fold:work-1-entry", "user-steer-entry", + "turn-fold:work-2-entry", "assistant-final-entry", ]); + // Pre-steer segment runs from the turn's own start to the steer; the + // post-steer segment runs from the steer to the turn's completion. + expect(settledRows.filter((row) => row.kind === "turn-fold").map((row) => row.label)).toEqual([ + "Worked for 3.0s", + "Worked for 20s", + ]); }); it("keeps fold row ids unique when an old-turn row straddles the next user message", () => { @@ -1478,12 +1494,48 @@ describe("deriveMessagesTimelineRows", () => { expect(rows.map((row) => row.id)).toEqual([ "user-1-entry", - "turn-fold:turn-1", + "turn-fold:work-1-entry", + "assistant-one-entry", + "user-2-entry", + "turn-fold:work-2-entry", + "assistant-two-entry", + ]); + }); + + it("keeps a straggling old-turn row from stealing the next response's start", () => { + const rows = deriveMessagesTimelineRows({ + ...baseFoldInput, + timelineEntries: [ + userEntry("user-1", "2026-01-01T00:00:00Z"), + workEntry("work-1", "2026-01-01T00:00:05Z", "turn-1"), + assistantEntry("assistant-one", "2026-01-01T00:00:10Z", "turn-1"), + userEntry("user-2", "2026-01-01T00:00:20Z"), + // The straggler lands before turn-2 opens: turn-1 already answered, so + // the row is residue and the second response still starts at user-2. + workEntry("work-late", "2026-01-01T00:00:21Z", "turn-1"), + workEntry("work-2", "2026-01-01T00:00:22Z", "turn-2"), + assistantEntry("assistant-two", "2026-01-01T00:00:40Z", "turn-2"), + ], + latestTurn: { + turnId: "turn-2" as never, + state: "completed", + startedAt: "2026-01-01T00:00:21Z", + completedAt: "2026-01-01T00:00:40Z", + }, + }); + + expect(rows.map((row) => row.id)).toEqual([ + "user-1-entry", + "turn-fold:work-1-entry", "assistant-one-entry", "user-2-entry", - "turn-fold:turn-2", + "turn-fold:work-2-entry", "assistant-two-entry", ]); + expect(rows.filter((row) => row.kind === "turn-fold").map((row) => row.turnId)).toEqual([ + "turn-1", + "turn-2", + ]); }); it("folds turn-less background rows into the latest response segment", () => { @@ -1518,10 +1570,10 @@ describe("deriveMessagesTimelineRows", () => { expect(rows.map((row) => row.id)).toEqual([ "user-1-entry", - "turn-fold:turn-1", + "turn-fold:work-1-entry", "assistant-one-entry", "user-2-entry", - "turn-fold:turn-2", + "turn-fold:work-2-entry", "assistant-two-entry", ]); }); @@ -1558,7 +1610,7 @@ describe("deriveMessagesTimelineRows", () => { const rows = deriveMessagesTimelineRows({ ...baseFoldInput, timelineEntries, latestTurn }); expect(rows.map((row) => row.id)).toEqual([ "user-1-entry", - "turn-fold:turn-1", + "turn-fold:work-1-entry", "spawn-1-entry", "spawn-wf-entry", "assistant-final-entry", @@ -1584,6 +1636,45 @@ describe("deriveMessagesTimelineRows", () => { }); }); + it("keeps the response and its spawn row in the post-steer segment only", () => { + const rows = deriveMessagesTimelineRows({ + ...baseFoldInput, + timelineEntries: [ + userEntry("user-1", "2026-01-01T00:00:00Z"), + assistantEntry("assistant-plan", "2026-01-01T00:00:04Z", "turn-1"), + workEntry("work-1", "2026-01-01T00:00:06Z", "turn-1"), + userEntry("user-steer", "2026-01-01T00:00:12Z"), + workEntry("work-2", "2026-01-01T00:00:18Z", "turn-1"), + spawnEntry("spawn-1", "2026-01-01T00:00:20Z", "turn-1", ["agent-a"]), + assistantEntry("assistant-final", "2026-01-01T00:00:40Z", "turn-1"), + ], + latestTurn: { + turnId: "turn-1" as never, + state: "completed", + startedAt: "2026-01-01T00:00:00Z", + completedAt: "2026-01-01T00:00:45Z", + }, + }); + + // The pre-steer segment hides its commentary too; only the segment that + // ends the turn keeps the response, its spawn row and the separator. + expect(rows.map((row) => row.id)).toEqual([ + "user-1-entry", + "turn-fold:assistant-plan-entry", + "user-steer-entry", + "turn-fold:work-2-entry", + "spawn-1-entry", + "assistant-final-entry", + ]); + expect(rows.filter((row) => row.kind === "turn-fold").map((row) => row.label)).toEqual([ + "Worked for 6.0s", + "Worked for 33s", + ]); + expect( + rows.flatMap((row) => (row.kind === "message" && row.showsTurnFoldSeparator ? [row.id] : [])), + ).toEqual(["assistant-final-entry"]); + }); + it("uses the stopped label when the interrupted turn is a grouped synthetic continuation", () => { const rows = deriveMessagesTimelineRows({ ...baseFoldInput, diff --git a/apps/web/src/components/chat/MessagesTimeline.logic.ts b/apps/web/src/components/chat/MessagesTimeline.logic.ts index 68f6d5060914b..3d7d98f049e8a 100644 --- a/apps/web/src/components/chat/MessagesTimeline.logic.ts +++ b/apps/web/src/components/chat/MessagesTimeline.logic.ts @@ -236,6 +236,8 @@ export type MessagesTimelineRow = message: ChatMessage; durationStart: string; showAssistantMeta: boolean; + /** Draws the fold's separator above this message when a fold leads into it. */ + showsTurnFoldSeparator: boolean; showAssistantCopyButton: boolean; assistantCopyStreaming: boolean; assistantTurnDiffSummary?: TurnDiffSummary | undefined; @@ -341,6 +343,8 @@ interface TurnFold { createdAt: string; hiddenEntryIds: ReadonlySet; label: string; + /** The terminal assistant message this fold leads into, when it has one. */ + terminalEntryId: string | null; /** The group's direct-spawn CTA, carrying every direct spawn the fold absorbed. */ spawnRow: { entryId: string; entry: WorkLogEntry } | null; } @@ -395,6 +399,8 @@ function workEntryIsActiveTurnActivity(entry: WorkLogEntry): boolean { * Settled turns keep only their terminal assistant message visible. * Everything before it folds behind a "Worked for ..." row anchored at the * first hidden entry, so the duration leads directly into the final response. + * A user message that lands mid-turn (a steer) splits the turn into segments + * that fold separately, so each fold stays above the work it covers. */ function deriveTurnFolds(input: { timelineEntries: ReadonlyArray; @@ -405,6 +411,8 @@ function deriveTurnFolds(input: { interface TurnGroup { /** The turn id that opened the group; keeps the fold's identity stable. */ turnId: TurnId; + /** Opened by a steer, so it cannot read the turn's own start time. */ + steered: boolean; entries: Array; terminalEntry: Extract | null; hasStreamingMessage: boolean; @@ -416,6 +424,8 @@ function deriveTurnFolds(input: { */ startBoundary: string | null; } + // Every segment in timeline order, plus the one each turn id writes into now. + const groups: Array = []; const groupsByTurnId = new Map(); let pendingUserBoundary: string | null = null; @@ -435,6 +445,13 @@ function deriveTurnFolds(input: { // group, even past the next user message, since no new response has // started until a turn id shows up. let group: TurnGroup | null = turnId ? (groupsByTurnId.get(turnId) ?? null) : lastGroup; + // The turn read a steer and kept working: close the segment it interrupted + // so that fold stays above the work it covers, and open a new one below the + // steer. Trade-off: a group that already holds its response is done talking, + // so a late row is residue and rides it instead of splitting. + const steeredGroup: TurnGroup | null = + group?.terminalEntry === null && turnId && pendingUserBoundary !== null ? group : null; + if (steeredGroup) group = null; if (!group) { if (!turnId) { continue; @@ -442,13 +459,18 @@ function deriveTurnFolds(input: { // A fresh turn id with no user message since the last group opened is a // synthetic mid-response continuation (subagent wake-up, stop-hook // retry): it joins that group instead of starting a fold of its own. - group = (pendingUserBoundary === null ? lastGroup : null) ?? { - turnId, + const joinedGroup: TurnGroup | null = pendingUserBoundary === null ? lastGroup : null; + group = joinedGroup ?? { + // A split segment keeps the interrupted group's turn id, so both of + // the turn's folds still expand together. + turnId: steeredGroup?.turnId ?? turnId, + steered: steeredGroup !== null, entries: [], terminalEntry: null, hasStreamingMessage: false, startBoundary: pendingUserBoundary, }; + if (!joinedGroup) groups.push(group); pendingUserBoundary = null; groupsByTurnId.set(turnId, group); lastGroup = group; @@ -465,7 +487,7 @@ function deriveTurnFolds(input: { } const foldsByAnchorEntryId = new Map(); - for (const group of new Set(groupsByTurnId.values())) { + for (const group of groups) { const { turnId } = group; if (input.unsettledTurnId !== null && groupsByTurnId.get(input.unsettledTurnId) === group) { continue; @@ -517,20 +539,20 @@ function deriveTurnFolds(input: { const isLatestInterruptedTurn = input.latestTurn?.state === "interrupted" && groupsByTurnId.get(input.latestTurn.turnId) === group; + // The turn's own clock, when this group opened under the latest turn. + const ownTurn = input.latestTurn?.turnId === turnId ? input.latestTurn : null; // A turn cut short by a steer leaves trailing work entries behind its // terminal message — take whichever ended last. const lastEntryEnd = lastEntry.kind === "message" ? lastEntry.message.updatedAt : lastEntry.createdAt; - const elapsedMs = - input.latestTurn?.turnId === turnId && - input.latestTurn.startedAt && - input.latestTurn.completedAt - ? computeElapsedMs(input.latestTurn.startedAt, input.latestTurn.completedAt) - : computeElapsedMs( - group.startBoundary ?? firstEntry.createdAt, - maxIsoTimestamp(group.terminalEntry?.message.updatedAt ?? null, lastEntryEnd) ?? - lastEntryEnd, - ); + // Only the segment that opened the turn may read its start, and only the + // one that closed it may read its completion; a steer bounds the rest. + const elapsedMs = computeElapsedMs( + (group.steered ? null : ownTurn?.startedAt) ?? group.startBoundary ?? firstEntry.createdAt, + (groupsByTurnId.get(turnId) === group ? ownTurn?.completedAt : null) ?? + maxIsoTimestamp(group.terminalEntry?.message.updatedAt ?? null, lastEntryEnd) ?? + lastEntryEnd, + ); const duration = elapsedMs !== null ? formatDuration(elapsedMs) : null; const label = isLatestInterruptedTurn ? duration @@ -546,6 +568,7 @@ function deriveTurnFolds(input: { createdAt: firstHiddenEntry.createdAt, hiddenEntryIds, label, + terminalEntryId: group.terminalEntry?.id ?? null, spawnRow, }); } @@ -580,7 +603,13 @@ export function deriveMessagesTimelineRows(input: { }); const collapsedEntryIds = new Set(); const mergedSpawnEntries = new Map(); + // A fold's separator rides the response it leads into, so it lands below any + // spawn row the fold kept visible. + const foldTerminalEntryIds = new Set(); for (const fold of foldsByAnchorEntryId.values()) { + if (fold.terminalEntryId !== null) { + foldTerminalEntryIds.add(fold.terminalEntryId); + } if (!input.expandedTurnIds?.has(fold.turnId)) { for (const entryId of fold.hiddenEntryIds) { collapsedEntryIds.add(entryId); @@ -704,7 +733,8 @@ export function deriveMessagesTimelineRows(input: { if (anchoredTurnFold) { nextRows.push({ kind: "turn-fold", - id: `turn-fold:${anchoredTurnFold.turnId}`, + // Keyed by anchor, not by turn: a steered turn folds once per segment. + id: `turn-fold:${anchoredTurnFold.anchorEntryId}`, createdAt: anchoredTurnFold.createdAt, turnId: anchoredTurnFold.turnId, label: anchoredTurnFold.label, @@ -858,6 +888,7 @@ export function deriveMessagesTimelineRows(input: { message: timelineEntry.message, durationStart, showAssistantMeta, + showsTurnFoldSeparator: foldTerminalEntryIds.has(timelineEntry.id), showAssistantCopyButton: showAssistantMeta, assistantCopyStreaming: timelineEntry.message.streaming || assistantTurnStillInProgress, assistantTurnDiffSummary: @@ -962,6 +993,7 @@ function isRowUnchanged(a: MessagesTimelineRow, b: MessagesTimelineRow): boolean a.message === bm.message && a.durationStart === bm.durationStart && a.showAssistantMeta === bm.showAssistantMeta && + a.showsTurnFoldSeparator === bm.showsTurnFoldSeparator && a.showAssistantCopyButton === bm.showAssistantCopyButton && a.assistantCopyStreaming === bm.assistantCopyStreaming && a.assistantTurnDiffSummary === bm.assistantTurnDiffSummary && diff --git a/apps/web/src/components/chat/MessagesTimeline.tsx b/apps/web/src/components/chat/MessagesTimeline.tsx index 2f9cd56c893c2..348475129b32c 100644 --- a/apps/web/src/components/chat/MessagesTimeline.tsx +++ b/apps/web/src/components/chat/MessagesTimeline.tsx @@ -169,7 +169,7 @@ interface TimelineRowSharedState { onFileOpen: (attachment: ChatFileAttachment) => void; openingVideoAttachmentId: string | null; onOpenTurnDiff: (turnId: TurnId, filePath?: string) => void; - onToggleTurnFold: (turnId: TurnId) => void; + onToggleTurnFold: (turnId: TurnId, anchorKey: string) => void; onToggleWorkGroup: (groupId: string, anchorKey: string) => void; agentPanelModel: AgentPanelModel; onOpenAgents: () => void; @@ -378,8 +378,8 @@ export const MessagesTimeline = memo(function MessagesTimeline({ ); const onToggleTurnFold = useCallback( - (turnId: TurnId) => { - suspendEndScrollMaintenanceForDisclosure(`turn-fold:${turnId}`); + (turnId: TurnId, anchorKey: string) => { + suspendEndScrollMaintenanceForDisclosure(anchorKey); setExpandedTurnIds((existing) => { const next = new Set(existing); if (next.has(turnId)) { @@ -998,6 +998,10 @@ const TimelineRowContent = memo(function TimelineRowContent({ row }: { row: Time ? "pb-2" : "pb-4", row.kind === "message" && row.message.role === "assistant" ? "group/assistant" : null, + // The separator belongs to the fold above, below any spawn row it kept. + row.kind === "message" && row.showsTurnFoldSeparator + ? "border-t border-border/60 pt-2" + : null, )} data-timeline-row-id={row.id} data-timeline-row-kind={row.kind} @@ -1240,12 +1244,12 @@ function TurnFoldTimelineRow({ row }: { row: Extract +