Open History to see the last commit
1import * as Equal from "effect/Equal";
2import {
3 formatDuration,
4 workEntryDisplayIndicatesToolFailure,
5 workEntryIndicatesToolNeutralStatus,
6 workLogEntryIsToolLike,
7 type TimelineEntry,
8 type TurnPlanEntry,
9 type WorkLogEntry,
10} from "../../session-logic";
11import { type ChatMessage, type ProposedPlan, type TurnDiffSummary } from "../../types";
12import { type MessageId, type OrchestrationLatestTurn, type TurnId } from "@t3tools/contracts";
13
14export const TIMELINE_MINIMAP_ITEM_SPACING = 8;
15export const TIMELINE_MINIMAP_MIN_ITEMS = 2;
16export const TIMELINE_MINIMAP_MAX_HEIGHT_CSS = "calc(100vh - 18rem)";
17export const TIMELINE_CONTENT_MAX_WIDTH = 768;
18export const TIMELINE_MINIMAP_PERSISTENT_GUTTER = 48;
19
20export function workEntryIsVisibleInGroup(
21 entry: WorkLogEntry,
22 expandedToolGroupEntry = false,
23): boolean {
24 return (
25 (expandedToolGroupEntry &&
26 (entry.toolLifecycleStatus === "inProgress" ||
27 entry.sourceActivityKind === "task.progress")) ||
28 !workEntryIndicatesToolNeutralStatus(entry)
29 );
30}
31
32export interface TimelineEndState {
33 readonly isAtEnd?: boolean;
34 readonly contentLength?: number;
35 readonly scroll?: number;
36 readonly scrollLength?: number;
37}
38
39/**
40 * Follow re-arm band above the hard bottom. Strict on purpose: LegendList's
41 * isNearEnd fires within half a viewport, which re-armed live-follow while the
42 * user was reading history and yanked them back down on the next stream chunk.
43 * A small pixel band (instead of the 1px isAtEnd epsilon alone) keeps re-arming
44 * reliable while streaming content is still growing under the viewport.
45 */
46export const TIMELINE_FOLLOW_REARM_THRESHOLD_PX = 40;
47
48export function resolveTimelineIsAtEnd(
49 state: TimelineEndState | undefined,
50 endInset = 0,
51): boolean | undefined {
52 if (!state) {
53 return undefined;
54 }
55 if (state.isAtEnd) {
56 return true;
57 }
58 const { contentLength, scroll, scrollLength } = state;
59 if (contentLength === undefined || scroll === undefined || scrollLength === undefined) {
60 return state.isAtEnd;
61 }
62 // contentLength includes the end inset (composer overlay), so subtract it to
63 // measure the distance to the real content bottom.
64 return contentLength - scroll - scrollLength - endInset <= TIMELINE_FOLLOW_REARM_THRESHOLD_PX;
65}
66
67export function shouldPreserveAssistantLineBreaks(text: string): boolean {
68 return /^★ Insight(?:\s|─)/mu.test(text);
69}
70
71export function resolveTimelineMinimapHeightStyle(itemCount: number): string {
72 const naturalHeight = Math.max(1, (itemCount - 1) * TIMELINE_MINIMAP_ITEM_SPACING);
73 return `min(${naturalHeight}px, ${TIMELINE_MINIMAP_MAX_HEIGHT_CSS})`;
74}
75
76export function resolveTimelineMinimapTopPercent(index: number, itemCount: number): number {
77 if (itemCount <= 1) {
78 return 0;
79 }
80 return (Math.max(0, Math.min(index, itemCount - 1)) / (itemCount - 1)) * 100;
81}
82
83export function resolveTimelineMinimapIndexFromPointer(input: {
84 readonly itemCount: number;
85 readonly railTop: number;
86 readonly railHeight: number;
87 readonly pointerY: number;
88}): number | null {
89 if (input.itemCount <= 0 || input.railHeight <= 0) {
90 return null;
91 }
92 if (input.itemCount === 1) {
93 return 0;
94 }
95
96 const progress = Math.max(0, Math.min(1, (input.pointerY - input.railTop) / input.railHeight));
97 return Math.max(0, Math.min(input.itemCount - 1, Math.round(progress * (input.itemCount - 1))));
98}
99
100export function resolveTimelineMinimapHasPersistentGutter(viewportWidth: number): boolean {
101 if (!Number.isFinite(viewportWidth) || viewportWidth <= 0) {
102 return false;
103 }
104
105 const contentWidth = Math.min(viewportWidth, TIMELINE_CONTENT_MAX_WIDTH);
106 const sideGutter = Math.max(0, (viewportWidth - contentWidth) / 2);
107 return sideGutter >= TIMELINE_MINIMAP_PERSISTENT_GUTTER;
108}
109
110export const TIMELINE_MINIMAP_HIT_STRIP_LEFT = 12;
111export const TIMELINE_MINIMAP_HIT_STRIP_MAX_WIDTH = 40;
112export const TIMELINE_MINIMAP_EXPANDED_HIT_STRIP_WIDTH = "22rem";
113
114/**
115 * The minimap overlays the viewport's left edge while the content column is
116 * centered, so the side gutter between them shrinks under browser zoom or a
117 * narrow pane. A fixed-width hover strip would then sit on top of the message
118 * text and swallow its pointer events. Cap the strip's width so it never
119 * extends past the gutter into the content column; 0 disables the strip.
120 */
121export function resolveTimelineMinimapHitStripWidth(viewportWidth: number): number {
122 if (!Number.isFinite(viewportWidth) || viewportWidth <= 0) {
123 return 0;
124 }
125
126 const contentWidth = Math.min(viewportWidth, TIMELINE_CONTENT_MAX_WIDTH);
127 const sideGutter = Math.max(0, (viewportWidth - contentWidth) / 2);
128 return Math.max(
129 0,
130 Math.min(
131 TIMELINE_MINIMAP_HIT_STRIP_MAX_WIDTH,
132 Math.floor(sideGutter) - TIMELINE_MINIMAP_HIT_STRIP_LEFT,
133 ),
134 );
135}
136
137/**
138 * Once the preview is open, keep the full preview and the space leading to it
139 * interactive. The collapsed strip remains gutter-capped so it cannot block
140 * selecting message text.
141 */
142export function resolveTimelineMinimapInteractiveWidth(
143 collapsedWidth: number,
144 expanded: boolean,
145): number | string {
146 return expanded ? TIMELINE_MINIMAP_EXPANDED_HIT_STRIP_WIDTH : collapsedWidth;
147}
148
149function computeElapsedMs(startIso: string, endIso: string): number | null {
150 const start = Date.parse(startIso);
151 const end = Date.parse(endIso);
152 if (!Number.isFinite(start) || !Number.isFinite(end)) return null;
153 return Math.max(0, end - start);
154}
155
156function maxIsoTimestamp(a: string | null, b: string | null): string | null {
157 if (a === null) return b;
158 if (b === null) return a;
159 const aMs = Date.parse(a);
160 const bMs = Date.parse(b);
161 if (!Number.isFinite(aMs)) return b;
162 if (!Number.isFinite(bMs)) return a;
163 return bMs > aMs ? b : a;
164}
165
166export interface TimelineDurationMessage {
167 id: string;
168 role: "user" | "assistant" | "system";
169 createdAt: string;
170 updatedAt: string;
171 streaming: boolean;
172}
173
174export type TimelineLatestTurn = Pick<
175 OrchestrationLatestTurn,
176 "turnId" | "state" | "startedAt" | "completedAt"
177>;
178
179export type MessagesTimelineRow =
180 | {
181 kind: "work";
182 id: string;
183 createdAt: string;
184 groupedEntries: WorkLogEntry[];
185 isExpandedToolGroupEntry: boolean;
186 isLastExpandedToolGroupEntry: boolean;
187 }
188 | {
189 kind: "work-live";
190 id: string;
191 createdAt: string;
192 entry: WorkLogEntry;
193 groupedEntries: WorkLogEntry[];
194 groupId: string;
195 expanded: boolean;
196 }
197 | {
198 kind: "work-toggle";
199 id: string;
200 createdAt: string;
201 groupId: string;
202 hiddenCount: number;
203 expanded: boolean;
204 summary: string;
205 summaryKind: ToolGroupSummaryKind;
206 hasFailure: boolean;
207 }
208 | {
209 kind: "turn-fold";
210 id: string;
211 createdAt: string;
212 turnId: TurnId;
213 label: string;
214 expanded: boolean;
215 }
216 | {
217 kind: "message";
218 id: string;
219 createdAt: string;
220 message: ChatMessage;
221 durationStart: string;
222 showAssistantMeta: boolean;
223 showAssistantCopyButton: boolean;
224 assistantCopyStreaming: boolean;
225 assistantTurnDiffSummary?: TurnDiffSummary | undefined;
226 revertTurnCount?: number | undefined;
227 }
228 | {
229 kind: "proposed-plan";
230 id: string;
231 createdAt: string;
232 proposedPlan: ProposedPlan;
233 }
234 | {
235 kind: "turn-plan";
236 id: string;
237 createdAt: string;
238 turnPlan: TurnPlanEntry;
239 };
240
241export interface StableMessagesTimelineRowsState {
242 byId: Map<string, MessagesTimelineRow>;
243 result: MessagesTimelineRow[];
244}
245
246export function computeMessageDurationStart(
247 messages: ReadonlyArray<TimelineDurationMessage>,
248): Map<string, string> {
249 const result = new Map<string, string>();
250 let lastBoundary: string | null = null;
251
252 for (const message of messages) {
253 if (message.role === "user") {
254 lastBoundary = message.createdAt;
255 }
256 result.set(message.id, lastBoundary ?? message.createdAt);
257 if (message.role === "assistant" && !message.streaming) {
258 lastBoundary = message.updatedAt;
259 }
260 }
261
262 return result;
263}
264
265export function normalizeCompactToolLabel(value: string): string {
266 return value.replace(/\s+(?:complete|completed)\s*$/i, "").trim();
267}
268
269type ToolGroupAction = "read" | "edit" | "command" | "code-search" | "search" | "other" | "update";
270type ToolGroupSummaryKind = ToolGroupAction | "dynamic-tool" | "agent-tool" | "tone-tool" | "mixed";
271
272export function workLogEntryIsLocalCodeSearch(entry: WorkLogEntry): boolean {
273 return (
274 entry.itemType === "web_search" &&
275 /\bgrep\b/i.test(normalizeCompactToolLabel(entry.toolTitle ?? entry.label))
276 );
277}
278
279export function toolGroupAction(entry: WorkLogEntry): ToolGroupAction {
280 if (
281 entry.requestKind === "file-read" ||
282 entry.itemType === "image_view" ||
283 (entry.itemType === "dynamic_tool_call" && entry.toolTitle === "Read File")
284 ) {
285 return "read";
286 }
287 if (
288 entry.requestKind === "file-change" ||
289 entry.itemType === "file_change" ||
290 (entry.changedFiles?.length ?? 0) > 0
291 ) {
292 return "edit";
293 }
294 if (entry.requestKind === "command" || entry.itemType === "command_execution" || entry.command) {
295 return "command";
296 }
297 if (workLogEntryIsLocalCodeSearch(entry)) return "code-search";
298 if (entry.itemType === "web_search") return "search";
299 return workLogEntryIsToolLike(entry) ? "other" : "update";
300}
301
302function toolGroupActionCount(
303 action: ToolGroupAction,
304 entries: ReadonlyArray<WorkLogEntry>,
305): number {
306 if (action !== "edit") return entries.length;
307
308 const changedFiles = new Set<string>();
309 let editsWithoutFileDetails = 0;
310 for (const entry of entries) {
311 if (!entry.changedFiles || entry.changedFiles.length === 0) {
312 editsWithoutFileDetails += 1;
313 continue;
314 }
315 for (const file of entry.changedFiles) changedFiles.add(file);
316 }
317 return changedFiles.size + editsWithoutFileDetails;
318}
319
320function toolGroupActionLabel(action: ToolGroupAction, count: number): string {
321 switch (action) {
322 case "read":
323 return `Read ${count} ${count === 1 ? "file" : "files"}`;
324 case "edit":
325 return `Changed ${count} ${count === 1 ? "file" : "files"}`;
326 case "command":
327 return `Ran ${count} ${count === 1 ? "command" : "commands"}`;
328 case "search":
329 return `Searched the web ${count} ${count === 1 ? "time" : "times"}`;
330 case "code-search":
331 return `Searched code ${count} ${count === 1 ? "time" : "times"}`;
332 case "other":
333 return `Used ${count} ${count === 1 ? "tool" : "tools"}`;
334 case "update":
335 return `Received ${count} ${count === 1 ? "update" : "updates"}`;
336 }
337}
338
339/** Immediate, provider-neutral fallback while generated tool summaries are disabled or unavailable. */
340export function summarizeToolGroup(entries: ReadonlyArray<WorkLogEntry>): string {
341 const summaryEntries = omitSupersededLifecycleMarkers(entries, (entry) => entry);
342 const groupedEntries = new Map<ToolGroupAction, WorkLogEntry[]>();
343 for (const entry of summaryEntries) {
344 const action = toolGroupAction(entry);
345 const group = groupedEntries.get(action);
346 if (group) group.push(entry);
347 else groupedEntries.set(action, [entry]);
348 }
349 const labels = [...groupedEntries].map(([action, actionEntries]) =>
350 toolGroupActionLabel(action, toolGroupActionCount(action, actionEntries)),
351 );
352 const sentenceLabels = labels.map((label, index) =>
353 index === 0 ? label : label.charAt(0).toLowerCase() + label.slice(1),
354 );
355 if (sentenceLabels.length < 2) return sentenceLabels[0] ?? "";
356 if (sentenceLabels.length === 2) return sentenceLabels.join(" and ");
357 return `${sentenceLabels.slice(0, -1).join(", ")}, and ${sentenceLabels.at(-1)}`;
358}
359
360function omitSupersededLifecycleMarkers<T>(
361 entries: readonly T[],
362 workEntryFor: (entry: T) => WorkLogEntry,
363): T[] {
364 const laterTerminalIdentities = new Set<string>();
365 const reversedEntries: T[] = [];
366
367 for (let index = entries.length - 1; index >= 0; index -= 1) {
368 const entry = entries[index]!;
369 const workEntry = workEntryFor(entry);
370 const normalizedLabel = normalizeCompactToolLabel(workEntry.toolTitle ?? workEntry.label);
371 const identity = [
372 workEntry.turnId ?? "no-turn",
373 workEntry.itemType ?? "",
374 normalizedLabel,
375 ].join("\u001f");
376 const isStatuslessIdlessMarker =
377 workEntry.toolCallId === undefined &&
378 workEntry.toolLifecycleStatus === undefined &&
379 (workEntry.sourceActivityKind === "tool.started" ||
380 workEntry.sourceActivityKind === "tool.updated");
381 if (isStatuslessIdlessMarker && laterTerminalIdentities.has(identity)) continue;
382
383 reversedEntries.push(entry);
384 if (
385 workEntry.sourceActivityKind === "tool.completed" ||
386 (workEntry.toolLifecycleStatus !== undefined &&
387 workEntry.toolLifecycleStatus !== "inProgress")
388 ) {
389 laterTerminalIdentities.add(identity);
390 }
391 }
392
393 return reversedEntries.toReversed();
394}
395
396function toolGroupSummaryKind(entries: ReadonlyArray<WorkLogEntry>): ToolGroupSummaryKind {
397 const actions = new Set(entries.map(toolGroupAction));
398 if (actions.size !== 1) return "mixed";
399
400 const action = actions.values().next().value!;
401 if (action !== "other") return action;
402
403 const fallbackKinds = new Set(
404 entries.map((entry): ToolGroupSummaryKind => {
405 if (entry.itemType === "mcp_tool_call") return "other";
406 if (entry.itemType === "dynamic_tool_call") return "dynamic-tool";
407 if (entry.itemType === "collab_agent_tool_call" || entry.taskId) return "agent-tool";
408 if (entry.tone === "thinking") return "agent-tool";
409 if (entry.tone === "tool") return "tone-tool";
410 return "other";
411 }),
412 );
413 return fallbackKinds.size === 1 ? fallbackKinds.values().next().value! : "mixed";
414}
415
416function workGroupIdentity(timelineEntryId: string, entry: WorkLogEntry): string {
417 return entry.toolCallId
418 ? `tool:${entry.turnId ?? "no-turn"}:${entry.toolCallId}`
419 : timelineEntryId;
420}
421
422function workGroupId(timelineEntryId: string, entry: WorkLogEntry): string {
423 return `work-group:${workGroupIdentity(timelineEntryId, entry)}`;
424}
425
426export function resolveAssistantMessageCopyState({
427 text,
428 showCopyButton,
429 streaming,
430}: {
431 text: string | null;
432 showCopyButton: boolean;
433 streaming: boolean;
434}) {
435 const hasText = text !== null && text.trim().length > 0;
436 return {
437 text: hasText ? text : null,
438 visible: showCopyButton && hasText && !streaming,
439 };
440}
441
442function deriveTerminalAssistantMessageIds(timelineEntries: ReadonlyArray<TimelineEntry>) {
443 const lastAssistantMessageIdByResponseKey = new Map<string, string>();
444 let nullTurnResponseIndex = 0;
445
446 for (const timelineEntry of timelineEntries) {
447 if (timelineEntry.kind !== "message") {
448 continue;
449 }
450 const { message } = timelineEntry;
451 if (message.role === "user") {
452 nullTurnResponseIndex += 1;
453 continue;
454 }
455 if (message.role !== "assistant") {
456 continue;
457 }
458
459 const responseKey = message.turnId
460 ? `turn:${message.turnId}`
461 : `unkeyed:${nullTurnResponseIndex}`;
462 lastAssistantMessageIdByResponseKey.set(responseKey, message.id);
463 }
464
465 return new Set(lastAssistantMessageIdByResponseKey.values());
466}
467
468interface TurnFold {
469 turnId: TurnId;
470 anchorEntryId: string;
471 createdAt: string;
472 hiddenEntryIds: ReadonlySet<string>;
473 label: string;
474}
475
476/**
477 * The session's running turn is authoritative when latestTurn briefly lags or
478 * regresses behind it. Otherwise, the latest turn counts as unsettled while it
479 * is still running (or has not recorded a completion). This is deliberately
480 * keyed on turn lifecycle rather than transient working state: right after the
481 * user sends a message, the previous turn is still the "active" one until the
482 * server creates the new turn, and folding must not flicker through that window.
483 */
484function deriveUnsettledTurnId(
485 latestTurn: TimelineLatestTurn | null,
486 runningTurnId: TurnId | null,
487): TurnId | null {
488 if (runningTurnId !== null) {
489 return runningTurnId;
490 }
491 if (!latestTurn) {
492 return null;
493 }
494 const isSettled = latestTurn.completedAt !== null && latestTurn.state !== "running";
495 return isSettled ? null : latestTurn.turnId;
496}
497
498function lastUserMessageIndex(timelineEntries: ReadonlyArray<TimelineEntry>): number {
499 return timelineEntries.findLastIndex(
500 (entry) => entry.kind === "message" && entry.message.role === "user",
501 );
502}
503
504function timelineEntryTurnId(entry: TimelineEntry): TurnId | null {
505 if (entry.kind === "message") {
506 return entry.message.role === "assistant" ? (entry.message.turnId ?? null) : null;
507 }
508 if (entry.kind === "turn-plan") {
509 return entry.turnPlan.turnId;
510 }
511 if (entry.kind === "proposed-plan") {
512 return entry.proposedPlan.turnId;
513 }
514 return entry.kind === "work" ? (entry.entry.turnId ?? null) : null;
515}
516
517/**
518 * Settled turns keep their first and terminal assistant messages visible.
519 * Everything between them folds behind a "Worked for ..." row anchored at
520 * the first hidden entry. Keeping both ends prevents a short follow-up from
521 * hiding a substantive opening response while still bounding noisy turns.
522 */
523function deriveTurnFolds(input: {
524 timelineEntries: ReadonlyArray<TimelineEntry>;
525 terminalAssistantMessageIds: ReadonlySet<string>;
526 latestTurn: TimelineLatestTurn | null;
527 unsettledTurnId: TurnId | null;
528}): ReadonlyMap<string, TurnFold> {
529 interface TurnGroup {
530 entries: Array<TimelineEntry>;
531 terminalEntry: Extract<TimelineEntry, { kind: "message" }> | null;
532 hasStreamingMessage: boolean;
533 /**
534 * The user message that kicked the turn off. Entry timestamps alone
535 * undercount the duration (the first entry appears only once the
536 * provider starts producing output), and a turn cut short by a steer may
537 * hold a single instantaneous commentary message.
538 */
539 startBoundary: string | null;
540 }
541 const groupsByTurnId = new Map<TurnId, TurnGroup>();
542
543 let pendingUserBoundary: string | null = null;
544 for (const entry of input.timelineEntries) {
545 if (entry.kind === "message" && entry.message.role === "user") {
546 pendingUserBoundary = entry.message.createdAt;
547 continue;
548 }
549 const turnId =
550 entry.kind === "message" && entry.message.role === "assistant"
551 ? (entry.message.turnId ?? null)
552 : entry.kind === "work"
553 ? (entry.entry.turnId ?? null)
554 : null;
555 if (!turnId) {
556 continue;
557 }
558 let group = groupsByTurnId.get(turnId);
559 if (!group) {
560 group = {
561 entries: [],
562 terminalEntry: null,
563 hasStreamingMessage: false,
564 // Each user boundary starts at most one turn; a second turn after the
565 // same user message (e.g. a steer-superseded continuation) falls back
566 // to its own first entry.
567 startBoundary: pendingUserBoundary,
568 };
569 pendingUserBoundary = null;
570 groupsByTurnId.set(turnId, group);
571 }
572 group.entries.push(entry);
573 if (entry.kind === "message") {
574 if (input.terminalAssistantMessageIds.has(entry.message.id)) {
575 group.terminalEntry = entry;
576 }
577 if (entry.message.streaming) {
578 group.hasStreamingMessage = true;
579 }
580 }
581 }
582
583 const foldsByAnchorEntryId = new Map<string, TurnFold>();
584 for (const [turnId, group] of groupsByTurnId) {
585 if (turnId === input.unsettledTurnId) {
586 continue;
587 }
588 if (group.hasStreamingMessage) {
589 continue;
590 }
591 const firstAssistantEntry = group.entries.find(
592 (entry): entry is Extract<TimelineEntry, { kind: "message" }> => entry.kind === "message",
593 );
594 const hiddenEntryIds = new Set<string>();
595 for (const entry of group.entries) {
596 if (entry.id === firstAssistantEntry?.id || entry.id === group.terminalEntry?.id) {
597 continue;
598 }
599 // Agent-spawn CTA rows never fold: workflows outlive their launching
600 // turn (dynamic spawns, background execution), and folding the CTA
601 // when the turn settles makes a still-running fleet invisible.
602 if (entry.kind === "work" && entry.entry.agentSpawn !== undefined) {
603 continue;
604 }
605 hiddenEntryIds.add(entry.id);
606 }
607 if (hiddenEntryIds.size === 0) {
608 continue;
609 }
610
611 const firstEntry = group.entries[0];
612 const firstHiddenEntry = group.entries.find((entry) => hiddenEntryIds.has(entry.id));
613 const lastEntry = group.entries.at(-1);
614 if (!firstEntry || !firstHiddenEntry || !lastEntry) {
615 continue;
616 }
617
618 const isLatestInterruptedTurn =
619 input.latestTurn?.turnId === turnId && input.latestTurn.state === "interrupted";
620 // A turn cut short by a steer leaves trailing work entries behind its
621 // terminal message — take whichever ended last.
622 const lastEntryEnd =
623 lastEntry.kind === "message" ? lastEntry.message.updatedAt : lastEntry.createdAt;
624 const elapsedMs =
625 input.latestTurn?.turnId === turnId &&
626 input.latestTurn.startedAt &&
627 input.latestTurn.completedAt
628 ? computeElapsedMs(input.latestTurn.startedAt, input.latestTurn.completedAt)
629 : computeElapsedMs(
630 group.startBoundary ?? firstEntry.createdAt,
631 maxIsoTimestamp(group.terminalEntry?.message.updatedAt ?? null, lastEntryEnd) ??
632 lastEntryEnd,
633 );
634 const duration = elapsedMs !== null ? formatDuration(elapsedMs) : null;
635 const label = isLatestInterruptedTurn
636 ? duration
637 ? `You stopped after ${duration}`
638 : "You stopped this response"
639 : duration
640 ? `Worked for ${duration}`
641 : "Worked";
642
643 foldsByAnchorEntryId.set(firstHiddenEntry.id, {
644 turnId,
645 anchorEntryId: firstHiddenEntry.id,
646 createdAt: firstHiddenEntry.createdAt,
647 hiddenEntryIds,
648 label,
649 });
650 }
651 return foldsByAnchorEntryId;
652}
653
654export function deriveMessagesTimelineRows(input: {
655 timelineEntries: ReadonlyArray<TimelineEntry>;
656 latestTurn?: TimelineLatestTurn | null;
657 runningTurnId?: TurnId | null;
658 expandedTurnIds?: ReadonlySet<TurnId>;
659 expandedWorkGroupIds?: ReadonlySet<string>;
660 isWorking: boolean;
661 turnDiffSummaryByAssistantMessageId: ReadonlyMap<MessageId, TurnDiffSummary>;
662 revertTurnCountByUserMessageId: ReadonlyMap<MessageId, number>;
663}): MessagesTimelineRow[] {
664 const nextRows: MessagesTimelineRow[] = [];
665 const durationStartByMessageId = computeMessageDurationStart(
666 input.timelineEntries.flatMap((entry) => (entry.kind === "message" ? [entry.message] : [])),
667 );
668 const terminalAssistantMessageIds = deriveTerminalAssistantMessageIds(input.timelineEntries);
669 const unsettledTurnId = deriveUnsettledTurnId(
670 input.latestTurn ?? null,
671 input.runningTurnId ?? null,
672 );
673 const foldsByAnchorEntryId = deriveTurnFolds({
674 timelineEntries: input.timelineEntries,
675 terminalAssistantMessageIds,
676 latestTurn: input.latestTurn ?? null,
677 unsettledTurnId,
678 });
679 const collapsedEntryIds = new Set<string>();
680 for (const fold of foldsByAnchorEntryId.values()) {
681 if (!input.expandedTurnIds?.has(fold.turnId)) {
682 for (const entryId of fold.hiddenEntryIds) {
683 collapsedEntryIds.add(entryId);
684 }
685 }
686 }
687
688 let activeTurnHeaderIndex = input.timelineEntries.length;
689 if (input.isWorking) {
690 const latestUserMessageIndex = lastUserMessageIndex(input.timelineEntries);
691 const firstOwnedAfterUser =
692 unsettledTurnId === null
693 ? -1
694 : input.timelineEntries.findIndex(
695 (entry, index) =>
696 index > latestUserMessageIndex && timelineEntryTurnId(entry) === unsettledTurnId,
697 );
698 activeTurnHeaderIndex =
699 firstOwnedAfterUser >= 0 ? firstOwnedAfterUser : latestUserMessageIndex + 1;
700 }
701 const entryBelongsToActiveTurn = (entry: TimelineEntry, index: number) =>
702 input.isWorking &&
703 index >= activeTurnHeaderIndex &&
704 (unsettledTurnId === null || timelineEntryTurnId(entry) === unsettledTurnId);
705 const workEntryIsInActiveRun = (entry: WorkLogEntry) =>
706 input.isWorking &&
707 unsettledTurnId !== null &&
708 entry.toolLifecycleStatus === "inProgress" &&
709 entry.turnId === unsettledTurnId;
710 const activeToolEntries: Array<Extract<TimelineEntry, { kind: "work" }>> = [];
711 for (let index = input.timelineEntries.length - 1; index >= activeTurnHeaderIndex; index -= 1) {
712 const entry = input.timelineEntries[index]!;
713 if (
714 !entryBelongsToActiveTurn(entry, index) ||
715 entry.kind !== "work" ||
716 entry.entry.agentSpawn !== undefined ||
717 entry.entry.tone === "error"
718 ) {
719 break;
720 }
721 activeToolEntries.unshift(entry);
722 }
723 const activeWorkEntryIds = new Set(activeToolEntries.map((entry) => entry.id));
724 const visibleActiveToolEntries = omitSupersededLifecycleMarkers(
725 activeToolEntries.filter((entry) => workEntryIsVisibleInGroup(entry.entry, true)),
726 (entry) => entry.entry,
727 );
728 const activeWorkAnchor = activeToolEntries[0];
729 const latestActiveToolEntry = visibleActiveToolEntries.at(-1);
730 const activeWorkPlacementEntryId = latestActiveToolEntry?.id;
731 const activeWorkRow =
732 activeWorkAnchor && latestActiveToolEntry
733 ? (() => {
734 const groupId = workGroupId(activeWorkAnchor.id, activeWorkAnchor.entry);
735 return {
736 kind: "work-live" as const,
737 id: `work-live:${workGroupIdentity(activeWorkAnchor.id, activeWorkAnchor.entry)}`,
738 createdAt: activeWorkAnchor.createdAt,
739 entry: latestActiveToolEntry.entry,
740 groupedEntries: visibleActiveToolEntries.map((entry) => entry.entry),
741 groupId,
742 expanded: input.expandedWorkGroupIds?.has(groupId) ?? false,
743 };
744 })()
745 : null;
746 const appendActiveWorkRows = () => {
747 if (activeWorkRow === null) return;
748 nextRows.push(activeWorkRow);
749 if (!activeWorkRow.expanded) return;
750 for (const [entryIndex, workEntry] of activeWorkRow.groupedEntries.entries()) {
751 nextRows.push({
752 kind: "work",
753 id: workEntry.id,
754 createdAt: workEntry.createdAt,
755 groupedEntries: [workEntry],
756 isExpandedToolGroupEntry: true,
757 isLastExpandedToolGroupEntry: entryIndex === activeWorkRow.groupedEntries.length - 1,
758 });
759 }
760 };
761
762 for (let index = 0; index < input.timelineEntries.length; index += 1) {
763 const timelineEntry = input.timelineEntries[index];
764 if (!timelineEntry) {
765 continue;
766 }
767
768 if (timelineEntry.id === activeWorkPlacementEntryId) {
769 appendActiveWorkRows();
770 }
771
772 const anchoredTurnFold = foldsByAnchorEntryId.get(timelineEntry.id);
773 if (anchoredTurnFold) {
774 nextRows.push({
775 kind: "turn-fold",
776 id: `turn-fold:${anchoredTurnFold.turnId}`,
777 createdAt: anchoredTurnFold.createdAt,
778 turnId: anchoredTurnFold.turnId,
779 label: anchoredTurnFold.label,
780 expanded: input.expandedTurnIds?.has(anchoredTurnFold.turnId) ?? false,
781 });
782 }
783
784 if (collapsedEntryIds.has(timelineEntry.id)) {
785 continue;
786 }
787
788 if (activeWorkEntryIds.has(timelineEntry.id)) {
789 continue;
790 }
791
792 if (timelineEntry.kind === "work") {
793 if (timelineEntry.entry.agentSpawn !== undefined || timelineEntry.entry.tone === "error") {
794 nextRows.push({
795 kind: "work",
796 id: timelineEntry.id,
797 createdAt: timelineEntry.createdAt,
798 groupedEntries: [timelineEntry.entry],
799 isExpandedToolGroupEntry: false,
800 isLastExpandedToolGroupEntry: false,
801 });
802 continue;
803 }
804 const groupedEntries = [timelineEntry.entry];
805 let cursor = index + 1;
806 while (cursor < input.timelineEntries.length) {
807 const nextEntry = input.timelineEntries[cursor];
808 if (
809 !nextEntry ||
810 nextEntry.kind !== "work" ||
811 nextEntry.entry.agentSpawn !== undefined ||
812 nextEntry.entry.tone === "error" ||
813 activeWorkEntryIds.has(nextEntry.id) ||
814 collapsedEntryIds.has(nextEntry.id) ||
815 foldsByAnchorEntryId.has(nextEntry.id)
816 ) {
817 break;
818 }
819 groupedEntries.push(nextEntry.entry);
820 cursor += 1;
821 }
822 const visibleGroupedEntries = omitSupersededLifecycleMarkers(
823 groupedEntries.filter((entry) =>
824 workEntryIsVisibleInGroup(entry, workEntryIsInActiveRun(entry)),
825 ),
826 (entry) => entry,
827 );
828 if (visibleGroupedEntries.length > 0) {
829 const activeInProgressToolEntries = visibleGroupedEntries.filter(workEntryIsInActiveRun);
830 if (activeInProgressToolEntries.length > 0) {
831 const groupId = workGroupId(timelineEntry.id, timelineEntry.entry);
832 const expanded = input.expandedWorkGroupIds?.has(groupId) ?? false;
833 const latestActiveToolEntry = activeInProgressToolEntries.at(-1)!;
834 nextRows.push({
835 kind: "work-live",
836 id: `work-live:${workGroupIdentity(timelineEntry.id, timelineEntry.entry)}`,
837 createdAt: timelineEntry.createdAt,
838 entry: latestActiveToolEntry,
839 groupedEntries: visibleGroupedEntries,
840 groupId,
841 expanded,
842 });
843 if (expanded) {
844 for (const [entryIndex, workEntry] of visibleGroupedEntries.entries()) {
845 nextRows.push({
846 kind: "work",
847 id: workEntry.id,
848 createdAt: workEntry.createdAt,
849 groupedEntries: [workEntry],
850 isExpandedToolGroupEntry: true,
851 isLastExpandedToolGroupEntry: entryIndex === visibleGroupedEntries.length - 1,
852 });
853 }
854 }
855 } else {
856 const groupId = workGroupId(timelineEntry.id, timelineEntry.entry);
857 const expanded = input.expandedWorkGroupIds?.has(groupId) ?? false;
858 const summaryKind = toolGroupSummaryKind(visibleGroupedEntries);
859 const latestToolEntry = visibleGroupedEntries.findLast(workLogEntryIsToolLike);
860 nextRows.push({
861 kind: "work-toggle",
862 id: `work-toggle:${timelineEntry.id}`,
863 createdAt: timelineEntry.createdAt,
864 groupId,
865 hiddenCount: visibleGroupedEntries.length,
866 expanded,
867 summary:
868 visibleGroupedEntries.length === 1 &&
869 !workLogEntryIsToolLike(visibleGroupedEntries[0]!)
870 ? visibleGroupedEntries[0]!.label
871 : summarizeToolGroup(visibleGroupedEntries),
872 summaryKind,
873 hasFailure:
874 latestToolEntry !== undefined &&
875 workEntryDisplayIndicatesToolFailure(latestToolEntry),
876 });
877 if (expanded) {
878 for (const [entryIndex, workEntry] of visibleGroupedEntries.entries()) {
879 nextRows.push({
880 kind: "work",
881 id: workEntry.id,
882 createdAt: workEntry.createdAt,
883 groupedEntries: [workEntry],
884 isExpandedToolGroupEntry: true,
885 isLastExpandedToolGroupEntry: entryIndex === visibleGroupedEntries.length - 1,
886 });
887 }
888 }
889 }
890 }
891 index = cursor - 1;
892 continue;
893 }
894
895 if (timelineEntry.kind === "proposed-plan") {
896 nextRows.push({
897 kind: "proposed-plan",
898 id: timelineEntry.id,
899 createdAt: timelineEntry.createdAt,
900 proposedPlan: timelineEntry.proposedPlan,
901 });
902 continue;
903 }
904
905 if (timelineEntry.kind === "turn-plan") {
906 nextRows.push({
907 kind: "turn-plan",
908 id: timelineEntry.id,
909 createdAt: timelineEntry.createdAt,
910 turnPlan: timelineEntry.turnPlan,
911 });
912 continue;
913 }
914
915 const assistantTurnStillInProgress =
916 timelineEntry.message.role === "assistant" &&
917 unsettledTurnId !== null &&
918 timelineEntry.message.turnId === unsettledTurnId;
919
920 const durationStart =
921 durationStartByMessageId.get(timelineEntry.message.id) ?? timelineEntry.message.createdAt;
922
923 // While the turn is still running, the latest assistant message is only
924 // provisionally terminal — withhold the metadata row until the turn
925 // settles so commentary doesn't flash timestamps mid-work.
926 const showAssistantMeta =
927 timelineEntry.message.role === "assistant" &&
928 terminalAssistantMessageIds.has(timelineEntry.message.id) &&
929 !assistantTurnStillInProgress;
930
931 nextRows.push({
932 kind: "message",
933 id: timelineEntry.id,
934 createdAt: timelineEntry.createdAt,
935 message: timelineEntry.message,
936 durationStart,
937 showAssistantMeta,
938 showAssistantCopyButton: showAssistantMeta,
939 assistantCopyStreaming: timelineEntry.message.streaming || assistantTurnStillInProgress,
940 assistantTurnDiffSummary:
941 timelineEntry.message.role === "assistant"
942 ? input.turnDiffSummaryByAssistantMessageId.get(timelineEntry.message.id)
943 : undefined,
944 revertTurnCount:
945 timelineEntry.message.role === "user"
946 ? input.revertTurnCountByUserMessageId.get(timelineEntry.message.id)
947 : undefined,
948 });
949 }
950
951 return nextRows;
952}
953
954export function computeStableMessagesTimelineRows(
955 rows: MessagesTimelineRow[],
956 previous: StableMessagesTimelineRowsState,
957): StableMessagesTimelineRowsState {
958 const next = new Map<string, MessagesTimelineRow>();
959 let anyChanged = rows.length !== previous.byId.size;
960
961 const result = rows.map((row, index) => {
962 const prevRow = previous.byId.get(row.id);
963 const nextRow = prevRow && isRowUnchanged(prevRow, row) ? prevRow : row;
964 next.set(row.id, nextRow);
965 if (!anyChanged && previous.result[index] !== nextRow) {
966 anyChanged = true;
967 }
968 return nextRow;
969 });
970
971 return anyChanged ? { byId: next, result } : previous;
972}
973
974/** Shallow field comparison per row variant — avoids deep equality cost. */
975function isRowUnchanged(a: MessagesTimelineRow, b: MessagesTimelineRow): boolean {
976 if (a.kind !== b.kind || a.id !== b.id) return false;
977
978 switch (a.kind) {
979 case "turn-fold": {
980 const bf = b as typeof a;
981 return a.createdAt === bf.createdAt && a.label === bf.label && a.expanded === bf.expanded;
982 }
983
984 case "proposed-plan":
985 return a.proposedPlan === (b as typeof a).proposedPlan;
986
987 case "turn-plan": {
988 const bp = b as typeof a;
989 // Plans rewrite in place: compare the snapshot's identity fields so an
990 // unchanged plan keeps its row reference (virtualization stability).
991 return a.createdAt === bp.createdAt && a.turnPlan.plan === bp.turnPlan.plan;
992 }
993
994 case "work": {
995 const bw = b as typeof a;
996 return (
997 a.isExpandedToolGroupEntry === bw.isExpandedToolGroupEntry &&
998 a.isLastExpandedToolGroupEntry === bw.isLastExpandedToolGroupEntry &&
999 Equal.equals(a.groupedEntries, bw.groupedEntries)
1000 );
1001 }
1002
1003 case "work-live": {
1004 const bw = b as typeof a;
1005 return (
1006 a.createdAt === bw.createdAt &&
1007 a.groupId === bw.groupId &&
1008 a.expanded === bw.expanded &&
1009 Equal.equals(a.entry, bw.entry) &&
1010 Equal.equals(a.groupedEntries, bw.groupedEntries)
1011 );
1012 }
1013
1014 case "work-toggle": {
1015 const bw = b as typeof a;
1016 return (
1017 a.createdAt === bw.createdAt &&
1018 a.groupId === bw.groupId &&
1019 a.hiddenCount === bw.hiddenCount &&
1020 a.expanded === bw.expanded &&
1021 a.summary === bw.summary &&
1022 a.summaryKind === bw.summaryKind &&
1023 a.hasFailure === bw.hasFailure
1024 );
1025 }
1026
1027 case "message": {
1028 const bm = b as typeof a;
1029 return (
1030 a.message === bm.message &&
1031 a.durationStart === bm.durationStart &&
1032 a.showAssistantMeta === bm.showAssistantMeta &&
1033 a.showAssistantCopyButton === bm.showAssistantCopyButton &&
1034 a.assistantCopyStreaming === bm.assistantCopyStreaming &&
1035 a.assistantTurnDiffSummary === bm.assistantTurnDiffSummary &&
1036 a.revertTurnCount === bm.revertTurnCount
1037 );
1038 }
1039 }
1040}