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

MessagesTimeline.logic.ts

1,057 lines35.7 KB

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