Open History to see the last commit
1import * as Equal from "effect/Equal";
2import { shallow } from "zustand/vanilla/shallow";
3import { renderCodexDirectivesForCopy } from "@t3tools/client-runtime/codex-markdown-directives";
4import { commandProgramName } from "@t3tools/client-runtime/work-log/command-label";
5import {
6 liveActivityToolStatus,
7 normalizeCompactToolLabel,
8 omitSupersededLifecycleMarkers,
9 resolveWorkEntryToolPresentation,
10 summarizeToolGroup,
11 toolGroupAction,
12 toolGroupSummaryKind,
13 type ToolGroupSummaryKind,
14} from "@t3tools/client-runtime/work-log/presentation";
15export {
16 normalizeCompactToolLabel,
17 toolGroupAction,
18} from "@t3tools/client-runtime/work-log/presentation";
19import {
20 formatDuration,
21 inferCheckpointTurnCountByTurnId,
22 isStreamingMessageTextUpdate,
23 workEntryDisplayIndicatesToolFailure,
24 workEntryIndicatesToolSuccess,
25 workEntryIndicatesToolNeutralStatus,
26 workLogEntryIsToolLike,
27 type TimelineEntry,
28 type WorkLogEntry,
29} from "../../session-logic";
30import { type ChatMessage, type ProposedPlan, type TurnDiffSummary } from "../../types";
31import {
32 type MessageId,
33 type OrchestrationLatestTurn,
34 type TurnId,
35 type WorktreeSetupSnapshot,
36} from "@t3tools/contracts";
37import { formatWorkspaceRelativePath } from "../../filePathDisplay";
38
39const TIMELINE_MINIMAP_ITEM_SPACING = 8;
40export const TIMELINE_MINIMAP_MIN_ITEMS = 2;
41const TIMELINE_MINIMAP_MAX_HEIGHT_CSS = "calc(100vh - 18rem)";
42const TIMELINE_CONTENT_MAX_WIDTH = 768;
43const TIMELINE_MINIMAP_PERSISTENT_GUTTER = 48;
44
45function singleToolCallLabel(entry: WorkLogEntry): string {
46 const toolPresentation = resolveWorkEntryToolPresentation(entry, "completed");
47 if (toolPresentation) return toolPresentation.displayName;
48 const command = entry.command?.trim();
49 if (command) return command;
50 const heading = normalizeCompactToolLabel(entry.toolTitle || entry.label);
51 return `${heading.charAt(0).toUpperCase()}${heading.slice(1)}`;
52}
53
54export function workEntryDisplayLabel(entry: WorkLogEntry, workspaceRoot: string | undefined) {
55 const toolPresentation = resolveWorkEntryToolPresentation(entry);
56 if (toolPresentation) return toolPresentation.displayName;
57 if (entry.command) return entry.command;
58 if (entry.detail) return entry.detail;
59 const [firstPath] = entry.changedFiles ?? [];
60 if (firstPath) {
61 const path = formatWorkspaceRelativePath(firstPath, workspaceRoot);
62 return entry.changedFiles!.length === 1
63 ? path
64 : `${path} +${entry.changedFiles!.length - 1} more`;
65 }
66 const heading = normalizeCompactToolLabel(entry.toolTitle || entry.label);
67 return `${heading.charAt(0).toUpperCase()}${heading.slice(1)}`;
68}
69
70export function liveWorkEntryLabel(
71 entry: WorkLogEntry,
72 workspaceRoot: string | undefined,
73 active: boolean,
74) {
75 const status = liveActivityToolStatus(entry.toolLifecycleStatus, active);
76 const toolPresentation = resolveWorkEntryToolPresentation({
77 ...entry,
78 toolLifecycleStatus: status,
79 });
80 if (toolPresentation) return toolPresentation.displayName;
81 const command = entry.command?.trim();
82 if (command) {
83 const verb =
84 status === "inProgress"
85 ? "Running"
86 : status === "failed"
87 ? "Failed"
88 : status === "declined"
89 ? "Declined"
90 : status === "stopped"
91 ? "Stopped"
92 : "Ran";
93 return `${verb} ${commandProgramName(command) ?? "command"}`;
94 }
95 return workEntryDisplayLabel(entry, workspaceRoot);
96}
97
98export function workEntryIsVisibleInGroup(
99 entry: WorkLogEntry,
100 expandedToolGroupEntry = false,
101): boolean {
102 return (
103 (expandedToolGroupEntry &&
104 (entry.toolLifecycleStatus === "inProgress" ||
105 entry.sourceActivityKind === "task.progress")) ||
106 !workEntryIndicatesToolNeutralStatus(entry)
107 );
108}
109
110export interface WorkGroupScrollAnchor {
111 readonly entryId: string;
112 readonly offset: number;
113}
114
115/** Restore a visible tool, including a position partway through its expanded output. */
116export function resolveWorkGroupScrollIndex(
117 entries: ReadonlyArray<{ readonly id: string }>,
118 anchor: WorkGroupScrollAnchor | undefined,
119): { index: number; viewOffset: number } | undefined {
120 if (!anchor) return undefined;
121 const index = entries.findIndex((entry) => entry.id === anchor.entryId);
122 return index < 0 ? undefined : { index, viewOffset: -anchor.offset };
123}
124
125/** Only newly appended calls may follow the end, never status or output updates. */
126export function shouldFollowWorkGroupAppend(
127 previous: ReadonlyArray<{ readonly id: string }>,
128 entries: ReadonlyArray<{ readonly id: string }>,
129 distanceFromEnd: number,
130): boolean {
131 return (
132 previous.length > 0 &&
133 entries.length > previous.length &&
134 distanceFromEnd <= 1 &&
135 previous.every((entry, index) => entry.id === entries[index]?.id)
136 );
137}
138
139export interface TimelineEndState {
140 readonly isAtEnd?: boolean;
141 readonly contentLength?: number;
142 readonly scroll?: number;
143 readonly scrollLength?: number;
144}
145
146/**
147 * Follow re-arm band above the hard bottom. Strict on purpose: LegendList's
148 * isNearEnd fires within half a viewport, which re-armed live-follow while the
149 * user was reading history and yanked them back down on the next stream chunk.
150 * A small pixel band (instead of the 1px isAtEnd epsilon alone) keeps re-arming
151 * reliable while streaming content is still growing under the viewport.
152 */
153const TIMELINE_FOLLOW_REARM_THRESHOLD_PX = 40;
154
155export function resolveTimelineIsAtEnd(state: TimelineEndState | undefined): boolean | undefined {
156 if (!state) {
157 return undefined;
158 }
159 const { contentLength, scroll, scrollLength } = state;
160 if (contentLength === undefined || scroll === undefined || scrollLength === undefined) {
161 return state.isAtEnd;
162 }
163 // contentLength includes the composer inset spacer, but the composer hides
164 // the same amount of viewport, so the inset cancels: plain
165 // contentLength - scroll - scrollLength is the gap between the last real row
166 // and the visible edge above the composer. LegendList's own isAtEnd subtracts
167 // the inset and is true anywhere in the bottom composer-height band, so it is
168 // only a fallback here, never a short-circuit.
169 return contentLength - scroll - scrollLength <= TIMELINE_FOLLOW_REARM_THRESHOLD_PX;
170}
171
172export function shouldPreserveAssistantLineBreaks(text: string): boolean {
173 return /^★ Insight(?:\s|─)/mu.test(text);
174}
175
176export function resolveTimelineMinimapHeightStyle(itemCount: number): string {
177 const naturalHeight = Math.max(1, (itemCount - 1) * TIMELINE_MINIMAP_ITEM_SPACING);
178 return `min(${naturalHeight}px, ${TIMELINE_MINIMAP_MAX_HEIGHT_CSS})`;
179}
180
181export function resolveTimelineMinimapTopPercent(index: number, itemCount: number): number {
182 if (itemCount <= 1) {
183 return 0;
184 }
185 return (Math.max(0, Math.min(index, itemCount - 1)) / (itemCount - 1)) * 100;
186}
187
188export function resolveTimelineMinimapIndexFromPointer(input: {
189 readonly itemCount: number;
190 readonly railTop: number;
191 readonly railHeight: number;
192 readonly pointerY: number;
193}): number | null {
194 if (input.itemCount <= 0 || input.railHeight <= 0) {
195 return null;
196 }
197 if (input.itemCount === 1) {
198 return 0;
199 }
200
201 const progress = Math.max(0, Math.min(1, (input.pointerY - input.railTop) / input.railHeight));
202 return Math.max(0, Math.min(input.itemCount - 1, Math.round(progress * (input.itemCount - 1))));
203}
204
205export function resolveTimelineMinimapCurrentIndex(input: {
206 readonly scrollTop: number;
207 readonly scrollBottom: number;
208 readonly itemBounds: ReadonlyArray<{
209 readonly top: number | null;
210 readonly height: number | null;
211 }>;
212}): number | null {
213 let precedingIndex: number | null = null;
214
215 for (const [index, item] of input.itemBounds.entries()) {
216 if (item.top === null) {
217 continue;
218 }
219 const inView =
220 item.top < input.scrollBottom && item.top + Math.max(1, item.height ?? 1) > input.scrollTop;
221 if (inView) {
222 // The first visible marker is the turn at the reader's current position.
223 return index;
224 }
225 if (item.top <= input.scrollTop) {
226 precedingIndex = index;
227 }
228 }
229
230 return precedingIndex;
231}
232
233export function resolveTimelineMinimapHasPersistentGutter(viewportWidth: number): boolean {
234 if (!Number.isFinite(viewportWidth) || viewportWidth <= 0) {
235 return false;
236 }
237
238 const contentWidth = Math.min(viewportWidth, TIMELINE_CONTENT_MAX_WIDTH);
239 const sideGutter = Math.max(0, (viewportWidth - contentWidth) / 2);
240 return sideGutter >= TIMELINE_MINIMAP_PERSISTENT_GUTTER;
241}
242
243const TIMELINE_MINIMAP_HIT_STRIP_LEFT = 12;
244const TIMELINE_MINIMAP_HIT_STRIP_MAX_WIDTH = 40;
245const TIMELINE_MINIMAP_EXPANDED_HIT_STRIP_WIDTH = "22rem";
246
247/**
248 * The minimap overlays the viewport's left edge while the content column is
249 * centered, so the side gutter between them shrinks under browser zoom or a
250 * narrow pane. A fixed-width hover strip would then sit on top of the message
251 * text and swallow its pointer events. Cap the strip's width so it never
252 * extends past the gutter into the content column; 0 disables the strip.
253 */
254export function resolveTimelineMinimapHitStripWidth(viewportWidth: number): number {
255 if (!Number.isFinite(viewportWidth) || viewportWidth <= 0) {
256 return 0;
257 }
258
259 const contentWidth = Math.min(viewportWidth, TIMELINE_CONTENT_MAX_WIDTH);
260 const sideGutter = Math.max(0, (viewportWidth - contentWidth) / 2);
261 return Math.max(
262 0,
263 Math.min(
264 TIMELINE_MINIMAP_HIT_STRIP_MAX_WIDTH,
265 Math.floor(sideGutter) - TIMELINE_MINIMAP_HIT_STRIP_LEFT,
266 ),
267 );
268}
269
270/**
271 * Once the preview is open, keep the full preview and the space leading to it
272 * interactive. The collapsed strip remains gutter-capped so it cannot block
273 * selecting message text.
274 */
275export function resolveTimelineMinimapInteractiveWidth(
276 collapsedWidth: number,
277 expanded: boolean,
278): number | string {
279 return expanded ? TIMELINE_MINIMAP_EXPANDED_HIT_STRIP_WIDTH : collapsedWidth;
280}
281
282function computeElapsedMs(startIso: string, endIso: string): number | null {
283 const start = Date.parse(startIso);
284 const end = Date.parse(endIso);
285 if (!Number.isFinite(start) || !Number.isFinite(end)) return null;
286 return Math.max(0, end - start);
287}
288
289function maxIsoTimestamp(a: string | null, b: string | null): string | null {
290 if (a === null) return b;
291 if (b === null) return a;
292 const aMs = Date.parse(a);
293 const bMs = Date.parse(b);
294 if (!Number.isFinite(aMs)) return b;
295 if (!Number.isFinite(bMs)) return a;
296 return bMs > aMs ? b : a;
297}
298
299export interface TimelineDurationMessage {
300 id: string;
301 role: "user" | "assistant" | "system";
302 createdAt: string;
303 updatedAt: string;
304 streaming: boolean;
305}
306
307export type TimelineLatestTurn = Pick<
308 OrchestrationLatestTurn,
309 "turnId" | "state" | "startedAt" | "completedAt"
310>;
311
312const LIVE_ACTIVITY_ROW_ID = "live-activity-row";
313
314export type MessagesTimelineRow =
315 | {
316 kind: "work";
317 id: string;
318 createdAt: string;
319 groupedEntries: WorkLogEntry[];
320 isExpandedToolGroup: boolean;
321 displayLabel?: string;
322 }
323 | {
324 kind: "work-live";
325 id: string;
326 createdAt: string;
327 entry: WorkLogEntry;
328 groupedEntries: WorkLogEntry[];
329 groupId: string;
330 expanded: boolean;
331 active: boolean;
332 }
333 | {
334 kind: "work-toggle";
335 id: string;
336 createdAt: string;
337 turnId?: TurnId | null;
338 groupId: string;
339 hiddenCount: number;
340 expanded: boolean;
341 summary: string;
342 summaryKind: ToolGroupSummaryKind;
343 toolSurface?: WorkLogEntry["toolSurface"];
344 toolIcon?: WorkLogEntry["toolIcon"];
345 summaryToolIcon?: "browser" | "device" | "t3-code" | "pull-request";
346 hasFailure: boolean;
347 }
348 | {
349 kind: "turn-fold";
350 id: string;
351 createdAt: string;
352 turnId: TurnId;
353 label: string;
354 expanded: boolean;
355 }
356 | {
357 kind: "context-compaction";
358 id: string;
359 createdAt: string;
360 label: string;
361 }
362 | {
363 kind: "message";
364 id: string;
365 createdAt: string;
366 message: ChatMessage;
367 durationStart: string;
368 showAssistantMeta: boolean;
369 showAssistantCopyButton: boolean;
370 assistantCopyStreaming: boolean;
371 assistantTurnDiffSummary?: TurnDiffSummary | undefined;
372 revertTurnCount?: number | undefined;
373 }
374 | {
375 kind: "assistant-meta";
376 id: string;
377 createdAt: string;
378 message: ChatMessage;
379 showAssistantCopyButton: boolean;
380 assistantCopyStreaming: boolean;
381 }
382 | {
383 kind: "proposed-plan";
384 id: string;
385 createdAt: string;
386 proposedPlan: ProposedPlan;
387 }
388 | {
389 kind: "working";
390 id: string;
391 createdAt: string | null;
392 }
393 | {
394 kind: "thinking";
395 id: string;
396 createdAt: string | null;
397 }
398 | {
399 kind: "worktree-setup";
400 id: string;
401 createdAt: string | null;
402 snapshot: WorktreeSetupSnapshot;
403 };
404
405export interface StableMessagesTimelineRowsState {
406 byId: Map<string, MessagesTimelineRow>;
407 result: MessagesTimelineRow[];
408}
409
410export function computeMessageDurationStart(
411 messages: ReadonlyArray<TimelineDurationMessage>,
412): Map<string, string> {
413 const result = new Map<string, string>();
414 let lastBoundary: string | null = null;
415
416 for (const message of messages) {
417 if (message.role === "user") {
418 lastBoundary = message.createdAt;
419 }
420 result.set(message.id, lastBoundary ?? message.createdAt);
421 if (message.role === "assistant" && !message.streaming) {
422 lastBoundary = message.updatedAt;
423 }
424 }
425
426 return result;
427}
428
429function workGroupIdentity(timelineEntryId: string, entry: WorkLogEntry): string {
430 return entry.toolCallId
431 ? `tool:${entry.turnId ?? "no-turn"}:${entry.toolCallId}`
432 : timelineEntryId;
433}
434
435function workGroupId(timelineEntryId: string, entry: WorkLogEntry): string {
436 return `work-group:${workGroupIdentity(timelineEntryId, entry)}`;
437}
438
439function expandedWorkGroupRow(
440 groupId: string,
441 createdAt: string,
442 groupedEntries: WorkLogEntry[],
443): Extract<MessagesTimelineRow, { kind: "work" }> {
444 return {
445 kind: "work",
446 id: `${groupId}:details`,
447 createdAt,
448 groupedEntries,
449 isExpandedToolGroup: true,
450 };
451}
452
453export function resolveAssistantMessageCopyState({
454 text,
455 showCopyButton,
456 streaming,
457}: {
458 text: string | null;
459 showCopyButton: boolean;
460 streaming: boolean;
461}) {
462 const hasText = text !== null && text.trim().length > 0;
463 const visible = showCopyButton && hasText && !streaming;
464 return {
465 text: hasText ? (visible ? renderCodexDirectivesForCopy(text) : text) : null,
466 visible,
467 };
468}
469
470function deriveTerminalAssistantMessageIds(timelineEntries: ReadonlyArray<TimelineEntry>) {
471 const lastAssistantMessageIdByResponseKey = new Map<string, string>();
472 let nullTurnResponseIndex = 0;
473
474 for (const timelineEntry of timelineEntries) {
475 if (timelineEntry.kind !== "message") {
476 continue;
477 }
478 const { message } = timelineEntry;
479 if (message.role === "user") {
480 nullTurnResponseIndex += 1;
481 continue;
482 }
483 if (message.role !== "assistant") {
484 continue;
485 }
486
487 const responseKey = message.turnId
488 ? `turn:${message.turnId}`
489 : `unkeyed:${nullTurnResponseIndex}`;
490 lastAssistantMessageIdByResponseKey.set(responseKey, message.id);
491 }
492
493 return new Set(lastAssistantMessageIdByResponseKey.values());
494}
495
496interface TurnFold {
497 turnId: TurnId;
498 anchorEntryId: string;
499 createdAt: string;
500 hiddenEntryIds: ReadonlySet<string>;
501 label: string;
502}
503
504/**
505 * The session's running turn is authoritative when latestTurn briefly lags or
506 * regresses behind it. Otherwise, the latest turn counts as unsettled while it
507 * is still running (or has not recorded a completion). This is deliberately
508 * keyed on turn lifecycle rather than transient working state: right after the
509 * user sends a message, the previous turn is still the "active" one until the
510 * server creates the new turn, and folding must not flicker through that window.
511 */
512function deriveUnsettledTurnId(
513 latestTurn: TimelineLatestTurn | null,
514 runningTurnId: TurnId | null,
515): TurnId | null {
516 if (runningTurnId !== null) {
517 return runningTurnId;
518 }
519 if (!latestTurn) {
520 return null;
521 }
522 const isSettled = latestTurn.completedAt !== null && latestTurn.state !== "running";
523 return isSettled ? null : latestTurn.turnId;
524}
525
526function lastUserMessageIndex(timelineEntries: ReadonlyArray<TimelineEntry>): number {
527 return timelineEntries.findLastIndex(
528 (entry) => entry.kind === "message" && entry.message.role === "user",
529 );
530}
531
532function timelineEntryTurnId(entry: TimelineEntry): TurnId | null {
533 if (entry.kind === "message") {
534 return entry.message.role === "assistant" ? (entry.message.turnId ?? null) : null;
535 }
536 if (entry.kind === "proposed-plan") {
537 return entry.proposedPlan.turnId;
538 }
539 return entry.kind === "work" ? (entry.entry.turnId ?? null) : null;
540}
541
542/**
543 * A promptless provider restart replaces the native turn without adding a
544 * user message. Keep every provider turn since the latest user message in one
545 * visual response until the replacement turn settles. A steer has its own
546 * user message, so it naturally starts a new visual response.
547 */
548function deriveActiveVisualResponseTurnIds(input: {
549 timelineEntries: ReadonlyArray<TimelineEntry>;
550 unsettledTurnId: TurnId | null;
551 isWorking: boolean;
552}): ReadonlySet<TurnId> {
553 const turnIds = new Set<TurnId>();
554 if (input.unsettledTurnId === null) {
555 return turnIds;
556 }
557
558 turnIds.add(input.unsettledTurnId);
559 if (!input.isWorking) {
560 return turnIds;
561 }
562
563 const latestUserMessageIndex = lastUserMessageIndex(input.timelineEntries);
564 for (let index = latestUserMessageIndex + 1; index < input.timelineEntries.length; index += 1) {
565 const turnId = timelineEntryTurnId(input.timelineEntries[index]!);
566 if (turnId !== null) {
567 turnIds.add(turnId);
568 }
569 }
570 return turnIds;
571}
572
573function workEntryIsActiveTurnActivity(entry: WorkLogEntry): boolean {
574 return (
575 entry.toolLifecycleStatus === "inProgress" ||
576 (entry.toolLifecycleStatus === undefined &&
577 (entry.sourceActivityKind === "task.progress" || workLogEntryIsToolLike(entry)))
578 );
579}
580
581/**
582 * Settled turns fold activity before their terminal assistant message behind
583 * a "Worked for ..." row. A single ordinary activity after that message joins
584 * the fold, while larger groups and failures stay visible as a trailing summary.
585 */
586function deriveTurnFolds(input: {
587 timelineEntries: ReadonlyArray<TimelineEntry>;
588 terminalAssistantMessageIds: ReadonlySet<string>;
589 latestTurn: TimelineLatestTurn | null;
590 unfoldedTurnIds: ReadonlySet<TurnId>;
591}): ReadonlyMap<string, TurnFold> {
592 interface TurnGroup {
593 entries: Array<TimelineEntry>;
594 terminalEntry: Extract<TimelineEntry, { kind: "message" }> | null;
595 hasStreamingMessage: boolean;
596 /**
597 * The user message that kicked the turn off. Entry timestamps alone
598 * undercount the duration (the first entry appears only once the
599 * provider starts producing output), and a turn cut short by a steer may
600 * hold a single instantaneous commentary message.
601 */
602 startBoundary: string | null;
603 }
604 const groupsByTurnId = new Map<TurnId, TurnGroup>();
605
606 let pendingUserBoundary: string | null = null;
607 for (const entry of input.timelineEntries) {
608 if (entry.kind === "message" && entry.message.role === "user") {
609 pendingUserBoundary = entry.message.createdAt;
610 continue;
611 }
612 const turnId =
613 entry.kind === "message" && entry.message.role === "assistant"
614 ? (entry.message.turnId ?? null)
615 : entry.kind === "work"
616 ? (entry.entry.turnId ?? null)
617 : null;
618 if (!turnId) {
619 continue;
620 }
621 let group = groupsByTurnId.get(turnId);
622 if (!group) {
623 group = {
624 entries: [],
625 terminalEntry: null,
626 hasStreamingMessage: false,
627 // Each user boundary starts at most one turn; a second turn after the
628 // same user message (e.g. a steer-superseded continuation) falls back
629 // to its own first entry.
630 startBoundary: pendingUserBoundary,
631 };
632 pendingUserBoundary = null;
633 groupsByTurnId.set(turnId, group);
634 }
635 group.entries.push(entry);
636 if (entry.kind === "message") {
637 if (input.terminalAssistantMessageIds.has(entry.message.id)) {
638 group.terminalEntry = entry;
639 }
640 if (entry.message.streaming) {
641 group.hasStreamingMessage = true;
642 }
643 }
644 }
645
646 const foldsByAnchorEntryId = new Map<string, TurnFold>();
647 for (const [turnId, group] of groupsByTurnId) {
648 if (input.unfoldedTurnIds.has(turnId)) {
649 continue;
650 }
651 if (group.hasStreamingMessage) {
652 continue;
653 }
654 const hiddenEntryIds = new Set<string>();
655 const terminalEntryIndex = group.terminalEntry
656 ? group.entries.findIndex((entry) => entry.id === group.terminalEntry?.id)
657 : group.entries.length;
658 for (const [index, entry] of group.entries.entries()) {
659 if (entry.id === group.terminalEntry?.id) {
660 continue;
661 }
662 const isCompaction =
663 entry.kind === "work" && entry.entry.sourceActivityKind === "context-compaction";
664 const isSingleTrailingActivity =
665 group.entries.length === terminalEntryIndex + 2 &&
666 entry.kind === "work" &&
667 !workEntryDisplayIndicatesToolFailure(entry.entry);
668 if (!isCompaction && index > terminalEntryIndex && !isSingleTrailingActivity) {
669 continue;
670 }
671 // User input and subagent batches stay visible after their turn settles.
672 if (
673 entry.kind === "work" &&
674 (entry.entry.questionAnswer !== undefined || entry.entry.agentSpawn !== undefined)
675 ) {
676 continue;
677 }
678 hiddenEntryIds.add(entry.id);
679 }
680 if (hiddenEntryIds.size === 0) {
681 continue;
682 }
683 // A lone compaction row stays visible on its own; it only folds away as
684 // part of a turn that already folds other work.
685 const hidesNonCompactionWork = group.entries.some(
686 (entry) =>
687 hiddenEntryIds.has(entry.id) &&
688 !(entry.kind === "work" && entry.entry.sourceActivityKind === "context-compaction"),
689 );
690 if (!hidesNonCompactionWork) {
691 continue;
692 }
693
694 const firstEntry = group.entries[0];
695 const firstHiddenEntry = group.entries.find((entry) => hiddenEntryIds.has(entry.id));
696 const lastEntry = group.entries.at(-1);
697 if (!firstEntry || !firstHiddenEntry || !lastEntry) {
698 continue;
699 }
700
701 const isLatestInterruptedTurn =
702 input.latestTurn?.turnId === turnId && input.latestTurn.state === "interrupted";
703 // A turn cut short by a steer leaves trailing work entries behind its
704 // terminal message — take whichever ended last.
705 const lastEntryEnd =
706 lastEntry.kind === "message" ? lastEntry.message.updatedAt : lastEntry.createdAt;
707 const elapsedMs =
708 input.latestTurn?.turnId === turnId &&
709 input.latestTurn.startedAt &&
710 input.latestTurn.completedAt
711 ? computeElapsedMs(input.latestTurn.startedAt, input.latestTurn.completedAt)
712 : computeElapsedMs(
713 group.startBoundary ?? firstEntry.createdAt,
714 maxIsoTimestamp(group.terminalEntry?.message.updatedAt ?? null, lastEntryEnd) ??
715 lastEntryEnd,
716 );
717 const duration = elapsedMs !== null ? formatDuration(elapsedMs) : null;
718 const label = isLatestInterruptedTurn
719 ? duration
720 ? `You stopped after ${duration}`
721 : "You stopped this response"
722 : duration
723 ? `Worked for ${duration}`
724 : "Worked";
725
726 foldsByAnchorEntryId.set(firstHiddenEntry.id, {
727 turnId,
728 anchorEntryId: firstHiddenEntry.id,
729 createdAt: firstHiddenEntry.createdAt,
730 hiddenEntryIds,
731 label,
732 });
733 }
734 return foldsByAnchorEntryId;
735}
736
737/**
738 * When a settled turn ends with tool calls after its terminal text, treat the
739 * text and tools as one visual response. The message metadata becomes the
740 * footer for the whole block instead of separating the prose from the tools.
741 */
742function attachTrailingToolGroupsToAssistant(
743 rows: ReadonlyArray<MessagesTimelineRow>,
744): MessagesTimelineRow[] {
745 const messageRowsWithoutMeta = new Set<string>();
746 const metaRowsAfterIndex = new Map<
747 number,
748 Extract<MessagesTimelineRow, { kind: "assistant-meta" }>
749 >();
750
751 for (const [messageIndex, row] of rows.entries()) {
752 const turnId = row.kind === "message" ? (row.message.turnId ?? null) : null;
753 if (
754 row.kind !== "message" ||
755 row.message.role !== "assistant" ||
756 !row.showAssistantMeta ||
757 turnId === null
758 ) {
759 continue;
760 }
761
762 let lastTrailingWorkIndex = -1;
763 let hasTrailingToolGroup = false;
764 for (let index = messageIndex + 1; index < rows.length; index += 1) {
765 const candidate = rows[index];
766 if (!candidate || candidate.kind === "message") {
767 break;
768 }
769 if (candidate.kind === "work-toggle" && candidate.turnId === turnId) {
770 hasTrailingToolGroup = true;
771 lastTrailingWorkIndex = index;
772 continue;
773 }
774 if (
775 candidate.kind === "work" &&
776 candidate.groupedEntries.some((entry) => entry.turnId === turnId)
777 ) {
778 if (
779 !candidate.isExpandedToolGroup &&
780 candidate.groupedEntries.some(workLogEntryIsToolLike)
781 ) {
782 hasTrailingToolGroup = true;
783 }
784 if (hasTrailingToolGroup) {
785 lastTrailingWorkIndex = index;
786 }
787 }
788 }
789
790 if (lastTrailingWorkIndex < 0) {
791 continue;
792 }
793
794 messageRowsWithoutMeta.add(row.id);
795 metaRowsAfterIndex.set(lastTrailingWorkIndex, {
796 kind: "assistant-meta",
797 id: `assistant-meta:${row.message.id}`,
798 createdAt: rows[lastTrailingWorkIndex]?.createdAt ?? row.message.updatedAt,
799 message: row.message,
800 showAssistantCopyButton: row.showAssistantCopyButton,
801 assistantCopyStreaming: row.assistantCopyStreaming,
802 });
803 }
804
805 const result: MessagesTimelineRow[] = [];
806 for (const [index, row] of rows.entries()) {
807 if (row.kind === "message" && messageRowsWithoutMeta.has(row.id)) {
808 result.push({ ...row, showAssistantMeta: false, showAssistantCopyButton: false });
809 } else {
810 result.push(row);
811 }
812 const metaRow = metaRowsAfterIndex.get(index);
813 if (metaRow) {
814 result.push(metaRow);
815 }
816 }
817 return result;
818}
819
820/** Match each user message to the next assistant checkpoint. */
821function buildRevertTurnCountByUserMessageId(input: {
822 supportsConversationRollback: boolean;
823 timelineEntries: ReadonlyArray<TimelineEntry>;
824 turnDiffSummaryByAssistantMessageId: ReadonlyMap<MessageId, TurnDiffSummary>;
825 inferredCheckpointTurnCountByTurnId: Readonly<Record<string, number | undefined>>;
826}): Map<MessageId, number> {
827 const byUserMessageId = new Map<MessageId, number>();
828 const entryCount = input.supportsConversationRollback ? input.timelineEntries.length : 0;
829 for (let index = 0; index < entryCount; index += 1) {
830 const entry = input.timelineEntries[index];
831 if (!entry || entry.kind !== "message" || entry.message.role !== "user") {
832 continue;
833 }
834
835 for (let nextIndex = index + 1; nextIndex < input.timelineEntries.length; nextIndex += 1) {
836 const nextEntry = input.timelineEntries[nextIndex];
837 if (!nextEntry || nextEntry.kind !== "message") {
838 continue;
839 }
840 if (nextEntry.message.role === "user") {
841 break;
842 }
843 const summary = input.turnDiffSummaryByAssistantMessageId.get(nextEntry.message.id);
844 if (!summary) {
845 continue;
846 }
847 const turnCount =
848 summary.checkpointTurnCount ?? input.inferredCheckpointTurnCountByTurnId[summary.turnId];
849 if (typeof turnCount !== "number") {
850 break;
851 }
852 byUserMessageId.set(entry.message.id, Math.max(0, turnCount - 1));
853 break;
854 }
855 }
856 return byUserMessageId;
857}
858
859export function deriveMessagesTimelineRows(input: {
860 timelineEntries: ReadonlyArray<TimelineEntry>;
861 latestTurn?: TimelineLatestTurn | null;
862 runningTurnId?: TurnId | null;
863 expandedTurnIds?: ReadonlySet<TurnId>;
864 expandedWorkGroupIds?: ReadonlySet<string>;
865 isWorking: boolean;
866 activeTurnStartedAt: string | null;
867 turnDiffSummaries: ReadonlyArray<TurnDiffSummary>;
868 supportsConversationRollback: boolean;
869 /** Task ids of subagents still working, used by the active tool indicator. */
870 liveAgentTaskIds?: ReadonlySet<string> | undefined;
871 /** Live bootstrap progress. Renders a stage card under the first user message. */
872 worktreeSetup?: WorktreeSetupSnapshot | null;
873}): MessagesTimelineRow[] {
874 const turnDiffSummaryByAssistantMessageId = new Map<MessageId, TurnDiffSummary>();
875 for (const summary of input.turnDiffSummaries) {
876 if (summary.assistantMessageId) {
877 turnDiffSummaryByAssistantMessageId.set(summary.assistantMessageId, summary);
878 }
879 }
880 const revertTurnCountByUserMessageId = buildRevertTurnCountByUserMessageId({
881 supportsConversationRollback: input.supportsConversationRollback,
882 timelineEntries: input.timelineEntries,
883 turnDiffSummaryByAssistantMessageId,
884 inferredCheckpointTurnCountByTurnId: input.supportsConversationRollback
885 ? inferCheckpointTurnCountByTurnId(input.turnDiffSummaries)
886 : {},
887 });
888 const nextRows: MessagesTimelineRow[] = [];
889 const durationStartByMessageId = computeMessageDurationStart(
890 input.timelineEntries.flatMap((entry) => (entry.kind === "message" ? [entry.message] : [])),
891 );
892 const terminalAssistantMessageIds = deriveTerminalAssistantMessageIds(input.timelineEntries);
893 const unsettledTurnId = deriveUnsettledTurnId(
894 input.latestTurn ?? null,
895 input.runningTurnId ?? null,
896 );
897 const activeVisualResponseTurnIds = deriveActiveVisualResponseTurnIds({
898 timelineEntries: input.timelineEntries,
899 unsettledTurnId,
900 isWorking: input.isWorking,
901 });
902 const foldsByAnchorEntryId = deriveTurnFolds({
903 timelineEntries: input.timelineEntries,
904 terminalAssistantMessageIds,
905 latestTurn: input.latestTurn ?? null,
906 unfoldedTurnIds: activeVisualResponseTurnIds,
907 });
908 const collapsedEntryIds = new Set<string>();
909 for (const fold of foldsByAnchorEntryId.values()) {
910 if (!input.expandedTurnIds?.has(fold.turnId)) {
911 for (const entryId of fold.hiddenEntryIds) {
912 collapsedEntryIds.add(entryId);
913 }
914 }
915 }
916
917 let activeTurnHeaderIndex = input.timelineEntries.length;
918 if (input.isWorking) {
919 const latestUserMessageIndex = lastUserMessageIndex(input.timelineEntries);
920 activeTurnHeaderIndex = latestUserMessageIndex + 1;
921 }
922 const entryBelongsToActiveTurn = (entry: TimelineEntry, index: number) =>
923 input.isWorking &&
924 index >= activeTurnHeaderIndex &&
925 (unsettledTurnId === null || timelineEntryTurnId(entry) === unsettledTurnId);
926 const workEntryIsInActiveRun = (entry: WorkLogEntry) =>
927 input.isWorking &&
928 unsettledTurnId !== null &&
929 entry.toolLifecycleStatus === "inProgress" &&
930 entry.turnId === unsettledTurnId;
931 const activeToolEntries: Array<Extract<TimelineEntry, { kind: "work" }>> = [];
932 for (let index = input.timelineEntries.length - 1; index >= activeTurnHeaderIndex; index -= 1) {
933 const entry = input.timelineEntries[index]!;
934 if (
935 !entryBelongsToActiveTurn(entry, index) ||
936 entry.kind !== "work" ||
937 entry.entry.questionAnswer !== undefined ||
938 entry.entry.sourceActivityKind === "context-compaction" ||
939 entry.entry.tone === "error"
940 ) {
941 break;
942 }
943 activeToolEntries.unshift(entry);
944 }
945 const visibleActiveToolEntries = omitSupersededLifecycleMarkers(
946 activeToolEntries.filter((entry) => workEntryIsVisibleInGroup(entry.entry, true)),
947 (entry) => entry.entry,
948 );
949 const activeWorkAnchor = activeToolEntries[0];
950 const latestVisibleToolEntry = visibleActiveToolEntries.at(-1);
951 const latestRunningToolEntry = visibleActiveToolEntries.findLast((entry) => {
952 const spawn = entry.entry.agentSpawn;
953 return spawn
954 ? entry === latestVisibleToolEntry &&
955 ((spawn.workflowId !== null && input.liveAgentTaskIds?.has(spawn.workflowId)) ||
956 spawn.agentTaskIds.some((taskId) => input.liveAgentTaskIds?.has(taskId)))
957 : workEntryIsActiveTurnActivity(entry.entry);
958 });
959 const latestToolFailed =
960 latestRunningToolEntry === undefined &&
961 latestVisibleToolEntry !== undefined &&
962 latestVisibleToolEntry.entry.toolLifecycleStatus !== "declined" &&
963 workEntryDisplayIndicatesToolFailure(latestVisibleToolEntry.entry);
964 const latestToolKeepsActivityLive =
965 latestRunningToolEntry !== undefined ||
966 (latestVisibleToolEntry !== undefined &&
967 latestVisibleToolEntry.entry.agentSpawn === undefined &&
968 (workEntryIndicatesToolSuccess(latestVisibleToolEntry.entry) ||
969 (latestVisibleToolEntry.entry.toolLifecycleStatus === "completed" &&
970 !workEntryDisplayIndicatesToolFailure(latestVisibleToolEntry.entry))));
971 const activeWorkPlacementEntryId = latestVisibleToolEntry?.id;
972 const activeWorkRow =
973 activeWorkAnchor && latestVisibleToolEntry && !latestToolFailed
974 ? (() => {
975 const groupId = workGroupId(activeWorkAnchor.id, activeWorkAnchor.entry);
976 return {
977 kind: "work-live" as const,
978 id: latestToolKeepsActivityLive
979 ? LIVE_ACTIVITY_ROW_ID
980 : `work-live:${workGroupIdentity(activeWorkAnchor.id, activeWorkAnchor.entry)}`,
981 createdAt: activeWorkAnchor.createdAt,
982 entry: (latestRunningToolEntry ?? latestVisibleToolEntry).entry,
983 groupedEntries: visibleActiveToolEntries.map((entry) => entry.entry),
984 groupId,
985 expanded: input.expandedWorkGroupIds?.has(groupId) ?? false,
986 active: latestToolKeepsActivityLive,
987 };
988 })()
989 : null;
990 const activeWorkEntryIds = new Set(
991 activeWorkRow !== null || latestToolFailed ? activeToolEntries.map((entry) => entry.id) : [],
992 );
993 const appendWorkingRow = () => {
994 const latestUserMessage = input.timelineEntries[lastUserMessageIndex(input.timelineEntries)];
995 const visualResponseStartedAt =
996 activeVisualResponseTurnIds.size > 1 &&
997 latestUserMessage?.kind === "message" &&
998 latestUserMessage.message.role === "user"
999 ? latestUserMessage.message.createdAt
1000 : input.activeTurnStartedAt;
1001 nextRows.push({
1002 kind: "working",
1003 id: "working-indicator-row",
1004 createdAt: visualResponseStartedAt,
1005 });
1006 };
1007 let hasActivityRow = false;
1008 const appendActiveWorkRows = () => {
1009 if (activeWorkRow === null) return;
1010 nextRows.push(activeWorkRow);
1011 hasActivityRow ||= activeWorkRow.active;
1012 if (!activeWorkRow.expanded || activeWorkRow.entry.agentSpawn) return;
1013 nextRows.push(
1014 expandedWorkGroupRow(
1015 activeWorkRow.groupId,
1016 activeWorkRow.createdAt,
1017 activeWorkRow.groupedEntries,
1018 ),
1019 );
1020 };
1021
1022 for (let index = 0; index < input.timelineEntries.length; index += 1) {
1023 const timelineEntry = input.timelineEntries[index];
1024 if (!timelineEntry) {
1025 continue;
1026 }
1027
1028 if (input.isWorking && index === activeTurnHeaderIndex) {
1029 appendWorkingRow();
1030 }
1031
1032 if (timelineEntry.id === activeWorkPlacementEntryId) {
1033 appendActiveWorkRows();
1034 }
1035
1036 const anchoredTurnFold = foldsByAnchorEntryId.get(timelineEntry.id);
1037 if (anchoredTurnFold) {
1038 nextRows.push({
1039 kind: "turn-fold",
1040 id: `turn-fold:${anchoredTurnFold.turnId}`,
1041 createdAt: anchoredTurnFold.createdAt,
1042 turnId: anchoredTurnFold.turnId,
1043 label: anchoredTurnFold.label,
1044 expanded: input.expandedTurnIds?.has(anchoredTurnFold.turnId) ?? false,
1045 });
1046 }
1047
1048 if (collapsedEntryIds.has(timelineEntry.id)) {
1049 continue;
1050 }
1051
1052 if (activeWorkEntryIds.has(timelineEntry.id)) {
1053 continue;
1054 }
1055
1056 if (
1057 timelineEntry.kind === "work" &&
1058 timelineEntry.entry.sourceActivityKind === "context-compaction"
1059 ) {
1060 nextRows.push({
1061 kind: "context-compaction",
1062 id: timelineEntry.id,
1063 createdAt: timelineEntry.createdAt,
1064 label: timelineEntry.entry.label,
1065 });
1066 continue;
1067 }
1068
1069 if (timelineEntry.kind === "work") {
1070 if (
1071 timelineEntry.entry.agentSpawn !== undefined ||
1072 timelineEntry.entry.questionAnswer !== undefined ||
1073 timelineEntry.entry.tone === "error"
1074 ) {
1075 const spawn = timelineEntry.entry.agentSpawn;
1076 if (spawn && entryBelongsToActiveTurn(timelineEntry, index)) {
1077 hasActivityRow ||=
1078 (spawn.workflowId !== null && input.liveAgentTaskIds?.has(spawn.workflowId)) ||
1079 spawn.agentTaskIds.some((taskId) => input.liveAgentTaskIds?.has(taskId));
1080 }
1081 nextRows.push({
1082 kind: "work",
1083 id: timelineEntry.id,
1084 createdAt: timelineEntry.createdAt,
1085 groupedEntries: [timelineEntry.entry],
1086 isExpandedToolGroup: false,
1087 });
1088 continue;
1089 }
1090 const groupedEntries = [timelineEntry.entry];
1091 let cursor = index + 1;
1092 while (cursor < input.timelineEntries.length) {
1093 const nextEntry = input.timelineEntries[cursor];
1094 if (
1095 !nextEntry ||
1096 nextEntry.kind !== "work" ||
1097 nextEntry.entry.agentSpawn !== undefined ||
1098 nextEntry.entry.questionAnswer !== undefined ||
1099 nextEntry.entry.sourceActivityKind === "context-compaction" ||
1100 nextEntry.entry.tone === "error" ||
1101 activeWorkEntryIds.has(nextEntry.id) ||
1102 collapsedEntryIds.has(nextEntry.id) ||
1103 foldsByAnchorEntryId.has(nextEntry.id)
1104 ) {
1105 break;
1106 }
1107 groupedEntries.push(nextEntry.entry);
1108 cursor += 1;
1109 }
1110 const visibleGroupedEntries = omitSupersededLifecycleMarkers(
1111 groupedEntries.filter((entry) =>
1112 workEntryIsVisibleInGroup(entry, workEntryIsInActiveRun(entry)),
1113 ),
1114 (entry) => entry,
1115 );
1116 if (visibleGroupedEntries.length > 0) {
1117 const activeInProgressToolEntries = visibleGroupedEntries.filter(workEntryIsInActiveRun);
1118 if (activeInProgressToolEntries.length > 0) {
1119 const groupId = workGroupId(timelineEntry.id, timelineEntry.entry);
1120 const expanded = input.expandedWorkGroupIds?.has(groupId) ?? false;
1121 const latestActiveToolEntry = activeInProgressToolEntries.at(-1)!;
1122 nextRows.push({
1123 kind: "work-live",
1124 id: `work-live:${workGroupIdentity(timelineEntry.id, timelineEntry.entry)}`,
1125 createdAt: timelineEntry.createdAt,
1126 entry: latestActiveToolEntry,
1127 groupedEntries: visibleGroupedEntries,
1128 groupId,
1129 expanded,
1130 active: true,
1131 });
1132 hasActivityRow = true;
1133 if (expanded) {
1134 nextRows.push(
1135 expandedWorkGroupRow(groupId, timelineEntry.createdAt, visibleGroupedEntries),
1136 );
1137 }
1138 } else if (
1139 visibleGroupedEntries.length === 1 &&
1140 workLogEntryIsToolLike(visibleGroupedEntries[0]!)
1141 ) {
1142 const singleEntry = visibleGroupedEntries[0]!;
1143 nextRows.push({
1144 kind: "work",
1145 id: timelineEntry.id,
1146 createdAt: timelineEntry.createdAt,
1147 groupedEntries: visibleGroupedEntries,
1148 isExpandedToolGroup: false,
1149 displayLabel:
1150 toolGroupAction(singleEntry) === "edit"
1151 ? summarizeToolGroup(visibleGroupedEntries)
1152 : singleToolCallLabel(singleEntry),
1153 });
1154 } else {
1155 const groupId = workGroupId(timelineEntry.id, timelineEntry.entry);
1156 const expanded = input.expandedWorkGroupIds?.has(groupId) ?? false;
1157 const summaryKind = toolGroupSummaryKind(visibleGroupedEntries);
1158 const primarySourceEntry = visibleGroupedEntries.find(
1159 (entry) => entry.toolSource !== undefined,
1160 );
1161 const primarySourceKey = primarySourceEntry?.toolSource?.key;
1162 const primarySourceIcon = primarySourceKey
1163 ? (visibleGroupedEntries.find(
1164 (entry) =>
1165 entry.toolSource?.key === primarySourceKey && entry.toolIcon !== undefined,
1166 )?.toolIcon ?? primarySourceEntry?.toolSource?.icon)
1167 : undefined;
1168 const groupToolSurface =
1169 primarySourceEntry?.toolSurface ??
1170 visibleGroupedEntries.findLast((entry) => entry.toolSurface !== undefined)?.toolSurface;
1171 const groupToolIcon =
1172 primarySourceIcon ??
1173 visibleGroupedEntries.findLast((entry) => entry.toolIcon !== undefined)?.toolIcon;
1174 const latestToolEntry = visibleGroupedEntries.findLast(workLogEntryIsToolLike);
1175 const singleEntry =
1176 visibleGroupedEntries.length === 1 ? (visibleGroupedEntries[0] ?? null) : null;
1177 const usesSingleToolCallLabel =
1178 singleEntry !== null &&
1179 workLogEntryIsToolLike(singleEntry) &&
1180 toolGroupAction(singleEntry) !== "edit";
1181 const summaryToolIcon = usesSingleToolCallLabel
1182 ? resolveWorkEntryToolPresentation(singleEntry, "completed")?.icon
1183 : undefined;
1184 nextRows.push({
1185 kind: "work-toggle",
1186 id: `work-toggle:${timelineEntry.id}`,
1187 createdAt: timelineEntry.createdAt,
1188 turnId: timelineEntry.entry.turnId ?? null,
1189 groupId,
1190 hiddenCount: visibleGroupedEntries.length,
1191 expanded,
1192 summary: usesSingleToolCallLabel
1193 ? singleToolCallLabel(singleEntry)
1194 : singleEntry !== null && !workLogEntryIsToolLike(singleEntry)
1195 ? singleEntry.label
1196 : summarizeToolGroup(visibleGroupedEntries),
1197 summaryKind,
1198 ...(groupToolSurface ? { toolSurface: groupToolSurface } : {}),
1199 ...(groupToolIcon ? { toolIcon: groupToolIcon } : {}),
1200 ...(summaryToolIcon ? { summaryToolIcon } : {}),
1201 hasFailure:
1202 latestToolEntry !== undefined &&
1203 workEntryDisplayIndicatesToolFailure(latestToolEntry),
1204 });
1205 if (expanded) {
1206 nextRows.push(
1207 expandedWorkGroupRow(groupId, timelineEntry.createdAt, visibleGroupedEntries),
1208 );
1209 }
1210 }
1211 }
1212 index = cursor - 1;
1213 continue;
1214 }
1215
1216 if (timelineEntry.kind === "proposed-plan") {
1217 nextRows.push({
1218 kind: "proposed-plan",
1219 id: timelineEntry.id,
1220 createdAt: timelineEntry.createdAt,
1221 proposedPlan: timelineEntry.proposedPlan,
1222 });
1223 continue;
1224 }
1225
1226 const assistantResponseStillInProgress =
1227 timelineEntry.message.role === "assistant" &&
1228 timelineEntry.message.turnId !== null &&
1229 timelineEntry.message.turnId !== undefined &&
1230 activeVisualResponseTurnIds.has(timelineEntry.message.turnId);
1231
1232 const durationStart =
1233 durationStartByMessageId.get(timelineEntry.message.id) ?? timelineEntry.message.createdAt;
1234
1235 // While the turn is still running, the latest assistant message is only
1236 // provisionally terminal — withhold the metadata row until the turn
1237 // settles so commentary doesn't flash timestamps mid-work.
1238 const showAssistantMeta =
1239 timelineEntry.message.role === "assistant" &&
1240 terminalAssistantMessageIds.has(timelineEntry.message.id) &&
1241 !assistantResponseStillInProgress;
1242
1243 nextRows.push({
1244 kind: "message",
1245 id: timelineEntry.id,
1246 createdAt: timelineEntry.createdAt,
1247 message: timelineEntry.message,
1248 durationStart,
1249 showAssistantMeta,
1250 showAssistantCopyButton: showAssistantMeta,
1251 assistantCopyStreaming: timelineEntry.message.streaming || assistantResponseStillInProgress,
1252 assistantTurnDiffSummary:
1253 timelineEntry.message.role === "assistant"
1254 ? turnDiffSummaryByAssistantMessageId.get(timelineEntry.message.id)
1255 : undefined,
1256 revertTurnCount:
1257 timelineEntry.message.role === "user"
1258 ? revertTurnCountByUserMessageId.get(timelineEntry.message.id)
1259 : undefined,
1260 });
1261 }
1262
1263 // The setup card takes the place of the working and thinking placeholders
1264 // while a worktree is being prepared. It stays after the setup settles so a
1265 // failure and its actions remain visible until the thread state moves on.
1266 if (input.worktreeSetup) {
1267 const setupRow = {
1268 kind: "worktree-setup",
1269 id: WORKTREE_SETUP_ROW_ID,
1270 createdAt: input.worktreeSetup.startedAt,
1271 snapshot: input.worktreeSetup,
1272 } as const;
1273 // Sit directly under the first user message: a finished snapshot can
1274 // outlive the first assistant reply, and it belongs to the send, not the
1275 // end of the thread.
1276 const firstUserRowIndex = nextRows.findIndex(
1277 (row) => row.kind === "message" && row.message.role === "user",
1278 );
1279 if (firstUserRowIndex >= 0) {
1280 nextRows.splice(firstUserRowIndex + 1, 0, setupRow);
1281 } else {
1282 nextRows.push(setupRow);
1283 }
1284 return attachTrailingToolGroupsToAssistant(nextRows);
1285 }
1286
1287 if (input.isWorking && activeTurnHeaderIndex === input.timelineEntries.length) {
1288 appendWorkingRow();
1289 }
1290 if (input.isWorking && (!hasActivityRow || latestToolFailed)) {
1291 nextRows.push({
1292 kind: "thinking",
1293 id: LIVE_ACTIVITY_ROW_ID,
1294 createdAt: input.activeTurnStartedAt,
1295 });
1296 }
1297
1298 return attachTrailingToolGroupsToAssistant(nextRows);
1299}
1300
1301export const WORKTREE_SETUP_ROW_ID = "worktree-setup-row";
1302
1303type MessagesTimelineRowsInput = Parameters<typeof deriveMessagesTimelineRows>[0];
1304
1305export interface MessagesTimelineRowsProjection {
1306 readonly input: MessagesTimelineRowsInput;
1307 readonly rows: MessagesTimelineRow[];
1308}
1309
1310function replaceStreamingMessageRows(
1311 input: MessagesTimelineRowsInput,
1312 previous: MessagesTimelineRowsProjection,
1313): MessagesTimelineRow[] | null {
1314 const {
1315 timelineEntries: previousEntries,
1316 turnDiffSummaries: previousSummaries,
1317 latestTurn: previousLatestTurn,
1318 expandedTurnIds: previousExpandedTurns,
1319 expandedWorkGroupIds: previousExpandedGroups,
1320 ...previousContext
1321 } = previous.input;
1322 const {
1323 timelineEntries,
1324 turnDiffSummaries,
1325 latestTurn,
1326 expandedTurnIds,
1327 expandedWorkGroupIds,
1328 ...context
1329 } = input;
1330 if (
1331 timelineEntries.length !== previousEntries.length ||
1332 !shallow(previousContext, context) ||
1333 !shallow(previousSummaries, turnDiffSummaries) ||
1334 !shallow(previousLatestTurn, latestTurn) ||
1335 !shallow(previousExpandedTurns, expandedTurnIds) ||
1336 !shallow(previousExpandedGroups, expandedWorkGroupIds)
1337 ) {
1338 return null;
1339 }
1340 const replacements = new Map<ChatMessage, ChatMessage>();
1341 for (const [index, entry] of timelineEntries.entries()) {
1342 const previousEntry = previousEntries[index]!;
1343 if (entry === previousEntry) continue;
1344 if (
1345 entry.kind !== "message" ||
1346 previousEntry.kind !== "message" ||
1347 entry.id !== previousEntry.id ||
1348 entry.createdAt !== previousEntry.createdAt
1349 ) {
1350 return null;
1351 }
1352 if (entry.message === previousEntry.message) continue;
1353 if (!isStreamingMessageTextUpdate(previousEntry.message, entry.message)) return null;
1354 replacements.set(previousEntry.message, entry.message);
1355 }
1356 if (replacements.size === 0) return previous.rows;
1357 return previous.rows.map((row) => {
1358 if (row.kind !== "message" && row.kind !== "assistant-meta") return row;
1359 const message = replacements.get(row.message);
1360 return message ? { ...row, message } : row;
1361 });
1362}
1363
1364/** Keep one projection per timeline. Reuse rows only when streaming content changes. */
1365export function deriveMessagesTimelineRowsWithState(
1366 input: MessagesTimelineRowsInput,
1367 previous: MessagesTimelineRowsProjection | null = null,
1368): MessagesTimelineRowsProjection {
1369 return {
1370 input,
1371 rows:
1372 (previous === null ? null : replaceStreamingMessageRows(input, previous)) ??
1373 deriveMessagesTimelineRows(input),
1374 };
1375}
1376
1377export function computeStableMessagesTimelineRows(
1378 rows: MessagesTimelineRow[],
1379 previous: StableMessagesTimelineRowsState,
1380): StableMessagesTimelineRowsState {
1381 const next = new Map<string, MessagesTimelineRow>();
1382 let anyChanged = rows.length !== previous.byId.size;
1383
1384 const result = rows.map((row, index) => {
1385 const prevRow = previous.byId.get(row.id);
1386 const nextRow = prevRow && isRowUnchanged(prevRow, row) ? prevRow : row;
1387 next.set(row.id, nextRow);
1388 if (!anyChanged && previous.result[index] !== nextRow) {
1389 anyChanged = true;
1390 }
1391 return nextRow;
1392 });
1393
1394 return anyChanged ? { byId: next, result } : previous;
1395}
1396
1397/** Shallow field comparison per row variant — avoids deep equality cost. */
1398function isRowUnchanged(a: MessagesTimelineRow, b: MessagesTimelineRow): boolean {
1399 if (a.kind !== b.kind || a.id !== b.id) return false;
1400
1401 switch (a.kind) {
1402 case "working":
1403 case "thinking":
1404 return a.createdAt === (b as typeof a).createdAt;
1405 case "worktree-setup":
1406 return a.snapshot === (b as typeof a).snapshot;
1407
1408 case "assistant-meta": {
1409 const bm = b as typeof a;
1410 return (
1411 a.createdAt === bm.createdAt &&
1412 a.message === bm.message &&
1413 a.showAssistantCopyButton === bm.showAssistantCopyButton &&
1414 a.assistantCopyStreaming === bm.assistantCopyStreaming
1415 );
1416 }
1417
1418 case "turn-fold": {
1419 const bf = b as typeof a;
1420 return a.createdAt === bf.createdAt && a.label === bf.label && a.expanded === bf.expanded;
1421 }
1422
1423 case "context-compaction": {
1424 const bc = b as typeof a;
1425 return a.createdAt === bc.createdAt && a.label === bc.label;
1426 }
1427
1428 case "proposed-plan":
1429 return a.proposedPlan === (b as typeof a).proposedPlan;
1430
1431 case "work": {
1432 const bw = b as typeof a;
1433 return (
1434 a.isExpandedToolGroup === bw.isExpandedToolGroup &&
1435 a.displayLabel === bw.displayLabel &&
1436 Equal.equals(a.groupedEntries, bw.groupedEntries)
1437 );
1438 }
1439
1440 case "work-live": {
1441 const bw = b as typeof a;
1442 return (
1443 a.createdAt === bw.createdAt &&
1444 a.groupId === bw.groupId &&
1445 a.expanded === bw.expanded &&
1446 a.active === bw.active &&
1447 Equal.equals(a.entry, bw.entry) &&
1448 Equal.equals(a.groupedEntries, bw.groupedEntries)
1449 );
1450 }
1451
1452 case "work-toggle": {
1453 const bw = b as typeof a;
1454 return (
1455 a.createdAt === bw.createdAt &&
1456 a.turnId === bw.turnId &&
1457 a.groupId === bw.groupId &&
1458 a.hiddenCount === bw.hiddenCount &&
1459 a.expanded === bw.expanded &&
1460 a.summary === bw.summary &&
1461 a.summaryKind === bw.summaryKind &&
1462 a.toolSurface === bw.toolSurface &&
1463 Equal.equals(a.toolIcon, bw.toolIcon) &&
1464 a.hasFailure === bw.hasFailure
1465 );
1466 }
1467
1468 case "message": {
1469 const bm = b as typeof a;
1470 return (
1471 a.message === bm.message &&
1472 a.durationStart === bm.durationStart &&
1473 a.showAssistantMeta === bm.showAssistantMeta &&
1474 a.showAssistantCopyButton === bm.showAssistantCopyButton &&
1475 a.assistantCopyStreaming === bm.assistantCopyStreaming &&
1476 a.assistantTurnDiffSummary === bm.assistantTurnDiffSummary &&
1477 a.revertTurnCount === bm.revertTurnCount
1478 );
1479 }
1480 }
1481}