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