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