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

MessagesTimeline.logic.ts

1,250 lines42.0 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 displayLabel?: string;
288 }
289 | {
290 kind: "work-live";
291 id: string;
292 createdAt: string;
293 entry: WorkLogEntry;
294 groupedEntries: WorkLogEntry[];
295 groupId: string;
296 expanded: boolean;
297 active: boolean;
298 }
299 | {
300 kind: "work-toggle";
301 id: string;
302 createdAt: string;
303 turnId?: TurnId | null;
304 groupId: string;
305 hiddenCount: number;
306 expanded: boolean;
307 summary: string;
308 summaryKind: ToolGroupSummaryKind;
309 toolSurface?: WorkLogEntry["toolSurface"];
310 toolIcon?: WorkLogEntry["toolIcon"];
311 summaryToolIcon?: "browser" | "t3-code";
312 hasFailure: boolean;
313 }
314 | {
315 kind: "turn-fold";
316 id: string;
317 createdAt: string;
318 turnId: TurnId;
319 label: string;
320 expanded: boolean;
321 }
322 | {
323 kind: "context-compaction";
324 id: string;
325 createdAt: string;
326 label: string;
327 }
328 | {
329 kind: "message";
330 id: string;
331 createdAt: string;
332 message: ChatMessage;
333 durationStart: string;
334 showAssistantMeta: boolean;
335 showAssistantCopyButton: boolean;
336 assistantCopyStreaming: boolean;
337 assistantTurnDiffSummary?: TurnDiffSummary | undefined;
338 revertTurnCount?: number | undefined;
339 }
340 | {
341 kind: "assistant-meta";
342 id: string;
343 createdAt: string;
344 message: ChatMessage;
345 showAssistantCopyButton: boolean;
346 assistantCopyStreaming: boolean;
347 }
348 | {
349 kind: "proposed-plan";
350 id: string;
351 createdAt: string;
352 proposedPlan: ProposedPlan;
353 }
354 | {
355 kind: "working";
356 id: string;
357 createdAt: string | null;
358 }
359 | {
360 kind: "thinking";
361 id: string;
362 createdAt: string | null;
363 };
364​
365export interface StableMessagesTimelineRowsState {
366 byId: Map<string, MessagesTimelineRow>;
367 result: MessagesTimelineRow[];
369​
370export function computeMessageDurationStart(
371 messages: ReadonlyArray<TimelineDurationMessage>,
372): Map<string, string> {
373 const result = new Map<string, string>();
374 let lastBoundary: string | null = null;
375​
376 for (const message of messages) {
377 if (message.role === "user") {
378 lastBoundary = message.createdAt;
379 }
380 result.set(message.id, lastBoundary ?? message.createdAt);
381 if (message.role === "assistant" && !message.streaming) {
382 lastBoundary = message.updatedAt;
383 }
384 }
385​
386 return result;
388​
389function workGroupIdentity(timelineEntryId: string, entry: WorkLogEntry): string {
390 return entry.toolCallId
391 ? `tool:${entry.turnId ?? "no-turn"}:${entry.toolCallId}`
392 : timelineEntryId;
394​
395function workGroupId(timelineEntryId: string, entry: WorkLogEntry): string {
396 return `work-group:${workGroupIdentity(timelineEntryId, entry)}`;
398​
399function expandedWorkGroupRow(
400 groupId: string,
401 createdAt: string,
402 groupedEntries: WorkLogEntry[],
403): Extract<MessagesTimelineRow, { kind: "work" }> {
404 return {
405 kind: "work",
406 id: `${groupId}:details`,
407 createdAt,
408 groupedEntries,
409 isExpandedToolGroup: true,
410 };
412​
413export function resolveAssistantMessageCopyState({
414 text,
415 showCopyButton,
416 streaming,
417}: {
418 text: string | null;
419 showCopyButton: boolean;
420 streaming: boolean;
421}) {
422 const hasText = text !== null && text.trim().length > 0;
423 const visible = showCopyButton && hasText && !streaming;
424 return {
425 text: hasText ? (visible ? renderCodexDirectivesForCopy(text) : text) : null,
426 visible,
427 };
429​
430function deriveTerminalAssistantMessageIds(timelineEntries: ReadonlyArray<TimelineEntry>) {
431 const lastAssistantMessageIdByResponseKey = new Map<string, string>();
432 let nullTurnResponseIndex = 0;
433​
434 for (const timelineEntry of timelineEntries) {
435 if (timelineEntry.kind !== "message") {
436 continue;
437 }
438 const { message } = timelineEntry;
439 if (message.role === "user") {
440 nullTurnResponseIndex += 1;
441 continue;
442 }
443 if (message.role !== "assistant") {
444 continue;
445 }
446​
447 const responseKey = message.turnId
448 ? `turn:${message.turnId}`
449 : `unkeyed:${nullTurnResponseIndex}`;
450 lastAssistantMessageIdByResponseKey.set(responseKey, message.id);
451 }
452​
453 return new Set(lastAssistantMessageIdByResponseKey.values());
455​
456interface TurnFold {
457 turnId: TurnId;
458 anchorEntryId: string;
459 createdAt: string;
460 hiddenEntryIds: ReadonlySet<string>;
461 label: string;
463​
464/**
465 * The session's running turn is authoritative when latestTurn briefly lags or
466 * regresses behind it. Otherwise, the latest turn counts as unsettled while it
467 * is still running (or has not recorded a completion). This is deliberately
468 * keyed on turn lifecycle rather than transient working state: right after the
469 * user sends a message, the previous turn is still the "active" one until the
470 * server creates the new turn, and folding must not flicker through that window.
471 */
472function deriveUnsettledTurnId(
473 latestTurn: TimelineLatestTurn | null,
474 runningTurnId: TurnId | null,
475): TurnId | null {
476 if (runningTurnId !== null) {
477 return runningTurnId;
478 }
479 if (!latestTurn) {
480 return null;
481 }
482 const isSettled = latestTurn.completedAt !== null && latestTurn.state !== "running";
483 return isSettled ? null : latestTurn.turnId;
485​
486function lastUserMessageIndex(timelineEntries: ReadonlyArray<TimelineEntry>): number {
487 return timelineEntries.findLastIndex(
488 (entry) => entry.kind === "message" && entry.message.role === "user",
489 );
491​
492function timelineEntryTurnId(entry: TimelineEntry): TurnId | null {
493 if (entry.kind === "message") {
494 return entry.message.role === "assistant" ? (entry.message.turnId ?? null) : null;
495 }
496 if (entry.kind === "proposed-plan") {
497 return entry.proposedPlan.turnId;
498 }
499 return entry.kind === "work" ? (entry.entry.turnId ?? null) : null;
501​
502/**
503 * A promptless provider restart replaces the native turn without adding a
504 * user message. Keep every provider turn since the latest user message in one
505 * visual response until the replacement turn settles. A steer has its own
506 * user message, so it naturally starts a new visual response.
507 */
508function deriveActiveVisualResponseTurnIds(input: {
509 timelineEntries: ReadonlyArray<TimelineEntry>;
510 unsettledTurnId: TurnId | null;
511 isWorking: boolean;
512}): ReadonlySet<TurnId> {
513 const turnIds = new Set<TurnId>();
514 if (input.unsettledTurnId === null) {
515 return turnIds;
516 }
517​
518 turnIds.add(input.unsettledTurnId);
519 if (!input.isWorking) {
520 return turnIds;
521 }
522​
523 const latestUserMessageIndex = lastUserMessageIndex(input.timelineEntries);
524 for (let index = latestUserMessageIndex + 1; index < input.timelineEntries.length; index += 1) {
525 const turnId = timelineEntryTurnId(input.timelineEntries[index]!);
526 if (turnId !== null) {
527 turnIds.add(turnId);
528 }
529 }
530 return turnIds;
532​
533function workEntryIsActiveTurnActivity(entry: WorkLogEntry): boolean {
534 return (
535 entry.toolLifecycleStatus === "inProgress" ||
536 (entry.toolLifecycleStatus === undefined &&
537 (entry.sourceActivityKind === "task.progress" || workLogEntryIsToolLike(entry)))
538 );
540​
541/**
542 * Settled turns fold activity before their terminal assistant message behind
543 * a "Worked for ..." row. Work that lands after that message stays visible so
544 * failed or interrupted turns do not hide their trailing tool-call summary.
545 */
546function deriveTurnFolds(input: {
547 timelineEntries: ReadonlyArray<TimelineEntry>;
548 terminalAssistantMessageIds: ReadonlySet<string>;
549 latestTurn: TimelineLatestTurn | null;
550 unfoldedTurnIds: ReadonlySet<TurnId>;
551}): ReadonlyMap<string, TurnFold> {
552 interface TurnGroup {
553 entries: Array<TimelineEntry>;
554 terminalEntry: Extract<TimelineEntry, { kind: "message" }> | null;
555 hasStreamingMessage: boolean;
556 /**
557 * The user message that kicked the turn off. Entry timestamps alone
558 * undercount the duration (the first entry appears only once the
559 * provider starts producing output), and a turn cut short by a steer may
560 * hold a single instantaneous commentary message.
561 */
562 startBoundary: string | null;
563 }
564 const groupsByTurnId = new Map<TurnId, TurnGroup>();
565​
566 let pendingUserBoundary: string | null = null;
567 for (const entry of input.timelineEntries) {
568 if (entry.kind === "message" && entry.message.role === "user") {
569 pendingUserBoundary = entry.message.createdAt;
570 continue;
571 }
572 const turnId =
573 entry.kind === "message" && entry.message.role === "assistant"
574 ? (entry.message.turnId ?? null)
575 : entry.kind === "work"
576 ? (entry.entry.turnId ?? null)
577 : null;
578 if (!turnId) {
579 continue;
580 }
581 let group = groupsByTurnId.get(turnId);
582 if (!group) {
583 group = {
584 entries: [],
585 terminalEntry: null,
586 hasStreamingMessage: false,
587 // Each user boundary starts at most one turn; a second turn after the
588 // same user message (e.g. a steer-superseded continuation) falls back
589 // to its own first entry.
590 startBoundary: pendingUserBoundary,
591 };
592 pendingUserBoundary = null;
593 groupsByTurnId.set(turnId, group);
594 }
595 group.entries.push(entry);
596 if (entry.kind === "message") {
597 if (input.terminalAssistantMessageIds.has(entry.message.id)) {
598 group.terminalEntry = entry;
599 }
600 if (entry.message.streaming) {
601 group.hasStreamingMessage = true;
602 }
603 }
604 }
605​
606 const foldsByAnchorEntryId = new Map<string, TurnFold>();
607 for (const [turnId, group] of groupsByTurnId) {
608 if (input.unfoldedTurnIds.has(turnId)) {
609 continue;
610 }
611 if (group.hasStreamingMessage) {
612 continue;
613 }
614 const hiddenEntryIds = new Set<string>();
615 const terminalEntryIndex = group.terminalEntry
616 ? group.entries.findIndex((entry) => entry.id === group.terminalEntry?.id)
617 : group.entries.length;
618 for (const [index, entry] of group.entries.entries()) {
619 if (entry.id === group.terminalEntry?.id) {
620 continue;
621 }
622 if (index > terminalEntryIndex) {
623 continue;
624 }
625 // Agent-spawn CTA rows never fold: workflows outlive their launching
626 // turn (dynamic spawns, background execution), and folding the CTA
627 // when the turn settles makes a still-running fleet invisible.
628 if (
629 entry.kind === "work" &&
630 (entry.entry.agentSpawn !== undefined ||
631 entry.entry.sourceActivityKind === "context-compaction")
632 ) {
633 continue;
634 }
635 hiddenEntryIds.add(entry.id);
636 }
637 if (hiddenEntryIds.size === 0) {
638 continue;
639 }
640​
641 const firstEntry = group.entries[0];
642 const firstHiddenEntry = group.entries.find((entry) => hiddenEntryIds.has(entry.id));
643 const lastEntry = group.entries.at(-1);
644 if (!firstEntry || !firstHiddenEntry || !lastEntry) {
645 continue;
646 }
647​
648 const isLatestInterruptedTurn =
649 input.latestTurn?.turnId === turnId && input.latestTurn.state === "interrupted";
650 // A turn cut short by a steer leaves trailing work entries behind its
651 // terminal message — take whichever ended last.
652 const lastEntryEnd =
653 lastEntry.kind === "message" ? lastEntry.message.updatedAt : lastEntry.createdAt;
654 const elapsedMs =
655 input.latestTurn?.turnId === turnId &&
656 input.latestTurn.startedAt &&
657 input.latestTurn.completedAt
658 ? computeElapsedMs(input.latestTurn.startedAt, input.latestTurn.completedAt)
659 : computeElapsedMs(
660 group.startBoundary ?? firstEntry.createdAt,
661 maxIsoTimestamp(group.terminalEntry?.message.updatedAt ?? null, lastEntryEnd) ??
662 lastEntryEnd,
663 );
664 const duration = elapsedMs !== null ? formatDuration(elapsedMs) : null;
665 const label = isLatestInterruptedTurn
666 ? duration
667 ? `You stopped after ${duration}`
668 : "You stopped this response"
669 : duration
670 ? `Worked for ${duration}`
671 : "Worked";
672​
673 foldsByAnchorEntryId.set(firstHiddenEntry.id, {
674 turnId,
675 anchorEntryId: firstHiddenEntry.id,
676 createdAt: firstHiddenEntry.createdAt,
677 hiddenEntryIds,
678 label,
679 });
680 }
681 return foldsByAnchorEntryId;
683​
684/**
685 * When a settled turn ends with tool calls after its terminal text, treat the
686 * text and tools as one visual response. The message metadata becomes the
687 * footer for the whole block instead of separating the prose from the tools.
688 */
689function attachTrailingToolGroupsToAssistant(
690 rows: ReadonlyArray<MessagesTimelineRow>,
691): MessagesTimelineRow[] {
692 const messageRowsWithoutMeta = new Set<string>();
693 const metaRowsAfterIndex = new Map<
694 number,
695 Extract<MessagesTimelineRow, { kind: "assistant-meta" }>
696 >();
697​
698 for (const [messageIndex, row] of rows.entries()) {
699 const turnId = row.kind === "message" ? (row.message.turnId ?? null) : null;
700 if (
701 row.kind !== "message" ||
702 row.message.role !== "assistant" ||
703 !row.showAssistantMeta ||
704 turnId === null
705 ) {
706 continue;
707 }
708​
709 let lastTrailingWorkIndex = -1;
710 let hasTrailingToolGroup = false;
711 for (let index = messageIndex + 1; index < rows.length; index += 1) {
712 const candidate = rows[index];
713 if (!candidate || candidate.kind === "message") {
714 break;
715 }
716 if (candidate.kind === "work-toggle" && candidate.turnId === turnId) {
717 hasTrailingToolGroup = true;
718 lastTrailingWorkIndex = index;
719 continue;
720 }
721 if (
722 candidate.kind === "work" &&
723 candidate.groupedEntries.some((entry) => entry.turnId === turnId)
724 ) {
725 if (
726 !candidate.isExpandedToolGroup &&
727 candidate.groupedEntries.some(workLogEntryIsToolLike)
728 ) {
729 hasTrailingToolGroup = true;
730 }
731 if (hasTrailingToolGroup) {
732 lastTrailingWorkIndex = index;
733 }
734 }
735 }
736​
737 if (lastTrailingWorkIndex < 0) {
738 continue;
739 }
740​
741 messageRowsWithoutMeta.add(row.id);
742 metaRowsAfterIndex.set(lastTrailingWorkIndex, {
743 kind: "assistant-meta",
744 id: `assistant-meta:${row.message.id}`,
745 createdAt: rows[lastTrailingWorkIndex]?.createdAt ?? row.message.updatedAt,
746 message: row.message,
747 showAssistantCopyButton: row.showAssistantCopyButton,
748 assistantCopyStreaming: row.assistantCopyStreaming,
749 });
750 }
751​
752 const result: MessagesTimelineRow[] = [];
753 for (const [index, row] of rows.entries()) {
754 if (row.kind === "message" && messageRowsWithoutMeta.has(row.id)) {
755 result.push({ ...row, showAssistantMeta: false, showAssistantCopyButton: false });
756 } else {
757 result.push(row);
758 }
759 const metaRow = metaRowsAfterIndex.get(index);
760 if (metaRow) {
761 result.push(metaRow);
762 }
763 }
764 return result;
766​
767export function deriveMessagesTimelineRows(input: {
768 timelineEntries: ReadonlyArray<TimelineEntry>;
769 latestTurn?: TimelineLatestTurn | null;
770 runningTurnId?: TurnId | null;
771 expandedTurnIds?: ReadonlySet<TurnId>;
772 expandedWorkGroupIds?: ReadonlySet<string>;
773 isWorking: boolean;
774 activeTurnStartedAt: string | null;
775 turnDiffSummaryByAssistantMessageId: ReadonlyMap<MessageId, TurnDiffSummary>;
776 revertTurnCountByUserMessageId: ReadonlyMap<MessageId, number>;
777}): MessagesTimelineRow[] {
778 const nextRows: MessagesTimelineRow[] = [];
779 const durationStartByMessageId = computeMessageDurationStart(
780 input.timelineEntries.flatMap((entry) => (entry.kind === "message" ? [entry.message] : [])),
781 );
782 const terminalAssistantMessageIds = deriveTerminalAssistantMessageIds(input.timelineEntries);
783 const unsettledTurnId = deriveUnsettledTurnId(
784 input.latestTurn ?? null,
785 input.runningTurnId ?? null,
786 );
787 const activeVisualResponseTurnIds = deriveActiveVisualResponseTurnIds({
788 timelineEntries: input.timelineEntries,
789 unsettledTurnId,
790 isWorking: input.isWorking,
791 });
792 const foldsByAnchorEntryId = deriveTurnFolds({
793 timelineEntries: input.timelineEntries,
794 terminalAssistantMessageIds,
795 latestTurn: input.latestTurn ?? null,
796 unfoldedTurnIds: activeVisualResponseTurnIds,
797 });
798 const collapsedEntryIds = new Set<string>();
799 for (const fold of foldsByAnchorEntryId.values()) {
800 if (!input.expandedTurnIds?.has(fold.turnId)) {
801 for (const entryId of fold.hiddenEntryIds) {
802 collapsedEntryIds.add(entryId);
803 }
804 }
805 }
806​
807 let activeTurnHeaderIndex = input.timelineEntries.length;
808 if (input.isWorking) {
809 const latestUserMessageIndex = lastUserMessageIndex(input.timelineEntries);
810 activeTurnHeaderIndex = latestUserMessageIndex + 1;
811 }
812 const entryBelongsToActiveTurn = (entry: TimelineEntry, index: number) =>
813 input.isWorking &&
814 index >= activeTurnHeaderIndex &&
815 (unsettledTurnId === null || timelineEntryTurnId(entry) === unsettledTurnId);
816 const workEntryIsInActiveRun = (entry: WorkLogEntry) =>
817 input.isWorking &&
818 unsettledTurnId !== null &&
819 entry.toolLifecycleStatus === "inProgress" &&
820 entry.turnId === unsettledTurnId;
821 const activeToolEntries: Array<Extract<TimelineEntry, { kind: "work" }>> = [];
822 for (let index = input.timelineEntries.length - 1; index >= activeTurnHeaderIndex; index -= 1) {
823 const entry = input.timelineEntries[index]!;
824 if (
825 !entryBelongsToActiveTurn(entry, index) ||
826 entry.kind !== "work" ||
827 entry.entry.agentSpawn !== undefined ||
828 entry.entry.sourceActivityKind === "context-compaction" ||
829 entry.entry.tone === "error"
830 ) {
831 break;
832 }
833 activeToolEntries.unshift(entry);
834 }
835 const visibleActiveToolEntries = omitSupersededLifecycleMarkers(
836 activeToolEntries.filter((entry) => workEntryIsVisibleInGroup(entry.entry, true)),
837 (entry) => entry.entry,
838 );
839 const activeWorkAnchor = activeToolEntries[0];
840 const latestVisibleToolEntry = visibleActiveToolEntries.at(-1);
841 const latestRunningToolEntry = visibleActiveToolEntries.findLast((entry) =>
842 workEntryIsActiveTurnActivity(entry.entry),
843 );
844 const latestToolFailed =
845 latestRunningToolEntry === undefined &&
846 latestVisibleToolEntry !== undefined &&
847 latestVisibleToolEntry.entry.toolLifecycleStatus !== "declined" &&
848 workEntryDisplayIndicatesToolFailure(latestVisibleToolEntry.entry);
849 const latestToolKeepsActivityLive =
850 latestRunningToolEntry !== undefined ||
851 (latestVisibleToolEntry !== undefined &&
852 workEntryIndicatesToolSuccess(latestVisibleToolEntry.entry));
853 const activeWorkPlacementEntryId = latestVisibleToolEntry?.id;
854 const activeWorkRow =
855 activeWorkAnchor && latestVisibleToolEntry && !latestToolFailed
856 ? (() => {
857 const groupId = workGroupId(activeWorkAnchor.id, activeWorkAnchor.entry);
858 return {
859 kind: "work-live" as const,
860 id: latestToolKeepsActivityLive
861 ? LIVE_ACTIVITY_ROW_ID
862 : `work-live:${workGroupIdentity(activeWorkAnchor.id, activeWorkAnchor.entry)}`,
863 createdAt: activeWorkAnchor.createdAt,
864 entry: (latestRunningToolEntry ?? latestVisibleToolEntry).entry,
865 groupedEntries: visibleActiveToolEntries.map((entry) => entry.entry),
866 groupId,
867 expanded: input.expandedWorkGroupIds?.has(groupId) ?? false,
868 active: latestToolKeepsActivityLive,
869 };
870 })()
871 : null;
872 const activeWorkEntryIds = new Set(
873 activeWorkRow !== null || latestToolFailed ? activeToolEntries.map((entry) => entry.id) : [],
874 );
875 const appendWorkingRow = () => {
876 const latestUserMessage = input.timelineEntries[lastUserMessageIndex(input.timelineEntries)];
877 const visualResponseStartedAt =
878 activeVisualResponseTurnIds.size > 1 &&
879 latestUserMessage?.kind === "message" &&
880 latestUserMessage.message.role === "user"
881 ? latestUserMessage.message.createdAt
882 : input.activeTurnStartedAt;
883 nextRows.push({
884 kind: "working",
885 id: "working-indicator-row",
886 createdAt: visualResponseStartedAt,
887 });
888 };
889 let hasActivityRow = false;
890 const appendActiveWorkRows = () => {
891 if (activeWorkRow === null) return;
892 nextRows.push(activeWorkRow);
893 hasActivityRow ||= activeWorkRow.active;
894 if (!activeWorkRow.expanded) return;
895 nextRows.push(
896 expandedWorkGroupRow(
897 activeWorkRow.groupId,
898 activeWorkRow.createdAt,
899 activeWorkRow.groupedEntries,
900 ),
901 );
902 };
903​
904 for (let index = 0; index < input.timelineEntries.length; index += 1) {
905 const timelineEntry = input.timelineEntries[index];
906 if (!timelineEntry) {
907 continue;
908 }
909​
910 if (input.isWorking && index === activeTurnHeaderIndex) {
911 appendWorkingRow();
912 }
913​
914 if (timelineEntry.id === activeWorkPlacementEntryId) {
915 appendActiveWorkRows();
916 }
917​
918 const anchoredTurnFold = foldsByAnchorEntryId.get(timelineEntry.id);
919 if (anchoredTurnFold) {
920 nextRows.push({
921 kind: "turn-fold",
922 id: `turn-fold:${anchoredTurnFold.turnId}`,
923 createdAt: anchoredTurnFold.createdAt,
924 turnId: anchoredTurnFold.turnId,
925 label: anchoredTurnFold.label,
926 expanded: input.expandedTurnIds?.has(anchoredTurnFold.turnId) ?? false,
927 });
928 }
929​
930 if (collapsedEntryIds.has(timelineEntry.id)) {
931 continue;
932 }
933​
934 if (activeWorkEntryIds.has(timelineEntry.id)) {
935 continue;
936 }
937​
938 if (
939 timelineEntry.kind === "work" &&
940 timelineEntry.entry.sourceActivityKind === "context-compaction"
941 ) {
942 nextRows.push({
943 kind: "context-compaction",
944 id: timelineEntry.id,
945 createdAt: timelineEntry.createdAt,
946 label: timelineEntry.entry.label,
947 });
948 continue;
949 }
950​
951 if (timelineEntry.kind === "work") {
952 if (timelineEntry.entry.agentSpawn !== undefined || timelineEntry.entry.tone === "error") {
953 nextRows.push({
954 kind: "work",
955 id: timelineEntry.id,
956 createdAt: timelineEntry.createdAt,
957 groupedEntries: [timelineEntry.entry],
958 isExpandedToolGroup: false,
959 });
960 continue;
961 }
962 const groupedEntries = [timelineEntry.entry];
963 let cursor = index + 1;
964 while (cursor < input.timelineEntries.length) {
965 const nextEntry = input.timelineEntries[cursor];
966 if (
967 !nextEntry ||
968 nextEntry.kind !== "work" ||
969 nextEntry.entry.agentSpawn !== undefined ||
970 nextEntry.entry.sourceActivityKind === "context-compaction" ||
971 nextEntry.entry.tone === "error" ||
972 activeWorkEntryIds.has(nextEntry.id) ||
973 collapsedEntryIds.has(nextEntry.id) ||
974 foldsByAnchorEntryId.has(nextEntry.id)
975 ) {
976 break;
977 }
978 groupedEntries.push(nextEntry.entry);
979 cursor += 1;
980 }
981 const visibleGroupedEntries = omitSupersededLifecycleMarkers(
982 groupedEntries.filter((entry) =>
983 workEntryIsVisibleInGroup(entry, workEntryIsInActiveRun(entry)),
984 ),
985 (entry) => entry,
986 );
987 if (visibleGroupedEntries.length > 0) {
988 const activeInProgressToolEntries = visibleGroupedEntries.filter(workEntryIsInActiveRun);
989 if (activeInProgressToolEntries.length > 0) {
990 const groupId = workGroupId(timelineEntry.id, timelineEntry.entry);
991 const expanded = input.expandedWorkGroupIds?.has(groupId) ?? false;
992 const latestActiveToolEntry = activeInProgressToolEntries.at(-1)!;
993 nextRows.push({
994 kind: "work-live",
995 id: `work-live:${workGroupIdentity(timelineEntry.id, timelineEntry.entry)}`,
996 createdAt: timelineEntry.createdAt,
997 entry: latestActiveToolEntry,
998 groupedEntries: visibleGroupedEntries,
999 groupId,
1000 expanded,
1001 active: true,
1002 });
1003 hasActivityRow = true;
1004 if (expanded) {
1005 nextRows.push(
1006 expandedWorkGroupRow(groupId, timelineEntry.createdAt, visibleGroupedEntries),
1007 );
1009 } else if (
1010 visibleGroupedEntries.length === 1 &&
1011 workLogEntryIsToolLike(visibleGroupedEntries[0]!)
1012 ) {
1013 const singleEntry = visibleGroupedEntries[0]!;
1014 nextRows.push({
1015 kind: "work",
1016 id: timelineEntry.id,
1017 createdAt: timelineEntry.createdAt,
1018 groupedEntries: visibleGroupedEntries,
1019 isExpandedToolGroup: false,
1020 displayLabel:
1021 toolGroupAction(singleEntry) === "edit"
1022 ? summarizeToolGroup(visibleGroupedEntries)
1023 : singleToolCallLabel(singleEntry),
1024 });
1025 } else {
1026 const groupId = workGroupId(timelineEntry.id, timelineEntry.entry);
1027 const expanded = input.expandedWorkGroupIds?.has(groupId) ?? false;
1028 const summaryKind = toolGroupSummaryKind(visibleGroupedEntries);
1029 const primarySourceEntry = visibleGroupedEntries.find(
1030 (entry) => entry.toolSource !== undefined,
1031 );
1032 const primarySourceKey = primarySourceEntry?.toolSource?.key;
1033 const primarySourceIcon = primarySourceKey
1034 ? (visibleGroupedEntries.find(
1035 (entry) =>
1036 entry.toolSource?.key === primarySourceKey && entry.toolIcon !== undefined,
1037 )?.toolIcon ?? primarySourceEntry?.toolSource?.icon)
1038 : undefined;
1039 const groupToolSurface =
1040 primarySourceEntry?.toolSurface ??
1041 visibleGroupedEntries.findLast((entry) => entry.toolSurface !== undefined)?.toolSurface;
1042 const groupToolIcon =
1043 primarySourceIcon ??
1044 visibleGroupedEntries.findLast((entry) => entry.toolIcon !== undefined)?.toolIcon;
1045 const latestToolEntry = visibleGroupedEntries.findLast(workLogEntryIsToolLike);
1046 const singleEntry =
1047 visibleGroupedEntries.length === 1 ? (visibleGroupedEntries[0] ?? null) : null;
1048 const usesSingleToolCallLabel =
1049 singleEntry !== null &&
1050 workLogEntryIsToolLike(singleEntry) &&
1051 toolGroupAction(singleEntry) !== "edit";
1052 const summaryToolIcon = usesSingleToolCallLabel
1053 ? resolveWorkEntryToolPresentation(singleEntry, "completed")?.icon
1054 : undefined;
1055 nextRows.push({
1056 kind: "work-toggle",
1057 id: `work-toggle:${timelineEntry.id}`,
1058 createdAt: timelineEntry.createdAt,
1059 turnId: timelineEntry.entry.turnId ?? null,
1060 groupId,
1061 hiddenCount: visibleGroupedEntries.length,
1062 expanded,
1063 summary: usesSingleToolCallLabel
1064 ? singleToolCallLabel(singleEntry)
1065 : singleEntry !== null && !workLogEntryIsToolLike(singleEntry)
1066 ? singleEntry.label
1067 : summarizeToolGroup(visibleGroupedEntries),
1068 summaryKind,
1069 ...(groupToolSurface ? { toolSurface: groupToolSurface } : {}),
1070 ...(groupToolIcon ? { toolIcon: groupToolIcon } : {}),
1071 ...(summaryToolIcon ? { summaryToolIcon } : {}),
1072 hasFailure:
1073 latestToolEntry !== undefined &&
1074 workEntryDisplayIndicatesToolFailure(latestToolEntry),
1075 });
1076 if (expanded) {
1077 nextRows.push(
1078 expandedWorkGroupRow(groupId, timelineEntry.createdAt, visibleGroupedEntries),
1079 );
1083 index = cursor - 1;
1084 continue;
1086​
1087 if (timelineEntry.kind === "proposed-plan") {
1088 nextRows.push({
1089 kind: "proposed-plan",
1090 id: timelineEntry.id,
1091 createdAt: timelineEntry.createdAt,
1092 proposedPlan: timelineEntry.proposedPlan,
1093 });
1094 continue;
1096​
1097 const assistantResponseStillInProgress =
1098 timelineEntry.message.role === "assistant" &&
1099 timelineEntry.message.turnId !== null &&
1100 timelineEntry.message.turnId !== undefined &&
1101 activeVisualResponseTurnIds.has(timelineEntry.message.turnId);
1102​
1103 const durationStart =
1104 durationStartByMessageId.get(timelineEntry.message.id) ?? timelineEntry.message.createdAt;
1105​
1106 // While the turn is still running, the latest assistant message is only
1107 // provisionally terminal — withhold the metadata row until the turn
1108 // settles so commentary doesn't flash timestamps mid-work.
1109 const showAssistantMeta =
1110 timelineEntry.message.role === "assistant" &&
1111 terminalAssistantMessageIds.has(timelineEntry.message.id) &&
1112 !assistantResponseStillInProgress;
1113​
1114 nextRows.push({
1115 kind: "message",
1116 id: timelineEntry.id,
1117 createdAt: timelineEntry.createdAt,
1118 message: timelineEntry.message,
1119 durationStart,
1120 showAssistantMeta,
1121 showAssistantCopyButton: showAssistantMeta,
1122 assistantCopyStreaming: timelineEntry.message.streaming || assistantResponseStillInProgress,
1123 assistantTurnDiffSummary:
1124 timelineEntry.message.role === "assistant"
1125 ? input.turnDiffSummaryByAssistantMessageId.get(timelineEntry.message.id)
1126 : undefined,
1127 revertTurnCount:
1128 timelineEntry.message.role === "user"
1129 ? input.revertTurnCountByUserMessageId.get(timelineEntry.message.id)
1130 : undefined,
1131 });
1133​
1134 if (input.isWorking && activeTurnHeaderIndex === input.timelineEntries.length) {
1135 appendWorkingRow();
1137 if (input.isWorking && (!hasActivityRow || latestToolFailed)) {
1138 nextRows.push({
1139 kind: "thinking",
1140 id: LIVE_ACTIVITY_ROW_ID,
1141 createdAt: input.activeTurnStartedAt,
1142 });
1144​
1145 return attachTrailingToolGroupsToAssistant(nextRows);
1147​
1148export function computeStableMessagesTimelineRows(
1149 rows: MessagesTimelineRow[],
1150 previous: StableMessagesTimelineRowsState,
1151): StableMessagesTimelineRowsState {
1152 const next = new Map<string, MessagesTimelineRow>();
1153 let anyChanged = rows.length !== previous.byId.size;
1154​
1155 const result = rows.map((row, index) => {
1156 const prevRow = previous.byId.get(row.id);
1157 const nextRow = prevRow && isRowUnchanged(prevRow, row) ? prevRow : row;
1158 next.set(row.id, nextRow);
1159 if (!anyChanged && previous.result[index] !== nextRow) {
1160 anyChanged = true;
1162 return nextRow;
1163 });
1164​
1165 return anyChanged ? { byId: next, result } : previous;
1167​
1168/** Shallow field comparison per row variant — avoids deep equality cost. */
1169function isRowUnchanged(a: MessagesTimelineRow, b: MessagesTimelineRow): boolean {
1170 if (a.kind !== b.kind || a.id !== b.id) return false;
1171​
1172 switch (a.kind) {
1173 case "working":
1174 case "thinking":
1175 return a.createdAt === (b as typeof a).createdAt;
1176​
1177 case "assistant-meta": {
1178 const bm = b as typeof a;
1179 return (
1180 a.createdAt === bm.createdAt &&
1181 a.message === bm.message &&
1182 a.showAssistantCopyButton === bm.showAssistantCopyButton &&
1183 a.assistantCopyStreaming === bm.assistantCopyStreaming
1184 );
1186​
1187 case "turn-fold": {
1188 const bf = b as typeof a;
1189 return a.createdAt === bf.createdAt && a.label === bf.label && a.expanded === bf.expanded;
1191​
1192 case "context-compaction": {
1193 const bc = b as typeof a;
1194 return a.createdAt === bc.createdAt && a.label === bc.label;
1196​
1197 case "proposed-plan":
1198 return a.proposedPlan === (b as typeof a).proposedPlan;
1199​
1200 case "work": {
1201 const bw = b as typeof a;
1202 return (
1203 a.isExpandedToolGroup === bw.isExpandedToolGroup &&
1204 a.displayLabel === bw.displayLabel &&
1205 Equal.equals(a.groupedEntries, bw.groupedEntries)
1206 );
1208​
1209 case "work-live": {
1210 const bw = b as typeof a;
1211 return (
1212 a.createdAt === bw.createdAt &&
1213 a.groupId === bw.groupId &&
1214 a.expanded === bw.expanded &&
1215 a.active === bw.active &&
1216 Equal.equals(a.entry, bw.entry) &&
1217 Equal.equals(a.groupedEntries, bw.groupedEntries)
1218 );
1220​
1221 case "work-toggle": {
1222 const bw = b as typeof a;
1223 return (
1224 a.createdAt === bw.createdAt &&
1225 a.turnId === bw.turnId &&
1226 a.groupId === bw.groupId &&
1227 a.hiddenCount === bw.hiddenCount &&
1228 a.expanded === bw.expanded &&
1229 a.summary === bw.summary &&
1230 a.summaryKind === bw.summaryKind &&
1231 a.toolSurface === bw.toolSurface &&
1232 Equal.equals(a.toolIcon, bw.toolIcon) &&
1233 a.hasFailure === bw.hasFailure
1234 );
1236​
1237 case "message": {
1238 const bm = b as typeof a;
1239 return (
1240 a.message === bm.message &&
1241 a.durationStart === bm.durationStart &&
1242 a.showAssistantMeta === bm.showAssistantMeta &&
1243 a.showAssistantCopyButton === bm.showAssistantCopyButton &&
1244 a.assistantCopyStreaming === bm.assistantCopyStreaming &&
1245 a.assistantTurnDiffSummary === bm.assistantTurnDiffSummary &&
1246 a.revertTurnCount === bm.revertTurnCount
1247 );