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

MessagesTimeline.logic.ts

1,135 lines38.9 KB

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 );
32​
33export interface TimelineEndState {
34 readonly isAtEnd?: boolean;
35 readonly contentLength?: number;
36 readonly scroll?: number;
37 readonly scrollLength?: number;
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;
67​
68export function shouldPreserveAssistantLineBreaks(text: string): boolean {
69 return /^★ Insight(?:\s|─)/mu.test(text);
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})`;
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;
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))));
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;
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 );
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;
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);
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;
166​
167export interface TimelineDurationMessage {
168 id: string;
169 role: "user" | "assistant" | "system";
170 createdAt: string;
171 updatedAt: string;
172 streaming: boolean;
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[];
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;
272​
273export function normalizeCompactToolLabel(value: string): string {
274 return value.replace(/\s+(?:complete|completed)\s*$/i, "").trim();
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 );
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";
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;
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 }
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)}`;
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();
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";
421​
422function workGroupIdentity(timelineEntryId: string, entry: WorkLogEntry): string {
423 return entry.toolCallId
424 ? `tool:${entry.turnId ?? "no-turn"}:${entry.toolCallId}`
425 : timelineEntryId;
427​
428function workGroupId(timelineEntryId: string, entry: WorkLogEntry): string {
429 return `work-group:${workGroupIdentity(timelineEntryId, entry)}`;
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 };
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());
473​
474interface TurnFold {
475 turnId: TurnId;
476 anchorEntryId: string;
477 createdAt: string;
478 hiddenEntryIds: ReadonlySet<string>;
479 label: string;
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;
503​
504function lastUserMessageIndex(timelineEntries: ReadonlyArray<TimelineEntry>): number {
505 return timelineEntries.findLastIndex(
506 (entry) => entry.kind === "message" && entry.message.role === "user",
507 );
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;
522​
523/**
524 * Settled turns keep their first and terminal assistant messages visible.
525 * Everything between them folds behind a "Worked for ..." row anchored at
526 * the first hidden entry. Keeping both ends prevents a short follow-up from
527 * hiding a substantive opening response while still bounding noisy turns.
528 */
529function deriveTurnFolds(input: {
530 timelineEntries: ReadonlyArray<TimelineEntry>;
531 terminalAssistantMessageIds: ReadonlySet<string>;
532 latestTurn: TimelineLatestTurn | null;
533 unsettledTurnId: TurnId | null;
534}): ReadonlyMap<string, TurnFold> {
535 interface TurnGroup {
536 entries: Array<TimelineEntry>;
537 terminalEntry: Extract<TimelineEntry, { kind: "message" }> | null;
538 hasStreamingMessage: boolean;
539 /**
540 * The user message that kicked the turn off. Entry timestamps alone
541 * undercount the duration (the first entry appears only once the
542 * provider starts producing output), and a turn cut short by a steer may
543 * hold a single instantaneous commentary message.
544 */
545 startBoundary: string | null;
546 }
547 const groupsByTurnId = new Map<TurnId, TurnGroup>();
548​
549 let pendingUserBoundary: string | null = null;
550 for (const entry of input.timelineEntries) {
551 if (entry.kind === "message" && entry.message.role === "user") {
552 pendingUserBoundary = entry.message.createdAt;
553 continue;
554 }
555 const turnId =
556 entry.kind === "message" && entry.message.role === "assistant"
557 ? (entry.message.turnId ?? null)
558 : entry.kind === "work"
559 ? (entry.entry.turnId ?? null)
560 : null;
561 if (!turnId) {
562 continue;
563 }
564 let group = groupsByTurnId.get(turnId);
565 if (!group) {
566 group = {
567 entries: [],
568 terminalEntry: null,
569 hasStreamingMessage: false,
570 // Each user boundary starts at most one turn; a second turn after the
571 // same user message (e.g. a steer-superseded continuation) falls back
572 // to its own first entry.
573 startBoundary: pendingUserBoundary,
574 };
575 pendingUserBoundary = null;
576 groupsByTurnId.set(turnId, group);
577 }
578 group.entries.push(entry);
579 if (entry.kind === "message") {
580 if (input.terminalAssistantMessageIds.has(entry.message.id)) {
581 group.terminalEntry = entry;
582 }
583 if (entry.message.streaming) {
584 group.hasStreamingMessage = true;
585 }
586 }
587 }
588​
589 const foldsByAnchorEntryId = new Map<string, TurnFold>();
590 for (const [turnId, group] of groupsByTurnId) {
591 if (turnId === input.unsettledTurnId) {
592 continue;
593 }
594 if (group.hasStreamingMessage) {
595 continue;
596 }
597 const firstAssistantEntry = group.entries.find(
598 (entry): entry is Extract<TimelineEntry, { kind: "message" }> => entry.kind === "message",
599 );
600 const hiddenEntryIds = new Set<string>();
601 for (const entry of group.entries) {
602 if (entry.id === firstAssistantEntry?.id || entry.id === group.terminalEntry?.id) {
603 continue;
604 }
605 // Agent-spawn CTA rows never fold: workflows outlive their launching
606 // turn (dynamic spawns, background execution), and folding the CTA
607 // when the turn settles makes a still-running fleet invisible.
608 if (entry.kind === "work" && entry.entry.agentSpawn !== undefined) {
609 continue;
610 }
611 hiddenEntryIds.add(entry.id);
612 }
613 if (hiddenEntryIds.size === 0) {
614 continue;
615 }
616​
617 const firstEntry = group.entries[0];
618 const firstHiddenEntry = group.entries.find((entry) => hiddenEntryIds.has(entry.id));
619 const lastEntry = group.entries.at(-1);
620 if (!firstEntry || !firstHiddenEntry || !lastEntry) {
621 continue;
622 }
623​
624 const isLatestInterruptedTurn =
625 input.latestTurn?.turnId === turnId && input.latestTurn.state === "interrupted";
626 // A turn cut short by a steer leaves trailing work entries behind its
627 // terminal message — take whichever ended last.
628 const lastEntryEnd =
629 lastEntry.kind === "message" ? lastEntry.message.updatedAt : lastEntry.createdAt;
630 const elapsedMs =
631 input.latestTurn?.turnId === turnId &&
632 input.latestTurn.startedAt &&
633 input.latestTurn.completedAt
634 ? computeElapsedMs(input.latestTurn.startedAt, input.latestTurn.completedAt)
635 : computeElapsedMs(
636 group.startBoundary ?? firstEntry.createdAt,
637 maxIsoTimestamp(group.terminalEntry?.message.updatedAt ?? null, lastEntryEnd) ??
638 lastEntryEnd,
639 );
640 const duration = elapsedMs !== null ? formatDuration(elapsedMs) : null;
641 const label = isLatestInterruptedTurn
642 ? duration
643 ? `You stopped after ${duration}`
644 : "You stopped this response"
645 : duration
646 ? `Worked for ${duration}`
647 : "Worked";
648​
649 foldsByAnchorEntryId.set(firstHiddenEntry.id, {
650 turnId,
651 anchorEntryId: firstHiddenEntry.id,
652 createdAt: firstHiddenEntry.createdAt,
653 hiddenEntryIds,
654 label,
655 });
656 }
657 return foldsByAnchorEntryId;
659​
660export function deriveMessagesTimelineRows(input: {
661 timelineEntries: ReadonlyArray<TimelineEntry>;
662 latestTurn?: TimelineLatestTurn | null;
663 runningTurnId?: TurnId | null;
664 expandedTurnIds?: ReadonlySet<TurnId>;
665 expandedWorkGroupIds?: ReadonlySet<string>;
666 isWorking: boolean;
667 activeTurnStartedAt: string | null;
668 turnDiffSummaryByAssistantMessageId: ReadonlyMap<MessageId, TurnDiffSummary>;
669 revertTurnCountByUserMessageId: ReadonlyMap<MessageId, number>;
670}): MessagesTimelineRow[] {
671 const nextRows: MessagesTimelineRow[] = [];
672 const durationStartByMessageId = computeMessageDurationStart(
673 input.timelineEntries.flatMap((entry) => (entry.kind === "message" ? [entry.message] : [])),
674 );
675 const terminalAssistantMessageIds = deriveTerminalAssistantMessageIds(input.timelineEntries);
676 const unsettledTurnId = deriveUnsettledTurnId(
677 input.latestTurn ?? null,
678 input.runningTurnId ?? null,
679 );
680 const foldsByAnchorEntryId = deriveTurnFolds({
681 timelineEntries: input.timelineEntries,
682 terminalAssistantMessageIds,
683 latestTurn: input.latestTurn ?? null,
684 unsettledTurnId,
685 });
686 const collapsedEntryIds = new Set<string>();
687 for (const fold of foldsByAnchorEntryId.values()) {
688 if (!input.expandedTurnIds?.has(fold.turnId)) {
689 for (const entryId of fold.hiddenEntryIds) {
690 collapsedEntryIds.add(entryId);
691 }
692 }
693 }
694​
695 let activeTurnHeaderIndex = input.timelineEntries.length;
696 if (input.isWorking) {
697 const latestUserMessageIndex = lastUserMessageIndex(input.timelineEntries);
698 const firstOwnedAfterUser =
699 unsettledTurnId === null
700 ? -1
701 : input.timelineEntries.findIndex(
702 (entry, index) =>
703 index > latestUserMessageIndex && timelineEntryTurnId(entry) === unsettledTurnId,
704 );
705 activeTurnHeaderIndex =
706 firstOwnedAfterUser >= 0 ? firstOwnedAfterUser : latestUserMessageIndex + 1;
707 }
708 const entryBelongsToActiveTurn = (entry: TimelineEntry, index: number) =>
709 input.isWorking &&
710 index >= activeTurnHeaderIndex &&
711 (unsettledTurnId === null || timelineEntryTurnId(entry) === unsettledTurnId);
712 const workEntryIsInActiveRun = (entry: WorkLogEntry) =>
713 input.isWorking &&
714 unsettledTurnId !== null &&
715 entry.toolLifecycleStatus === "inProgress" &&
716 entry.turnId === unsettledTurnId;
717 const isVisibleActiveToolEntry = (entry: WorkLogEntry) =>
718 workLogEntryIsToolLike(entry) && workEntryIsVisibleInGroup(entry, true);
719 const activeEntries = input.isWorking
720 ? input.timelineEntries.filter((entry, index) => entryBelongsToActiveTurn(entry, index))
721 : [];
722 const activeTurnHasVisibleContent = activeEntries.some((entry) => {
723 if (entry.kind === "message") {
724 return entry.message.role === "assistant" && (entry.message.text?.trim().length ?? 0) > 0;
725 }
726 if (entry.kind === "work") {
727 return (
728 entry.entry.agentSpawn === undefined &&
729 workLogEntryIsToolLike(entry.entry) &&
730 entry.entry.toolLifecycleStatus === "inProgress"
731 );
732 }
733 if (entry.kind === "proposed-plan" || entry.kind === "turn-plan") return true;
734 return false;
735 });
736​
737 const activeToolEntries: Array<Extract<TimelineEntry, { kind: "work" }>> = [];
738 for (let index = input.timelineEntries.length - 1; index >= activeTurnHeaderIndex; index -= 1) {
739 const entry = input.timelineEntries[index]!;
740 if (
741 !entryBelongsToActiveTurn(entry, index) ||
742 entry.kind !== "work" ||
743 entry.entry.agentSpawn !== undefined ||
744 entry.entry.tone === "error" ||
745 !workLogEntryIsToolLike(entry.entry)
746 ) {
747 break;
748 }
749 activeToolEntries.unshift(entry);
750 }
751 const activeWorkEntryIds = new Set(activeToolEntries.map((entry) => entry.id));
752 const visibleActiveToolEntries = omitSupersededLifecycleMarkers(
753 activeToolEntries.filter((entry) => isVisibleActiveToolEntry(entry.entry)),
754 (entry) => entry.entry,
755 );
756 const activeWorkAnchor = activeToolEntries[0];
757 const latestActiveToolEntry = visibleActiveToolEntries.at(-1);
758 const activeWorkPlacementEntryId = latestActiveToolEntry?.id;
759 const activeWorkRow =
760 activeWorkAnchor && latestActiveToolEntry
761 ? (() => {
762 const groupId = workGroupId(activeWorkAnchor.id, activeWorkAnchor.entry);
763 return {
764 kind: "work-live" as const,
765 id: `work-live:${workGroupIdentity(activeWorkAnchor.id, activeWorkAnchor.entry)}`,
766 createdAt: activeWorkAnchor.createdAt,
767 entry: latestActiveToolEntry.entry,
768 groupedEntries: visibleActiveToolEntries.map((entry) => entry.entry),
769 groupId,
770 expanded: input.expandedWorkGroupIds?.has(groupId) ?? false,
771 };
772 })()
773 : null;
774 const appendWorkingRow = () => {
775 nextRows.push({
776 kind: "working",
777 id: "working-indicator-row",
778 createdAt: input.activeTurnStartedAt,
779 showThinking: activeWorkRow === null && !activeTurnHasVisibleContent,
780 });
781 };
782 const appendActiveWorkRows = () => {
783 if (activeWorkRow === null) return;
784 nextRows.push(activeWorkRow);
785 if (!activeWorkRow.expanded) return;
786 for (const [entryIndex, workEntry] of activeWorkRow.groupedEntries.entries()) {
787 nextRows.push({
788 kind: "work",
789 id: workEntry.id,
790 createdAt: workEntry.createdAt,
791 groupedEntries: [workEntry],
792 isExpandedToolGroupEntry: true,
793 isLastExpandedToolGroupEntry: entryIndex === activeWorkRow.groupedEntries.length - 1,
794 });
795 }
796 };
797​
798 for (let index = 0; index < input.timelineEntries.length; index += 1) {
799 const timelineEntry = input.timelineEntries[index];
800 if (!timelineEntry) {
801 continue;
802 }
803​
804 if (input.isWorking && index === activeTurnHeaderIndex) {
805 appendWorkingRow();
806 }
807​
808 if (timelineEntry.id === activeWorkPlacementEntryId) {
809 appendActiveWorkRows();
810 }
811​
812 const anchoredTurnFold = foldsByAnchorEntryId.get(timelineEntry.id);
813 if (anchoredTurnFold) {
814 nextRows.push({
815 kind: "turn-fold",
816 id: `turn-fold:${anchoredTurnFold.turnId}`,
817 createdAt: anchoredTurnFold.createdAt,
818 turnId: anchoredTurnFold.turnId,
819 label: anchoredTurnFold.label,
820 expanded: input.expandedTurnIds?.has(anchoredTurnFold.turnId) ?? false,
821 });
822 }
823​
824 if (collapsedEntryIds.has(timelineEntry.id)) {
825 continue;
826 }
827​
828 if (activeWorkEntryIds.has(timelineEntry.id)) {
829 continue;
830 }
831​
832 if (timelineEntry.kind === "work") {
833 const groupedEntries = [timelineEntry.entry];
834 let cursor = index + 1;
835 while (cursor < input.timelineEntries.length) {
836 const nextEntry = input.timelineEntries[cursor];
837 if (
838 !nextEntry ||
839 nextEntry.kind !== "work" ||
840 activeWorkEntryIds.has(nextEntry.id) ||
841 collapsedEntryIds.has(nextEntry.id) ||
842 foldsByAnchorEntryId.has(nextEntry.id)
843 ) {
844 break;
845 }
846 groupedEntries.push(nextEntry.entry);
847 cursor += 1;
848 }
849 const visibleGroupedEntries = omitSupersededLifecycleMarkers(
850 groupedEntries.filter((entry) =>
851 workEntryIsVisibleInGroup(entry, workEntryIsInActiveRun(entry)),
852 ),
853 (entry) => entry,
854 );
855 if (visibleGroupedEntries.length > 0) {
856 const onlyToolEntries = visibleGroupedEntries.every(
857 (entry) =>
858 workLogEntryIsToolLike(entry) &&
859 entry.agentSpawn === undefined &&
860 entry.tone !== "error",
861 );
862 const activeInProgressToolEntries = visibleGroupedEntries.filter(workEntryIsInActiveRun);
863 if (onlyToolEntries && activeInProgressToolEntries.length > 0) {
864 const groupId = workGroupId(timelineEntry.id, timelineEntry.entry);
865 const expanded = input.expandedWorkGroupIds?.has(groupId) ?? false;
866 const latestActiveToolEntry = activeInProgressToolEntries.at(-1)!;
867 nextRows.push({
868 kind: "work-live",
869 id: `work-live:${workGroupIdentity(timelineEntry.id, timelineEntry.entry)}`,
870 createdAt: timelineEntry.createdAt,
871 entry: latestActiveToolEntry,
872 groupedEntries: visibleGroupedEntries,
873 groupId,
874 expanded,
875 });
876 if (expanded) {
877 for (const [entryIndex, workEntry] of visibleGroupedEntries.entries()) {
878 nextRows.push({
879 kind: "work",
880 id: workEntry.id,
881 createdAt: workEntry.createdAt,
882 groupedEntries: [workEntry],
883 isExpandedToolGroupEntry: true,
884 isLastExpandedToolGroupEntry: entryIndex === visibleGroupedEntries.length - 1,
885 });
886 }
887 }
888 } else if (onlyToolEntries) {
889 const groupId = workGroupId(timelineEntry.id, timelineEntry.entry);
890 const expanded = input.expandedWorkGroupIds?.has(groupId) ?? false;
891 const summaryKind = toolGroupSummaryKind(visibleGroupedEntries);
892 nextRows.push({
893 kind: "work-toggle",
894 id: `work-toggle:${timelineEntry.id}`,
895 createdAt: timelineEntry.createdAt,
896 groupId,
897 hiddenCount: visibleGroupedEntries.length,
898 expanded,
899 onlyToolEntries: true,
900 summary: summarizeToolGroup(visibleGroupedEntries),
901 summaryKind,
902 hasFailure: workEntryDisplayIndicatesToolFailure(visibleGroupedEntries.at(-1)!),
903 });
904 if (expanded) {
905 for (const [entryIndex, workEntry] of visibleGroupedEntries.entries()) {
906 nextRows.push({
907 kind: "work",
908 id: workEntry.id,
909 createdAt: workEntry.createdAt,
910 groupedEntries: [workEntry],
911 isExpandedToolGroupEntry: true,
912 isLastExpandedToolGroupEntry: entryIndex === visibleGroupedEntries.length - 1,
913 });
914 }
915 }
916 } else if (visibleGroupedEntries.length <= MAX_VISIBLE_WORK_LOG_ENTRIES) {
917 nextRows.push({
918 kind: "work",
919 id: timelineEntry.id,
920 createdAt: timelineEntry.createdAt,
921 groupedEntries: visibleGroupedEntries,
922 isExpandedToolGroupEntry: false,
923 isLastExpandedToolGroupEntry: false,
924 });
925 } else {
926 const groupId = workGroupId(timelineEntry.id, timelineEntry.entry);
927 const expanded = input.expandedWorkGroupIds?.has(groupId) ?? false;
928 // Agent-spawn CTA rows are always visible: a running fleet must
929 // never hide behind a "+N tool calls" toggle. Selection is by
930 // membership (spawn OR recent-tail), preserving the group's
931 // chronological order in both collapsed and expanded states
932 // (review finding: concatenating two filtered lists moved a
933 // mid-group spawn row above earlier tool rows).
934 const overflowCandidates = visibleGroupedEntries.filter(
935 (entry) => entry.agentSpawn === undefined,
936 );
937 const hiddenEntries = overflowCandidates.slice(0, -MAX_VISIBLE_WORK_LOG_ENTRIES);
938 const hiddenIds = new Set(hiddenEntries.map((entry) => entry.id));
939 const visibleEntries = visibleGroupedEntries.filter(
940 (entry) => entry.agentSpawn !== undefined || !hiddenIds.has(entry.id),
941 );
942 const renderedEntries = expanded ? visibleGroupedEntries : visibleEntries;
943​
944 for (const workEntry of renderedEntries) {
945 nextRows.push({
946 kind: "work",
947 id: workEntry.id,
948 createdAt: workEntry.createdAt,
949 groupedEntries: [workEntry],
950 isExpandedToolGroupEntry: false,
951 isLastExpandedToolGroupEntry: false,
952 });
953 }
954​
955 if (hiddenEntries.length > 0) {
956 const latestToolEntry = visibleGroupedEntries.findLast(workLogEntryIsToolLike);
957​
958 nextRows.push({
959 kind: "work-toggle",
960 id: `work-toggle:${timelineEntry.id}`,
961 createdAt: timelineEntry.createdAt,
962 groupId,
963 hiddenCount: hiddenEntries.length,
964 expanded,
965 onlyToolEntries: hiddenEntries.every(workLogEntryIsToolLike),
966 summary: null,
967 summaryKind: null,
968 hasFailure:
969 latestToolEntry !== undefined &&
970 workEntryDisplayIndicatesToolFailure(latestToolEntry) &&
971 hiddenEntries.some(workEntryDisplayIndicatesToolFailure),
972 });
973 }
974 }
975 }
976 index = cursor - 1;
977 continue;
978 }
979​
980 if (timelineEntry.kind === "proposed-plan") {
981 nextRows.push({
982 kind: "proposed-plan",
983 id: timelineEntry.id,
984 createdAt: timelineEntry.createdAt,
985 proposedPlan: timelineEntry.proposedPlan,
986 });
987 continue;
988 }
989​
990 if (timelineEntry.kind === "turn-plan") {
991 nextRows.push({
992 kind: "turn-plan",
993 id: timelineEntry.id,
994 createdAt: timelineEntry.createdAt,
995 turnPlan: timelineEntry.turnPlan,
996 });
997 continue;
998 }
999​
1000 const assistantTurnStillInProgress =
1001 timelineEntry.message.role === "assistant" &&
1002 unsettledTurnId !== null &&
1003 timelineEntry.message.turnId === unsettledTurnId;
1004​
1005 const durationStart =
1006 durationStartByMessageId.get(timelineEntry.message.id) ?? timelineEntry.message.createdAt;
1007​
1008 // While the turn is still running, the latest assistant message is only
1009 // provisionally terminal — withhold the metadata row until the turn
1010 // settles so commentary doesn't flash timestamps mid-work.
1011 const showAssistantMeta =
1012 timelineEntry.message.role === "assistant" &&
1013 terminalAssistantMessageIds.has(timelineEntry.message.id) &&
1014 !assistantTurnStillInProgress;
1015​
1016 nextRows.push({
1017 kind: "message",
1018 id: timelineEntry.id,
1019 createdAt: timelineEntry.createdAt,
1020 message: timelineEntry.message,
1021 durationStart,
1022 showAssistantMeta,
1023 showAssistantCopyButton: showAssistantMeta,
1024 assistantCopyStreaming: timelineEntry.message.streaming || assistantTurnStillInProgress,
1025 assistantTurnDiffSummary:
1026 timelineEntry.message.role === "assistant"
1027 ? input.turnDiffSummaryByAssistantMessageId.get(timelineEntry.message.id)
1028 : undefined,
1029 revertTurnCount:
1030 timelineEntry.message.role === "user"
1031 ? input.revertTurnCountByUserMessageId.get(timelineEntry.message.id)
1032 : undefined,
1033 });
1035​
1036 if (input.isWorking && activeTurnHeaderIndex === input.timelineEntries.length) {
1037 appendWorkingRow();
1039​
1040 return nextRows;
1042​
1043export function computeStableMessagesTimelineRows(
1044 rows: MessagesTimelineRow[],
1045 previous: StableMessagesTimelineRowsState,
1046): StableMessagesTimelineRowsState {
1047 const next = new Map<string, MessagesTimelineRow>();
1048 let anyChanged = rows.length !== previous.byId.size;
1049​
1050 const result = rows.map((row, index) => {
1051 const prevRow = previous.byId.get(row.id);
1052 const nextRow = prevRow && isRowUnchanged(prevRow, row) ? prevRow : row;
1053 next.set(row.id, nextRow);
1054 if (!anyChanged && previous.result[index] !== nextRow) {
1055 anyChanged = true;
1057 return nextRow;
1058 });
1059​
1060 return anyChanged ? { byId: next, result } : previous;
1062​
1063/** Shallow field comparison per row variant — avoids deep equality cost. */
1064function isRowUnchanged(a: MessagesTimelineRow, b: MessagesTimelineRow): boolean {
1065 if (a.kind !== b.kind || a.id !== b.id) return false;
1066​
1067 switch (a.kind) {
1068 case "working":
1069 return (
1070 a.createdAt === (b as typeof a).createdAt && a.showThinking === (b as typeof a).showThinking
1071 );
1072​
1073 case "turn-fold": {
1074 const bf = b as typeof a;
1075 return a.createdAt === bf.createdAt && a.label === bf.label && a.expanded === bf.expanded;
1077​
1078 case "proposed-plan":
1079 return a.proposedPlan === (b as typeof a).proposedPlan;
1080​
1081 case "turn-plan": {
1082 const bp = b as typeof a;
1083 // Plans rewrite in place: compare the snapshot's identity fields so an
1084 // unchanged plan keeps its row reference (virtualization stability).
1085 return a.createdAt === bp.createdAt && a.turnPlan.plan === bp.turnPlan.plan;
1087​
1088 case "work": {
1089 const bw = b as typeof a;
1090 return (
1091 a.isExpandedToolGroupEntry === bw.isExpandedToolGroupEntry &&
1092 a.isLastExpandedToolGroupEntry === bw.isLastExpandedToolGroupEntry &&
1093 Equal.equals(a.groupedEntries, bw.groupedEntries)
1094 );
1096​
1097 case "work-live": {
1098 const bw = b as typeof a;
1099 return (
1100 a.createdAt === bw.createdAt &&
1101 a.groupId === bw.groupId &&
1102 a.expanded === bw.expanded &&
1103 Equal.equals(a.entry, bw.entry) &&
1104 Equal.equals(a.groupedEntries, bw.groupedEntries)
1105 );
1107​
1108 case "work-toggle": {
1109 const bw = b as typeof a;
1110 return (
1111 a.createdAt === bw.createdAt &&
1112 a.groupId === bw.groupId &&
1113 a.hiddenCount === bw.hiddenCount &&
1114 a.expanded === bw.expanded &&
1115 a.onlyToolEntries === bw.onlyToolEntries &&
1116 a.summary === bw.summary &&
1117 a.summaryKind === bw.summaryKind &&
1118 a.hasFailure === bw.hasFailure
1119 );
1121​
1122 case "message": {
1123 const bm = b as typeof a;
1124 return (
1125 a.message === bm.message &&
1126 a.durationStart === bm.durationStart &&
1127 a.showAssistantMeta === bm.showAssistantMeta &&
1128 a.showAssistantCopyButton === bm.showAssistantCopyButton &&
1129 a.assistantCopyStreaming === bm.assistantCopyStreaming &&
1130 a.assistantTurnDiffSummary === bm.assistantTurnDiffSummary &&
1131 a.revertTurnCount === bm.revertTurnCount
1132 );