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