Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

MessagesTimeline.logic.ts

1,418 lines47.9 KB

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)}`;
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)}`;
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);
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 );
104​
105export interface WorkGroupScrollAnchor {
106 readonly entryId: string;
107 readonly offset: number;
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 };
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 );
133​
134export interface TimelineEndState {
135 readonly isAtEnd?: boolean;
136 readonly contentLength?: number;
137 readonly scroll?: number;
138 readonly scrollLength?: number;
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;
166​
167export function shouldPreserveAssistantLineBreaks(text: string): boolean {
168 return /^★ Insight(?:\s|─)/mu.test(text);
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})`;
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;
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))));
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;
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;
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 );
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;
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);
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;
293​
294export interface TimelineDurationMessage {
295 id: string;
296 role: "user" | "assistant" | "system";
297 createdAt: string;
298 updatedAt: string;
299 streaming: boolean;
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[];
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;
417​
418function workGroupIdentity(timelineEntryId: string, entry: WorkLogEntry): string {
419 return entry.toolCallId
420 ? `tool:${entry.turnId ?? "no-turn"}:${entry.toolCallId}`
421 : timelineEntryId;
423​
424function workGroupId(timelineEntryId: string, entry: WorkLogEntry): string {
425 return `work-group:${workGroupIdentity(timelineEntryId, entry)}`;
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 };
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 };
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());
484​
485interface TurnFold {
486 turnId: TurnId;
487 anchorEntryId: string;
488 createdAt: string;
489 hiddenEntryIds: ReadonlySet<string>;
490 label: string;
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;
514​
515function lastUserMessageIndex(timelineEntries: ReadonlyArray<TimelineEntry>): number {
516 return timelineEntries.findLastIndex(
517 (entry) => entry.kind === "message" && entry.message.role === "user",
518 );
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;
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;
561​
562function workEntryIsActiveTurnActivity(entry: WorkLogEntry): boolean {
563 return (
564 entry.toolLifecycleStatus === "inProgress" ||
565 (entry.toolLifecycleStatus === undefined &&
566 (entry.sourceActivityKind === "task.progress" || workLogEntryIsToolLike(entry)))
567 );
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 // Agent-spawn CTA rows never fold: workflows outlive their launching
661 // turn (dynamic spawns, background execution), and folding the CTA
662 // when the turn settles makes a still-running fleet invisible.
663 if (entry.kind === "work" && entry.entry.agentSpawn !== undefined) {
664 continue;
665 }
666 hiddenEntryIds.add(entry.id);
667 }
668 if (hiddenEntryIds.size === 0) {
669 continue;
670 }
671 // A lone compaction row stays visible on its own; it only folds away as
672 // part of a turn that already folds other work.
673 const hidesNonCompactionWork = group.entries.some(
674 (entry) =>
675 hiddenEntryIds.has(entry.id) &&
676 !(entry.kind === "work" && entry.entry.sourceActivityKind === "context-compaction"),
677 );
678 if (!hidesNonCompactionWork) {
679 continue;
680 }
681​
682 const firstEntry = group.entries[0];
683 const firstHiddenEntry = group.entries.find((entry) => hiddenEntryIds.has(entry.id));
684 const lastEntry = group.entries.at(-1);
685 if (!firstEntry || !firstHiddenEntry || !lastEntry) {
686 continue;
687 }
688​
689 const isLatestInterruptedTurn =
690 input.latestTurn?.turnId === turnId && input.latestTurn.state === "interrupted";
691 // A turn cut short by a steer leaves trailing work entries behind its
692 // terminal message — take whichever ended last.
693 const lastEntryEnd =
694 lastEntry.kind === "message" ? lastEntry.message.updatedAt : lastEntry.createdAt;
695 const elapsedMs =
696 input.latestTurn?.turnId === turnId &&
697 input.latestTurn.startedAt &&
698 input.latestTurn.completedAt
699 ? computeElapsedMs(input.latestTurn.startedAt, input.latestTurn.completedAt)
700 : computeElapsedMs(
701 group.startBoundary ?? firstEntry.createdAt,
702 maxIsoTimestamp(group.terminalEntry?.message.updatedAt ?? null, lastEntryEnd) ??
703 lastEntryEnd,
704 );
705 const duration = elapsedMs !== null ? formatDuration(elapsedMs) : null;
706 const label = isLatestInterruptedTurn
707 ? duration
708 ? `You stopped after ${duration}`
709 : "You stopped this response"
710 : duration
711 ? `Worked for ${duration}`
712 : "Worked";
713​
714 foldsByAnchorEntryId.set(firstHiddenEntry.id, {
715 turnId,
716 anchorEntryId: firstHiddenEntry.id,
717 createdAt: firstHiddenEntry.createdAt,
718 hiddenEntryIds,
719 label,
720 });
721 }
722 return foldsByAnchorEntryId;
724​
725/**
726 * When a settled turn ends with tool calls after its terminal text, treat the
727 * text and tools as one visual response. The message metadata becomes the
728 * footer for the whole block instead of separating the prose from the tools.
729 */
730function attachTrailingToolGroupsToAssistant(
731 rows: ReadonlyArray<MessagesTimelineRow>,
732): MessagesTimelineRow[] {
733 const messageRowsWithoutMeta = new Set<string>();
734 const metaRowsAfterIndex = new Map<
735 number,
736 Extract<MessagesTimelineRow, { kind: "assistant-meta" }>
737 >();
738​
739 for (const [messageIndex, row] of rows.entries()) {
740 const turnId = row.kind === "message" ? (row.message.turnId ?? null) : null;
741 if (
742 row.kind !== "message" ||
743 row.message.role !== "assistant" ||
744 !row.showAssistantMeta ||
745 turnId === null
746 ) {
747 continue;
748 }
749​
750 let lastTrailingWorkIndex = -1;
751 let hasTrailingToolGroup = false;
752 for (let index = messageIndex + 1; index < rows.length; index += 1) {
753 const candidate = rows[index];
754 if (!candidate || candidate.kind === "message") {
755 break;
756 }
757 if (candidate.kind === "work-toggle" && candidate.turnId === turnId) {
758 hasTrailingToolGroup = true;
759 lastTrailingWorkIndex = index;
760 continue;
761 }
762 if (
763 candidate.kind === "work" &&
764 candidate.groupedEntries.some((entry) => entry.turnId === turnId)
765 ) {
766 if (
767 !candidate.isExpandedToolGroup &&
768 candidate.groupedEntries.some(workLogEntryIsToolLike)
769 ) {
770 hasTrailingToolGroup = true;
771 }
772 if (hasTrailingToolGroup) {
773 lastTrailingWorkIndex = index;
774 }
775 }
776 }
777​
778 if (lastTrailingWorkIndex < 0) {
779 continue;
780 }
781​
782 messageRowsWithoutMeta.add(row.id);
783 metaRowsAfterIndex.set(lastTrailingWorkIndex, {
784 kind: "assistant-meta",
785 id: `assistant-meta:${row.message.id}`,
786 createdAt: rows[lastTrailingWorkIndex]?.createdAt ?? row.message.updatedAt,
787 message: row.message,
788 showAssistantCopyButton: row.showAssistantCopyButton,
789 assistantCopyStreaming: row.assistantCopyStreaming,
790 });
791 }
792​
793 const result: MessagesTimelineRow[] = [];
794 for (const [index, row] of rows.entries()) {
795 if (row.kind === "message" && messageRowsWithoutMeta.has(row.id)) {
796 result.push({ ...row, showAssistantMeta: false, showAssistantCopyButton: false });
797 } else {
798 result.push(row);
799 }
800 const metaRow = metaRowsAfterIndex.get(index);
801 if (metaRow) {
802 result.push(metaRow);
803 }
804 }
805 return result;
807​
808/** Match each user message to the next assistant checkpoint. */
809function buildRevertTurnCountByUserMessageId(input: {
810 supportsConversationRollback: boolean;
811 timelineEntries: ReadonlyArray<TimelineEntry>;
812 turnDiffSummaryByAssistantMessageId: ReadonlyMap<MessageId, TurnDiffSummary>;
813 inferredCheckpointTurnCountByTurnId: Readonly<Record<string, number | undefined>>;
814}): Map<MessageId, number> {
815 const byUserMessageId = new Map<MessageId, number>();
816 const entryCount = input.supportsConversationRollback ? input.timelineEntries.length : 0;
817 for (let index = 0; index < entryCount; index += 1) {
818 const entry = input.timelineEntries[index];
819 if (!entry || entry.kind !== "message" || entry.message.role !== "user") {
820 continue;
821 }
822​
823 for (let nextIndex = index + 1; nextIndex < input.timelineEntries.length; nextIndex += 1) {
824 const nextEntry = input.timelineEntries[nextIndex];
825 if (!nextEntry || nextEntry.kind !== "message") {
826 continue;
827 }
828 if (nextEntry.message.role === "user") {
829 break;
830 }
831 const summary = input.turnDiffSummaryByAssistantMessageId.get(nextEntry.message.id);
832 if (!summary) {
833 continue;
834 }
835 const turnCount =
836 summary.checkpointTurnCount ?? input.inferredCheckpointTurnCountByTurnId[summary.turnId];
837 if (typeof turnCount !== "number") {
838 break;
839 }
840 byUserMessageId.set(entry.message.id, Math.max(0, turnCount - 1));
841 break;
842 }
843 }
844 return byUserMessageId;
846​
847export function deriveMessagesTimelineRows(input: {
848 timelineEntries: ReadonlyArray<TimelineEntry>;
849 latestTurn?: TimelineLatestTurn | null;
850 runningTurnId?: TurnId | null;
851 expandedTurnIds?: ReadonlySet<TurnId>;
852 expandedWorkGroupIds?: ReadonlySet<string>;
853 isWorking: boolean;
854 activeTurnStartedAt: string | null;
855 turnDiffSummaries: ReadonlyArray<TurnDiffSummary>;
856 supportsConversationRollback: boolean;
857}): MessagesTimelineRow[] {
858 const turnDiffSummaryByAssistantMessageId = new Map<MessageId, TurnDiffSummary>();
859 for (const summary of input.turnDiffSummaries) {
860 if (summary.assistantMessageId) {
861 turnDiffSummaryByAssistantMessageId.set(summary.assistantMessageId, summary);
862 }
863 }
864 const revertTurnCountByUserMessageId = buildRevertTurnCountByUserMessageId({
865 supportsConversationRollback: input.supportsConversationRollback,
866 timelineEntries: input.timelineEntries,
867 turnDiffSummaryByAssistantMessageId,
868 inferredCheckpointTurnCountByTurnId: input.supportsConversationRollback
869 ? inferCheckpointTurnCountByTurnId(input.turnDiffSummaries)
870 : {},
871 });
872 const nextRows: MessagesTimelineRow[] = [];
873 const durationStartByMessageId = computeMessageDurationStart(
874 input.timelineEntries.flatMap((entry) => (entry.kind === "message" ? [entry.message] : [])),
875 );
876 const terminalAssistantMessageIds = deriveTerminalAssistantMessageIds(input.timelineEntries);
877 const unsettledTurnId = deriveUnsettledTurnId(
878 input.latestTurn ?? null,
879 input.runningTurnId ?? null,
880 );
881 const activeVisualResponseTurnIds = deriveActiveVisualResponseTurnIds({
882 timelineEntries: input.timelineEntries,
883 unsettledTurnId,
884 isWorking: input.isWorking,
885 });
886 const foldsByAnchorEntryId = deriveTurnFolds({
887 timelineEntries: input.timelineEntries,
888 terminalAssistantMessageIds,
889 latestTurn: input.latestTurn ?? null,
890 unfoldedTurnIds: activeVisualResponseTurnIds,
891 });
892 const collapsedEntryIds = new Set<string>();
893 for (const fold of foldsByAnchorEntryId.values()) {
894 if (!input.expandedTurnIds?.has(fold.turnId)) {
895 for (const entryId of fold.hiddenEntryIds) {
896 collapsedEntryIds.add(entryId);
897 }
898 }
899 }
900​
901 let activeTurnHeaderIndex = input.timelineEntries.length;
902 if (input.isWorking) {
903 const latestUserMessageIndex = lastUserMessageIndex(input.timelineEntries);
904 activeTurnHeaderIndex = latestUserMessageIndex + 1;
905 }
906 const entryBelongsToActiveTurn = (entry: TimelineEntry, index: number) =>
907 input.isWorking &&
908 index >= activeTurnHeaderIndex &&
909 (unsettledTurnId === null || timelineEntryTurnId(entry) === unsettledTurnId);
910 const workEntryIsInActiveRun = (entry: WorkLogEntry) =>
911 input.isWorking &&
912 unsettledTurnId !== null &&
913 entry.toolLifecycleStatus === "inProgress" &&
914 entry.turnId === unsettledTurnId;
915 const activeToolEntries: Array<Extract<TimelineEntry, { kind: "work" }>> = [];
916 for (let index = input.timelineEntries.length - 1; index >= activeTurnHeaderIndex; index -= 1) {
917 const entry = input.timelineEntries[index]!;
918 if (
919 !entryBelongsToActiveTurn(entry, index) ||
920 entry.kind !== "work" ||
921 entry.entry.agentSpawn !== undefined ||
922 entry.entry.sourceActivityKind === "context-compaction" ||
923 entry.entry.tone === "error"
924 ) {
925 break;
926 }
927 activeToolEntries.unshift(entry);
928 }
929 const visibleActiveToolEntries = omitSupersededLifecycleMarkers(
930 activeToolEntries.filter((entry) => workEntryIsVisibleInGroup(entry.entry, true)),
931 (entry) => entry.entry,
932 );
933 const activeWorkAnchor = activeToolEntries[0];
934 const latestVisibleToolEntry = visibleActiveToolEntries.at(-1);
935 const latestRunningToolEntry = visibleActiveToolEntries.findLast((entry) =>
936 workEntryIsActiveTurnActivity(entry.entry),
937 );
938 const latestToolFailed =
939 latestRunningToolEntry === undefined &&
940 latestVisibleToolEntry !== undefined &&
941 latestVisibleToolEntry.entry.toolLifecycleStatus !== "declined" &&
942 workEntryDisplayIndicatesToolFailure(latestVisibleToolEntry.entry);
943 const latestToolKeepsActivityLive =
944 latestRunningToolEntry !== undefined ||
945 (latestVisibleToolEntry !== undefined &&
946 workEntryIndicatesToolSuccess(latestVisibleToolEntry.entry));
947 const activeWorkPlacementEntryId = latestVisibleToolEntry?.id;
948 const activeWorkRow =
949 activeWorkAnchor && latestVisibleToolEntry && !latestToolFailed
950 ? (() => {
951 const groupId = workGroupId(activeWorkAnchor.id, activeWorkAnchor.entry);
952 return {
953 kind: "work-live" as const,
954 id: latestToolKeepsActivityLive
955 ? LIVE_ACTIVITY_ROW_ID
956 : `work-live:${workGroupIdentity(activeWorkAnchor.id, activeWorkAnchor.entry)}`,
957 createdAt: activeWorkAnchor.createdAt,
958 entry: (latestRunningToolEntry ?? latestVisibleToolEntry).entry,
959 groupedEntries: visibleActiveToolEntries.map((entry) => entry.entry),
960 groupId,
961 expanded: input.expandedWorkGroupIds?.has(groupId) ?? false,
962 active: latestToolKeepsActivityLive,
963 };
964 })()
965 : null;
966 const activeWorkEntryIds = new Set(
967 activeWorkRow !== null || latestToolFailed ? activeToolEntries.map((entry) => entry.id) : [],
968 );
969 const appendWorkingRow = () => {
970 const latestUserMessage = input.timelineEntries[lastUserMessageIndex(input.timelineEntries)];
971 const visualResponseStartedAt =
972 activeVisualResponseTurnIds.size > 1 &&
973 latestUserMessage?.kind === "message" &&
974 latestUserMessage.message.role === "user"
975 ? latestUserMessage.message.createdAt
976 : input.activeTurnStartedAt;
977 nextRows.push({
978 kind: "working",
979 id: "working-indicator-row",
980 createdAt: visualResponseStartedAt,
981 });
982 };
983 let hasActivityRow = false;
984 const appendActiveWorkRows = () => {
985 if (activeWorkRow === null) return;
986 nextRows.push(activeWorkRow);
987 hasActivityRow ||= activeWorkRow.active;
988 if (!activeWorkRow.expanded) return;
989 nextRows.push(
990 expandedWorkGroupRow(
991 activeWorkRow.groupId,
992 activeWorkRow.createdAt,
993 activeWorkRow.groupedEntries,
994 ),
995 );
996 };
997​
998 for (let index = 0; index < input.timelineEntries.length; index += 1) {
999 const timelineEntry = input.timelineEntries[index];
1000 if (!timelineEntry) {
1001 continue;
1003​
1004 if (input.isWorking && index === activeTurnHeaderIndex) {
1005 appendWorkingRow();
1007​
1008 if (timelineEntry.id === activeWorkPlacementEntryId) {
1009 appendActiveWorkRows();
1011​
1012 const anchoredTurnFold = foldsByAnchorEntryId.get(timelineEntry.id);
1013 if (anchoredTurnFold) {
1014 nextRows.push({
1015 kind: "turn-fold",
1016 id: `turn-fold:${anchoredTurnFold.turnId}`,
1017 createdAt: anchoredTurnFold.createdAt,
1018 turnId: anchoredTurnFold.turnId,
1019 label: anchoredTurnFold.label,
1020 expanded: input.expandedTurnIds?.has(anchoredTurnFold.turnId) ?? false,
1021 });
1023​
1024 if (collapsedEntryIds.has(timelineEntry.id)) {
1025 continue;
1027​
1028 if (activeWorkEntryIds.has(timelineEntry.id)) {
1029 continue;
1031​
1032 if (
1033 timelineEntry.kind === "work" &&
1034 timelineEntry.entry.sourceActivityKind === "context-compaction"
1035 ) {
1036 nextRows.push({
1037 kind: "context-compaction",
1038 id: timelineEntry.id,
1039 createdAt: timelineEntry.createdAt,
1040 label: timelineEntry.entry.label,
1041 });
1042 continue;
1044​
1045 if (timelineEntry.kind === "work") {
1046 if (timelineEntry.entry.agentSpawn !== undefined || timelineEntry.entry.tone === "error") {
1047 nextRows.push({
1048 kind: "work",
1049 id: timelineEntry.id,
1050 createdAt: timelineEntry.createdAt,
1051 groupedEntries: [timelineEntry.entry],
1052 isExpandedToolGroup: false,
1053 });
1054 continue;
1056 const groupedEntries = [timelineEntry.entry];
1057 let cursor = index + 1;
1058 while (cursor < input.timelineEntries.length) {
1059 const nextEntry = input.timelineEntries[cursor];
1060 if (
1061 !nextEntry ||
1062 nextEntry.kind !== "work" ||
1063 nextEntry.entry.agentSpawn !== undefined ||
1064 nextEntry.entry.sourceActivityKind === "context-compaction" ||
1065 nextEntry.entry.tone === "error" ||
1066 activeWorkEntryIds.has(nextEntry.id) ||
1067 collapsedEntryIds.has(nextEntry.id) ||
1068 foldsByAnchorEntryId.has(nextEntry.id)
1069 ) {
1070 break;
1072 groupedEntries.push(nextEntry.entry);
1073 cursor += 1;
1075 const visibleGroupedEntries = omitSupersededLifecycleMarkers(
1076 groupedEntries.filter((entry) =>
1077 workEntryIsVisibleInGroup(entry, workEntryIsInActiveRun(entry)),
1078 ),
1079 (entry) => entry,
1080 );
1081 if (visibleGroupedEntries.length > 0) {
1082 const activeInProgressToolEntries = visibleGroupedEntries.filter(workEntryIsInActiveRun);
1083 if (activeInProgressToolEntries.length > 0) {
1084 const groupId = workGroupId(timelineEntry.id, timelineEntry.entry);
1085 const expanded = input.expandedWorkGroupIds?.has(groupId) ?? false;
1086 const latestActiveToolEntry = activeInProgressToolEntries.at(-1)!;
1087 nextRows.push({
1088 kind: "work-live",
1089 id: `work-live:${workGroupIdentity(timelineEntry.id, timelineEntry.entry)}`,
1090 createdAt: timelineEntry.createdAt,
1091 entry: latestActiveToolEntry,
1092 groupedEntries: visibleGroupedEntries,
1093 groupId,
1094 expanded,
1095 active: true,
1096 });
1097 hasActivityRow = true;
1098 if (expanded) {
1099 nextRows.push(
1100 expandedWorkGroupRow(groupId, timelineEntry.createdAt, visibleGroupedEntries),
1101 );
1103 } else if (
1104 visibleGroupedEntries.length === 1 &&
1105 workLogEntryIsToolLike(visibleGroupedEntries[0]!)
1106 ) {
1107 const singleEntry = visibleGroupedEntries[0]!;
1108 nextRows.push({
1109 kind: "work",
1110 id: timelineEntry.id,
1111 createdAt: timelineEntry.createdAt,
1112 groupedEntries: visibleGroupedEntries,
1113 isExpandedToolGroup: false,
1114 displayLabel:
1115 toolGroupAction(singleEntry) === "edit"
1116 ? summarizeToolGroup(visibleGroupedEntries)
1117 : singleToolCallLabel(singleEntry),
1118 });
1119 } else {
1120 const groupId = workGroupId(timelineEntry.id, timelineEntry.entry);
1121 const expanded = input.expandedWorkGroupIds?.has(groupId) ?? false;
1122 const summaryKind = toolGroupSummaryKind(visibleGroupedEntries);
1123 const primarySourceEntry = visibleGroupedEntries.find(
1124 (entry) => entry.toolSource !== undefined,
1125 );
1126 const primarySourceKey = primarySourceEntry?.toolSource?.key;
1127 const primarySourceIcon = primarySourceKey
1128 ? (visibleGroupedEntries.find(
1129 (entry) =>
1130 entry.toolSource?.key === primarySourceKey && entry.toolIcon !== undefined,
1131 )?.toolIcon ?? primarySourceEntry?.toolSource?.icon)
1132 : undefined;
1133 const groupToolSurface =
1134 primarySourceEntry?.toolSurface ??
1135 visibleGroupedEntries.findLast((entry) => entry.toolSurface !== undefined)?.toolSurface;
1136 const groupToolIcon =
1137 primarySourceIcon ??
1138 visibleGroupedEntries.findLast((entry) => entry.toolIcon !== undefined)?.toolIcon;
1139 const latestToolEntry = visibleGroupedEntries.findLast(workLogEntryIsToolLike);
1140 const singleEntry =
1141 visibleGroupedEntries.length === 1 ? (visibleGroupedEntries[0] ?? null) : null;
1142 const usesSingleToolCallLabel =
1143 singleEntry !== null &&
1144 workLogEntryIsToolLike(singleEntry) &&
1145 toolGroupAction(singleEntry) !== "edit";
1146 const summaryToolIcon = usesSingleToolCallLabel
1147 ? resolveWorkEntryToolPresentation(singleEntry, "completed")?.icon
1148 : undefined;
1149 nextRows.push({
1150 kind: "work-toggle",
1151 id: `work-toggle:${timelineEntry.id}`,
1152 createdAt: timelineEntry.createdAt,
1153 turnId: timelineEntry.entry.turnId ?? null,
1154 groupId,
1155 hiddenCount: visibleGroupedEntries.length,
1156 expanded,
1157 summary: usesSingleToolCallLabel
1158 ? singleToolCallLabel(singleEntry)
1159 : singleEntry !== null && !workLogEntryIsToolLike(singleEntry)
1160 ? singleEntry.label
1161 : summarizeToolGroup(visibleGroupedEntries),
1162 summaryKind,
1163 ...(groupToolSurface ? { toolSurface: groupToolSurface } : {}),
1164 ...(groupToolIcon ? { toolIcon: groupToolIcon } : {}),
1165 ...(summaryToolIcon ? { summaryToolIcon } : {}),
1166 hasFailure:
1167 latestToolEntry !== undefined &&
1168 workEntryDisplayIndicatesToolFailure(latestToolEntry),
1169 });
1170 if (expanded) {
1171 nextRows.push(
1172 expandedWorkGroupRow(groupId, timelineEntry.createdAt, visibleGroupedEntries),
1173 );
1177 index = cursor - 1;
1178 continue;
1180​
1181 if (timelineEntry.kind === "proposed-plan") {
1182 nextRows.push({
1183 kind: "proposed-plan",
1184 id: timelineEntry.id,
1185 createdAt: timelineEntry.createdAt,
1186 proposedPlan: timelineEntry.proposedPlan,
1187 });
1188 continue;
1190​
1191 const assistantResponseStillInProgress =
1192 timelineEntry.message.role === "assistant" &&
1193 timelineEntry.message.turnId !== null &&
1194 timelineEntry.message.turnId !== undefined &&
1195 activeVisualResponseTurnIds.has(timelineEntry.message.turnId);
1196​
1197 const durationStart =
1198 durationStartByMessageId.get(timelineEntry.message.id) ?? timelineEntry.message.createdAt;
1199​
1200 // While the turn is still running, the latest assistant message is only
1201 // provisionally terminal — withhold the metadata row until the turn
1202 // settles so commentary doesn't flash timestamps mid-work.
1203 const showAssistantMeta =
1204 timelineEntry.message.role === "assistant" &&
1205 terminalAssistantMessageIds.has(timelineEntry.message.id) &&
1206 !assistantResponseStillInProgress;
1207​
1208 nextRows.push({
1209 kind: "message",
1210 id: timelineEntry.id,
1211 createdAt: timelineEntry.createdAt,
1212 message: timelineEntry.message,
1213 durationStart,
1214 showAssistantMeta,
1215 showAssistantCopyButton: showAssistantMeta,
1216 assistantCopyStreaming: timelineEntry.message.streaming || assistantResponseStillInProgress,
1217 assistantTurnDiffSummary:
1218 timelineEntry.message.role === "assistant"
1219 ? turnDiffSummaryByAssistantMessageId.get(timelineEntry.message.id)
1220 : undefined,
1221 revertTurnCount:
1222 timelineEntry.message.role === "user"
1223 ? revertTurnCountByUserMessageId.get(timelineEntry.message.id)
1224 : undefined,
1225 });
1227​
1228 if (input.isWorking && activeTurnHeaderIndex === input.timelineEntries.length) {
1229 appendWorkingRow();
1231 if (input.isWorking && (!hasActivityRow || latestToolFailed)) {
1232 nextRows.push({
1233 kind: "thinking",
1234 id: LIVE_ACTIVITY_ROW_ID,
1235 createdAt: input.activeTurnStartedAt,
1236 });
1238​
1239 return attachTrailingToolGroupsToAssistant(nextRows);
1241​
1242type MessagesTimelineRowsInput = Parameters<typeof deriveMessagesTimelineRows>[0];
1243​
1244export interface MessagesTimelineRowsProjection {
1245 readonly input: MessagesTimelineRowsInput;
1246 readonly rows: MessagesTimelineRow[];
1248​
1249function replaceStreamingMessageRows(
1250 input: MessagesTimelineRowsInput,
1251 previous: MessagesTimelineRowsProjection,
1252): MessagesTimelineRow[] | null {
1253 const {
1254 timelineEntries: previousEntries,
1255 turnDiffSummaries: previousSummaries,
1256 latestTurn: previousLatestTurn,
1257 expandedTurnIds: previousExpandedTurns,
1258 expandedWorkGroupIds: previousExpandedGroups,
1259 ...previousContext
1260 } = previous.input;
1261 const {
1262 timelineEntries,
1263 turnDiffSummaries,
1264 latestTurn,
1265 expandedTurnIds,
1266 expandedWorkGroupIds,
1267 ...context
1268 } = input;
1269 if (
1270 timelineEntries.length !== previousEntries.length ||
1271 !shallow(previousContext, context) ||
1272 !shallow(previousSummaries, turnDiffSummaries) ||
1273 !shallow(previousLatestTurn, latestTurn) ||
1274 !shallow(previousExpandedTurns, expandedTurnIds) ||
1275 !shallow(previousExpandedGroups, expandedWorkGroupIds)
1276 ) {
1277 return null;
1279 const replacements = new Map<ChatMessage, ChatMessage>();
1280 for (const [index, entry] of timelineEntries.entries()) {
1281 const previousEntry = previousEntries[index]!;
1282 if (entry === previousEntry) continue;
1283 if (
1284 entry.kind !== "message" ||
1285 previousEntry.kind !== "message" ||
1286 entry.id !== previousEntry.id ||
1287 entry.createdAt !== previousEntry.createdAt
1288 ) {
1289 return null;
1291 if (entry.message === previousEntry.message) continue;
1292 if (!isStreamingMessageTextUpdate(previousEntry.message, entry.message)) return null;
1293 replacements.set(previousEntry.message, entry.message);
1295 if (replacements.size === 0) return previous.rows;
1296 return previous.rows.map((row) => {
1297 if (row.kind !== "message" && row.kind !== "assistant-meta") return row;
1298 const message = replacements.get(row.message);
1299 return message ? { ...row, message } : row;
1300 });
1302​
1303/** Keep one projection per timeline. Reuse rows only when streaming content changes. */
1304export function deriveMessagesTimelineRowsWithState(
1305 input: MessagesTimelineRowsInput,
1306 previous: MessagesTimelineRowsProjection | null = null,
1307): MessagesTimelineRowsProjection {
1308 return {
1309 input,
1310 rows:
1311 (previous === null ? null : replaceStreamingMessageRows(input, previous)) ??
1312 deriveMessagesTimelineRows(input),
1313 };
1315​
1316export function computeStableMessagesTimelineRows(
1317 rows: MessagesTimelineRow[],
1318 previous: StableMessagesTimelineRowsState,
1319): StableMessagesTimelineRowsState {
1320 const next = new Map<string, MessagesTimelineRow>();
1321 let anyChanged = rows.length !== previous.byId.size;
1322​
1323 const result = rows.map((row, index) => {
1324 const prevRow = previous.byId.get(row.id);
1325 const nextRow = prevRow && isRowUnchanged(prevRow, row) ? prevRow : row;
1326 next.set(row.id, nextRow);
1327 if (!anyChanged && previous.result[index] !== nextRow) {
1328 anyChanged = true;
1330 return nextRow;
1331 });
1332​
1333 return anyChanged ? { byId: next, result } : previous;
1335​
1336/** Shallow field comparison per row variant — avoids deep equality cost. */
1337function isRowUnchanged(a: MessagesTimelineRow, b: MessagesTimelineRow): boolean {
1338 if (a.kind !== b.kind || a.id !== b.id) return false;
1339​
1340 switch (a.kind) {
1341 case "working":
1342 case "thinking":
1343 return a.createdAt === (b as typeof a).createdAt;
1344​
1345 case "assistant-meta": {
1346 const bm = b as typeof a;
1347 return (
1348 a.createdAt === bm.createdAt &&
1349 a.message === bm.message &&
1350 a.showAssistantCopyButton === bm.showAssistantCopyButton &&
1351 a.assistantCopyStreaming === bm.assistantCopyStreaming
1352 );
1354​
1355 case "turn-fold": {
1356 const bf = b as typeof a;
1357 return a.createdAt === bf.createdAt && a.label === bf.label && a.expanded === bf.expanded;
1359​
1360 case "context-compaction": {
1361 const bc = b as typeof a;
1362 return a.createdAt === bc.createdAt && a.label === bc.label;
1364​
1365 case "proposed-plan":
1366 return a.proposedPlan === (b as typeof a).proposedPlan;
1367​
1368 case "work": {
1369 const bw = b as typeof a;
1370 return (
1371 a.isExpandedToolGroup === bw.isExpandedToolGroup &&
1372 a.displayLabel === bw.displayLabel &&
1373 Equal.equals(a.groupedEntries, bw.groupedEntries)
1374 );
1376​
1377 case "work-live": {
1378 const bw = b as typeof a;
1379 return (
1380 a.createdAt === bw.createdAt &&
1381 a.groupId === bw.groupId &&
1382 a.expanded === bw.expanded &&
1383 a.active === bw.active &&
1384 Equal.equals(a.entry, bw.entry) &&
1385 Equal.equals(a.groupedEntries, bw.groupedEntries)
1386 );
1388​
1389 case "work-toggle": {
1390 const bw = b as typeof a;
1391 return (
1392 a.createdAt === bw.createdAt &&
1393 a.turnId === bw.turnId &&
1394 a.groupId === bw.groupId &&
1395 a.hiddenCount === bw.hiddenCount &&
1396 a.expanded === bw.expanded &&
1397 a.summary === bw.summary &&
1398 a.summaryKind === bw.summaryKind &&
1399 a.toolSurface === bw.toolSurface &&
1400 Equal.equals(a.toolIcon, bw.toolIcon) &&
1401 a.hasFailure === bw.hasFailure
1402 );
1404​
1405 case "message": {
1406 const bm = b as typeof a;
1407 return (
1408 a.message === bm.message &&
1409 a.durationStart === bm.durationStart &&
1410 a.showAssistantMeta === bm.showAssistantMeta &&
1411 a.showAssistantCopyButton === bm.showAssistantCopyButton &&
1412 a.assistantCopyStreaming === bm.assistantCopyStreaming &&
1413 a.assistantTurnDiffSummary === bm.assistantTurnDiffSummary &&
1414 a.revertTurnCount === bm.revertTurnCount
1415 );