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