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 fold activity before their terminal assistant message behind
544 * a "Worked for ..." row. A single ordinary activity after that message joins
545 * the fold, while larger groups and failures stay visible as a trailing summary.
546 */
547function deriveTurnFolds(input: {
548 timelineEntries: ReadonlyArray<TimelineEntry>;
549 terminalAssistantMessageIds: ReadonlySet<string>;
550 latestTurn: TimelineLatestTurn | null;
551 unfoldedTurnIds: ReadonlySet<TurnId>;
552}): ReadonlyMap<string, TurnFold> {
553 interface TurnGroup {
554 entries: Array<TimelineEntry>;
555 terminalEntry: Extract<TimelineEntry, { kind: "message" }> | null;
556 hasStreamingMessage: boolean;
557 /**
558 * The user message that kicked the turn off. Entry timestamps alone
559 * undercount the duration (the first entry appears only once the
560 * provider starts producing output), and a turn cut short by a steer may
561 * hold a single instantaneous commentary message.
562 */
563 startBoundary: string | null;
564 }
565 const groupsByTurnId = new Map<TurnId, TurnGroup>();
566
567 let pendingUserBoundary: string | null = null;
568 for (const entry of input.timelineEntries) {
569 if (entry.kind === "message" && entry.message.role === "user") {
570 pendingUserBoundary = entry.message.createdAt;
571 continue;
572 }
573 const turnId =
574 entry.kind === "message" && entry.message.role === "assistant"
575 ? (entry.message.turnId ?? null)
576 : entry.kind === "work"
577 ? (entry.entry.turnId ?? null)
578 : null;
579 if (!turnId) {
580 continue;
581 }
582 let group = groupsByTurnId.get(turnId);
583 if (!group) {
584 group = {
585 entries: [],
586 terminalEntry: null,
587 hasStreamingMessage: false,
588 // Each user boundary starts at most one turn; a second turn after the
589 // same user message (e.g. a steer-superseded continuation) falls back
590 // to its own first entry.
591 startBoundary: pendingUserBoundary,
592 };
593 pendingUserBoundary = null;
594 groupsByTurnId.set(turnId, group);
595 }
596 group.entries.push(entry);
597 if (entry.kind === "message") {
598 if (input.terminalAssistantMessageIds.has(entry.message.id)) {
599 group.terminalEntry = entry;
600 }
601 if (entry.message.streaming) {
602 group.hasStreamingMessage = true;
603 }
604 }
605 }
606
607 const foldsByAnchorEntryId = new Map<string, TurnFold>();
608 for (const [turnId, group] of groupsByTurnId) {
609 if (input.unfoldedTurnIds.has(turnId)) {
610 continue;
611 }
612 if (group.hasStreamingMessage) {
613 continue;
614 }
615 const hiddenEntryIds = new Set<string>();
616 const terminalEntryIndex = group.terminalEntry
617 ? group.entries.findIndex((entry) => entry.id === group.terminalEntry?.id)
618 : group.entries.length;
619 for (const [index, entry] of group.entries.entries()) {
620 if (entry.id === group.terminalEntry?.id) {
621 continue;
622 }
623 const isCompaction =
624 entry.kind === "work" && entry.entry.sourceActivityKind === "context-compaction";
625 const isSingleTrailingActivity =
626 group.entries.length === terminalEntryIndex + 2 &&
627 entry.kind === "work" &&
628 !workEntryDisplayIndicatesToolFailure(entry.entry);
629 if (!isCompaction && index > terminalEntryIndex && !isSingleTrailingActivity) {
630 continue;
631 }
632 // Agent-spawn CTA rows never fold: workflows outlive their launching
633 // turn (dynamic spawns, background execution), and folding the CTA
634 // when the turn settles makes a still-running fleet invisible.
635 if (entry.kind === "work" && entry.entry.agentSpawn !== undefined) {
636 continue;
637 }
638 hiddenEntryIds.add(entry.id);
639 }
640 if (hiddenEntryIds.size === 0) {
641 continue;
642 }
643 // A lone compaction row stays visible on its own; it only folds away as
644 // part of a turn that already folds other work.
645 const hidesNonCompactionWork = group.entries.some(
646 (entry) =>
647 hiddenEntryIds.has(entry.id) &&
648 !(entry.kind === "work" && entry.entry.sourceActivityKind === "context-compaction"),
649 );
650 if (!hidesNonCompactionWork) {
651 continue;
652 }
653
654 const firstEntry = group.entries[0];
655 const firstHiddenEntry = group.entries.find((entry) => hiddenEntryIds.has(entry.id));
656 const lastEntry = group.entries.at(-1);
657 if (!firstEntry || !firstHiddenEntry || !lastEntry) {
658 continue;
659 }
660
661 const isLatestInterruptedTurn =
662 input.latestTurn?.turnId === turnId && input.latestTurn.state === "interrupted";
663 // A turn cut short by a steer leaves trailing work entries behind its
664 // terminal message — take whichever ended last.
665 const lastEntryEnd =
666 lastEntry.kind === "message" ? lastEntry.message.updatedAt : lastEntry.createdAt;
667 const elapsedMs =
668 input.latestTurn?.turnId === turnId &&
669 input.latestTurn.startedAt &&
670 input.latestTurn.completedAt
671 ? computeElapsedMs(input.latestTurn.startedAt, input.latestTurn.completedAt)
672 : computeElapsedMs(
673 group.startBoundary ?? firstEntry.createdAt,
674 maxIsoTimestamp(group.terminalEntry?.message.updatedAt ?? null, lastEntryEnd) ??
675 lastEntryEnd,
676 );
677 const duration = elapsedMs !== null ? formatDuration(elapsedMs) : null;
678 const label = isLatestInterruptedTurn
679 ? duration
680 ? `You stopped after ${duration}`
681 : "You stopped this response"
682 : duration
683 ? `Worked for ${duration}`
684 : "Worked";
685
686 foldsByAnchorEntryId.set(firstHiddenEntry.id, {
687 turnId,
688 anchorEntryId: firstHiddenEntry.id,
689 createdAt: firstHiddenEntry.createdAt,
690 hiddenEntryIds,
691 label,
692 });
693 }
694 return foldsByAnchorEntryId;
695}
696
697/**
698 * When a settled turn ends with tool calls after its terminal text, treat the
699 * text and tools as one visual response. The message metadata becomes the
700 * footer for the whole block instead of separating the prose from the tools.
701 */
702function attachTrailingToolGroupsToAssistant(
703 rows: ReadonlyArray<MessagesTimelineRow>,
704): MessagesTimelineRow[] {
705 const messageRowsWithoutMeta = new Set<string>();
706 const metaRowsAfterIndex = new Map<
707 number,
708 Extract<MessagesTimelineRow, { kind: "assistant-meta" }>
709 >();
710
711 for (const [messageIndex, row] of rows.entries()) {
712 const turnId = row.kind === "message" ? (row.message.turnId ?? null) : null;
713 if (
714 row.kind !== "message" ||
715 row.message.role !== "assistant" ||
716 !row.showAssistantMeta ||
717 turnId === null
718 ) {
719 continue;
720 }
721
722 let lastTrailingWorkIndex = -1;
723 let hasTrailingToolGroup = false;
724 for (let index = messageIndex + 1; index < rows.length; index += 1) {
725 const candidate = rows[index];
726 if (!candidate || candidate.kind === "message") {
727 break;
728 }
729 if (candidate.kind === "work-toggle" && candidate.turnId === turnId) {
730 hasTrailingToolGroup = true;
731 lastTrailingWorkIndex = index;
732 continue;
733 }
734 if (
735 candidate.kind === "work" &&
736 candidate.groupedEntries.some((entry) => entry.turnId === turnId)
737 ) {
738 if (
739 !candidate.isExpandedToolGroup &&
740 candidate.groupedEntries.some(workLogEntryIsToolLike)
741 ) {
742 hasTrailingToolGroup = true;
743 }
744 if (hasTrailingToolGroup) {
745 lastTrailingWorkIndex = index;
746 }
747 }
748 }
749
750 if (lastTrailingWorkIndex < 0) {
751 continue;
752 }
753
754 messageRowsWithoutMeta.add(row.id);
755 metaRowsAfterIndex.set(lastTrailingWorkIndex, {
756 kind: "assistant-meta",
757 id: `assistant-meta:${row.message.id}`,
758 createdAt: rows[lastTrailingWorkIndex]?.createdAt ?? row.message.updatedAt,
759 message: row.message,
760 showAssistantCopyButton: row.showAssistantCopyButton,
761 assistantCopyStreaming: row.assistantCopyStreaming,
762 });
763 }
764
765 const result: MessagesTimelineRow[] = [];
766 for (const [index, row] of rows.entries()) {
767 if (row.kind === "message" && messageRowsWithoutMeta.has(row.id)) {
768 result.push({ ...row, showAssistantMeta: false, showAssistantCopyButton: false });
769 } else {
770 result.push(row);
771 }
772 const metaRow = metaRowsAfterIndex.get(index);
773 if (metaRow) {
774 result.push(metaRow);
775 }
776 }
777 return result;
778}
779
780/** Match each user message to the next assistant checkpoint. */
781function buildRevertTurnCountByUserMessageId(input: {
782 supportsConversationRollback: boolean;
783 timelineEntries: ReadonlyArray<TimelineEntry>;
784 turnDiffSummaryByAssistantMessageId: ReadonlyMap<MessageId, TurnDiffSummary>;
785 inferredCheckpointTurnCountByTurnId: Readonly<Record<string, number | undefined>>;
786}): Map<MessageId, number> {
787 const byUserMessageId = new Map<MessageId, number>();
788 const entryCount = input.supportsConversationRollback ? input.timelineEntries.length : 0;
789 for (let index = 0; index < entryCount; index += 1) {
790 const entry = input.timelineEntries[index];
791 if (!entry || entry.kind !== "message" || entry.message.role !== "user") {
792 continue;
793 }
794
795 for (let nextIndex = index + 1; nextIndex < input.timelineEntries.length; nextIndex += 1) {
796 const nextEntry = input.timelineEntries[nextIndex];
797 if (!nextEntry || nextEntry.kind !== "message") {
798 continue;
799 }
800 if (nextEntry.message.role === "user") {
801 break;
802 }
803 const summary = input.turnDiffSummaryByAssistantMessageId.get(nextEntry.message.id);
804 if (!summary) {
805 continue;
806 }
807 const turnCount =
808 summary.checkpointTurnCount ?? input.inferredCheckpointTurnCountByTurnId[summary.turnId];
809 if (typeof turnCount !== "number") {
810 break;
811 }
812 byUserMessageId.set(entry.message.id, Math.max(0, turnCount - 1));
813 break;
814 }
815 }
816 return byUserMessageId;
817}
818
819export function deriveMessagesTimelineRows(input: {
820 timelineEntries: ReadonlyArray<TimelineEntry>;
821 latestTurn?: TimelineLatestTurn | null;
822 runningTurnId?: TurnId | null;
823 expandedTurnIds?: ReadonlySet<TurnId>;
824 expandedWorkGroupIds?: ReadonlySet<string>;
825 isWorking: boolean;
826 activeTurnStartedAt: string | null;
827 turnDiffSummaries: ReadonlyArray<TurnDiffSummary>;
828 supportsConversationRollback: boolean;
829}): MessagesTimelineRow[] {
830 const turnDiffSummaryByAssistantMessageId = new Map<MessageId, TurnDiffSummary>();
831 for (const summary of input.turnDiffSummaries) {
832 if (summary.assistantMessageId) {
833 turnDiffSummaryByAssistantMessageId.set(summary.assistantMessageId, summary);
834 }
835 }
836 const revertTurnCountByUserMessageId = buildRevertTurnCountByUserMessageId({
837 supportsConversationRollback: input.supportsConversationRollback,
838 timelineEntries: input.timelineEntries,
839 turnDiffSummaryByAssistantMessageId,
840 inferredCheckpointTurnCountByTurnId: input.supportsConversationRollback
841 ? inferCheckpointTurnCountByTurnId(input.turnDiffSummaries)
842 : {},
843 });
844 const nextRows: MessagesTimelineRow[] = [];
845 const durationStartByMessageId = computeMessageDurationStart(
846 input.timelineEntries.flatMap((entry) => (entry.kind === "message" ? [entry.message] : [])),
847 );
848 const terminalAssistantMessageIds = deriveTerminalAssistantMessageIds(input.timelineEntries);
849 const unsettledTurnId = deriveUnsettledTurnId(
850 input.latestTurn ?? null,
851 input.runningTurnId ?? null,
852 );
853 const activeVisualResponseTurnIds = deriveActiveVisualResponseTurnIds({
854 timelineEntries: input.timelineEntries,
855 unsettledTurnId,
856 isWorking: input.isWorking,
857 });
858 const foldsByAnchorEntryId = deriveTurnFolds({
859 timelineEntries: input.timelineEntries,
860 terminalAssistantMessageIds,
861 latestTurn: input.latestTurn ?? null,
862 unfoldedTurnIds: activeVisualResponseTurnIds,
863 });
864 const collapsedEntryIds = new Set<string>();
865 for (const fold of foldsByAnchorEntryId.values()) {
866 if (!input.expandedTurnIds?.has(fold.turnId)) {
867 for (const entryId of fold.hiddenEntryIds) {
868 collapsedEntryIds.add(entryId);
869 }
870 }
871 }
872
873 let activeTurnHeaderIndex = input.timelineEntries.length;
874 if (input.isWorking) {
875 const latestUserMessageIndex = lastUserMessageIndex(input.timelineEntries);
876 activeTurnHeaderIndex = latestUserMessageIndex + 1;
877 }
878 const entryBelongsToActiveTurn = (entry: TimelineEntry, index: number) =>
879 input.isWorking &&
880 index >= activeTurnHeaderIndex &&
881 (unsettledTurnId === null || timelineEntryTurnId(entry) === unsettledTurnId);
882 const workEntryIsInActiveRun = (entry: WorkLogEntry) =>
883 input.isWorking &&
884 unsettledTurnId !== null &&
885 entry.toolLifecycleStatus === "inProgress" &&
886 entry.turnId === unsettledTurnId;
887 const activeToolEntries: Array<Extract<TimelineEntry, { kind: "work" }>> = [];
888 for (let index = input.timelineEntries.length - 1; index >= activeTurnHeaderIndex; index -= 1) {
889 const entry = input.timelineEntries[index]!;
890 if (
891 !entryBelongsToActiveTurn(entry, index) ||
892 entry.kind !== "work" ||
893 entry.entry.agentSpawn !== undefined ||
894 entry.entry.sourceActivityKind === "context-compaction" ||
895 entry.entry.tone === "error"
896 ) {
897 break;
898 }
899 activeToolEntries.unshift(entry);
900 }
901 const visibleActiveToolEntries = omitSupersededLifecycleMarkers(
902 activeToolEntries.filter((entry) => workEntryIsVisibleInGroup(entry.entry, true)),
903 (entry) => entry.entry,
904 );
905 const activeWorkAnchor = activeToolEntries[0];
906 const latestVisibleToolEntry = visibleActiveToolEntries.at(-1);
907 const latestRunningToolEntry = visibleActiveToolEntries.findLast((entry) =>
908 workEntryIsActiveTurnActivity(entry.entry),
909 );
910 const latestToolFailed =
911 latestRunningToolEntry === undefined &&
912 latestVisibleToolEntry !== undefined &&
913 latestVisibleToolEntry.entry.toolLifecycleStatus !== "declined" &&
914 workEntryDisplayIndicatesToolFailure(latestVisibleToolEntry.entry);
915 const latestToolKeepsActivityLive =
916 latestRunningToolEntry !== undefined ||
917 (latestVisibleToolEntry !== undefined &&
918 workEntryIndicatesToolSuccess(latestVisibleToolEntry.entry));
919 const activeWorkPlacementEntryId = latestVisibleToolEntry?.id;
920 const activeWorkRow =
921 activeWorkAnchor && latestVisibleToolEntry && !latestToolFailed
922 ? (() => {
923 const groupId = workGroupId(activeWorkAnchor.id, activeWorkAnchor.entry);
924 return {
925 kind: "work-live" as const,
926 id: latestToolKeepsActivityLive
927 ? LIVE_ACTIVITY_ROW_ID
928 : `work-live:${workGroupIdentity(activeWorkAnchor.id, activeWorkAnchor.entry)}`,
929 createdAt: activeWorkAnchor.createdAt,
930 entry: (latestRunningToolEntry ?? latestVisibleToolEntry).entry,
931 groupedEntries: visibleActiveToolEntries.map((entry) => entry.entry),
932 groupId,
933 expanded: input.expandedWorkGroupIds?.has(groupId) ?? false,
934 active: latestToolKeepsActivityLive,
935 };
936 })()
937 : null;
938 const activeWorkEntryIds = new Set(
939 activeWorkRow !== null || latestToolFailed ? activeToolEntries.map((entry) => entry.id) : [],
940 );
941 const appendWorkingRow = () => {
942 const latestUserMessage = input.timelineEntries[lastUserMessageIndex(input.timelineEntries)];
943 const visualResponseStartedAt =
944 activeVisualResponseTurnIds.size > 1 &&
945 latestUserMessage?.kind === "message" &&
946 latestUserMessage.message.role === "user"
947 ? latestUserMessage.message.createdAt
948 : input.activeTurnStartedAt;
949 nextRows.push({
950 kind: "working",
951 id: "working-indicator-row",
952 createdAt: visualResponseStartedAt,
953 });
954 };
955 let hasActivityRow = false;
956 const appendActiveWorkRows = () => {
957 if (activeWorkRow === null) return;
958 nextRows.push(activeWorkRow);
959 hasActivityRow ||= activeWorkRow.active;
960 if (!activeWorkRow.expanded) return;
961 nextRows.push(
962 expandedWorkGroupRow(
963 activeWorkRow.groupId,
964 activeWorkRow.createdAt,
965 activeWorkRow.groupedEntries,
966 ),
967 );
968 };
969
970 for (let index = 0; index < input.timelineEntries.length; index += 1) {
971 const timelineEntry = input.timelineEntries[index];
972 if (!timelineEntry) {
973 continue;
974 }
975
976 if (input.isWorking && index === activeTurnHeaderIndex) {
977 appendWorkingRow();
978 }
979
980 if (timelineEntry.id === activeWorkPlacementEntryId) {
981 appendActiveWorkRows();
982 }
983
984 const anchoredTurnFold = foldsByAnchorEntryId.get(timelineEntry.id);
985 if (anchoredTurnFold) {
986 nextRows.push({
987 kind: "turn-fold",
988 id: `turn-fold:${anchoredTurnFold.turnId}`,
989 createdAt: anchoredTurnFold.createdAt,
990 turnId: anchoredTurnFold.turnId,
991 label: anchoredTurnFold.label,
992 expanded: input.expandedTurnIds?.has(anchoredTurnFold.turnId) ?? false,
993 });
994 }
995
996 if (collapsedEntryIds.has(timelineEntry.id)) {
997 continue;
998 }
999
1000 if (activeWorkEntryIds.has(timelineEntry.id)) {
1001 continue;
1002 }
1003
1004 if (
1005 timelineEntry.kind === "work" &&
1006 timelineEntry.entry.sourceActivityKind === "context-compaction"
1007 ) {
1008 nextRows.push({
1009 kind: "context-compaction",
1010 id: timelineEntry.id,
1011 createdAt: timelineEntry.createdAt,
1012 label: timelineEntry.entry.label,
1013 });
1014 continue;
1015 }
1016
1017 if (timelineEntry.kind === "work") {
1018 if (timelineEntry.entry.agentSpawn !== undefined || timelineEntry.entry.tone === "error") {
1019 nextRows.push({
1020 kind: "work",
1021 id: timelineEntry.id,
1022 createdAt: timelineEntry.createdAt,
1023 groupedEntries: [timelineEntry.entry],
1024 isExpandedToolGroup: false,
1025 });
1026 continue;
1027 }
1028 const groupedEntries = [timelineEntry.entry];
1029 let cursor = index + 1;
1030 while (cursor < input.timelineEntries.length) {
1031 const nextEntry = input.timelineEntries[cursor];
1032 if (
1033 !nextEntry ||
1034 nextEntry.kind !== "work" ||
1035 nextEntry.entry.agentSpawn !== undefined ||
1036 nextEntry.entry.sourceActivityKind === "context-compaction" ||
1037 nextEntry.entry.tone === "error" ||
1038 activeWorkEntryIds.has(nextEntry.id) ||
1039 collapsedEntryIds.has(nextEntry.id) ||
1040 foldsByAnchorEntryId.has(nextEntry.id)
1041 ) {
1042 break;
1043 }
1044 groupedEntries.push(nextEntry.entry);
1045 cursor += 1;
1046 }
1047 const visibleGroupedEntries = omitSupersededLifecycleMarkers(
1048 groupedEntries.filter((entry) =>
1049 workEntryIsVisibleInGroup(entry, workEntryIsInActiveRun(entry)),
1050 ),
1051 (entry) => entry,
1052 );
1053 if (visibleGroupedEntries.length > 0) {
1054 const activeInProgressToolEntries = visibleGroupedEntries.filter(workEntryIsInActiveRun);
1055 if (activeInProgressToolEntries.length > 0) {
1056 const groupId = workGroupId(timelineEntry.id, timelineEntry.entry);
1057 const expanded = input.expandedWorkGroupIds?.has(groupId) ?? false;
1058 const latestActiveToolEntry = activeInProgressToolEntries.at(-1)!;
1059 nextRows.push({
1060 kind: "work-live",
1061 id: `work-live:${workGroupIdentity(timelineEntry.id, timelineEntry.entry)}`,
1062 createdAt: timelineEntry.createdAt,
1063 entry: latestActiveToolEntry,
1064 groupedEntries: visibleGroupedEntries,
1065 groupId,
1066 expanded,
1067 active: true,
1068 });
1069 hasActivityRow = true;
1070 if (expanded) {
1071 nextRows.push(
1072 expandedWorkGroupRow(groupId, timelineEntry.createdAt, visibleGroupedEntries),
1073 );
1074 }
1075 } else if (
1076 visibleGroupedEntries.length === 1 &&
1077 workLogEntryIsToolLike(visibleGroupedEntries[0]!)
1078 ) {
1079 const singleEntry = visibleGroupedEntries[0]!;
1080 nextRows.push({
1081 kind: "work",
1082 id: timelineEntry.id,
1083 createdAt: timelineEntry.createdAt,
1084 groupedEntries: visibleGroupedEntries,
1085 isExpandedToolGroup: false,
1086 displayLabel:
1087 toolGroupAction(singleEntry) === "edit"
1088 ? summarizeToolGroup(visibleGroupedEntries)
1089 : singleToolCallLabel(singleEntry),
1090 });
1091 } else {
1092 const groupId = workGroupId(timelineEntry.id, timelineEntry.entry);
1093 const expanded = input.expandedWorkGroupIds?.has(groupId) ?? false;
1094 const summaryKind = toolGroupSummaryKind(visibleGroupedEntries);
1095 const primarySourceEntry = visibleGroupedEntries.find(
1096 (entry) => entry.toolSource !== undefined,
1097 );
1098 const primarySourceKey = primarySourceEntry?.toolSource?.key;
1099 const primarySourceIcon = primarySourceKey
1100 ? (visibleGroupedEntries.find(
1101 (entry) =>
1102 entry.toolSource?.key === primarySourceKey && entry.toolIcon !== undefined,
1103 )?.toolIcon ?? primarySourceEntry?.toolSource?.icon)
1104 : undefined;
1105 const groupToolSurface =
1106 primarySourceEntry?.toolSurface ??
1107 visibleGroupedEntries.findLast((entry) => entry.toolSurface !== undefined)?.toolSurface;
1108 const groupToolIcon =
1109 primarySourceIcon ??
1110 visibleGroupedEntries.findLast((entry) => entry.toolIcon !== undefined)?.toolIcon;
1111 const latestToolEntry = visibleGroupedEntries.findLast(workLogEntryIsToolLike);
1112 const singleEntry =
1113 visibleGroupedEntries.length === 1 ? (visibleGroupedEntries[0] ?? null) : null;
1114 const usesSingleToolCallLabel =
1115 singleEntry !== null &&
1116 workLogEntryIsToolLike(singleEntry) &&
1117 toolGroupAction(singleEntry) !== "edit";
1118 const summaryToolIcon = usesSingleToolCallLabel
1119 ? resolveWorkEntryToolPresentation(singleEntry, "completed")?.icon
1120 : undefined;
1121 nextRows.push({
1122 kind: "work-toggle",
1123 id: `work-toggle:${timelineEntry.id}`,
1124 createdAt: timelineEntry.createdAt,
1125 turnId: timelineEntry.entry.turnId ?? null,
1126 groupId,
1127 hiddenCount: visibleGroupedEntries.length,
1128 expanded,
1129 summary: usesSingleToolCallLabel
1130 ? singleToolCallLabel(singleEntry)
1131 : singleEntry !== null && !workLogEntryIsToolLike(singleEntry)
1132 ? singleEntry.label
1133 : summarizeToolGroup(visibleGroupedEntries),
1134 summaryKind,
1135 ...(groupToolSurface ? { toolSurface: groupToolSurface } : {}),
1136 ...(groupToolIcon ? { toolIcon: groupToolIcon } : {}),
1137 ...(summaryToolIcon ? { summaryToolIcon } : {}),
1138 hasFailure:
1139 latestToolEntry !== undefined &&
1140 workEntryDisplayIndicatesToolFailure(latestToolEntry),
1141 });
1142 if (expanded) {
1143 nextRows.push(
1144 expandedWorkGroupRow(groupId, timelineEntry.createdAt, visibleGroupedEntries),
1145 );
1146 }
1147 }
1148 }
1149 index = cursor - 1;
1150 continue;
1151 }
1152
1153 if (timelineEntry.kind === "proposed-plan") {
1154 nextRows.push({
1155 kind: "proposed-plan",
1156 id: timelineEntry.id,
1157 createdAt: timelineEntry.createdAt,
1158 proposedPlan: timelineEntry.proposedPlan,
1159 });
1160 continue;
1161 }
1162
1163 const assistantResponseStillInProgress =
1164 timelineEntry.message.role === "assistant" &&
1165 timelineEntry.message.turnId !== null &&
1166 timelineEntry.message.turnId !== undefined &&
1167 activeVisualResponseTurnIds.has(timelineEntry.message.turnId);
1168
1169 const durationStart =
1170 durationStartByMessageId.get(timelineEntry.message.id) ?? timelineEntry.message.createdAt;
1171
1172 // While the turn is still running, the latest assistant message is only
1173 // provisionally terminal — withhold the metadata row until the turn
1174 // settles so commentary doesn't flash timestamps mid-work.
1175 const showAssistantMeta =
1176 timelineEntry.message.role === "assistant" &&
1177 terminalAssistantMessageIds.has(timelineEntry.message.id) &&
1178 !assistantResponseStillInProgress;
1179
1180 nextRows.push({
1181 kind: "message",
1182 id: timelineEntry.id,
1183 createdAt: timelineEntry.createdAt,
1184 message: timelineEntry.message,
1185 durationStart,
1186 showAssistantMeta,
1187 showAssistantCopyButton: showAssistantMeta,
1188 assistantCopyStreaming: timelineEntry.message.streaming || assistantResponseStillInProgress,
1189 assistantTurnDiffSummary:
1190 timelineEntry.message.role === "assistant"
1191 ? turnDiffSummaryByAssistantMessageId.get(timelineEntry.message.id)
1192 : undefined,
1193 revertTurnCount:
1194 timelineEntry.message.role === "user"
1195 ? revertTurnCountByUserMessageId.get(timelineEntry.message.id)
1196 : undefined,
1197 });
1198 }
1199
1200 if (input.isWorking && activeTurnHeaderIndex === input.timelineEntries.length) {
1201 appendWorkingRow();
1202 }
1203 if (input.isWorking && (!hasActivityRow || latestToolFailed)) {
1204 nextRows.push({
1205 kind: "thinking",
1206 id: LIVE_ACTIVITY_ROW_ID,
1207 createdAt: input.activeTurnStartedAt,
1208 });
1209 }
1210
1211 return attachTrailingToolGroupsToAssistant(nextRows);
1212}
1213
1214type MessagesTimelineRowsInput = Parameters<typeof deriveMessagesTimelineRows>[0];
1215
1216export interface MessagesTimelineRowsProjection {
1217 readonly input: MessagesTimelineRowsInput;
1218 readonly rows: MessagesTimelineRow[];
1219}
1220
1221function replaceStreamingMessageRows(
1222 input: MessagesTimelineRowsInput,
1223 previous: MessagesTimelineRowsProjection,
1224): MessagesTimelineRow[] | null {
1225 const {
1226 timelineEntries: previousEntries,
1227 turnDiffSummaries: previousSummaries,
1228 latestTurn: previousLatestTurn,
1229 expandedTurnIds: previousExpandedTurns,
1230 expandedWorkGroupIds: previousExpandedGroups,
1231 ...previousContext
1232 } = previous.input;
1233 const {
1234 timelineEntries,
1235 turnDiffSummaries,
1236 latestTurn,
1237 expandedTurnIds,
1238 expandedWorkGroupIds,
1239 ...context
1240 } = input;
1241 if (
1242 timelineEntries.length !== previousEntries.length ||
1243 !shallow(previousContext, context) ||
1244 !shallow(previousSummaries, turnDiffSummaries) ||
1245 !shallow(previousLatestTurn, latestTurn) ||
1246 !shallow(previousExpandedTurns, expandedTurnIds) ||
1247 !shallow(previousExpandedGroups, expandedWorkGroupIds)
1248 ) {
1249 return null;
1250 }
1251 const replacements = new Map<ChatMessage, ChatMessage>();
1252 for (const [index, entry] of timelineEntries.entries()) {
1253 const previousEntry = previousEntries[index]!;
1254 if (entry === previousEntry) continue;
1255 if (
1256 entry.kind !== "message" ||
1257 previousEntry.kind !== "message" ||
1258 entry.id !== previousEntry.id ||
1259 entry.createdAt !== previousEntry.createdAt
1260 ) {
1261 return null;
1262 }
1263 if (entry.message === previousEntry.message) continue;
1264 if (!isStreamingMessageTextUpdate(previousEntry.message, entry.message)) return null;
1265 replacements.set(previousEntry.message, entry.message);
1266 }
1267 if (replacements.size === 0) return previous.rows;
1268 return previous.rows.map((row) => {
1269 if (row.kind !== "message" && row.kind !== "assistant-meta") return row;
1270 const message = replacements.get(row.message);
1271 return message ? { ...row, message } : row;
1272 });
1273}
1274
1275/** Keep one projection per timeline. Reuse rows only when streaming content changes. */
1276export function deriveMessagesTimelineRowsWithState(
1277 input: MessagesTimelineRowsInput,
1278 previous: MessagesTimelineRowsProjection | null = null,
1279): MessagesTimelineRowsProjection {
1280 return {
1281 input,
1282 rows:
1283 (previous === null ? null : replaceStreamingMessageRows(input, previous)) ??
1284 deriveMessagesTimelineRows(input),
1285 };
1286}
1287
1288export function computeStableMessagesTimelineRows(
1289 rows: MessagesTimelineRow[],
1290 previous: StableMessagesTimelineRowsState,
1291): StableMessagesTimelineRowsState {
1292 const next = new Map<string, MessagesTimelineRow>();
1293 let anyChanged = rows.length !== previous.byId.size;
1294
1295 const result = rows.map((row, index) => {
1296 const prevRow = previous.byId.get(row.id);
1297 const nextRow = prevRow && isRowUnchanged(prevRow, row) ? prevRow : row;
1298 next.set(row.id, nextRow);
1299 if (!anyChanged && previous.result[index] !== nextRow) {
1300 anyChanged = true;
1301 }
1302 return nextRow;
1303 });
1304
1305 return anyChanged ? { byId: next, result } : previous;
1306}
1307
1308/** Shallow field comparison per row variant — avoids deep equality cost. */
1309function isRowUnchanged(a: MessagesTimelineRow, b: MessagesTimelineRow): boolean {
1310 if (a.kind !== b.kind || a.id !== b.id) return false;
1311
1312 switch (a.kind) {
1313 case "working":
1314 case "thinking":
1315 return a.createdAt === (b as typeof a).createdAt;
1316
1317 case "assistant-meta": {
1318 const bm = b as typeof a;
1319 return (
1320 a.createdAt === bm.createdAt &&
1321 a.message === bm.message &&
1322 a.showAssistantCopyButton === bm.showAssistantCopyButton &&
1323 a.assistantCopyStreaming === bm.assistantCopyStreaming
1324 );
1325 }
1326
1327 case "turn-fold": {
1328 const bf = b as typeof a;
1329 return a.createdAt === bf.createdAt && a.label === bf.label && a.expanded === bf.expanded;
1330 }
1331
1332 case "context-compaction": {
1333 const bc = b as typeof a;
1334 return a.createdAt === bc.createdAt && a.label === bc.label;
1335 }
1336
1337 case "proposed-plan":
1338 return a.proposedPlan === (b as typeof a).proposedPlan;
1339
1340 case "work": {
1341 const bw = b as typeof a;
1342 return (
1343 a.isExpandedToolGroup === bw.isExpandedToolGroup &&
1344 a.displayLabel === bw.displayLabel &&
1345 Equal.equals(a.groupedEntries, bw.groupedEntries)
1346 );
1347 }
1348
1349 case "work-live": {
1350 const bw = b as typeof a;
1351 return (
1352 a.createdAt === bw.createdAt &&
1353 a.groupId === bw.groupId &&
1354 a.expanded === bw.expanded &&
1355 a.active === bw.active &&
1356 Equal.equals(a.entry, bw.entry) &&
1357 Equal.equals(a.groupedEntries, bw.groupedEntries)
1358 );
1359 }
1360
1361 case "work-toggle": {
1362 const bw = b as typeof a;
1363 return (
1364 a.createdAt === bw.createdAt &&
1365 a.turnId === bw.turnId &&
1366 a.groupId === bw.groupId &&
1367 a.hiddenCount === bw.hiddenCount &&
1368 a.expanded === bw.expanded &&
1369 a.summary === bw.summary &&
1370 a.summaryKind === bw.summaryKind &&
1371 a.toolSurface === bw.toolSurface &&
1372 Equal.equals(a.toolIcon, bw.toolIcon) &&
1373 a.hasFailure === bw.hasFailure
1374 );
1375 }
1376
1377 case "message": {
1378 const bm = b as typeof a;
1379 return (
1380 a.message === bm.message &&
1381 a.durationStart === bm.durationStart &&
1382 a.showAssistantMeta === bm.showAssistantMeta &&
1383 a.showAssistantCopyButton === bm.showAssistantCopyButton &&
1384 a.assistantCopyStreaming === bm.assistantCopyStreaming &&
1385 a.assistantTurnDiffSummary === bm.assistantTurnDiffSummary &&
1386 a.revertTurnCount === bm.revertTurnCount
1387 );
1388 }
1389 }
1390}