The best way to control Claude Code, Codex and more from any computer or phone

main
ts 2,942 lines 104 KB
Raw
1 import * as DateTime from "effect/DateTime";
2 import { msg } from "gt-react";
3 import { worktreeSetupAgentStarted } from "@t3tools/client-runtime/worktree-setup";
4 import { resolveUserMessagePresentation } from "@t3tools/client-runtime/user-message";
5 import {
6 isLiveSubagentTurnItem,
7 waitingOnSubagentsLabel,
8 } from "@t3tools/client-runtime/state/subagentRuntime";
9 import * as Equal from "effect/Equal";
10 import { shallow } from "zustand/vanilla/shallow";
11 import { claudeResumeCompactionAge } from "@t3tools/shared/claudeCompaction";
12 import {
13 IDLE_COMPACTING_LABELS,
14 IDLE_COMPACTION_TITLES,
15 } from "@t3tools/client-runtime/user-message";
16 import type { HandoffTimelineRun } from "@t3tools/client-runtime/handoff";
17 import { renderCodexDirectivesForCopy } from "@t3tools/shared/codexMarkdownDirectives";
18 import {
19 commandDisplayText,
20 commandProgramName,
21 } from "@t3tools/client-runtime/work-log/command-label";
22 import {
23 commandlessCommandLabel,
24 genericCommandStatusLabel,
25 liveActivityToolStatus,
26 normalizeCompactToolLabel,
27 resolveWorkEntryToolPresentation,
28 summarizeToolGroup,
29 toolGroupAction,
30 toolGroupSummaryKind,
31 contextCompactionTokenCounts,
32 workEntriesViewedImagePaths,
33 type ToolGroupSummaryKind,
34 liveThoughtLine,
35 workEntryHiddenByToolCallVisibility,
36 } from "@t3tools/client-runtime/work-log/presentation";
37 import {
38 deriveRevertTurnCountByUserMessageId,
39 isStreamingMessageTextUpdate,
40 isStreamingTurnItemTextUpdate,
41 timelineEntryIsPersistentResourceCard,
42 workEntryDisplayIndicatesToolFailure,
43 workEntryIndicatesToolSuccess,
44 workEntryIndicatesToolNeutralStatus,
45 workLogEntryIsToolLike,
46 type TimelineEntry,
47 type WorkLogEntry,
48 } from "../../session-logic";
49 import {
50 type ChatMessage,
51 type ProposedPlan,
52 type ThreadShell,
53 type TurnDiffSummary,
54 } from "../../types";
55 import {
56 idleCompactionOf,
57 isCompactionCommandMessage,
58 isOrchestrationV2WorkActive,
59 type MessageId,
60 type OrchestrationV2IdleCompaction,
61 type WorktreeSetupSnapshot,
62 type OrchestrationV2ProjectedTurnItem,
63 type RunAttemptId,
64 type RuntimeRequestId,
65 RunId,
66 type ThreadId,
67 type TurnItemId,
68 } from "@t3tools/contracts";
69 import type { ThreadRunSummary } from "@t3tools/client-runtime/state/shell";
70 import type { ToolCallVisibility } from "@t3tools/contracts/settings";
71 import { resolveT3McpToolDefinition } from "@t3tools/shared/t3McpToolPresentation";
72 import { compactDynamicToolOutput } from "@t3tools/shared/toolOutput";
73 import { htmlRenderReferencesEqual, type HtmlRenderReference } from "@t3tools/shared/htmlRender";
74 import { mcpAppReferencesEqual, type McpAppReference } from "@t3tools/shared/mcpApp";
75 import { formatDuration } from "@t3tools/shared/orchestrationTimingCopy";
76 import { formatWorkspaceRelativePath } from "../../filePathDisplay";
77 import { m, type MessageResolver } from "../../i18n/messages";
78 import { collectToolFilePaths } from "@t3tools/shared/toolActivity";
79 import {
80 dynamicToolTitle,
81 formatReadToolLabel,
82 formatSearchToolLabel,
83 } from "@t3tools/shared/toolActivityCopy";
84 import { isHostPath } from "@t3tools/shared/path";
85
86 export function timelineEntryRunId(entry: TimelineEntry): RunId | null {
87 if (entry.kind === "message") {
88 return entry.message.role === "assistant" ? (entry.message.runId ?? null) : null;
89 }
90 if (entry.kind === "proposed-plan") {
91 return entry.proposedPlan.runId;
92 }
93 if (entry.kind === "html-render" || entry.kind === "mcp-app" || entry.kind === "sent-message") {
94 return entry.runId;
95 }
96 return entry.kind === "work" ? (entry.entry.runId ?? null) : null;
97 }
98
99 function workEntryIsActiveTurnActivity(entry: WorkLogEntry): boolean {
100 return (
101 entry.toolLifecycleStatus === "inProgress" ||
102 (entry.toolLifecycleStatus === undefined &&
103 (entry.sourceActivityKind === "task.progress" || workLogEntryIsToolLike(entry)))
104 );
105 }
106
107 function singleToolCallLabel(entry: WorkLogEntry, resolve: MessageResolver): string {
108 if (entry.itemType === "reasoning") {
109 return entry.detail?.trim().replace(/\s+/g, " ") || resolve(msg("Thought"));
110 }
111 const toolPresentation = resolveWorkEntryToolPresentation(entry, "completed", resolve);
112 if (toolPresentation) return toolPresentation.displayName;
113 const item = entry.structuredPayload;
114 const title =
115 item?.type === "dynamic_tool"
116 ? dynamicToolTitle(item.toolName, item.input, item.title, resolve)
117 : null;
118 if (title) return title;
119 if (entry.itemType === "web_search") return entry.toolTitle ?? resolve(msg("Web search"));
120 return workEntryDisplayLabel(entry, undefined, resolve);
121 }
122
123 function workEntryToolDataRecord(entry: WorkLogEntry): Record<string, unknown> | undefined {
124 return entry.toolData !== null &&
125 typeof entry.toolData === "object" &&
126 !Array.isArray(entry.toolData)
127 ? (entry.toolData as Record<string, unknown>)
128 : undefined;
129 }
130
131 function workEntryReadRawPaths(entry: WorkLogEntry): readonly string[] {
132 const fromChanged = entry.changedFiles ?? [];
133 if (fromChanged.length > 0) return fromChanged;
134 const structured = entry.structuredPayload;
135 if (structured?.type === "dynamic_tool") {
136 const structuredPaths = collectToolFilePaths({ input: structured.input });
137 if (structuredPaths.length > 0) return structuredPaths;
138 }
139 return collectToolFilePaths(workEntryToolDataRecord(entry));
140 }
141
142 function workEntryReadPaths(entry: WorkLogEntry, workspaceRoot: string | undefined): string[] {
143 return workEntryReadRawPaths(entry).map((filePath) =>
144 formatWorkspaceRelativePath(filePath, workspaceRoot),
145 );
146 }
147
148 /** Components pass `useMessages()` so the label follows a language switch. */
149 export function workEntryDisplayLabel(
150 entry: WorkLogEntry,
151 workspaceRoot: string | undefined,
152 resolve: MessageResolver = m,
153 ) {
154 if (entry.itemType === "system_notice") return entry.label;
155 if (entry.itemType === "reasoning" || entry.tone === "thinking") {
156 const thought = entry.detail?.trim().replace(/\s+/g, " ");
157 return thought || entry.label;
158 }
159 const toolPresentation = resolveWorkEntryToolPresentation(entry, undefined, resolve);
160 if (toolPresentation) return toolPresentation.displayName;
161 if (entry.command?.trim()) return commandDisplayText(entry.command);
162 const commandless = commandlessCommandLabel(
163 entry,
164 liveActivityToolStatus(entry.toolLifecycleStatus, false),
165 resolve,
166 );
167 if (commandless) return commandless;
168 const action = toolGroupAction(entry);
169 if (action === "code-search" || action === "search") {
170 const searchLabel =
171 entry.itemType === "file_search"
172 ? entry.label
173 : formatSearchToolLabel(workEntryToolDataRecord(entry), resolve);
174 if (searchLabel) return searchLabel;
175 }
176 const readPaths = action === "read" ? workEntryReadPaths(entry, workspaceRoot) : [];
177 if (action === "read" && readPaths[0]) {
178 return formatReadToolLabel(readPaths[0], readPaths.length - 1, resolve);
179 }
180 const providerRetry =
181 entry.projectedItem?.item.type === "error" && entry.projectedItem.item.retry !== undefined;
182 const item = entry.structuredPayload;
183 const title =
184 item?.type === "dynamic_tool"
185 ? dynamicToolTitle(item.toolName, item.input, item.title, resolve)
186 : null;
187 if (title) return title;
188 const compactDetail = entry.detail?.trim();
189 const detailIsSearchOutput =
190 (action === "code-search" || action === "search") && /[\r\n]/.test(compactDetail ?? "");
191 if (compactDetail && !providerRetry && action !== "read" && !detailIsSearchOutput) {
192 return compactDetail;
193 }
194 const [firstPath] = entry.changedFiles ?? [];
195 if (firstPath) {
196 const path = formatWorkspaceRelativePath(firstPath, workspaceRoot);
197 return entry.changedFiles!.length === 1
198 ? path
199 : resolve(
200 msg("{count, plural, one {{path} +{count} more} other {{path} +{count} more}}", {
201 path,
202 count: entry.changedFiles!.length - 1,
203 }),
204 );
205 }
206 if (action === "read" && !entry.viewedImagePath) {
207 return resolve(msg("Read file"));
208 }
209 const heading = normalizeCompactToolLabel(entry.toolTitle || entry.label);
210 return `${heading.charAt(0).toUpperCase()}${heading.slice(1)}`;
211 }
212
213 export function threadReadTargetId(entry: Pick<WorkLogEntry, "structuredPayload">) {
214 const item = entry.structuredPayload;
215 if (item?.type !== "dynamic_tool") return null;
216 if (resolveT3McpToolDefinition(item.toolName)?.summaryAction !== "thread-read") return null;
217 const input = item.input;
218 const threadId =
219 input !== null && typeof input === "object" && "threadId" in input ? input.threadId : null;
220 return typeof threadId === "string" && threadId.trim().length > 0 ? threadId.trim() : null;
221 }
222
223 export function threadReadTargetTitle(
224 shell: Pick<ThreadShell, "title" | "archivedAt" | "deletedAt"> | null,
225 ) {
226 if (!shell || shell.archivedAt !== null || shell.deletedAt !== null) return null;
227 return shell.title.trim() || null;
228 }
229
230 export function workEntryReadOutput(
231 entry: Pick<
232 WorkLogEntry,
233 "changedFiles" | "detail" | "viewedImagePath" | "structuredPayload" | "toolData"
234 >,
235 workspaceRoot: string | undefined,
236 ): string | null {
237 const paths = [
238 ...new Set(
239 workEntryReadRawPaths(entry as WorkLogEntry)
240 .map((path) => {
241 const trimmed = path.trim().replaceAll("\\", "/");
242 if (!workspaceRoot || isHostPath(trimmed)) {
243 return trimmed;
244 }
245 const root = workspaceRoot.replaceAll("\\", "/").replace(/\/+$/, "");
246 const relative = trimmed.replace(/^\.\//, "").replace(/^\/+/, "");
247 return `${root}/${relative}`;
248 })
249 .filter((path) => path.length > 0),
250 ),
251 ];
252 if (paths.length > 0) {
253 return paths.join("\n");
254 }
255 return null;
256 }
257
258 /** Components pass `useMessages()` so the label follows a language switch. */
259 export function liveWorkEntryLabel(
260 entry: WorkLogEntry,
261 workspaceRoot: string | undefined,
262 active: boolean,
263 resolve: MessageResolver = m,
264 ) {
265 const status = liveActivityToolStatus(entry.toolLifecycleStatus, active);
266 if (entry.itemType === "reasoning") {
267 return (
268 entry.detail?.trim().replace(/\s+/g, " ") ||
269 (status === "inProgress" ? resolve(msg("Thinking")) : resolve(msg("Thought")))
270 );
271 }
272 const toolPresentation = resolveWorkEntryToolPresentation(
273 { ...entry, toolLifecycleStatus: status },
274 undefined,
275 resolve,
276 );
277 if (toolPresentation) return toolPresentation.displayName;
278 const command = entry.command?.trim();
279 if (command) {
280 const program = commandProgramName(command);
281 if (program == null) {
282 return genericCommandStatusLabel(status, resolve);
283 }
284 return resolve(
285 status === "inProgress"
286 ? msg("Running {program}", { program })
287 : status === "failed"
288 ? msg("Failed {program}", { program })
289 : status === "declined"
290 ? msg("Declined {program}", { program })
291 : status === "stopped"
292 ? msg("Stopped {program}", { program })
293 : msg("Ran {program}", { program }),
294 );
295 }
296 return (
297 commandlessCommandLabel(entry, status, resolve) ??
298 workEntryDisplayLabel(entry, workspaceRoot, resolve)
299 );
300 }
301
302 export function workEntryIsVisibleInGroup(
303 entry: WorkLogEntry,
304 expandedToolGroupEntry = false,
305 ): boolean {
306 if (entry.itemType === "reasoning") return Boolean(entry.detail?.trim());
307 return (
308 (expandedToolGroupEntry &&
309 (entry.toolLifecycleStatus === "inProgress" ||
310 entry.sourceActivityKind === "task.progress")) ||
311 entry.toolLifecycleStatus === "stopped" ||
312 !workEntryIndicatesToolNeutralStatus(entry)
313 );
314 }
315 const TIMELINE_MINIMAP_ITEM_SPACING = 8;
316 export const TIMELINE_MINIMAP_MIN_ITEMS = 2;
317 export const TIMELINE_MINIMAP_TARGET_OFFSET = 24;
318 // Relative to the timeline, not the viewport, so an open terminal shrinks the rail and
319 // endpoint previews (centered on their strip) still fit above and below it.
320 const TIMELINE_MINIMAP_MAX_HEIGHT_CSS = "max(4rem, calc(100% - 14.75rem))";
321 const TIMELINE_MINIMAP_PERSISTENT_GUTTER = 48;
322
323 export interface WorkGroupScrollAnchor {
324 readonly entryId: string;
325 readonly offset: number;
326 }
327
328 export function resolveWorkGroupScrollIndex(
329 entries: ReadonlyArray<{ readonly id: string }>,
330 anchor: WorkGroupScrollAnchor | undefined,
331 ): { index: number; viewOffset: number } | undefined {
332 if (!anchor) return undefined;
333 const index = entries.findIndex((entry) => entry.id === anchor.entryId);
334 return index < 0 ? undefined : { index, viewOffset: -anchor.offset };
335 }
336
337 export function shouldFollowWorkGroupAppend(
338 previous: ReadonlyArray<{ readonly id: string }>,
339 entries: ReadonlyArray<{ readonly id: string }>,
340 distanceFromEnd: number,
341 ): boolean {
342 return (
343 previous.length > 0 &&
344 entries.length > previous.length &&
345 distanceFromEnd <= 1 &&
346 previous.every((entry, index) => entry.id === entries[index]?.id)
347 );
348 }
349
350 interface TimelineEndState {
351 readonly isAtEnd?: boolean;
352 readonly isNearEnd?: boolean;
353 readonly contentLength?: number;
354 readonly scroll?: number;
355 readonly scrollLength?: number;
356 }
357
358 // Streaming can briefly unset isAtEnd; re-arm near the content bottom.
359 const TIMELINE_FOLLOW_REARM_THRESHOLD_PX = 40;
360
361 export function resolveTimelineIsAtEnd(state: TimelineEndState | undefined): boolean | undefined {
362 if (!state) {
363 return undefined;
364 }
365 const { contentLength, scroll, scrollLength } = state;
366 if (contentLength === undefined || scroll === undefined || scrollLength === undefined) {
367 return state.isAtEnd;
368 }
369 // LegendList double-subtracts the composer inset, so its isAtEnd is only a fallback.
370 return contentLength - scroll - scrollLength <= TIMELINE_FOLLOW_REARM_THRESHOLD_PX;
371 }
372
373 export function resolveTimelineMinimapHeightStyle(itemCount: number): string {
374 const naturalHeight = Math.max(1, (itemCount - 1) * TIMELINE_MINIMAP_ITEM_SPACING);
375 return `min(${naturalHeight}px, ${TIMELINE_MINIMAP_MAX_HEIGHT_CSS})`;
376 }
377
378 export function resolveTimelineMinimapTopPercent(index: number, itemCount: number): number {
379 if (itemCount <= 1) {
380 return 0;
381 }
382 return (Math.max(0, Math.min(index, itemCount - 1)) / (itemCount - 1)) * 100;
383 }
384
385 export function resolveTimelineMinimapIndexFromPointer(input: {
386 readonly itemCount: number;
387 readonly railTop: number;
388 readonly railHeight: number;
389 readonly pointerY: number;
390 }): number | null {
391 if (input.itemCount <= 0 || input.railHeight <= 0) {
392 return null;
393 }
394 if (input.itemCount === 1) {
395 return 0;
396 }
397
398 const progress = Math.max(0, Math.min(1, (input.pointerY - input.railTop) / input.railHeight));
399 return Math.max(0, Math.min(input.itemCount - 1, Math.round(progress * (input.itemCount - 1))));
400 }
401
402 /** Recheck the rendered buffer: LegendList's unbuffered range can lag during scrolling. */
403 export function resolveTimelineMinimapVisibleRange(state: {
404 readonly startBuffered: number | null | undefined;
405 readonly endBuffered: number | null | undefined;
406 readonly scroll: number;
407 readonly scrollLength: number;
408 readonly positionAtIndex: (index: number) => number | undefined;
409 readonly sizeAtIndex: (index: number) => number | undefined;
410 }) {
411 let start: number | null = null;
412 let end: number | null = null;
413 if (state.startBuffered == null || state.endBuffered == null || state.startBuffered < 0) {
414 return { start, end };
415 }
416 const bottom = state.scroll + state.scrollLength;
417 for (let index = state.startBuffered; index <= state.endBuffered; index += 1) {
418 const top = state.positionAtIndex(index);
419 const height = state.sizeAtIndex(index);
420 if (
421 top != null &&
422 Number.isFinite(top) &&
423 top < bottom &&
424 top + Math.max(1, height != null && Number.isFinite(height) ? height : 1) > state.scroll
425 ) {
426 start ??= index;
427 end = index;
428 }
429 }
430 return { start, end };
431 }
432
433 /** A turn spans its user message up to the next one, so a long reply keeps its strip lit. */
434 export function isTimelineMinimapTurnVisible(
435 turnStartRowIndex: number,
436 nextTurnStartRowIndex: number | undefined,
437 visibleStart: number | null | undefined,
438 visibleEnd: number | null | undefined,
439 ): boolean {
440 return (
441 visibleStart != null &&
442 visibleEnd != null &&
443 turnStartRowIndex <= visibleEnd &&
444 (nextTurnStartRowIndex === undefined || nextTurnStartRowIndex > visibleStart)
445 );
446 }
447
448 export function resolveTimelineMinimapCurrentIndex(input: {
449 readonly visibleStart: number | null | undefined;
450 readonly visibleEnd: number | null | undefined;
451 readonly rowIndices: ReadonlyArray<number>;
452 }): number | null {
453 if (input.visibleStart == null || input.visibleEnd == null) {
454 return null;
455 }
456 let precedingIndex: number | null = null;
457 for (const [index, rowIndex] of input.rowIndices.entries()) {
458 if (rowIndex >= input.visibleStart) {
459 // Prefer the first visible user message, otherwise the turn being read.
460 return rowIndex <= input.visibleEnd ? index : precedingIndex;
461 }
462 precedingIndex = index;
463 }
464 return precedingIndex;
465 }
466
467 function resolveTimelineSideGutter(viewportWidth: number, contentWidth: number): number {
468 if (!Number.isFinite(viewportWidth) || viewportWidth <= 0 || !Number.isFinite(contentWidth)) {
469 return 0;
470 }
471 return Math.max(0, (viewportWidth - Math.min(viewportWidth, contentWidth)) / 2);
472 }
473
474 export function resolveTimelineMinimapHasPersistentGutter(
475 viewportWidth: number,
476 contentWidth: number,
477 ): boolean {
478 return (
479 resolveTimelineSideGutter(viewportWidth, contentWidth) >= TIMELINE_MINIMAP_PERSISTENT_GUTTER
480 );
481 }
482
483 const TIMELINE_MINIMAP_HIT_STRIP_LEFT = 12;
484 const TIMELINE_MINIMAP_HIT_STRIP_MAX_WIDTH = 40;
485
486 export function resolveTimelineMinimapHitStripWidth(
487 viewportWidth: number,
488 contentWidth: number,
489 ): number {
490 const sideGutter = resolveTimelineSideGutter(viewportWidth, contentWidth);
491 return Math.max(
492 0,
493 Math.min(
494 TIMELINE_MINIMAP_HIT_STRIP_MAX_WIDTH,
495 Math.floor(sideGutter) - TIMELINE_MINIMAP_HIT_STRIP_LEFT,
496 ),
497 );
498 }
499
500 const TIMELINE_MINIMAP_NAVIGATION_REACH = 14;
501
502 export function resolveTimelineMinimapNavigationInteractive(collapsedWidth: number): boolean {
503 return collapsedWidth >= TIMELINE_MINIMAP_NAVIGATION_REACH;
504 }
505
506 function computeElapsedMs(startIso: string, endIso: string): number | null {
507 const start = Date.parse(startIso);
508 const end = Date.parse(endIso);
509 if (!Number.isFinite(start) || !Number.isFinite(end)) return null;
510 return Math.max(0, end - start);
511 }
512
513 function maxIsoTimestamp(a: string | null, b: string | null): string | null {
514 if (a === null) return b;
515 if (b === null) return a;
516 const aMs = Date.parse(a);
517 const bMs = Date.parse(b);
518 if (!Number.isFinite(aMs)) return b;
519 if (!Number.isFinite(bMs)) return a;
520 return bMs > aMs ? b : a;
521 }
522
523 export type TimelineLatestRun = Pick<
524 ThreadRunSummary,
525 "runId" | "status" | "startedAt" | "completedAt" | "turnEnded"
526 >;
527
528 const LIVE_ACTIVITY_ROW_ID = "live-activity-row";
529
530 export type MessagesTimelineRow = MessagesTimelineRowContent & {
531 readonly continuesWorkLog?: boolean;
532 };
533
534 type MessagesTimelineRowContent =
535 | {
536 kind: "worktree-setup";
537 id: string;
538 createdAt: string | null;
539 snapshot: WorktreeSetupSnapshot;
540 embedded: boolean;
541 }
542 | {
543 kind: "work";
544 id: string;
545 createdAt: string;
546 groupedEntries: WorkLogEntry[];
547 isExpandedToolGroup: boolean;
548 displayLabel?: string;
549 }
550 | {
551 kind: "work-live";
552 id: string;
553 createdAt: string;
554 entry: WorkLogEntry;
555 groupedEntries: WorkLogEntry[];
556 groupId: string;
557 expanded: boolean;
558 active: boolean;
559 thought?: WorkLogEntry;
560 }
561 | {
562 kind: "working";
563 id: string;
564 createdAt: string | null;
565 /** A running compaction owns the working row, so its divider appears only once it ends. */
566 compacting?: true;
567 }
568 | {
569 kind: "thinking";
570 id: string;
571 createdAt: string | null;
572 /** Replaces "Thinking" while the run has done nothing since launching children that still run. */
573 label?: string;
574 groupId?: string;
575 expanded?: boolean;
576 }
577 | {
578 kind: "work-toggle";
579 id: string;
580 createdAt: string;
581 runId?: RunId | null;
582 groupId: string;
583 hiddenCount: number;
584 expanded: boolean;
585 summary: string;
586 summaryKind: ToolGroupSummaryKind;
587 toolSurface?: WorkLogEntry["toolSurface"];
588 toolIcon?: WorkLogEntry["toolIcon"];
589 hasFailure: boolean;
590 }
591 | {
592 /** Images the agent opened in the tool group above, kept visible while the group is collapsed. */
593 kind: "viewed-images";
594 id: string;
595 createdAt: string;
596 paths: ReadonlyArray<string>;
597 }
598 | {
599 kind: "turn-fold";
600 deferredWorkItemIds?: ReadonlyArray<string>;
601 id: string;
602 createdAt: string;
603 runId: RunId;
604 label: string;
605 expanded: boolean;
606 }
607 | {
608 kind: "attempt-fold";
609 deferredWorkItemIds?: ReadonlyArray<string>;
610 id: string;
611 createdAt: string;
612 runId: RunId;
613 attemptId: RunAttemptId;
614 label: string;
615 expanded: boolean;
616 }
617 | {
618 kind: "context-compaction";
619 id: string;
620 createdAt: string;
621 label: string;
622 tokenCounts: ReturnType<typeof contextCompactionTokenCounts>;
623 active: boolean;
624 /** Replaces "Context compacted" when T3 Code compacted without being asked. */
625 title?: string;
626 /** The compaction finished, so `title` names it. */
627 compacted?: true;
628 failed?: true;
629 /** The provider's reason, when a failed compaction gave one. */
630 failure?: string;
631 }
632 | {
633 kind: "message";
634 id: string;
635 createdAt: string;
636 message: ChatMessage;
637 projectedItem?: OrchestrationV2ProjectedTurnItem;
638 showAssistantMeta: boolean;
639 suppressEmptyResponse?: boolean;
640 showAssistantCopyButton: boolean;
641 assistantCopyStreaming: boolean;
642 assistantTurnDiffSummary?: TurnDiffSummary | undefined;
643 revertTurnCount?: number | undefined;
644 /** Another of your messages follows directly, so the two sit closer together. */
645 groupedWithNext?: boolean;
646 /** Another of your messages sits directly above, so the joined corners tighten. */
647 groupedWithPrevious?: boolean;
648 /** Set when the message above is a steer too, so the label shows once. */
649 continuesSteer?: boolean;
650 }
651 | {
652 kind: "assistant-meta";
653 projectedItem?: OrchestrationV2ProjectedTurnItem;
654 id: string;
655 createdAt: string;
656 message: ChatMessage;
657 showAssistantCopyButton: boolean;
658 assistantCopyStreaming: boolean;
659 }
660 | {
661 kind: "event";
662 id: string;
663 createdAt: string;
664 projectedItem: OrchestrationV2ProjectedTurnItem;
665 subagents?: ReadonlyArray<OrchestrationV2ProjectedTurnItem>;
666 resourceSummary?: boolean;
667 }
668 | {
669 kind: "proposed-plan";
670 id: string;
671 createdAt: string;
672 proposedPlan: ProposedPlan;
673 }
674 | {
675 kind: "html-render";
676 id: string;
677 createdAt: string;
678 htmlRender: HtmlRenderReference;
679 }
680 | {
681 kind: "sent-message";
682 id: string;
683 createdAt: string;
684 text: string;
685 }
686 | {
687 kind: "mcp-app";
688 id: string;
689 createdAt: string;
690 sourceThreadId: ThreadId;
691 itemId: TurnItemId;
692 revision: string;
693 mcpApp: McpAppReference;
694 };
695
696 export interface StableMessagesTimelineRowsState {
697 byId: Map<string, MessagesTimelineRow>;
698 result: MessagesTimelineRow[];
699 }
700
701 function workGroupId(timelineEntryId: string): string {
702 return `work-group:${timelineEntryId}`;
703 }
704
705 function expandedWorkGroupRow(
706 groupId: string,
707 createdAt: string,
708 groupedEntries: WorkLogEntry[],
709 ): Extract<MessagesTimelineRow, { kind: "work" }> {
710 return {
711 kind: "work",
712 id: `${groupId}:details`,
713 createdAt,
714 groupedEntries,
715 isExpandedToolGroup: true,
716 };
717 }
718
719 function viewedImagesRows(
720 groupId: string,
721 createdAt: string,
722 groupedEntries: ReadonlyArray<WorkLogEntry>,
723 ): Array<Extract<MessagesTimelineRow, { kind: "viewed-images" }>> {
724 const paths = workEntriesViewedImagePaths(groupedEntries);
725 return paths.length === 0
726 ? []
727 : [{ kind: "viewed-images", id: `${groupId}:viewed-images`, createdAt, paths }];
728 }
729
730 export function resolveAssistantMessageCopyState({
731 text,
732 showCopyButton,
733 streaming,
734 }: {
735 text: string | null;
736 showCopyButton: boolean;
737 streaming: boolean;
738 }) {
739 const hasText = text !== null && text.trim().length > 0;
740 const visible = showCopyButton && hasText && !streaming;
741 return {
742 text: hasText ? (visible ? renderCodexDirectivesForCopy(text) : text) : null,
743 visible,
744 };
745 }
746
747 function deriveTerminalAssistantMessageIds(timelineEntries: ReadonlyArray<TimelineEntry>) {
748 const lastAssistantMessageIdByResponseKey = new Map<string, string>();
749 let nullTurnResponseIndex = 0;
750
751 for (const timelineEntry of timelineEntries) {
752 if (timelineEntry.kind !== "message") {
753 continue;
754 }
755 const { message } = timelineEntry;
756 if (message.role === "user") {
757 nullTurnResponseIndex += 1;
758 continue;
759 }
760 if (message.role !== "assistant") {
761 continue;
762 }
763
764 const responseKey = message.runId
765 ? `turn:${message.runId}`
766 : `unkeyed:${nullTurnResponseIndex}`;
767 lastAssistantMessageIdByResponseKey.set(responseKey, message.id);
768 }
769
770 return new Set(lastAssistantMessageIdByResponseKey.values());
771 }
772
773 interface TurnFold {
774 runId: RunId;
775 anchorEntryId: string;
776 createdAt: string;
777 hiddenEntryIds: ReadonlySet<string>;
778 /** Every entry in the segment, including the cards a fold never hides. */
779 entryIds: ReadonlySet<string>;
780 label: string;
781 }
782
783 interface SupersededAttemptFold {
784 readonly deferredWorkItemIds: ReadonlyArray<string>;
785 readonly runId: RunId;
786 readonly attemptId: RunAttemptId;
787 readonly anchorEntryId: string;
788 readonly createdAt: string;
789 readonly hiddenEntryIds: ReadonlySet<string>;
790 }
791
792 // Only an explicit final phase proves a reply cut short by steering was an answer.
793 function retainedAssistantReplyEntryIds(
794 timelineEntries: ReadonlyArray<TimelineEntry>,
795 ): ReadonlySet<string> {
796 const replyEntryIds = new Set<string>();
797 const lastOutputByAttemptId = new Map<RunAttemptId, TimelineEntry>();
798 for (const entry of timelineEntries) {
799 if (
800 entry.kind === "message" &&
801 entry.projectedItem?.item.type === "assistant_message" &&
802 entry.projectedItem.item.phase === "final_answer"
803 )
804 replyEntryIds.add(entry.id);
805
806 if (
807 entry.attempt?.status !== "superseded" ||
808 (entry.kind === "message" && entry.message.role === "user") ||
809 (entry.kind === "work" &&
810 (entry.entry.itemType === "system_notice" || entry.entry.itemType === "notification")) ||
811 (entry.kind !== "message" && entry.kind !== "work")
812 ) {
813 continue;
814 }
815 const previous = lastOutputByAttemptId.get(entry.attempt.id);
816 const deferredEnd =
817 previous?.kind === "work"
818 ? previous.entry.projectedItem?.item.deferredWork?.lastOrdinal
819 : undefined;
820 const ordinal =
821 entry.kind === "work"
822 ? entry.entry.projectedItem?.item.ordinal
823 : entry.kind === "message"
824 ? entry.projectedItem?.item.ordinal
825 : undefined;
826 if (deferredEnd !== undefined && ordinal !== undefined && deferredEnd > ordinal) continue;
827 lastOutputByAttemptId.set(entry.attempt.id, entry);
828 }
829 for (const entry of lastOutputByAttemptId.values()) {
830 const item = entry.kind === "message" ? entry.projectedItem?.item : undefined;
831 const supersededAt = entry.attempt?.completedAt ?? null;
832 if (
833 entry.kind === "message" &&
834 !entry.message.streaming &&
835 item?.type === "assistant_message" &&
836 item.phase === undefined &&
837 item.status === "completed" &&
838 item.completedAt !== null &&
839 supersededAt !== null &&
840 DateTime.isLessThan(item.completedAt, supersededAt)
841 ) {
842 replyEntryIds.add(entry.id);
843 }
844 }
845 return replyEntryIds;
846 }
847
848 function deriveSupersededAttemptFolds(
849 timelineEntries: ReadonlyArray<TimelineEntry>,
850 unfoldedRunIds: ReadonlySet<RunId>,
851 liveSubagentEntryIds: ReadonlySet<string>,
852 retainedReplyEntryIds: ReadonlySet<string>,
853 ): ReadonlyMap<string, SupersededAttemptFold> {
854 const retainedAttemptIds = new Set(
855 timelineEntries.flatMap((entry) =>
856 entry.attempt !== undefined && retainedReplyEntryIds.has(entry.id) ? [entry.attempt.id] : [],
857 ),
858 );
859 const entriesByAttemptId = new Map<RunAttemptId, TimelineEntry[]>();
860 for (const entry of timelineEntries) {
861 if (
862 entry.attempt?.status !== "superseded" ||
863 retainedAttemptIds.has(entry.attempt.id) ||
864 unfoldedRunIds.has(entry.attempt.runId) ||
865 (entry.kind === "message" && entry.message.role === "user") ||
866 (entry.kind === "event" && entry.projectedItem.item.type === "handoff") ||
867 entry.kind === "html-render" ||
868 entry.kind === "mcp-app" ||
869 entry.kind === "sent-message" ||
870 timelineEntryIsPersistentResourceCard(entry) ||
871 liveSubagentEntryIds.has(entry.id) ||
872 (entry.kind === "work" && entry.entry.itemType === "system_notice")
873 ) {
874 continue;
875 }
876 const entries = entriesByAttemptId.get(entry.attempt.id) ?? [];
877 entries.push(entry);
878 entriesByAttemptId.set(entry.attempt.id, entries);
879 }
880
881 const foldsByAnchorEntryId = new Map<string, SupersededAttemptFold>();
882 for (const entries of entriesByAttemptId.values()) {
883 const firstEntry = entries[0];
884 const attempt = firstEntry?.attempt;
885 if (firstEntry === undefined || attempt === undefined) continue;
886 foldsByAnchorEntryId.set(firstEntry.id, {
887 deferredWorkItemIds: entries.flatMap((entry) =>
888 entry.kind === "work" && entry.entry.projectedItem?.item.deferredWork
889 ? [String(entry.entry.projectedItem.sourceItemId)]
890 : [],
891 ),
892 runId: attempt.runId,
893 attemptId: attempt.id,
894 anchorEntryId: firstEntry.id,
895 createdAt: firstEntry.createdAt,
896 hiddenEntryIds: new Set(entries.map((entry) => entry.id)),
897 });
898 }
899 return foldsByAnchorEntryId;
900 }
901
902 // After send, the previous turn stays active until the server creates its replacement.
903 function deriveUnsettledRunId(
904 latestRun: TimelineLatestRun | null,
905 runningRunId: RunId | null = null,
906 ): RunId | null {
907 if (runningRunId !== null) return runningRunId;
908 if (!latestRun) {
909 return null;
910 }
911 const isSettled =
912 latestRun.completedAt !== null &&
913 latestRun.status !== "running" &&
914 latestRun.status !== "starting" &&
915 latestRun.status !== "waiting";
916 return isSettled ? null : latestRun.runId;
917 }
918
919 // Children can outlive their launching turn; keep cards visible while the footer counts them.
920 function liveSubagentCardEntryIds(entries: ReadonlyArray<TimelineEntry>): ReadonlySet<string> {
921 const visible = new Set<string>();
922 let batch: Array<Extract<TimelineEntry, { kind: "event" }>> = [];
923 const flush = () => {
924 if (batch.length === 0) return;
925 if (batch.some((entry) => isLiveSubagentTurnItem(entry.projectedItem.item))) {
926 for (const entry of batch) visible.add(entry.id);
927 }
928 batch = [];
929 };
930 for (const entry of entries) {
931 if (entry.kind !== "event" || entry.projectedItem.item.type !== "subagent") {
932 flush();
933 continue;
934 }
935 const item = entry.projectedItem.item;
936 const previous = batch.at(-1)?.projectedItem.item;
937 if (
938 previous !== undefined &&
939 (previous.runId !== item.runId || previous.providerTurnId !== item.providerTurnId)
940 ) {
941 flush();
942 }
943 batch.push(entry);
944 }
945 flush();
946 return visible;
947 }
948
949 function timelineEntryFoldRunId(entry: TimelineEntry, runlessKey: RunId | null): RunId | null {
950 if (entry.kind === "work" && entry.entry.itemType === "system_notice") return null;
951 if (entry.kind === "message" && entry.message.role === "assistant") {
952 return entry.message.runId ?? runlessKey;
953 }
954 if (entry.kind === "work") {
955 return entry.entry.runId ?? runlessKey;
956 }
957 if (
958 entry.kind === "event" &&
959 (timelineEntryIsPersistentResourceCard(entry) || entry.projectedItem.item.type === "subagent")
960 ) {
961 return entry.projectedItem.item.runId ?? runlessKey;
962 }
963 return null;
964 }
965
966 function timelineEntryIsSteer(entry: TimelineEntry): boolean {
967 return (
968 entry.kind === "message" &&
969 entry.message.role === "user" &&
970 (entry.message.inputIntent === "steer" ||
971 entry.message.inputIntent === "promoted_queued_to_steer")
972 );
973 }
974
975 export function timelineEntryStartsResponse(entry: TimelineEntry): boolean {
976 return (
977 (entry.kind === "message" && entry.message.role === "user" && !timelineEntryIsSteer(entry)) ||
978 (entry.kind === "work" && entry.entry.itemType === "notification")
979 );
980 }
981
982 function timelineEntryEnd(entry: TimelineEntry): string {
983 return entry.kind === "message" ? entry.message.updatedAt : entry.createdAt;
984 }
985
986 function timelineEntryIsCompaction(entry: TimelineEntry): boolean {
987 return entry.kind === "work" && entry.entry.sourceActivityKind === "context-compaction";
988 }
989
990 function responseBoundaryRunId(entry: TimelineEntry): RunId | null {
991 if (entry.kind === "message") return entry.message.runId ?? null;
992 if (entry.kind === "work") return entry.entry.runId ?? null;
993 return null;
994 }
995
996 // Group promptless restarts under the initiating prompt until settled.
997 function lastResponseBoundaryIndex(timelineEntries: ReadonlyArray<TimelineEntry>): number {
998 return timelineEntries.findLastIndex(timelineEntryStartsResponse);
999 }
1000
1001 function deriveActiveVisualResponseRunIds(input: {
1002 timelineEntries: ReadonlyArray<TimelineEntry>;
1003 unsettledRunId: RunId | null;
1004 isWorking: boolean;
1005 }): ReadonlySet<RunId> {
1006 const runIds = new Set<RunId>();
1007 if (input.unsettledRunId === null) {
1008 return runIds;
1009 }
1010
1011 runIds.add(input.unsettledRunId);
1012 if (!input.isWorking) {
1013 return runIds;
1014 }
1015
1016 const latestResponseBoundaryIndex = lastResponseBoundaryIndex(input.timelineEntries);
1017 for (
1018 let index = latestResponseBoundaryIndex + 1;
1019 index < input.timelineEntries.length;
1020 index += 1
1021 ) {
1022 const runId = timelineEntryRunId(input.timelineEntries[index]!);
1023 if (runId !== null) {
1024 runIds.add(runId);
1025 }
1026 }
1027 return runIds;
1028 }
1029
1030 function timelineEntryFailedItem(entry: TimelineEntry) {
1031 const item =
1032 entry.kind === "event"
1033 ? entry.projectedItem.item
1034 : entry.kind === "work"
1035 ? entry.entry.projectedItem?.item
1036 : null;
1037 return item?.type === "error" && item.status === "failed" && item.parentItemId === null
1038 ? item
1039 : null;
1040 }
1041
1042 function failedTimelineRunIds(
1043 entries: ReadonlyArray<TimelineEntry>,
1044 latestRun: TimelineLatestRun | null,
1045 ) {
1046 const failed = new Set<RunId>();
1047 if (latestRun?.status === "failed") failed.add(latestRun.runId);
1048 for (const entry of entries) {
1049 const runId = timelineEntryFailedItem(entry)?.runId;
1050 if (runId) failed.add(runId);
1051 }
1052 return failed;
1053 }
1054
1055 /** Usage-limit pauses keep their tool groups; any other failure itemizes the run's work. */
1056 function itemizedFailedRunIds(
1057 entries: ReadonlyArray<TimelineEntry>,
1058 failedRunIds: ReadonlySet<RunId>,
1059 ) {
1060 const usageLimited = new Set<RunId>();
1061 const otherFailures = new Set<RunId>();
1062 for (const entry of entries) {
1063 const item = timelineEntryFailedItem(entry);
1064 if (item?.runId) {
1065 (item.failure.class === "usage_limit" ? usageLimited : otherFailures).add(item.runId);
1066 }
1067 }
1068 return new Set(
1069 [...failedRunIds].filter((runId) => !usageLimited.has(runId) || otherFailures.has(runId)),
1070 );
1071 }
1072
1073 function deriveTurnFolds(input: {
1074 timelineEntries: ReadonlyArray<TimelineEntry>;
1075 terminalAssistantMessageIds: ReadonlySet<string>;
1076 latestRun: TimelineLatestRun | null;
1077 unfoldedRunIds: ReadonlySet<RunId>;
1078 runlessWorkActive: boolean;
1079 liveSubagentEntryIds: ReadonlySet<string>;
1080 retainedAssistantReplyEntryIds: ReadonlySet<string>;
1081 resolve: MessageResolver;
1082 }): ReadonlyMap<string, TurnFold> {
1083 const interruptedRunIds = new Set<RunId>();
1084 const promptIndexByRunId = new Map<RunId, number>();
1085 for (const [index, entry] of input.timelineEntries.entries()) {
1086 if (timelineEntryStartsResponse(entry)) {
1087 const runId = responseBoundaryRunId(entry);
1088 if (runId !== null && !promptIndexByRunId.has(runId)) promptIndexByRunId.set(runId, index);
1089 }
1090 if (
1091 entry.kind === "event" &&
1092 entry.projectedItem.item.runId !== null &&
1093 (entry.projectedItem.item.type === "run_interrupt_request" ||
1094 entry.projectedItem.item.type === "run_interrupt_result")
1095 ) {
1096 interruptedRunIds.add(entry.projectedItem.item.runId);
1097 }
1098 }
1099
1100 interface TurnGroup {
1101 entries: Array<TimelineEntry>;
1102 terminalEntry: Extract<TimelineEntry, { kind: "message" }> | null;
1103 hasStreamingMessage: boolean;
1104 // Entry timestamps omit startup and can collapse steered turns to an instant.
1105 startBoundary: string | null;
1106 anchorEntryId: string;
1107 /**
1108 * Each steer after the turn has produced output starts a new segment at
1109 * this index into `entries`, so the steer sits between the work it split.
1110 */
1111 steerSegments: Array<{ startIndex: number; steer: TimelineEntry }>;
1112 }
1113 const groupsByRunId = new Map<RunId, TurnGroup>();
1114 const runlessFailedKeys = new Set<RunId>();
1115
1116 // Key runless responses per prompt to prevent V2 runs unfolding imported turns.
1117 let runlessKey: RunId | null = null;
1118 let responseKey: RunId | null = null;
1119 let pendingBoundary: { createdAt: string; anchorEntryId: string } | null = null;
1120 for (const [index, entry] of input.timelineEntries.entries()) {
1121 if (timelineEntryStartsResponse(entry)) {
1122 const nextEntry = input.timelineEntries[index + 1];
1123 pendingBoundary = nextEntry
1124 ? { createdAt: entry.createdAt, anchorEntryId: nextEntry.id }
1125 : null;
1126 const boundaryRunId = responseBoundaryRunId(entry);
1127 runlessKey = boundaryRunId == null ? RunId.make(`runless:${entry.id}`) : null;
1128 responseKey = boundaryRunId ?? runlessKey;
1129 continue;
1130 }
1131 if (entry.kind === "message" && timelineEntryIsSteer(entry)) {
1132 const steerRunId = entry.message.runId ?? responseKey;
1133 const group = steerRunId === null ? undefined : groupsByRunId.get(steerRunId);
1134 if (group !== undefined && group.entries.length > 0) {
1135 // Back-to-back steers split once, after the last of them.
1136 if (group.steerSegments.at(-1)?.startIndex === group.entries.length) {
1137 group.steerSegments.pop();
1138 }
1139 group.steerSegments.push({ startIndex: group.entries.length, steer: entry });
1140 }
1141 continue;
1142 }
1143 const ownRunId = timelineEntryFoldRunId(entry, runlessKey);
1144 if (!ownRunId) {
1145 continue;
1146 }
1147 // Resumed subagents keep their position and fold with their original turn.
1148 const runId =
1149 responseKey !== null && (promptIndexByRunId.get(ownRunId) ?? -1) > index
1150 ? responseKey
1151 : ownRunId;
1152 if (runId === runlessKey && timelineEntryFailedItem(entry) !== null) {
1153 runlessFailedKeys.add(runId);
1154 }
1155 let group = groupsByRunId.get(runId);
1156 if (!group) {
1157 group = {
1158 entries: [],
1159 terminalEntry: null,
1160 hasStreamingMessage: false,
1161 startBoundary: pendingBoundary?.createdAt ?? null,
1162 anchorEntryId: pendingBoundary?.anchorEntryId ?? entry.id,
1163 steerSegments: [],
1164 };
1165 pendingBoundary = null;
1166 groupsByRunId.set(runId, group);
1167 }
1168 group.entries.push(entry);
1169 if (entry.kind === "message") {
1170 if (input.terminalAssistantMessageIds.has(entry.message.id)) {
1171 group.terminalEntry = entry;
1172 }
1173 if (entry.message.streaming) {
1174 group.hasStreamingMessage = true;
1175 }
1176 }
1177 }
1178
1179 const foldsByAnchorEntryId = new Map<string, TurnFold>();
1180 for (const [runId, group] of groupsByRunId) {
1181 if (
1182 input.unfoldedRunIds.has(runId) ||
1183 interruptedRunIds.has(runId) ||
1184 runlessFailedKeys.has(runId) ||
1185 (input.runlessWorkActive && runId === runlessKey)
1186 ) {
1187 continue;
1188 }
1189 if (group.hasStreamingMessage) {
1190 continue;
1191 }
1192 const hiddenEntryIds = new Set<string>();
1193 const terminalEntryIndex = group.terminalEntry
1194 ? group.entries.findIndex((entry) => entry.id === group.terminalEntry?.id)
1195 : group.entries.length;
1196 // Folded dividers lose their place in the turn, so only the latest stays visible.
1197 const visibleCompactionId = group.entries.findLast(timelineEntryIsCompaction)?.id;
1198 for (const [index, entry] of group.entries.entries()) {
1199 if (entry.id === group.terminalEntry?.id) {
1200 continue;
1201 }
1202 const isCompaction = timelineEntryIsCompaction(entry);
1203 const isFoldableTrailingActivity =
1204 entry.kind === "work" &&
1205 entry.entry.toolLifecycleStatus !== "inProgress" &&
1206 !workEntryDisplayIndicatesToolFailure(entry.entry);
1207 if (!isCompaction && index > terminalEntryIndex && !isFoldableTrailingActivity) {
1208 continue;
1209 }
1210 if (
1211 entry.id === visibleCompactionId ||
1212 timelineEntryIsPersistentResourceCard(entry) ||
1213 input.liveSubagentEntryIds.has(entry.id) ||
1214 input.retainedAssistantReplyEntryIds.has(entry.id)
1215 ) {
1216 continue;
1217 }
1218 if (entry.kind === "work" && entry.entry.itemType === "notification") continue;
1219 if (entry.kind === "work" && entry.entry.questionAnswer !== undefined) continue;
1220 hiddenEntryIds.add(entry.id);
1221 }
1222 if (hiddenEntryIds.size === 0) {
1223 continue;
1224 }
1225 const hidesNonCompactionWork = (entries: ReadonlyArray<TimelineEntry>) =>
1226 entries.some((entry) => hiddenEntryIds.has(entry.id) && !timelineEntryIsCompaction(entry));
1227 if (!hidesNonCompactionWork(group.entries)) {
1228 continue;
1229 }
1230
1231 const firstEntry = group.entries[0];
1232 const lastEntry = group.entries.at(-1);
1233 if (!firstEntry || !lastEntry) {
1234 continue;
1235 }
1236
1237 const isLatestInterruptedTurn =
1238 input.latestRun?.runId === runId && input.latestRun.status === "interrupted";
1239 // A turn cut short by a steer leaves trailing work entries behind its
1240 // terminal message — take whichever ended last. A subagent card after it was
1241 // spawned by background work once the turn settled, so it adds no turn time.
1242 const lateSubagentIds = new Set(
1243 group.entries.flatMap((entry, index) =>
1244 index > terminalEntryIndex &&
1245 entry.kind === "event" &&
1246 entry.projectedItem.item.type === "subagent"
1247 ? [entry.id]
1248 : [],
1249 ),
1250 );
1251 const lastTurnEntry =
1252 group.entries.findLast((entry) => !lateSubagentIds.has(entry.id)) ?? lastEntry;
1253 const lastEntryEnd = timelineEntryEnd(lastTurnEntry);
1254 const elapsedMs =
1255 input.latestRun?.runId === runId && input.latestRun.startedAt && input.latestRun.completedAt
1256 ? computeElapsedMs(input.latestRun.startedAt, input.latestRun.completedAt)
1257 : computeElapsedMs(
1258 group.startBoundary ?? firstEntry.createdAt,
1259 maxIsoTimestamp(group.terminalEntry?.message.updatedAt ?? null, lastEntryEnd) ??
1260 lastEntryEnd,
1261 );
1262 const { resolve } = input;
1263 const duration = elapsedMs !== null ? formatDuration(elapsedMs, resolve) : null;
1264 const label = isLatestInterruptedTurn
1265 ? duration
1266 ? resolve(msg("You stopped after {duration}", { duration }))
1267 : resolve(msg("You stopped this response"))
1268 : duration
1269 ? resolve(msg("Worked for {duration}", { duration }))
1270 : resolve(msg("Worked"));
1271
1272 // The top row keeps the whole turn's time, steers included. Work after a
1273 // steer folds under its own row below that steer, keyed apart from the run
1274 // so each segment opens on its own.
1275 const segmentHiddenIds = (entries: ReadonlyArray<TimelineEntry>) =>
1276 new Set(entries.flatMap((entry) => (hiddenEntryIds.has(entry.id) ? [entry.id] : [])));
1277 const firstSegment = group.entries.slice(0, group.steerSegments[0]?.startIndex);
1278 foldsByAnchorEntryId.set(group.anchorEntryId, {
1279 runId,
1280 anchorEntryId: group.anchorEntryId,
1281 createdAt: group.startBoundary ?? firstEntry.createdAt,
1282 hiddenEntryIds: segmentHiddenIds(firstSegment),
1283 entryIds: new Set(firstSegment.map((entry) => entry.id)),
1284 label,
1285 });
1286 for (const [index, { startIndex, steer }] of group.steerSegments.entries()) {
1287 const entries = group.entries.slice(startIndex, group.steerSegments[index + 1]?.startIndex);
1288 const anchorEntry = entries[0];
1289 if (anchorEntry === undefined || !hidesNonCompactionWork(entries)) continue;
1290 const segmentMs = computeElapsedMs(
1291 steer.createdAt,
1292 entries
1293 .filter((entry) => !lateSubagentIds.has(entry.id))
1294 .map(timelineEntryEnd)
1295 .reduce<string | null>(maxIsoTimestamp, null) ?? steer.createdAt,
1296 );
1297 foldsByAnchorEntryId.set(anchorEntry.id, {
1298 runId: RunId.make(`${runId}:steer:${steer.id}`),
1299 anchorEntryId: anchorEntry.id,
1300 createdAt: steer.createdAt,
1301 hiddenEntryIds: segmentHiddenIds(entries),
1302 entryIds: new Set(entries.map((entry) => entry.id)),
1303 label:
1304 segmentMs !== null
1305 ? resolve(
1306 msg("Continued for {duration}", { duration: formatDuration(segmentMs, resolve) }),
1307 )
1308 : resolve(msg("Continued")),
1309 });
1310 }
1311 }
1312 return foldsByAnchorEntryId;
1313 }
1314
1315 function attachTrailingToolGroupsToAssistant(
1316 rows: ReadonlyArray<MessagesTimelineRow>,
1317 ): MessagesTimelineRow[] {
1318 const messageRowsWithoutMeta = new Set<string>();
1319 const metaRowsAfterIndex = new Map<
1320 number,
1321 Extract<MessagesTimelineRow, { kind: "assistant-meta" }>
1322 >();
1323
1324 for (const [messageIndex, row] of rows.entries()) {
1325 const runId = row.kind === "message" ? (row.message.runId ?? null) : null;
1326 if (
1327 row.kind !== "message" ||
1328 row.message.role !== "assistant" ||
1329 !row.showAssistantMeta ||
1330 runId === null
1331 ) {
1332 continue;
1333 }
1334
1335 let lastTrailingWorkIndex = -1;
1336 let hasTrailingToolGroup = false;
1337 for (let index = messageIndex + 1; index < rows.length; index += 1) {
1338 const candidate = rows[index];
1339 if (!candidate || candidate.kind === "message") {
1340 break;
1341 }
1342 if (candidate.kind === "work-toggle" && candidate.runId === runId) {
1343 hasTrailingToolGroup = true;
1344 lastTrailingWorkIndex = index;
1345 continue;
1346 }
1347 if (
1348 candidate.kind === "event" &&
1349 candidate.resourceSummary &&
1350 candidate.projectedItem.item.runId === runId
1351 ) {
1352 hasTrailingToolGroup = true;
1353 lastTrailingWorkIndex = index;
1354 continue;
1355 }
1356 if (
1357 candidate.kind === "work" &&
1358 candidate.groupedEntries.some((entry) => entry.runId === runId)
1359 ) {
1360 if (
1361 !candidate.isExpandedToolGroup &&
1362 candidate.groupedEntries.some(
1363 (entry) =>
1364 workLogEntryIsToolLike(entry) ||
1365 (entry.projectedItem?.item.type === "error" &&
1366 entry.projectedItem.item.status === "failed"),
1367 )
1368 ) {
1369 hasTrailingToolGroup = true;
1370 }
1371 if (hasTrailingToolGroup) {
1372 lastTrailingWorkIndex = index;
1373 }
1374 }
1375 }
1376
1377 if (lastTrailingWorkIndex < 0) {
1378 continue;
1379 }
1380
1381 messageRowsWithoutMeta.add(row.id);
1382 metaRowsAfterIndex.set(lastTrailingWorkIndex, {
1383 kind: "assistant-meta",
1384 id: `assistant-meta:${row.message.id}`,
1385 ...(row.projectedItem === undefined ? {} : { projectedItem: row.projectedItem }),
1386 createdAt: rows[lastTrailingWorkIndex]?.createdAt ?? row.message.updatedAt,
1387 message: row.message,
1388 showAssistantCopyButton: row.showAssistantCopyButton,
1389 assistantCopyStreaming: row.assistantCopyStreaming,
1390 });
1391 }
1392
1393 const result: MessagesTimelineRow[] = [];
1394 for (const [index, row] of rows.entries()) {
1395 if (row.kind === "message" && messageRowsWithoutMeta.has(row.id)) {
1396 result.push({ ...row, showAssistantMeta: false, showAssistantCopyButton: false });
1397 } else {
1398 result.push(row);
1399 }
1400 const metaRow = metaRowsAfterIndex.get(index);
1401 if (metaRow) {
1402 result.push(metaRow);
1403 }
1404 }
1405 return result;
1406 }
1407
1408 // Hide delegation rows only when task ids identify durable child cards; prompts can repeat.
1409 function withoutSubagentDelegationRows(entries: ReadonlyArray<TimelineEntry>) {
1410 const childrenByRun = new Map<RunId, Set<string>>();
1411 for (const entry of entries) {
1412 if (entry.kind !== "event" || entry.projectedItem.item.type !== "subagent") continue;
1413 const item = entry.projectedItem.item;
1414 if (item.origin !== "app_owned" || item.runId === null) continue;
1415 const children = childrenByRun.get(item.runId) ?? new Set<string>();
1416 children.add(item.subagentId);
1417 childrenByRun.set(item.runId, children);
1418 }
1419 return entries.filter((entry) => {
1420 if (entry.kind !== "work" || workEntryDisplayIndicatesToolFailure(entry.entry)) return true;
1421 const item = entry.entry.projectedItem?.item ?? entry.entry.structuredPayload;
1422 if (
1423 item?.type !== "dynamic_tool" ||
1424 item.runId === null ||
1425 (item.status !== "running" && item.status !== "completed") ||
1426 resolveT3McpToolDefinition(item.toolName)?.summaryAction !== "delegate"
1427 )
1428 return true;
1429 const output = compactDynamicToolOutput(item.output);
1430 if (output?.isError) return true;
1431 if (output?.taskId !== undefined) {
1432 return !childrenByRun.get(item.runId)?.has(output.taskId);
1433 }
1434 return true;
1435 });
1436 }
1437
1438 const supersededReasoningEntries = new WeakMap<TimelineEntry, TimelineEntry>();
1439
1440 function settleSupersededReasoning(entries: ReadonlyArray<TimelineEntry>) {
1441 return entries.map((entry, index) => {
1442 if (
1443 index === entries.length - 1 ||
1444 entry.kind !== "work" ||
1445 entry.entry.itemType !== "reasoning" ||
1446 entry.entry.toolLifecycleStatus !== "inProgress"
1447 ) {
1448 return entry;
1449 }
1450 let settled = supersededReasoningEntries.get(entry);
1451 if (!settled) {
1452 settled = { ...entry, entry: { ...entry.entry, toolLifecycleStatus: "completed" } };
1453 supersededReasoningEntries.set(entry, settled);
1454 }
1455 return settled;
1456 });
1457 }
1458
1459 function workShownAsFinalAnswerOnly(
1460 entry: TimelineEntry,
1461 pendingApprovalRequestIds: ReadonlySet<RuntimeRequestId> | undefined,
1462 ): boolean {
1463 if (entry.kind === "event") return entry.projectedItem.item.type !== "subagent";
1464 if (entry.kind !== "work") return true;
1465 const work = entry.entry;
1466 const item = work.projectedItem?.item;
1467 return (
1468 (item?.type === "approval_request" &&
1469 pendingApprovalRequestIds?.has(item.requestId) === true) ||
1470 work.questionAnswer !== undefined ||
1471 timelineEntryIsCompaction(entry) ||
1472 timelineEntryStartsResponse(entry) ||
1473 work.tone === "error" ||
1474 work.sourceActivityKind === "runtime.error" ||
1475 (work.itemType === "error" && work.toolLifecycleStatus !== "completed")
1476 );
1477 }
1478
1479 function deriveInFlightSteerAnswerIds(entries: ReadonlyArray<TimelineEntry>): ReadonlySet<string> {
1480 const ids = new Set<string>();
1481 let awaitingReply = false;
1482 let candidate: string | null = null;
1483 for (const entry of entries) {
1484 if (entry.kind === "work" && entry.entry.itemType === "reasoning") continue;
1485 const reply = entry.kind === "message" && entry.message.role === "assistant" ? entry : null;
1486 if (candidate !== null && reply !== null) ids.add(candidate);
1487 candidate = null;
1488 if (timelineEntryIsSteer(entry)) {
1489 awaitingReply = true;
1490 } else if (entry.kind === "message" && entry.message.role === "user") {
1491 awaitingReply = false;
1492 } else if (reply !== null && awaitingReply) {
1493 candidate = reply.message.id;
1494 awaitingReply = false;
1495 }
1496 }
1497 return ids;
1498 }
1499
1500 export function liveAnswerPreview(entries: ReadonlyArray<TimelineEntry>): string | null {
1501 const boundary = lastResponseBoundaryIndex(entries);
1502 for (let index = entries.length - 1; index > boundary; index -= 1) {
1503 const entry = entries[index]!;
1504 const text =
1505 entry.kind === "message" && entry.message.role === "assistant"
1506 ? entry.message.text
1507 : entry.kind === "work" && entry.entry.itemType === "reasoning"
1508 ? (entry.entry.detail ?? "")
1509 : "";
1510 const line = liveThoughtLine(text);
1511 if (line !== "") return line;
1512 }
1513 return null;
1514 }
1515
1516 /** Reads entries before tool visibility filters them, so hidden newer parent work still counts. */
1517 function runningSubagentsAtRunTail(entries: ReadonlyArray<TimelineEntry>, runId: RunId): number {
1518 let running = 0;
1519 for (let index = entries.length - 1; index >= 0; index -= 1) {
1520 const entry = entries[index]!;
1521 if (entry.kind !== "event") break;
1522 const { item } = entry.projectedItem;
1523 if (item.type !== "subagent" || item.runId !== runId) break;
1524 if (isLiveSubagentTurnItem(item)) running += 1;
1525 }
1526 return running;
1527 }
1528
1529 function timelineRowEntries(
1530 input: Pick<
1531 MessagesTimelineRowsInput,
1532 | "timelineEntries"
1533 | "toolCallVisibility"
1534 | "revealedMessageId"
1535 | "isWorking"
1536 | "latestRun"
1537 | "runningRunId"
1538 | "pendingApprovalRequestIds"
1539 >,
1540 ) {
1541 const visibility = input.toolCallVisibility ?? "showAll";
1542 const entries = input.timelineEntries;
1543 let shown = entries;
1544 if (visibility === "zen") {
1545 const answering = input.isWorking && input.latestRun?.turnEnded !== true;
1546 const answeringRunId = answering
1547 ? deriveUnsettledRunId(input.latestRun ?? null, input.runningRunId ?? null)
1548 : null;
1549 const answeringFrom = answering ? lastResponseBoundaryIndex(entries) + 1 : entries.length;
1550 const terminalIds = deriveTerminalAssistantMessageIds(entries);
1551 const steerAnswerIds = deriveInFlightSteerAnswerIds(entries);
1552 const retainedReplyIds = retainedAssistantReplyEntryIds(entries);
1553 shown = entries.filter((entry, index) => {
1554 if (entry.kind !== "message") {
1555 return workShownAsFinalAnswerOnly(entry, input.pendingApprovalRequestIds);
1556 }
1557 const { message } = entry;
1558 return (
1559 message.role !== "assistant" ||
1560 message.id === input.revealedMessageId ||
1561 steerAnswerIds.has(message.id) ||
1562 retainedReplyIds.has(entry.id) ||
1563 (terminalIds.has(message.id) &&
1564 index < answeringFrom &&
1565 (answeringRunId === null || message.runId !== answeringRunId))
1566 );
1567 });
1568 } else if (visibility !== "showAll") {
1569 shown = entries.filter(
1570 (entry) =>
1571 entry.kind !== "work" || !workEntryHiddenByToolCallVisibility(entry.entry, visibility),
1572 );
1573 }
1574 return withoutSubagentDelegationRows(settleSupersededReasoning(shown));
1575 }
1576
1577 function deriveTimelineTurnFolds(
1578 input: Pick<
1579 MessagesTimelineRowsInput,
1580 | "timelineEntries"
1581 | "latestRun"
1582 | "isWorking"
1583 | "runlessWorkActive"
1584 | "runningRunId"
1585 | "toolCallVisibility"
1586 | "revealedMessageId"
1587 >,
1588 ) {
1589 if (input.toolCallVisibility === "zen") return new Map<string, TurnFold>();
1590 const timelineEntries = timelineRowEntries(input);
1591 const unsettledRunId = deriveUnsettledRunId(input.latestRun ?? null, input.runningRunId ?? null);
1592 const failedRunIds = failedTimelineRunIds(timelineEntries, input.latestRun ?? null);
1593 const activeVisualResponseRunIds = deriveActiveVisualResponseRunIds({
1594 timelineEntries,
1595 unsettledRunId,
1596 isWorking: input.isWorking,
1597 });
1598 return deriveTurnFolds({
1599 timelineEntries,
1600 terminalAssistantMessageIds: deriveTerminalAssistantMessageIds(timelineEntries),
1601 latestRun: input.latestRun ?? null,
1602 unfoldedRunIds: new Set([...activeVisualResponseRunIds, ...failedRunIds]),
1603 runlessWorkActive: input.isWorking && input.runlessWorkActive === true,
1604 liveSubagentEntryIds: liveSubagentCardEntryIds(timelineEntries),
1605 retainedAssistantReplyEntryIds: retainedAssistantReplyEntryIds(timelineEntries),
1606 resolve: m,
1607 });
1608 }
1609
1610 export function deriveMessagesTimelineRows(
1611 input: {
1612 timelineEntries: ReadonlyArray<TimelineEntry>;
1613 pendingApprovalRequestIds?: ReadonlySet<RuntimeRequestId>;
1614 latestRun?: TimelineLatestRun | null;
1615 runningRunId?: RunId | null;
1616 expandedRunIds?: ReadonlySet<RunId>;
1617 expandedAttemptIds?: ReadonlySet<RunAttemptId>;
1618 expandedWorkGroupIds?: ReadonlySet<string>;
1619 isWorking: boolean;
1620 /** Native subagent work has no app run; runless entries form the live response. */
1621 runlessWorkActive?: boolean;
1622 activeTurnStartedAt?: string | null;
1623 turnDiffSummaries: ReadonlyArray<TurnDiffSummary>;
1624 supportsConversationRollback: boolean;
1625 threadStartCheckpointAvailable?: boolean;
1626 availableRevertTurnCounts?: ReadonlySet<number> | undefined;
1627 worktreeSetup?: WorktreeSetupSnapshot | null;
1628 toolCallVisibility?: ToolCallVisibility;
1629 revealedMessageId?: MessageId | null;
1630 },
1631 resolve: MessageResolver = m,
1632 ): MessagesTimelineRow[] {
1633 const timelineEntries = timelineRowEntries(input);
1634 const embeddedResultRunIds = new Set<RunId>();
1635 for (const entry of timelineEntries) {
1636 if ((entry.kind === "html-render" || entry.kind === "mcp-app") && entry.runId !== null) {
1637 embeddedResultRunIds.add(entry.runId);
1638 }
1639 }
1640 const isPendingApproval = (entry: WorkLogEntry) => {
1641 const item = entry.projectedItem?.item;
1642 return (
1643 item?.type === "approval_request" &&
1644 input.pendingApprovalRequestIds?.has(item.requestId) === true
1645 );
1646 };
1647 const turnDiffSummaryByAssistantMessageId = new Map<MessageId, TurnDiffSummary>();
1648 for (const summary of input.turnDiffSummaries) {
1649 if (summary.assistantMessageId) {
1650 turnDiffSummaryByAssistantMessageId.set(summary.assistantMessageId, summary);
1651 }
1652 }
1653 const unsettledRunId = deriveUnsettledRunId(input.latestRun ?? null, input.runningRunId ?? null);
1654 const revertTurnCountByUserMessageId = input.supportsConversationRollback
1655 ? deriveRevertTurnCountByUserMessageId({
1656 timelineEntries: input.timelineEntries,
1657 checkpoints: input.turnDiffSummaries,
1658 threadStartCheckpointAvailable: input.threadStartCheckpointAvailable === true,
1659 unsettledRunId,
1660 availableRevertTurnCounts: input.availableRevertTurnCounts,
1661 })
1662 : new Map<MessageId, number>();
1663 const nextRows: MessagesTimelineRow[] = [];
1664 const terminalAssistantMessageIds = deriveTerminalAssistantMessageIds(timelineEntries);
1665 const failedRunIds = failedTimelineRunIds(timelineEntries, input.latestRun ?? null);
1666 const itemizedRunIds = itemizedFailedRunIds(timelineEntries, failedRunIds);
1667 const liveSubagentEntryIds = liveSubagentCardEntryIds(timelineEntries);
1668 const retainedAssistantReplyIds = retainedAssistantReplyEntryIds(timelineEntries);
1669 const supersededFoldsByAnchorEntryId = deriveSupersededAttemptFolds(
1670 timelineEntries,
1671 failedRunIds,
1672 liveSubagentEntryIds,
1673 retainedAssistantReplyIds,
1674 );
1675 const supersededWorkItemIds = new Set(
1676 [...supersededFoldsByAnchorEntryId.values()].flatMap((fold) => fold.deferredWorkItemIds),
1677 );
1678 const activeVisualResponseRunIds = deriveActiveVisualResponseRunIds({
1679 timelineEntries: timelineEntries,
1680 unsettledRunId,
1681 isWorking: input.isWorking,
1682 });
1683 const runlessWorkActive = input.isWorking && input.runlessWorkActive === true;
1684 const foldsByAnchorEntryId =
1685 input.toolCallVisibility === "zen"
1686 ? new Map<string, TurnFold>()
1687 : deriveTurnFolds({
1688 timelineEntries: timelineEntries,
1689 terminalAssistantMessageIds,
1690 latestRun: input.latestRun ?? null,
1691 unfoldedRunIds: new Set([...activeVisualResponseRunIds, ...failedRunIds]),
1692 runlessWorkActive,
1693 liveSubagentEntryIds,
1694 retainedAssistantReplyEntryIds: retainedAssistantReplyIds,
1695 resolve,
1696 });
1697 const timelineEntryById = new Map(timelineEntries.map((entry) => [entry.id, entry]));
1698 const collapsedEntryIds = new Set<string>();
1699 const collapsedFoldMemberIds = new Set<string>();
1700 for (const fold of foldsByAnchorEntryId.values()) {
1701 if (!input.expandedRunIds?.has(fold.runId)) {
1702 for (const entryId of fold.hiddenEntryIds) {
1703 collapsedEntryIds.add(entryId);
1704 }
1705 for (const entryId of fold.entryIds) {
1706 collapsedFoldMemberIds.add(entryId);
1707 }
1708 }
1709 }
1710 const collapsedSupersededEntryIds = new Set<string>();
1711 for (const fold of supersededFoldsByAnchorEntryId.values()) {
1712 if (!input.expandedAttemptIds?.has(fold.attemptId)) {
1713 for (const entryId of fold.hiddenEntryIds) {
1714 collapsedSupersededEntryIds.add(entryId);
1715 }
1716 }
1717 }
1718 if (input.pendingApprovalRequestIds?.size) {
1719 for (const entry of timelineEntries) {
1720 if (entry.kind === "work" && isPendingApproval(entry.entry)) {
1721 collapsedEntryIds.delete(entry.id);
1722 collapsedSupersededEntryIds.delete(entry.id);
1723 }
1724 }
1725 }
1726 const runIdIsActiveResponse = (runId: RunId | null | undefined) =>
1727 runId == null ? runlessWorkActive : activeVisualResponseRunIds.has(runId);
1728 const workEntryIsInActiveRun = (entry: WorkLogEntry) =>
1729 input.isWorking &&
1730 entry.toolLifecycleStatus === "inProgress" &&
1731 (entry.runId == null ? runlessWorkActive : entry.runId === unsettledRunId);
1732
1733 const activeTurnHeaderIndex = input.isWorking
1734 ? lastResponseBoundaryIndex(timelineEntries) + 1
1735 : timelineEntries.length;
1736
1737 const activeToolEntries: Array<Extract<TimelineEntry, { kind: "work" }>> = [];
1738 if (input.isWorking && (unsettledRunId !== null || runlessWorkActive)) {
1739 let tailAttemptId: string | null | undefined;
1740 for (let index = timelineEntries.length - 1; index >= activeTurnHeaderIndex; index -= 1) {
1741 const entry = timelineEntries[index]!;
1742 if (
1743 entry.kind !== "work" ||
1744 entry.entry.tone === "error" ||
1745 entry.entry.sourceActivityKind === "runtime.error" ||
1746 entry.entry.itemType === "system_notice" ||
1747 entry.entry.itemType === "notification" ||
1748 entry.entry.itemType === "todo_list" ||
1749 entry.entry.questionAnswer !== undefined ||
1750 isPendingApproval(entry.entry) ||
1751 !runIdIsActiveResponse(entry.entry.runId) ||
1752 entry.entry.sourceActivityKind === "context-compaction" ||
1753 collapsedEntryIds.has(entry.id) ||
1754 collapsedSupersededEntryIds.has(entry.id) ||
1755 foldsByAnchorEntryId.has(entry.id) ||
1756 supersededFoldsByAnchorEntryId.has(entry.id)
1757 ) {
1758 break;
1759 }
1760 if (tailAttemptId === undefined) {
1761 tailAttemptId = entry.attempt?.id ?? null;
1762 } else if ((entry.attempt?.id ?? null) !== tailAttemptId) {
1763 break;
1764 }
1765 activeToolEntries.push(entry);
1766 }
1767 }
1768 activeToolEntries.reverse();
1769 const visibleActiveToolEntries = activeToolEntries.filter((entry) =>
1770 workEntryIsVisibleInGroup(entry.entry, true),
1771 );
1772 const activeWorkAnchor = activeToolEntries[0];
1773 const latestVisibleToolEntry = visibleActiveToolEntries.at(-1);
1774 const latestRunningToolEntry = visibleActiveToolEntries.findLast((entry) =>
1775 workEntryIsActiveTurnActivity(entry.entry),
1776 );
1777 const latestToolKeepsActivityLive =
1778 latestRunningToolEntry !== undefined ||
1779 (latestVisibleToolEntry !== undefined &&
1780 workEntryIndicatesToolSuccess(latestVisibleToolEntry.entry) &&
1781 !input.pendingApprovalRequestIds?.size);
1782 const latestToolFailed =
1783 latestRunningToolEntry === undefined &&
1784 latestVisibleToolEntry !== undefined &&
1785 latestVisibleToolEntry.entry.toolLifecycleStatus !== "declined" &&
1786 workEntryDisplayIndicatesToolFailure(latestVisibleToolEntry.entry);
1787
1788 const latestThoughtEntry = visibleActiveToolEntries.findLast(
1789 (entry) => entry.entry.itemType === "reasoning" && (entry.entry.detail?.trim() ?? "") !== "",
1790 );
1791 const activeWorkPlacementEntryId = latestVisibleToolEntry?.id;
1792 const activeWorkRow =
1793 activeWorkAnchor && latestVisibleToolEntry && !latestToolFailed
1794 ? (() => {
1795 const groupId = workGroupId(activeWorkAnchor.id);
1796 return {
1797 kind: "work-live" as const,
1798 id: latestToolKeepsActivityLive
1799 ? LIVE_ACTIVITY_ROW_ID
1800 : `work-live:${activeWorkAnchor.id}`,
1801 createdAt: activeWorkAnchor.createdAt,
1802 entry: (latestRunningToolEntry ?? latestVisibleToolEntry).entry,
1803 groupedEntries: visibleActiveToolEntries.map((entry) => entry.entry),
1804 groupId,
1805 expanded: input.expandedWorkGroupIds?.has(groupId) ?? false,
1806 active: latestToolKeepsActivityLive,
1807 ...(latestThoughtEntry ? { thought: latestThoughtEntry.entry } : {}),
1808 };
1809 })()
1810 : null;
1811 const activeWorkEntryIds = new Set(
1812 activeWorkRow !== null || latestToolFailed ? activeToolEntries.map((entry) => entry.id) : [],
1813 );
1814 // A bare `/compact` turn is the compaction itself: one compaction row stands in for its prompt
1815 // and working indicator, from the moment the turn starts. Likewise an answered "compact before
1816 // continuing?" question folds into the compaction it asked for.
1817 const compactionRuns = new Map<RunId, OrchestrationV2IdleCompaction | undefined>();
1818 const compactedRunIds = new Set<RunId>();
1819 const pendingResumeCompactionAgeByRunId = new Map<RunId, string>();
1820 const resumeCompactionAgeByEntryId = new Map<string, string>();
1821 for (const entry of timelineEntries) {
1822 if (
1823 entry.kind === "message" &&
1824 entry.message.runId !== null &&
1825 isCompactionCommandMessage(entry.message)
1826 ) {
1827 compactionRuns.set(entry.message.runId, idleCompactionOf(entry.message));
1828 } else if (entry.kind === "work" && entry.entry.runId) {
1829 if (timelineEntryIsCompaction(entry)) {
1830 compactedRunIds.add(entry.entry.runId);
1831 const age = pendingResumeCompactionAgeByRunId.get(entry.entry.runId);
1832 if (age !== undefined) {
1833 resumeCompactionAgeByEntryId.set(entry.id, age);
1834 pendingResumeCompactionAgeByRunId.delete(entry.entry.runId);
1835 }
1836 }
1837 const age = entry.entry.questionAnswer
1838 ? claudeResumeCompactionAge(entry.entry.questionAnswer)
1839 : null;
1840 if (age !== null) pendingResumeCompactionAgeByRunId.set(entry.entry.runId, age);
1841 }
1842 }
1843 const compactionTitle = (runId: RunId | null | undefined, entryId: string) => {
1844 if (runId == null) return undefined;
1845 const reason = compactionRuns.get(runId);
1846 if (reason !== undefined) return resolve(IDLE_COMPACTION_TITLES[reason]);
1847 const age = resumeCompactionAgeByEntryId.get(entryId);
1848 return age ? resolve(msg("Context compacted after {age} idle", { age })) : undefined;
1849 };
1850 const activeCompactionEntry = timelineEntries.find(
1851 (entry): entry is Extract<TimelineEntry, { kind: "work" }> =>
1852 timelineEntryIsCompaction(entry) &&
1853 entry.kind === "work" &&
1854 workEntryIsInActiveRun(entry.entry),
1855 );
1856 const activeRunIsCompaction =
1857 input.isWorking && unsettledRunId !== null && compactionRuns.has(unsettledRunId);
1858 // The item can finish before its run settles; only other work should keep activity visible.
1859 const compactionRunFinished =
1860 activeRunIsCompaction &&
1861 compactedRunIds.has(unsettledRunId) &&
1862 activeCompactionEntry === undefined;
1863 const compactionOnlyRunFinished =
1864 compactionRunFinished &&
1865 !timelineEntries.some(
1866 (entry) =>
1867 timelineEntryRunId(entry) === unsettledRunId &&
1868 !timelineEntryIsCompaction(entry) &&
1869 !(entry.kind === "message" && isCompactionCommandMessage(entry.message)),
1870 );
1871 const runningCompactionRunId =
1872 activeRunIsCompaction && !compactionRunFinished ? unsettledRunId : null;
1873 // Compacting on return holds back the message the user just sent, so the working row says why
1874 // it is waiting. Any other compaction shows only its live divider, never both.
1875 const compactsOnReturn =
1876 runningCompactionRunId !== null && compactionRuns.get(runningCompactionRunId) === "onReturn";
1877 // The question is answered mid-turn, so the row times this compaction, not the turn.
1878 const resumeCompactionEntry =
1879 activeCompactionEntry?.entry.runId != null &&
1880 resumeCompactionAgeByEntryId.has(activeCompactionEntry.id)
1881 ? activeCompactionEntry
1882 : undefined;
1883 const activeCompactionRunId = compactsOnReturn
1884 ? runningCompactionRunId
1885 : (resumeCompactionEntry?.entry.runId ?? null);
1886 const endedRunId = input.latestRun?.turnEnded === true ? input.latestRun.runId : null;
1887 const zenAnswerLanded =
1888 input.toolCallVisibility === "zen" &&
1889 endedRunId !== null &&
1890 timelineEntries.findLastIndex((entry) => timelineEntryRunId(entry) === endedRunId) >=
1891 activeTurnHeaderIndex;
1892 const appendWorkingRow = () => {
1893 if (compactionOnlyRunFinished || zenAnswerLanded) return;
1894 if (runningCompactionRunId !== null && activeCompactionRunId === null) return;
1895 nextRows.push({
1896 kind: "working",
1897 id: "working-indicator-row",
1898 createdAt:
1899 (compactsOnReturn ? undefined : resumeCompactionEntry?.entry.createdAt) ??
1900 input.activeTurnStartedAt ??
1901 null,
1902 ...(activeCompactionRunId !== null ? { compacting: true as const } : {}),
1903 });
1904 };
1905 let hasActivityRow = false;
1906 const hasActiveCompaction =
1907 activeCompactionEntry !== undefined || (activeRunIsCompaction && !compactionRunFinished);
1908 const appendActiveWorkRows = () => {
1909 if (activeWorkRow === null) return;
1910 nextRows.push(activeWorkRow);
1911 hasActivityRow ||= activeWorkRow.active;
1912 if (activeWorkRow.expanded) {
1913 nextRows.push(
1914 expandedWorkGroupRow(
1915 activeWorkRow.groupId,
1916 activeWorkRow.createdAt,
1917 activeWorkRow.groupedEntries,
1918 ),
1919 );
1920 }
1921 nextRows.push(
1922 ...viewedImagesRows(
1923 activeWorkRow.groupId,
1924 activeWorkRow.createdAt,
1925 activeWorkRow.groupedEntries,
1926 ),
1927 );
1928 };
1929
1930 for (let index = 0; index < timelineEntries.length; index += 1) {
1931 const timelineEntry = timelineEntries[index];
1932 if (!timelineEntry) {
1933 continue;
1934 }
1935
1936 if (input.isWorking && index === activeTurnHeaderIndex) {
1937 appendWorkingRow();
1938 }
1939
1940 if (timelineEntry.id === activeWorkPlacementEntryId) {
1941 appendActiveWorkRows();
1942 }
1943
1944 // A stopped compaction's own divider already says it stopped.
1945 if (
1946 timelineEntry.kind === "event" &&
1947 (timelineEntry.projectedItem.item.type === "run_interrupt_request" ||
1948 (timelineEntry.projectedItem.item.type === "run_interrupt_result" &&
1949 timelineEntry.projectedItem.item.runId !== null &&
1950 compactionRuns.has(timelineEntry.projectedItem.item.runId) &&
1951 compactedRunIds.has(timelineEntry.projectedItem.item.runId)))
1952 ) {
1953 continue;
1954 }
1955
1956 const turnFold = foldsByAnchorEntryId.get(timelineEntry.id);
1957 if (turnFold) {
1958 const deferredWorkItemIds = [...turnFold.entryIds].flatMap((entryId) => {
1959 const entry = timelineEntryById.get(entryId);
1960 return entry?.kind === "work" &&
1961 entry.entry.projectedItem?.item.deferredWork &&
1962 !supersededWorkItemIds.has(String(entry.entry.projectedItem.sourceItemId))
1963 ? [String(entry.entry.projectedItem.sourceItemId)]
1964 : [];
1965 });
1966 nextRows.push({
1967 kind: "turn-fold",
1968 id: `turn-fold:${turnFold.runId}`,
1969 ...(deferredWorkItemIds.length > 0 ? { deferredWorkItemIds } : {}),
1970 createdAt: turnFold.createdAt,
1971 runId: turnFold.runId,
1972 label: turnFold.label,
1973 expanded: input.expandedRunIds?.has(turnFold.runId) ?? false,
1974 });
1975 }
1976
1977 if (collapsedEntryIds.has(timelineEntry.id)) {
1978 continue;
1979 }
1980
1981 const supersededFold = supersededFoldsByAnchorEntryId.get(timelineEntry.id);
1982 if (supersededFold) {
1983 nextRows.push({
1984 kind: "attempt-fold",
1985 deferredWorkItemIds: supersededFold.deferredWorkItemIds,
1986 id: `attempt-fold:${supersededFold.attemptId}`,
1987 createdAt: supersededFold.createdAt,
1988 runId: supersededFold.runId,
1989 attemptId: supersededFold.attemptId,
1990 label: resolve(msg("Superseded attempt")),
1991 expanded: input.expandedAttemptIds?.has(supersededFold.attemptId) ?? false,
1992 });
1993 }
1994
1995 if (collapsedSupersededEntryIds.has(timelineEntry.id)) {
1996 continue;
1997 }
1998
1999 if (activeWorkEntryIds.has(timelineEntry.id)) {
2000 continue;
2001 }
2002
2003 if (
2004 timelineEntry.kind === "work" &&
2005 timelineEntry.entry.sourceActivityKind === "context-compaction"
2006 ) {
2007 const active = workEntryIsInActiveRun(timelineEntry.entry);
2008 if (
2009 active &&
2010 activeCompactionRunId !== null &&
2011 timelineEntry.entry.runId === activeCompactionRunId
2012 )
2013 continue;
2014 const compaction = timelineEntry.entry.structuredPayload;
2015 const compactionRunId = timelineEntry.entry.runId;
2016 const title = compactionTitle(compactionRunId, timelineEntry.id);
2017 const reason = compactionRunId == null ? undefined : compactionRuns.get(compactionRunId);
2018 const failed = compaction?.type === "compaction" && compaction.status === "failed";
2019 const failure = failed ? compaction.summary?.trim() || undefined : undefined;
2020 const compacted =
2021 !(active && reason) &&
2022 compaction?.type === "compaction" &&
2023 compaction.status !== "failed" &&
2024 compaction.status !== "cancelled" &&
2025 compaction.status !== "interrupted" &&
2026 !isOrchestrationV2WorkActive(compaction.status);
2027 nextRows.push({
2028 kind: "context-compaction",
2029 id: timelineEntry.id,
2030 ...(title ? { title } : {}),
2031 ...(compacted ? { compacted: true } : {}),
2032 ...(failed ? { failed: true } : {}),
2033 ...(failure ? { failure } : {}),
2034 createdAt: timelineEntry.createdAt,
2035 label:
2036 active && reason ? resolve(IDLE_COMPACTING_LABELS[reason]) : timelineEntry.entry.label,
2037 tokenCounts:
2038 compaction?.type === "compaction" ? contextCompactionTokenCounts(compaction) : null,
2039 active,
2040 });
2041 continue;
2042 }
2043
2044 if (
2045 timelineEntry.kind === "work" &&
2046 timelineEntry.entry.runId != null &&
2047 compactedRunIds.has(timelineEntry.entry.runId) &&
2048 timelineEntry.entry.questionAnswer !== undefined &&
2049 claudeResumeCompactionAge(timelineEntry.entry.questionAnswer) !== null
2050 ) {
2051 continue;
2052 }
2053
2054 if (timelineEntry.kind === "work") {
2055 if (
2056 isPendingApproval(timelineEntry.entry) ||
2057 (timelineEntry.entry.runId != null && itemizedRunIds.has(timelineEntry.entry.runId)) ||
2058 (timelineEntry.entry.itemType === "error" &&
2059 timelineEntry.entry.toolLifecycleStatus === "failed") ||
2060 timelineEntry.entry.tone === "error" ||
2061 timelineEntry.entry.sourceActivityKind === "runtime.error" ||
2062 timelineEntry.entry.itemType === "system_notice" ||
2063 timelineEntry.entry.itemType === "notification" ||
2064 timelineEntry.entry.itemType === "todo_list" ||
2065 timelineEntry.entry.questionAnswer !== undefined
2066 ) {
2067 nextRows.push({
2068 kind: "work",
2069 id: timelineEntry.id,
2070 createdAt: timelineEntry.createdAt,
2071 groupedEntries: [timelineEntry.entry],
2072 isExpandedToolGroup: false,
2073 });
2074 continue;
2075 }
2076 const groupedEntries = [timelineEntry.entry];
2077 let cursor = index + 1;
2078 while (cursor < timelineEntries.length) {
2079 const nextEntry = timelineEntries[cursor];
2080 if (
2081 !nextEntry ||
2082 nextEntry.kind !== "work" ||
2083 nextEntry.entry.sourceActivityKind === "context-compaction" ||
2084 (nextEntry.entry.itemType === "error" &&
2085 nextEntry.entry.toolLifecycleStatus === "failed") ||
2086 nextEntry.entry.tone === "error" ||
2087 nextEntry.entry.sourceActivityKind === "runtime.error" ||
2088 nextEntry.entry.itemType === "system_notice" ||
2089 nextEntry.entry.itemType === "notification" ||
2090 nextEntry.entry.itemType === "todo_list" ||
2091 nextEntry.entry.questionAnswer !== undefined ||
2092 isPendingApproval(nextEntry.entry) ||
2093 activeWorkEntryIds.has(nextEntry.id) ||
2094 collapsedEntryIds.has(nextEntry.id) ||
2095 collapsedSupersededEntryIds.has(nextEntry.id) ||
2096 foldsByAnchorEntryId.has(nextEntry.id) ||
2097 supersededFoldsByAnchorEntryId.has(nextEntry.id) ||
2098 (nextEntry.entry.runId ?? null) !== (timelineEntry.entry.runId ?? null) ||
2099 nextEntry.attempt?.id !== timelineEntry.attempt?.id
2100 ) {
2101 break;
2102 }
2103 groupedEntries.push(nextEntry.entry);
2104 cursor += 1;
2105 }
2106 const visibleGroupedEntries = groupedEntries.filter((entry) =>
2107 workEntryIsVisibleInGroup(entry, workEntryIsInActiveRun(entry)),
2108 );
2109 if (visibleGroupedEntries.length > 0) {
2110 const activeInProgressToolEntries = visibleGroupedEntries.filter(workEntryIsInActiveRun);
2111 if (activeInProgressToolEntries.length > 0) {
2112 const groupId = workGroupId(timelineEntry.id);
2113 const expanded = input.expandedWorkGroupIds?.has(groupId) ?? false;
2114 const latestActiveToolEntry = activeInProgressToolEntries.at(-1)!;
2115 nextRows.push({
2116 kind: "work-live",
2117 id: `work-live:${timelineEntry.id}`,
2118 createdAt: timelineEntry.createdAt,
2119 entry: latestActiveToolEntry,
2120 groupedEntries: visibleGroupedEntries,
2121 groupId,
2122 expanded,
2123 active: true,
2124 });
2125 hasActivityRow = true;
2126 if (expanded) {
2127 nextRows.push(
2128 expandedWorkGroupRow(groupId, timelineEntry.createdAt, visibleGroupedEntries),
2129 );
2130 }
2131 } else if (
2132 visibleGroupedEntries.length === 1 &&
2133 workLogEntryIsToolLike(visibleGroupedEntries[0]!)
2134 ) {
2135 const singleEntry = visibleGroupedEntries[0]!;
2136 nextRows.push({
2137 kind: "work",
2138 id: timelineEntry.id,
2139 createdAt: timelineEntry.createdAt,
2140 groupedEntries: visibleGroupedEntries,
2141 isExpandedToolGroup: false,
2142 displayLabel:
2143 toolGroupAction(singleEntry) === "edit"
2144 ? summarizeToolGroup(visibleGroupedEntries, resolve).summary
2145 : singleToolCallLabel(singleEntry, resolve),
2146 });
2147 } else {
2148 const groupId = workGroupId(timelineEntry.id);
2149 const expanded = input.expandedWorkGroupIds?.has(groupId) ?? false;
2150 const summaryKind = toolGroupSummaryKind(visibleGroupedEntries);
2151 const primarySourceEntry = visibleGroupedEntries.find(
2152 (entry) => entry.toolSource !== undefined,
2153 );
2154 const primarySourceKey = primarySourceEntry?.toolSource?.key;
2155 const primarySourceIcon = primarySourceKey
2156 ? (visibleGroupedEntries.find(
2157 (entry) =>
2158 entry.toolSource?.key === primarySourceKey && entry.toolIcon !== undefined,
2159 )?.toolIcon ?? primarySourceEntry?.toolSource?.icon)
2160 : undefined;
2161 const groupToolSurface =
2162 primarySourceEntry?.toolSurface ??
2163 visibleGroupedEntries.findLast((entry) => entry.toolSurface !== undefined)?.toolSurface;
2164 const groupToolIcon =
2165 primarySourceIcon ??
2166 visibleGroupedEntries.findLast((entry) => entry.toolIcon !== undefined)?.toolIcon;
2167 const latestToolEntry = visibleGroupedEntries.findLast(workLogEntryIsToolLike);
2168 const singleEntry =
2169 visibleGroupedEntries.length === 1 ? (visibleGroupedEntries[0] ?? null) : null;
2170 nextRows.push({
2171 kind: "work-toggle",
2172 id: `work-toggle:${timelineEntry.id}`,
2173 createdAt: timelineEntry.createdAt,
2174 runId: timelineEntry.entry.runId ?? null,
2175 groupId,
2176 hiddenCount: visibleGroupedEntries.length,
2177 expanded,
2178 summary:
2179 singleEntry !== null && !workLogEntryIsToolLike(singleEntry)
2180 ? singleEntry.label
2181 : summarizeToolGroup(visibleGroupedEntries, resolve).summary,
2182 summaryKind,
2183 ...(groupToolSurface ? { toolSurface: groupToolSurface } : {}),
2184 ...(groupToolIcon ? { toolIcon: groupToolIcon } : {}),
2185 hasFailure:
2186 latestToolEntry !== undefined &&
2187 workEntryDisplayIndicatesToolFailure(latestToolEntry),
2188 });
2189 if (expanded) {
2190 nextRows.push(
2191 expandedWorkGroupRow(groupId, timelineEntry.createdAt, visibleGroupedEntries),
2192 );
2193 }
2194 }
2195 nextRows.push(
2196 ...viewedImagesRows(
2197 workGroupId(timelineEntry.id),
2198 timelineEntry.createdAt,
2199 visibleGroupedEntries,
2200 ),
2201 );
2202 }
2203 index = cursor - 1;
2204 continue;
2205 }
2206
2207 if (timelineEntry.kind === "proposed-plan") {
2208 nextRows.push({
2209 kind: "proposed-plan",
2210 id: timelineEntry.id,
2211 createdAt: timelineEntry.createdAt,
2212 proposedPlan: timelineEntry.proposedPlan,
2213 });
2214 continue;
2215 }
2216
2217 if (timelineEntry.kind === "html-render") {
2218 nextRows.push({
2219 kind: "html-render",
2220 id: timelineEntry.id,
2221 createdAt: timelineEntry.createdAt,
2222 htmlRender: timelineEntry.htmlRender,
2223 });
2224 continue;
2225 }
2226
2227 if (timelineEntry.kind === "sent-message") {
2228 nextRows.push({
2229 kind: "sent-message",
2230 id: timelineEntry.id,
2231 createdAt: timelineEntry.createdAt,
2232 text: timelineEntry.text,
2233 });
2234 continue;
2235 }
2236
2237 if (timelineEntry.kind === "mcp-app") {
2238 nextRows.push({
2239 kind: "mcp-app",
2240 id: timelineEntry.id,
2241 createdAt: timelineEntry.createdAt,
2242 sourceThreadId: timelineEntry.sourceThreadId,
2243 itemId: timelineEntry.itemId,
2244 revision: timelineEntry.revision,
2245 mcpApp: timelineEntry.mcpApp,
2246 });
2247 continue;
2248 }
2249
2250 if (timelineEntry.kind === "event") {
2251 const previous = nextRows.at(-1);
2252 if (
2253 timelineEntry.projectedItem.item.type === "subagent" &&
2254 previous?.kind === "event" &&
2255 previous.projectedItem.item.type === "subagent" &&
2256 previous.projectedItem.item.runId === timelineEntry.projectedItem.item.runId &&
2257 previous.projectedItem.item.providerTurnId ===
2258 timelineEntry.projectedItem.item.providerTurnId
2259 ) {
2260 nextRows[nextRows.length - 1] = {
2261 ...previous,
2262 subagents: [
2263 ...(previous.subagents ?? [previous.projectedItem]),
2264 timelineEntry.projectedItem,
2265 ],
2266 };
2267 continue;
2268 }
2269 nextRows.push({
2270 kind: "event",
2271 id: timelineEntry.id,
2272 createdAt: timelineEntry.createdAt,
2273 projectedItem: timelineEntry.projectedItem,
2274 });
2275 continue;
2276 }
2277
2278 const compactionRunId = timelineEntry.message.runId;
2279 const compactionRun =
2280 compactionRunId !== null && isCompactionCommandMessage(timelineEntry.message);
2281 if (compactionRun) {
2282 if (!compactedRunIds.has(compactionRunId) && compactionRunId !== activeCompactionRunId) {
2283 const pending = compactionRunId === runningCompactionRunId;
2284 const reason = compactionRuns.get(compactionRunId);
2285 nextRows.push({
2286 kind: "context-compaction",
2287 id: `compaction:${compactionRunId}`,
2288 createdAt: timelineEntry.createdAt,
2289 label: pending
2290 ? reason
2291 ? resolve(IDLE_COMPACTING_LABELS[reason])
2292 : resolve(msg("Compacting context"))
2293 : resolve(msg("Context compaction")),
2294 tokenCounts: null,
2295 active: pending,
2296 });
2297 }
2298 continue;
2299 }
2300
2301 const assistantResponseStillInProgress =
2302 timelineEntry.message.role === "assistant" &&
2303 runIdIsActiveResponse(timelineEntry.message.runId);
2304
2305 const showAssistantMeta =
2306 timelineEntry.message.role === "assistant" &&
2307 terminalAssistantMessageIds.has(timelineEntry.message.id) &&
2308 !assistantResponseStillInProgress;
2309
2310 nextRows.push({
2311 kind: "message",
2312 id: timelineEntry.id,
2313 createdAt: timelineEntry.createdAt,
2314 message: timelineEntry.message,
2315 ...(timelineEntry.projectedItem === undefined
2316 ? {}
2317 : { projectedItem: timelineEntry.projectedItem }),
2318 showAssistantMeta,
2319 suppressEmptyResponse:
2320 timelineEntry.message.role === "assistant" &&
2321 timelineEntry.message.runId != null &&
2322 embeddedResultRunIds.has(timelineEntry.message.runId),
2323 showAssistantCopyButton: showAssistantMeta,
2324 assistantCopyStreaming: timelineEntry.message.streaming || assistantResponseStillInProgress,
2325 assistantTurnDiffSummary:
2326 timelineEntry.message.role === "assistant"
2327 ? turnDiffSummaryByAssistantMessageId.get(timelineEntry.message.id)
2328 : undefined,
2329 revertTurnCount:
2330 timelineEntry.message.role === "user"
2331 ? revertTurnCountByUserMessageId.get(timelineEntry.message.id)
2332 : undefined,
2333 });
2334 }
2335
2336 const setupHandedOff =
2337 input.worktreeSetup !== null &&
2338 input.worktreeSetup !== undefined &&
2339 worktreeSetupAgentStarted(input.worktreeSetup) &&
2340 input.latestRun?.startedAt != null;
2341 const setupOwnsWorkingSlot =
2342 !setupHandedOff &&
2343 (input.worktreeSetup?.phase === "running" || input.worktreeSetup?.phase === "done");
2344 if (input.worktreeSetup && (!setupHandedOff || input.worktreeSetup.phase !== "running")) {
2345 const setupRow = {
2346 kind: "worktree-setup",
2347 id: WORKTREE_SETUP_ROW_ID,
2348 createdAt: input.worktreeSetup.startedAt,
2349 snapshot: input.worktreeSetup,
2350 embedded: setupHandedOff,
2351 } as const;
2352 const firstUserRowIndex = nextRows.findIndex(
2353 (row) => row.kind === "message" && row.message.role === "user",
2354 );
2355 const workingRowIndex = setupOwnsWorkingSlot
2356 ? nextRows.findIndex((row) => row.kind === "working")
2357 : -1;
2358 if (workingRowIndex >= 0) {
2359 nextRows.splice(workingRowIndex + 1, 0, setupRow);
2360 } else {
2361 const insertAt = firstUserRowIndex >= 0 ? firstUserRowIndex + 1 : nextRows.length;
2362 nextRows.splice(
2363 insertAt,
2364 0,
2365 ...(setupOwnsWorkingSlot
2366 ? [
2367 {
2368 kind: "working",
2369 id: "working-indicator-row",
2370 createdAt: input.worktreeSetup.startedAt,
2371 } as const,
2372 setupRow,
2373 ]
2374 : [setupRow]),
2375 );
2376 }
2377 }
2378
2379 const hasWorkingRow = nextRows.some((row) => row.kind === "working");
2380 if (input.isWorking && !hasWorkingRow && activeTurnHeaderIndex === timelineEntries.length) {
2381 appendWorkingRow();
2382 }
2383 if (
2384 input.isWorking &&
2385 input.latestRun?.turnEnded !== true &&
2386 !setupOwnsWorkingSlot &&
2387 !hasActiveCompaction &&
2388 !compactionOnlyRunFinished &&
2389 (latestToolFailed || (!hasActivityRow && !input.pendingApprovalRequestIds?.size))
2390 ) {
2391 const failedGroupAnchor = latestToolFailed ? activeWorkAnchor : undefined;
2392 if (failedGroupAnchor) {
2393 const groupId = workGroupId(failedGroupAnchor.id);
2394 const expanded = input.expandedWorkGroupIds?.has(groupId) ?? false;
2395 const groupedEntries = visibleActiveToolEntries.map((entry) => entry.entry);
2396 nextRows.push({
2397 kind: "thinking",
2398 id: LIVE_ACTIVITY_ROW_ID,
2399 createdAt: input.activeTurnStartedAt ?? null,
2400 groupId,
2401 expanded,
2402 });
2403 if (expanded) {
2404 nextRows.push(expandedWorkGroupRow(groupId, failedGroupAnchor.createdAt, groupedEntries));
2405 }
2406 nextRows.push(...viewedImagesRows(groupId, failedGroupAnchor.createdAt, groupedEntries));
2407 } else {
2408 const waitingOn =
2409 unsettledRunId === null
2410 ? 0
2411 : runningSubagentsAtRunTail(input.timelineEntries, unsettledRunId);
2412 nextRows.push({
2413 kind: "thinking",
2414 id: LIVE_ACTIVITY_ROW_ID,
2415 createdAt: input.activeTurnStartedAt ?? null,
2416 ...(waitingOn > 0 ? { label: waitingOnSubagentsLabel(waitingOn, resolve) } : {}),
2417 });
2418 }
2419 }
2420
2421 const result = attachTrailingToolGroupsToAssistant(
2422 attachCreatedThreadSummaries(nextRows, timelineEntries, collapsedFoldMemberIds),
2423 );
2424 return result.map((row, index) => {
2425 if (timelineRowIsWorkLog(row) && timelineRowIsWorkLog(result[index + 1])) {
2426 return { ...row, continuesWorkLog: true };
2427 }
2428 if (!timelineRowIsOwnUserMessage(row)) return row;
2429 const previous = result[index - 1];
2430 const groupedWithNext = timelineRowIsOwnUserMessage(result[index + 1]);
2431 const groupedWithPrevious = timelineRowIsOwnUserMessage(previous);
2432 const continuesSteer =
2433 groupedWithPrevious && messageIsSteer(row.message) && messageIsSteer(previous.message);
2434 if (!groupedWithNext && !groupedWithPrevious) return row;
2435 return { ...row, groupedWithNext, groupedWithPrevious, continuesSteer };
2436 });
2437 }
2438
2439 function timelineRowIsOwnUserMessage(
2440 row: MessagesTimelineRow | undefined,
2441 ): row is Extract<MessagesTimelineRow, { kind: "message" }> {
2442 return (
2443 row?.kind === "message" &&
2444 row.message.role === "user" &&
2445 resolveUserMessagePresentation(row.message).attribution === null
2446 );
2447 }
2448
2449 function messageIsSteer(message: ChatMessage): boolean {
2450 return message.inputIntent === "steer" || message.inputIntent === "promoted_queued_to_steer";
2451 }
2452
2453 function timelineRowIsWorkLog(row: MessagesTimelineRow | undefined): boolean {
2454 return (
2455 row !== undefined &&
2456 (row.kind === "work" ||
2457 row.kind === "work-toggle" ||
2458 row.kind === "work-live" ||
2459 row.kind === "thinking")
2460 );
2461 }
2462
2463 function attachCreatedThreadSummaries(
2464 rows: MessagesTimelineRow[],
2465 timelineEntries: ReadonlyArray<TimelineEntry>,
2466 collapsedFoldMemberIds: ReadonlySet<string>,
2467 ): MessagesTimelineRow[] {
2468 const terminalIndexes = new Map<RunId, number>();
2469 const createdByRun = new Map<RunId, Array<Extract<MessagesTimelineRow, { kind: "event" }>>>();
2470 for (const [index, row] of rows.entries()) {
2471 if (row.kind === "message" && row.showAssistantMeta && row.message.runId) {
2472 terminalIndexes.set(row.message.runId, index);
2473 }
2474 }
2475 for (const entry of timelineEntries) {
2476 const projectedItem =
2477 entry.kind === "work"
2478 ? entry.entry.projectedItem
2479 : entry.kind === "event"
2480 ? entry.projectedItem
2481 : undefined;
2482 if (projectedItem?.item.type === "thread_created" && projectedItem.item.runId) {
2483 const runId = projectedItem.item.runId;
2484 const entries = createdByRun.get(runId) ?? [];
2485 entries.push({ kind: "event", id: entry.id, createdAt: entry.createdAt, projectedItem });
2486 createdByRun.set(runId, entries);
2487 }
2488 }
2489 return rows.flatMap((row, index): MessagesTimelineRow[] => {
2490 if (row.kind === "event" && row.projectedItem.item.type === "thread_created") {
2491 const runId = row.projectedItem.item.runId;
2492 const terminalIndex = runId === null ? undefined : terminalIndexes.get(runId);
2493 if (
2494 terminalIndex !== undefined &&
2495 (collapsedFoldMemberIds.has(row.id) || index > terminalIndex)
2496 )
2497 return [];
2498 }
2499 if (row.kind === "message" && row.showAssistantMeta && row.message.runId) {
2500 return [
2501 row,
2502 ...(createdByRun.get(row.message.runId) ?? []).map((entry) => ({
2503 ...entry,
2504 id: `summary:${entry.id}`,
2505 resourceSummary: true,
2506 })),
2507 ];
2508 }
2509 return [row];
2510 });
2511 }
2512
2513 const WORKTREE_SETUP_ROW_ID = "worktree-setup-row";
2514
2515 export type MessagesTimelineRowsInput = Parameters<typeof deriveMessagesTimelineRows>[0];
2516
2517 interface MessagesTimelineRowsProjection {
2518 readonly input: MessagesTimelineRowsInput;
2519 readonly rows: MessagesTimelineRow[];
2520 }
2521
2522 /**
2523 * Runless (imported V1) turns and work after a steer fold under synthetic
2524 * keys, so the entry's own run id is not enough to open them.
2525 */
2526 export function timelineTurnFoldRunIdsByEntryId(
2527 input: Pick<
2528 MessagesTimelineRowsInput,
2529 | "timelineEntries"
2530 | "latestRun"
2531 | "isWorking"
2532 | "runlessWorkActive"
2533 | "runningRunId"
2534 | "toolCallVisibility"
2535 | "revealedMessageId"
2536 >,
2537 ): ReadonlyMap<string, RunId> {
2538 const byEntryId = new Map<string, RunId>();
2539 for (const fold of deriveTimelineTurnFolds(input).values()) {
2540 for (const entryId of fold.hiddenEntryIds) byEntryId.set(entryId, fold.runId);
2541 }
2542 return byEntryId;
2543 }
2544
2545 function sameCheckpointSummaries(
2546 previous: MessagesTimelineRowsInput["turnDiffSummaries"],
2547 next: MessagesTimelineRowsInput["turnDiffSummaries"],
2548 ): boolean {
2549 if (previous === next) return true;
2550 if (previous.length !== next.length) return false;
2551 for (const [index, summary] of previous.entries()) {
2552 if (!shallow(summary, next[index])) return false;
2553 }
2554 return true;
2555 }
2556
2557 function replaceStreamingMessageRows(
2558 input: MessagesTimelineRowsInput,
2559 previous: MessagesTimelineRowsProjection,
2560 ): MessagesTimelineRow[] | null {
2561 const {
2562 timelineEntries: previousEntries,
2563 latestRun: previousRun,
2564 turnDiffSummaries: previousCheckpoints,
2565 expandedRunIds: previousExpandedRuns,
2566 expandedAttemptIds: previousExpandedAttempts,
2567 expandedWorkGroupIds: previousExpandedGroups,
2568 pendingApprovalRequestIds: previousPendingApprovalRequestIds,
2569 availableRevertTurnCounts: previousAvailableRevertTurnCounts,
2570 ...previousContext
2571 } = previous.input;
2572 const {
2573 timelineEntries,
2574 latestRun,
2575 turnDiffSummaries,
2576 expandedRunIds,
2577 expandedAttemptIds,
2578 expandedWorkGroupIds,
2579 pendingApprovalRequestIds,
2580 availableRevertTurnCounts,
2581 ...context
2582 } = input;
2583 // Shell/checkpoint selectors rebuild summaries per event; compare contents.
2584 if (
2585 timelineEntries.length !== previousEntries.length ||
2586 !shallow(previousContext, context) ||
2587 !shallow(previousRun, latestRun) ||
2588 !shallow(previousExpandedRuns, expandedRunIds) ||
2589 !shallow(previousExpandedAttempts, expandedAttemptIds) ||
2590 !shallow(previousExpandedGroups, expandedWorkGroupIds) ||
2591 !shallow(previousPendingApprovalRequestIds, pendingApprovalRequestIds) ||
2592 !shallow(previousAvailableRevertTurnCounts, availableRevertTurnCounts) ||
2593 !sameCheckpointSummaries(previousCheckpoints, turnDiffSummaries)
2594 ) {
2595 return null;
2596 }
2597 const replacements = new Map<ChatMessage, Extract<TimelineEntry, { kind: "message" }>>();
2598 const thoughts = new Map<string, WorkLogEntry>();
2599 const plans = new Map<string, ProposedPlan>();
2600 for (let index = 0; index < timelineEntries.length; index += 1) {
2601 const entry = timelineEntries[index]!;
2602 const previousEntry = previousEntries[index]!;
2603 if (entry === previousEntry) continue;
2604 if (
2605 entry.kind !== previousEntry.kind ||
2606 entry.id !== previousEntry.id ||
2607 entry.createdAt !== previousEntry.createdAt ||
2608 entry.attempt !== previousEntry.attempt
2609 ) {
2610 return null;
2611 }
2612 if (entry.kind === "work" && previousEntry.kind === "work") {
2613 if (!isStreamingThoughtUpdate(previousEntry.entry, entry.entry)) return null;
2614 thoughts.set(entry.id, entry.entry);
2615 continue;
2616 }
2617 if (entry.kind === "proposed-plan" && previousEntry.kind === "proposed-plan") {
2618 const { planMarkdown: _before, updatedAt: _beforeAt, ...before } = previousEntry.proposedPlan;
2619 const { planMarkdown: _after, updatedAt: _afterAt, ...after } = entry.proposedPlan;
2620 if (!shallow(before, after)) return null;
2621 plans.set(entry.id, entry.proposedPlan);
2622 continue;
2623 }
2624 if (entry.kind !== "message" || previousEntry.kind !== "message") return null;
2625 if (
2626 entry.projectedItem !== previousEntry.projectedItem &&
2627 (entry.projectedItem === undefined ||
2628 previousEntry.projectedItem === undefined ||
2629 !isStreamingTurnItemTextUpdate(previousEntry.projectedItem, entry.projectedItem))
2630 ) {
2631 return null;
2632 }
2633 if (
2634 entry.message === previousEntry.message &&
2635 entry.projectedItem === previousEntry.projectedItem
2636 )
2637 continue;
2638 if (!isStreamingMessageTextUpdate(previousEntry.message, entry.message)) return null;
2639 replacements.set(previousEntry.message, entry);
2640 }
2641 if (replacements.size === 0 && thoughts.size === 0 && plans.size === 0) return previous.rows;
2642 // Rows settle superseded thinking after tool visibility filtering, which these entries
2643 // have not seen; the fast path keeps item status, so the row's settled status still holds.
2644 const patchedThoughts = new Map<WorkLogEntry, WorkLogEntry>();
2645 const patchThought = (entry: WorkLogEntry) => {
2646 const thought = thoughts.get(entry.id);
2647 if (!thought) return entry;
2648 let patched = patchedThoughts.get(entry);
2649 if (!patched) {
2650 patched =
2651 entry.toolLifecycleStatus === thought.toolLifecycleStatus ||
2652 entry.toolLifecycleStatus === undefined
2653 ? thought
2654 : { ...thought, toolLifecycleStatus: entry.toolLifecycleStatus };
2655 patchedThoughts.set(entry, patched);
2656 }
2657 return patched;
2658 };
2659 const patchedGroups = new Map<WorkLogEntry[], WorkLogEntry[]>();
2660 const patchGroup = (group: WorkLogEntry[]) => {
2661 if (!group.some((entry) => thoughts.has(entry.id))) return group;
2662 const patched = patchedGroups.get(group) ?? group.map(patchThought);
2663 patchedGroups.set(group, patched);
2664 return patched;
2665 };
2666 const patchedLiveThoughtIds = new Set<string>();
2667 const rows = previous.rows.map((row): MessagesTimelineRow => {
2668 if (row.kind === "proposed-plan") {
2669 const proposedPlan = plans.get(row.id);
2670 return proposedPlan ? { ...row, proposedPlan } : row;
2671 }
2672 if (row.kind === "work-live") {
2673 const groupedEntries = patchGroup(row.groupedEntries);
2674 if (groupedEntries === row.groupedEntries) return row;
2675 for (const entry of groupedEntries) {
2676 if (thoughts.has(entry.id)) patchedLiveThoughtIds.add(entry.id);
2677 }
2678 return {
2679 ...row,
2680 entry: patchThought(row.entry),
2681 groupedEntries,
2682 ...(row.thought ? { thought: patchThought(row.thought) } : {}),
2683 };
2684 }
2685 if (row.kind === "work") {
2686 const groupedEntries = patchGroup(row.groupedEntries);
2687 return groupedEntries === row.groupedEntries ? row : { ...row, groupedEntries };
2688 }
2689 if (row.kind !== "message" && row.kind !== "assistant-meta") return row;
2690 const entry = replacements.get(row.message);
2691 return entry
2692 ? {
2693 ...row,
2694 message: entry.message,
2695 ...(entry.projectedItem === undefined ? {} : { projectedItem: entry.projectedItem }),
2696 }
2697 : row;
2698 });
2699 // Only a live row holds thinking without deriving a label from its text. Settled
2700 // groups, folded turns, and work toggles summarize it, so they need the full rebuild.
2701 for (const id of thoughts.keys()) if (!patchedLiveThoughtIds.has(id)) return null;
2702 return rows;
2703 }
2704
2705 /**
2706 * Rows read a thought's text only through its blankness (visibility, the live
2707 * thought line) and through labels that live rows do not store.
2708 */
2709 function isStreamingThoughtUpdate(previous: WorkLogEntry, next: WorkLogEntry): boolean {
2710 if (
2711 previous.itemType !== "reasoning" ||
2712 previous.projectedItem === undefined ||
2713 next.projectedItem === undefined ||
2714 !isStreamingTurnItemTextUpdate(previous.projectedItem, next.projectedItem) ||
2715 Boolean(previous.detail?.trim()) !== Boolean(next.detail?.trim())
2716 ) {
2717 return false;
2718 }
2719 const {
2720 detail: _before,
2721 structuredPayload: _beforeItem,
2722 projectedItem: _beforeRow,
2723 ...rest
2724 } = previous;
2725 const {
2726 detail: _after,
2727 structuredPayload: _afterItem,
2728 projectedItem: _afterRow,
2729 ...nextRest
2730 } = next;
2731 return shallow(rest, nextRest);
2732 }
2733
2734 export function deriveMessagesTimelineRowsWithState(
2735 input: MessagesTimelineRowsInput,
2736 previous: MessagesTimelineRowsProjection | null = null,
2737 resolve: MessageResolver = m,
2738 ): MessagesTimelineRowsProjection {
2739 return {
2740 input,
2741 rows:
2742 (previous === null ? null : replaceStreamingMessageRows(input, previous)) ??
2743 deriveMessagesTimelineRows(input, resolve),
2744 };
2745 }
2746
2747 export function computeStableMessagesTimelineRows(
2748 rows: MessagesTimelineRow[],
2749 previous: StableMessagesTimelineRowsState,
2750 ): StableMessagesTimelineRowsState {
2751 const next = new Map<string, MessagesTimelineRow>();
2752 let anyChanged = rows.length !== previous.byId.size;
2753
2754 const result = rows.map((row, index) => {
2755 const prevRow = previous.byId.get(row.id);
2756 const nextRow = prevRow && isRowUnchanged(prevRow, row) ? prevRow : row;
2757 next.set(row.id, nextRow);
2758 if (!anyChanged && previous.result[index] !== nextRow) {
2759 anyChanged = true;
2760 }
2761 return nextRow;
2762 });
2763
2764 return anyChanged ? { byId: next, result } : previous;
2765 }
2766
2767 function isRowUnchanged(a: MessagesTimelineRow, b: MessagesTimelineRow): boolean {
2768 if (a.kind !== b.kind || a.id !== b.id) return false;
2769
2770 switch (a.kind) {
2771 case "working":
2772 return (
2773 a.createdAt === (b as typeof a).createdAt && a.compacting === (b as typeof a).compacting
2774 );
2775 case "thinking": {
2776 const bt = b as typeof a;
2777 return (
2778 a.createdAt === bt.createdAt &&
2779 a.groupId === bt.groupId &&
2780 a.expanded === bt.expanded &&
2781 a.label === bt.label
2782 );
2783 }
2784 case "worktree-setup":
2785 return a.snapshot === (b as typeof a).snapshot;
2786
2787 case "assistant-meta": {
2788 const bm = b as typeof a;
2789 return (
2790 a.createdAt === bm.createdAt &&
2791 a.projectedItem === bm.projectedItem &&
2792 a.message === bm.message &&
2793 a.showAssistantCopyButton === bm.showAssistantCopyButton &&
2794 a.assistantCopyStreaming === bm.assistantCopyStreaming
2795 );
2796 }
2797
2798 case "attempt-fold":
2799 case "turn-fold": {
2800 const bf = b as typeof a;
2801 const anchors = a.deferredWorkItemIds ?? [];
2802 const nextAnchors = bf.deferredWorkItemIds ?? [];
2803 return (
2804 a.createdAt === bf.createdAt &&
2805 a.label === bf.label &&
2806 a.expanded === bf.expanded &&
2807 anchors.length === nextAnchors.length &&
2808 anchors.every((id, index) => id === nextAnchors[index])
2809 );
2810 }
2811
2812 case "context-compaction": {
2813 const bc = b as typeof a;
2814 return (
2815 a.createdAt === bc.createdAt &&
2816 a.label === bc.label &&
2817 a.active === bc.active &&
2818 a.title === bc.title &&
2819 a.failed === bc.failed &&
2820 a.failure === bc.failure
2821 );
2822 }
2823
2824 case "proposed-plan":
2825 return a.proposedPlan === (b as typeof a).proposedPlan;
2826
2827 case "viewed-images": {
2828 const bv = b as typeof a;
2829 return (
2830 a.createdAt === bv.createdAt &&
2831 a.paths.length === bv.paths.length &&
2832 a.paths.every((path, index) => path === bv.paths[index])
2833 );
2834 }
2835
2836 case "html-render": {
2837 // Tool updates rebuild entries; preserve frames for unchanged pages.
2838 const bh = b as typeof a;
2839 return a.createdAt === bh.createdAt && htmlRenderReferencesEqual(a.htmlRender, bh.htmlRender);
2840 }
2841
2842 case "sent-message": {
2843 const bs = b as typeof a;
2844 return a.createdAt === bs.createdAt && a.text === bs.text;
2845 }
2846
2847 case "mcp-app": {
2848 const bm = b as typeof a;
2849 return (
2850 a.createdAt === bm.createdAt &&
2851 a.revision === bm.revision &&
2852 mcpAppReferencesEqual(a.mcpApp, bm.mcpApp)
2853 );
2854 }
2855
2856 case "event":
2857 return (
2858 a.projectedItem === (b as typeof a).projectedItem &&
2859 a.resourceSummary === (b as typeof a).resourceSummary &&
2860 Equal.equals(a.subagents, (b as typeof a).subagents)
2861 );
2862
2863 case "work": {
2864 const bw = b as typeof a;
2865 return (
2866 a.isExpandedToolGroup === bw.isExpandedToolGroup &&
2867 a.displayLabel === bw.displayLabel &&
2868 Equal.equals(a.groupedEntries, bw.groupedEntries)
2869 );
2870 }
2871
2872 case "work-live": {
2873 const bw = b as typeof a;
2874 return (
2875 a.createdAt === bw.createdAt &&
2876 a.groupId === bw.groupId &&
2877 a.expanded === bw.expanded &&
2878 a.active === bw.active &&
2879 Equal.equals(a.entry, bw.entry) &&
2880 Equal.equals(a.groupedEntries, bw.groupedEntries)
2881 );
2882 }
2883
2884 case "work-toggle": {
2885 const bw = b as typeof a;
2886 return (
2887 a.createdAt === bw.createdAt &&
2888 a.runId === bw.runId &&
2889 a.groupId === bw.groupId &&
2890 a.hiddenCount === bw.hiddenCount &&
2891 a.expanded === bw.expanded &&
2892 a.summary === bw.summary &&
2893 a.summaryKind === bw.summaryKind &&
2894 a.toolSurface === bw.toolSurface &&
2895 Equal.equals(a.toolIcon, bw.toolIcon) &&
2896 a.hasFailure === bw.hasFailure
2897 );
2898 }
2899
2900 case "message": {
2901 const bm = b as typeof a;
2902 return (
2903 a.message === bm.message &&
2904 a.projectedItem === bm.projectedItem &&
2905 a.showAssistantMeta === bm.showAssistantMeta &&
2906 a.suppressEmptyResponse === bm.suppressEmptyResponse &&
2907 a.showAssistantCopyButton === bm.showAssistantCopyButton &&
2908 a.assistantCopyStreaming === bm.assistantCopyStreaming &&
2909 a.assistantTurnDiffSummary === bm.assistantTurnDiffSummary &&
2910 a.revertTurnCount === bm.revertTurnCount &&
2911 a.groupedWithNext === bm.groupedWithNext &&
2912 a.groupedWithPrevious === bm.groupedWithPrevious &&
2913 a.continuesSteer === bm.continuesSteer
2914 );
2915 }
2916 }
2917 }
2918
2919 export function handoffRunsSignature(runs: ReadonlyArray<HandoffTimelineRun>): string {
2920 return runs
2921 .map(
2922 (run) =>
2923 `${run.id}\0${run.providerInstanceId}\0${run.ordinal}\0${run.modelSelection.instanceId}\0${run.modelSelection.model}`,
2924 )
2925 .join("\n");
2926 }
2927
2928 // Expanded-id sets can be rebuilt during render; comparing them by content keeps
2929 // the render-time state update in useIncrementalTimelineRows from repeating forever.
2930 export function sameRowsInput(
2931 left: MessagesTimelineRowsInput,
2932 right: MessagesTimelineRowsInput,
2933 ): boolean {
2934 for (const key of Object.keys(right) as Array<keyof MessagesTimelineRowsInput>) {
2935 const previous = left[key];
2936 const next = right[key];
2937 if (Object.is(previous, next)) continue;
2938 if (previous instanceof Set && next instanceof Set && shallow(previous, next)) continue;
2939 return false;
2940 }
2941 return Object.keys(left).length === Object.keys(right).length;
2942 }