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

MessagesTimeline.logic.ts

1,034 lines34.6 KB

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