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

main
ts 2,820 lines 98.4 KB
Raw
1 import type {
2 ThreadPendingApproval,
3 ThreadPendingUserInput,
4 } from "@t3tools/client-runtime/state/thread-requests";
5 import { linkRequestTargetName } from "@t3tools/client-runtime/link-request";
6 import { turnItemIsWorkspacePreparation } from "@t3tools/client-runtime/state/turn-item-presentation";
7 import type { ThreadCheckpointSummary } from "@t3tools/client-runtime/state/thread-checkpoints";
8 import { formatSubagentDisplayTitle } from "@t3tools/client-runtime/state/subagent-display";
9 import {
10 isLiveSubagentTurnItem,
11 waitingOnSubagentsLabel,
12 } from "@t3tools/client-runtime/state/subagentRuntime";
13 import { extractToolActivityPresentation } from "@t3tools/client-runtime/work-log/tool-presentation";
14 import {
15 turnItemDetailRevision,
16 turnItemHasDetail,
17 turnItemNeedsDetailFetch,
18 } from "@t3tools/client-runtime/work-log/item-detail";
19 import {
20 commandDisplayText,
21 commandProgramName,
22 } from "@t3tools/client-runtime/work-log/command-label";
23 import {
24 commandlessCommandLabel,
25 contextCompactionLabel,
26 liveThoughtLine,
27 toolItemForDisplay,
28 workEntryDisplayIndicatesToolFailure,
29 liveActivityToolStatus,
30 toolGroupAction,
31 resolveWorkEntryToolPresentation,
32 summarizeToolGroup,
33 toolGroupSummaryKind,
34 workEntriesViewedImagePaths,
35 type ToolGroupSummaryKind,
36 type WorkLogPresentationEntry,
37 type WorkLogToolLifecycleStatus,
38 workEntryHiddenByToolCallVisibility,
39 } from "@t3tools/client-runtime/work-log/presentation";
40 import type { ToolCallVisibility } from "@t3tools/contracts/settings";
41 import {
42 resolveT3McpToolDefinition,
43 type T3McpToolLogo,
44 type T3McpToolPresentation,
45 } from "@t3tools/shared/t3McpToolPresentation";
46 import { resolveT3McpToolPresentation } from "@t3tools/shared/t3McpToolPresentationCopy";
47 import type {
48 ChatAttachment,
49 MessageId,
50 OrchestrationV2Actor,
51 OrchestrationV2CreationSource,
52 OrchestrationV2ExecutionNode,
53 OrchestrationMessageContext,
54 OrchestrationV2ProjectedTurnItem,
55 OrchestrationV2RunAttempt,
56 OrchestrationV2RunStatus,
57 OrchestrationV2TurnItem,
58 OrchestrationV2UserMessageInputIntent,
59 RunAttemptId,
60 ScheduledTaskId,
61 TurnItemId,
62 } from "@t3tools/contracts";
63 import { idleCompactionOf, isCompactionCommandMessage, RunId, ThreadId } from "@t3tools/contracts";
64 import {
65 classifyToolActivity,
66 collectToolFilePaths,
67 isJavaScriptReplTool,
68 } from "@t3tools/shared/toolActivity";
69 import {
70 dynamicToolTitle,
71 formatReadToolLabel,
72 formatSearchToolLabel,
73 } from "@t3tools/shared/toolActivityCopy";
74 import { claudeResumeCompactionAge } from "@t3tools/shared/claudeCompaction";
75 import { formatDuration } from "@t3tools/shared/orchestrationTimingCopy";
76 import { truncate } from "@t3tools/shared/String";
77 import type { HtmlRenderReference } from "@t3tools/shared/htmlRender";
78 import type { McpAppReference } from "@t3tools/shared/mcpApp";
79 import {
80 compactDynamicToolOutput,
81 htmlRenderFromToolItem,
82 sentMessageFromToolItem,
83 mcpAppFromToolItem,
84 } from "@t3tools/shared/toolOutput";
85 import * as DateTime from "effect/DateTime";
86 import { msg } from "gt-react-native";
87 import { m, type MessageResolver } from "../i18n/messages";
88 import {
89 IDLE_COMPACTION_TITLES,
90 IDLE_COMPACTING_LABELS,
91 } from "@t3tools/client-runtime/user-message";
92
93 export type PendingApproval = ThreadPendingApproval;
94 export type PendingUserInput = ThreadPendingUserInput;
95
96 export interface ThreadFeedActivity {
97 readonly id: string;
98 readonly createdAt: string;
99 readonly runId: RunId | null;
100 readonly attemptId: RunAttemptId | null;
101 readonly summary: string;
102 readonly detail: string | null;
103 readonly canExpand: boolean;
104 readonly fetchesDetail: boolean;
105 readonly getFullDetail: () => string | null;
106 readonly getCopyText: () => string;
107 readonly icon:
108 | "agent"
109 | "alert"
110 | "browser"
111 | "computer"
112 | "code"
113 | "check"
114 | "command"
115 | "edit"
116 | "eye"
117 | "globe"
118 | "search"
119 | "stop"
120 | "hammer"
121 | "lock"
122 | "message"
123 | "warning"
124 | "wrench"
125 | "zap";
126 readonly logo: T3McpToolLogo | null;
127 readonly toolLike: boolean;
128 readonly prominent: boolean;
129 readonly status: "success" | "failure" | "neutral" | null;
130 readonly lifecycleStatus: WorkLogToolLifecycleStatus;
131 readonly workEntry: WorkLogPresentationEntry;
132 readonly groupedToolDetail?: boolean;
133 readonly live?: boolean;
134 /** Lone calls carry the group header's label and id until a second call joins. */
135 readonly groupStandIn?: { readonly groupId: string; readonly label: string };
136 readonly projectedItem: OrchestrationV2ProjectedTurnItem;
137 }
138
139 export interface ThreadFeedMessage {
140 readonly context?: import("@t3tools/contracts").OrchestrationMessageContext | undefined;
141 readonly id: MessageId;
142 readonly role: "user" | "assistant";
143 readonly text: string;
144 readonly attachments: ReadonlyArray<ChatAttachment>;
145 readonly runId: RunId | null;
146 readonly streaming: boolean;
147 readonly inputIntent?: OrchestrationV2UserMessageInputIntent;
148 readonly createdBy?: OrchestrationV2Actor;
149 readonly creationSource?: OrchestrationV2CreationSource;
150 readonly scheduledTaskId?: ScheduledTaskId;
151 readonly senderThreadId?: ThreadId;
152 readonly linkedSender?: import("@t3tools/contracts").OrchestrationV2LinkedSender;
153 readonly idleCompaction?: import("@t3tools/contracts").OrchestrationV2IdleCompaction;
154 readonly visibility: OrchestrationV2ProjectedTurnItem["visibility"];
155 readonly sourceThreadId: ThreadId;
156 readonly createdAt: string;
157 readonly updatedAt: string;
158 readonly projectedItem?: OrchestrationV2ProjectedTurnItem;
159 readonly checkpointSummary?: ThreadCheckpointSummary;
160 }
161
162 export interface LocalThreadMessage {
163 readonly id: MessageId;
164 readonly role: string;
165 readonly text: string;
166 readonly context?: OrchestrationMessageContext | undefined;
167 readonly attachments?: ReadonlyArray<ChatAttachment> | undefined;
168 readonly streaming: boolean;
169 readonly createdAt: string;
170 readonly updatedAt: string;
171 }
172
173 type RawThreadFeedEntry =
174 | {
175 readonly type: "message";
176 readonly id: string;
177 readonly createdAt: string;
178 readonly message: ThreadFeedMessage;
179 }
180 | {
181 readonly type: "activity";
182 readonly id: string;
183 readonly createdAt: string;
184 readonly runId: RunId | null;
185 readonly activity: ThreadFeedActivity;
186 }
187 | {
188 readonly type: "html-render";
189 readonly id: string;
190 readonly createdAt: string;
191 readonly runId: RunId | null;
192 readonly render: HtmlRenderReference;
193 }
194 | {
195 readonly type: "sent-message";
196 readonly id: string;
197 readonly createdAt: string;
198 readonly runId: RunId | null;
199 readonly text: string;
200 }
201 | {
202 readonly type: "mcp-app";
203 readonly id: string;
204 readonly createdAt: string;
205 readonly runId: RunId | null;
206 /** The thread and item that own the app; a fork's inherited app is its source's. */
207 readonly sourceThreadId: ThreadId;
208 readonly itemId: TurnItemId;
209 readonly revision: string;
210 readonly app: McpAppReference;
211 };
212
213 export type ThreadFeedEntry = ThreadFeedEntryContent & {
214 readonly continuesWorkLog?: boolean;
215 readonly checkpointSummary?: ThreadCheckpointSummary;
216 };
217
218 type ThreadFeedEntryContent =
219 | Extract<RawThreadFeedEntry, { type: "message" | "html-render" | "sent-message" | "mcp-app" }>
220 | {
221 readonly type: "activity-group";
222 readonly id: string;
223 readonly createdAt: string;
224 readonly runId: RunId | null;
225 readonly activities: ReadonlyArray<ThreadFeedActivity>;
226 }
227 | {
228 readonly type: "work-toggle";
229 readonly id: string;
230 readonly createdAt: string;
231 readonly runId: RunId | null;
232 readonly groupId: string;
233 readonly hiddenCount: number;
234 readonly expanded: boolean;
235 readonly summary: string;
236 readonly summaryKind: ToolGroupSummaryKind;
237 readonly toolSurface?: WorkLogPresentationEntry["toolSurface"];
238 readonly toolIcon?: WorkLogPresentationEntry["toolIcon"];
239 readonly summaryToolIcon?: "browser" | "device" | "t3-code" | "pull-request";
240 readonly hasFailure: boolean;
241 readonly live: boolean;
242 readonly shimmer: boolean;
243 readonly thought?: string;
244 }
245 | {
246 /** Images the agent opened in the tool group above, kept visible while the group is collapsed. */
247 readonly type: "viewed-images";
248 readonly id: string;
249 readonly createdAt: string;
250 readonly runId: RunId | null;
251 readonly paths: ReadonlyArray<string>;
252 }
253 | {
254 readonly type: "run-fold";
255 readonly deferredWorkItemIds?: ReadonlyArray<string>;
256 /** Set while the run works: the row shows a live timer and does not toggle. */
257 readonly workingSince?: string;
258 readonly id: string;
259 readonly createdAt: string;
260 readonly runId: RunId;
261 readonly label: string;
262 readonly expanded: boolean;
263 }
264 | {
265 readonly type: "thinking";
266 readonly id: string;
267 readonly createdAt: string;
268 readonly runId: RunId | null;
269 readonly label?: string;
270 /** Shown instead of "Thinking" while the provider has not started a turn. */
271 readonly providerStartingLabel?: string;
272 };
273
274 export interface ThreadFeedLatestRun {
275 readonly runId: RunId;
276 readonly status: OrchestrationV2RunStatus;
277 readonly startedAt: string | null;
278 readonly completedAt: string | null;
279 readonly turnEnded?: boolean;
280 readonly providerStartingLabel?: string;
281 readonly providerStartingLabelMsg?: string;
282 }
283
284 /** Long Android headers can ANR despite one-line display; cap labels only, preserving expanded and copied text. */
285 const WORK_LOG_LABEL_MAX_LENGTH = 200;
286
287 function compactWorkEntryText(value: string): string {
288 return truncate(value.replace(/\s+/gu, " "), WORK_LOG_LABEL_MAX_LENGTH);
289 }
290
291 export function workEntryRowLabel(
292 entry: WorkLogPresentationEntry,
293 expanded = false,
294 resolve: MessageResolver = m,
295 ): string {
296 if (entry.itemType === "fork") return entry.label;
297 if (expanded && entry.itemType === "reasoning")
298 return entry.toolLifecycleStatus === "inProgress"
299 ? resolve(msg("Thinking"))
300 : resolve(msg("Thought"));
301 const presentation = resolveWorkEntryToolPresentation(entry, undefined, resolve);
302 if (presentation) return presentation.displayName;
303 if (entry.command?.trim()) return compactWorkEntryText(commandDisplayText(entry.command));
304 const commandless = commandlessCommandLabel(
305 entry,
306 liveActivityToolStatus(entry.toolLifecycleStatus, false),
307 resolve,
308 );
309 if (commandless) return commandless;
310 const action = toolGroupAction(entry);
311 const isToolRead = action === "read" && entry.itemType === "dynamic_tool";
312 if (action === "code-search" || action === "search") {
313 const toolData =
314 entry.toolData !== null &&
315 typeof entry.toolData === "object" &&
316 !Array.isArray(entry.toolData)
317 ? (entry.toolData as Record<string, unknown>)
318 : undefined;
319 const searchLabel =
320 entry.itemType === "file_search" ? entry.label : formatSearchToolLabel(toolData, resolve);
321 if (searchLabel) return searchLabel;
322 }
323 if (isToolRead) {
324 const [firstPath] = entry.changedFiles ?? collectToolFilePaths(entry.toolData);
325 if (firstPath) {
326 return formatReadToolLabel(
327 firstPath,
328 Math.max(0, (entry.changedFiles?.length ?? 1) - 1),
329 resolve,
330 );
331 }
332 if (!expanded) return resolve(msg("Read file"));
333 }
334 const preview =
335 entry.command ??
336 (isToolRead || (!expanded && (action === "code-search" || action === "search"))
337 ? null
338 : entry.detail) ??
339 (entry.changedFiles?.length
340 ? entry.changedFiles.length === 1
341 ? entry.changedFiles[0]!
342 : resolve(
343 msg("{path} +{count} more", {
344 path: entry.changedFiles[0]!,
345 count: String(entry.changedFiles.length - 1),
346 }),
347 )
348 : null);
349 if (expanded) return preview?.trim() ? truncate(preview, WORK_LOG_LABEL_MAX_LENGTH) : entry.label;
350 return preview ? compactWorkEntryText(preview) || entry.label : entry.label;
351 }
352
353 type ThreadFeedActivityGroup = Extract<ThreadFeedEntry, { readonly type: "activity-group" }>;
354
355 // Immutable source rows let retained history keep its identities while the active item streams.
356 const projectedEntriesCache = new WeakMap<
357 OrchestrationV2ProjectedTurnItem,
358 {
359 readonly attemptId: RunAttemptId | null;
360 readonly locale: string | undefined;
361 readonly entries: ReadonlyArray<RawThreadFeedEntry>;
362 }
363 >();
364 const localMessageEntriesCache = new WeakMap<
365 LocalThreadMessage,
366 Extract<RawThreadFeedEntry, { readonly type: "message" }>
367 >();
368 const activityGroupsCache = new WeakMap<ThreadFeedActivity, ThreadFeedActivityGroup>();
369 const failedActivityGroupsCache = new WeakMap<
370 ThreadFeedActivityGroup,
371 ReadonlyArray<ThreadFeedActivityGroup>
372 >();
373 const presentedActivityGroupsCache = new WeakMap<
374 ThreadFeedActivityGroup,
375 {
376 readonly activeRunId: RunId | null;
377 readonly isWorking: boolean;
378 readonly activeTail: boolean;
379 readonly locale: string | undefined;
380 readonly rows: ReadonlyArray<ThreadFeedEntry>;
381 }
382 >();
383 const runFoldRowsCache = new WeakMap<
384 ThreadFeedEntry,
385 Extract<ThreadFeedEntry, { readonly type: "run-fold" }>
386 >();
387 let cachedThinkingRow: Extract<ThreadFeedEntry, { readonly type: "thinking" }> | null = null;
388
389 export function isContextCompactionActivityGroup(entry: ThreadFeedActivityGroup): boolean {
390 return (
391 entry.activities.length === 1 && entry.activities[0]?.projectedItem.item.type === "compaction"
392 );
393 }
394
395 export function threadFeedCompactionLabels(
396 feed: ReadonlyArray<ThreadFeedEntry>,
397 resolve: MessageResolver = m,
398 ) {
399 const labelsByRunId = new Map<RunId, { title: string; compacting: string }>();
400 const labelsByEntryId = new Map<string, { title: string; compacting: string }>();
401 const pendingResumeAgeByRunId = new Map<RunId, string>();
402 for (const entry of feed) {
403 const reason = entry.type === "message" ? idleCompactionOf(entry.message) : undefined;
404 if (entry.type === "message" && entry.message.runId !== null && reason !== undefined) {
405 labelsByRunId.set(entry.message.runId, {
406 title: resolve(IDLE_COMPACTION_TITLES[reason]),
407 compacting: resolve(IDLE_COMPACTING_LABELS[reason]),
408 });
409 } else if (entry.type === "activity-group" && entry.runId !== null) {
410 if (isContextCompactionActivityGroup(entry)) {
411 const age = pendingResumeAgeByRunId.get(entry.runId);
412 const labels =
413 labelsByRunId.get(entry.runId) ??
414 (age === undefined
415 ? undefined
416 : {
417 title: resolve(msg("Context compacted after {age} idle", { age })),
418 compacting: resolve(msg("Compacting…")),
419 });
420 if (labels) labelsByEntryId.set(entry.id, labels);
421 pendingResumeAgeByRunId.delete(entry.runId);
422 }
423 for (const activity of entry.activities) {
424 const age = activity.workEntry.questionAnswer
425 ? claudeResumeCompactionAge(activity.workEntry.questionAnswer)
426 : null;
427 if (age !== null) pendingResumeAgeByRunId.set(entry.runId, age);
428 }
429 }
430 }
431 return labelsByEntryId;
432 }
433
434 function isResumeCompactionAnswerGroup(entry: ThreadFeedActivityGroup): boolean {
435 return entry.activities.every((activity) => {
436 const answer = activity.workEntry.questionAnswer;
437 return answer !== undefined && claudeResumeCompactionAge(answer) !== null;
438 });
439 }
440
441 export function isContextHandoffActivityGroup(entry: ThreadFeedActivityGroup): boolean {
442 return (
443 entry.activities.length === 1 && entry.activities[0]?.projectedItem.item.type === "handoff"
444 );
445 }
446
447 export function isSecretRequestActivityGroup(entry: ThreadFeedActivityGroup): boolean {
448 return (
449 entry.activities.length === 1 &&
450 entry.activities[0]?.projectedItem.item.type === "secret_request"
451 );
452 }
453
454 export function isLinkRequestActivityGroup(entry: ThreadFeedActivityGroup): boolean {
455 return (
456 entry.activities.length === 1 && entry.activities[0]?.projectedItem.item.type === "link_request"
457 );
458 }
459
460 function isUserInputActivityGroup(entry: ThreadFeedActivityGroup): boolean {
461 return entry.activities.some((activity) => activity.workEntry.questionAnswer !== undefined);
462 }
463
464 function capitalizePhrase(value: string): string {
465 const trimmed = value.trim();
466 return trimmed.length === 0 ? value : `${trimmed.charAt(0).toUpperCase()}${trimmed.slice(1)}`;
467 }
468
469 function memoizeValue<T>(build: () => T): () => T {
470 let value: T;
471 let initialized = false;
472 return () => {
473 if (!initialized) {
474 value = build();
475 initialized = true;
476 }
477 return value;
478 };
479 }
480
481 function itemIsToolLike(item: OrchestrationV2TurnItem): boolean {
482 return (
483 item.type === "reasoning" ||
484 item.type === "command_execution" ||
485 item.type === "file_change" ||
486 item.type === "file_search" ||
487 item.type === "web_search" ||
488 item.type === "approval_request" ||
489 item.type === "user_input_request" ||
490 item.type === "dynamic_tool" ||
491 item.type === "subagent"
492 );
493 }
494
495 function itemIsProminent(item: OrchestrationV2TurnItem): boolean {
496 return (
497 item.type === "fork" ||
498 item.type === "thread_created" ||
499 item.type === "system_notice" ||
500 item.type === "proposed_plan" ||
501 item.type === "secret_request" ||
502 item.type === "link_request"
503 );
504 }
505
506 function itemStatus(item: OrchestrationV2TurnItem): ThreadFeedActivity["status"] {
507 if (item.type === "notification") return item.outcome === "failed" ? "failure" : null;
508 if (item.type === "error") {
509 if (item.status === "failed")
510 return item.failure.class === "usage_limit" ? "neutral" : "failure";
511 return item.status === "completed" ? "success" : "neutral";
512 }
513 if (!itemIsToolLike(item)) return null;
514 if (item.status === "failed") return "failure";
515 return item.status === "completed" ? "success" : "neutral";
516 }
517
518 function itemLifecycleStatus(item: OrchestrationV2TurnItem): WorkLogToolLifecycleStatus {
519 switch (item.status) {
520 case "pending":
521 case "running":
522 case "waiting":
523 return "inProgress";
524 case "idle":
525 return "idle";
526 case "completed":
527 return "completed";
528 case "failed":
529 return "failed";
530 case "cancelled":
531 case "interrupted":
532 return "stopped";
533 }
534 }
535
536 function itemWorkLogTone(item: OrchestrationV2TurnItem): WorkLogPresentationEntry["tone"] {
537 if (item.type === "error") return "info";
538 if (item.type === "reasoning") return "thinking";
539 switch (item.type) {
540 case "command_execution":
541 case "file_change":
542 case "file_search":
543 case "web_search":
544 case "dynamic_tool":
545 case "subagent":
546 return "tool";
547 default:
548 return "info";
549 }
550 }
551
552 function itemIcon(item: OrchestrationV2TurnItem): ThreadFeedActivity["icon"] {
553 if (item.type === "notification") {
554 const source = item.source;
555 switch (source.kind) {
556 case "subagent":
557 case "delegated_task":
558 return "hammer";
559 case "command":
560 return "command";
561 case "monitor":
562 return "eye";
563 case "background_task":
564 case "system":
565 return "zap";
566 default:
567 source satisfies never;
568 return "zap";
569 }
570 }
571 if (item.type === "dynamic_tool") {
572 const classified = classifyToolActivity({
573 itemType: "dynamic_tool_call",
574 data: { toolName: item.toolName ?? undefined, input: item.input },
575 });
576 if (classified === "read") {
577 return "eye";
578 }
579 if (classified === "search") return "search";
580 }
581 switch (item.type) {
582 case "reasoning":
583 return "agent";
584 case "command_execution":
585 return "command";
586 case "file_change":
587 return "edit";
588 case "file_search":
589 return "search";
590 case "web_search":
591 return "globe";
592 case "approval_request":
593 return item.requestKind === "permission" ? "lock" : "message";
594 case "user_input_request":
595 case "user_message":
596 case "assistant_message":
597 return "message";
598 case "dynamic_tool":
599 return isJavaScriptReplTool(item.toolName) ? "code" : "wrench";
600 case "subagent":
601 return "hammer";
602 case "system_notice":
603 return item.level === "info" ? "zap" : "warning";
604 case "run_interrupt_request":
605 case "run_interrupt_result":
606 return "stop";
607 case "error":
608 return item.failure.class === "usage_limit"
609 ? item.status === "completed"
610 ? "check"
611 : "warning"
612 : "alert";
613 case "checkpoint":
614 case "proposed_plan":
615 case "todo_list":
616 return "check";
617 case "compaction":
618 case "handoff":
619 case "fork":
620 case "thread_created":
621 return "zap";
622 case "secret_request":
623 return "lock";
624 case "link_request":
625 return "globe";
626 }
627 }
628
629 function itemToolPresentation(
630 item: OrchestrationV2TurnItem,
631 resolve: MessageResolver,
632 ): T3McpToolPresentation | null {
633 if (item.type !== "dynamic_tool") {
634 return null;
635 }
636 return (
637 resolveT3McpToolPresentation(item.toolName, item.input, resolve) ??
638 resolveT3McpToolPresentation(item.title, item.input, resolve)
639 );
640 }
641
642 function itemSummary(
643 item: OrchestrationV2TurnItem,
644 toolPresentation: T3McpToolPresentation | null,
645 resolve: MessageResolver,
646 ): string {
647 if (item.type === "notification") return item.summary;
648 if (item.type === "system_notice") return item.message;
649 if (item.type === "compaction") return contextCompactionLabel(item, resolve);
650 const title =
651 (item.type === "dynamic_tool"
652 ? dynamicToolTitle(item.toolName, item.input, item.title, resolve)
653 : undefined) ?? item.title?.trim();
654 if (item.type === "subagent")
655 return formatSubagentDisplayTitle(title || resolve(msg("Subagent")));
656 if (title) return toolPresentation?.displayName ?? capitalizePhrase(title);
657 switch (item.type) {
658 case "reasoning":
659 return resolve(msg("Thinking"));
660 case "command_execution":
661 return resolve(msg("Command", { $context: "noun, a shell command the agent ran" }));
662 case "file_change":
663 return item.changes !== undefined && item.changes.length > 1
664 ? resolve(
665 msg("{count, plural, one {Changed {count} file} other {Changed {count} files}}", {
666 count: item.changes.length,
667 }),
668 )
669 : resolve(msg("Changed {fileName}", { fileName: item.fileName }));
670 case "file_search":
671 return (
672 item.title?.trim() || formatSearchToolLabel(item, resolve) || resolve(msg("Searched files"))
673 );
674 case "web_search":
675 return resolve(msg("Searched the web"));
676 case "approval_request":
677 return resolve(msg("Approval requested"));
678 case "user_input_request":
679 return resolve(msg("Input requested"));
680 case "checkpoint":
681 return resolve(msg("Checkpoint captured"));
682 case "run_interrupt_request":
683 return resolve(msg("Interrupt requested"));
684 case "run_interrupt_result":
685 return resolve(msg("Run interrupted"));
686 case "error":
687 return item.failure.class === "usage_limit"
688 ? resolve(msg("Usage limit reached"))
689 : resolve(msg("Provider error"));
690 case "handoff":
691 return resolve(msg("Context handed off"));
692 case "fork":
693 return resolve(msg("Thread forked"));
694 case "thread_created":
695 return resolve(msg("Thread created"));
696 case "secret_request":
697 return item.label;
698 case "link_request":
699 return resolve(msg("Link {target}", { target: linkRequestTargetName(item, resolve) }));
700 case "dynamic_tool": {
701 const classified = classifyToolActivity({
702 itemType: "dynamic_tool_call",
703 data: { toolName: item.toolName ?? undefined, input: item.input },
704 });
705 if (classified === "read") {
706 const [path] = collectToolFilePaths({ input: item.input });
707 return formatReadToolLabel(path ?? "", 0, resolve);
708 }
709 if (classified === "search") {
710 return (
711 formatSearchToolLabel({ input: item.input }, resolve) ??
712 item.toolName ??
713 resolve(msg("Tool call"))
714 );
715 }
716 return toolPresentation?.displayName ?? item.toolName ?? resolve(msg("Tool call"));
717 }
718 case "proposed_plan":
719 return resolve(msg("Proposed plan"));
720 case "todo_list":
721 return resolve(msg("Plan updated"));
722 case "user_message":
723 return resolve(msg("User message"));
724 case "assistant_message":
725 return resolve(msg("Assistant message"));
726 }
727 }
728
729 function itemPreview(item: OrchestrationV2TurnItem, resolve: MessageResolver): string | null {
730 switch (item.type) {
731 case "reasoning":
732 return item.text || null;
733 case "command_execution":
734 return item.input || null;
735 case "file_change":
736 return item.fileName;
737 case "file_search":
738 return item.pattern ?? null;
739 case "web_search":
740 return item.patterns?.join(", ") ?? null;
741 case "approval_request":
742 return item.prompt ?? null;
743 case "user_input_request":
744 return item.questions.map((question) => question.question).join(" · ") || null;
745 case "checkpoint":
746 return item.files.length === 1
747 ? (item.files[0]?.path ?? null)
748 : resolve(
749 msg("{count, plural, one {{count} changed file} other {{count} changed files}}", {
750 count: item.files.length,
751 }),
752 );
753 case "run_interrupt_request":
754 case "run_interrupt_result":
755 case "system_notice":
756 return item.message || null;
757 case "error":
758 return item.failure.message;
759 case "compaction":
760 case "handoff":
761 return item.summary ?? null;
762 case "fork":
763 case "thread_created":
764 return item.targetThreadId;
765 case "secret_request":
766 case "link_request":
767 return item.reason || null;
768 case "subagent":
769 return item.result ?? item.progress ?? item.prompt;
770 case "dynamic_tool":
771 return null;
772 case "notification":
773 return item.detail ?? null;
774 case "proposed_plan":
775 return item.markdown || null;
776 case "todo_list":
777 return resolve(
778 msg("{completed}/{total} completed", {
779 completed: item.steps.filter((step) => step.status === "completed").length,
780 total: item.steps.length,
781 }),
782 );
783 case "user_message":
784 case "assistant_message":
785 return item.text || null;
786 }
787 }
788
789 function toWorkLogEntry(
790 item: OrchestrationV2TurnItem,
791 createdAt: string,
792 summary: string,
793 detail: string | null,
794 resolve: MessageResolver,
795 ): WorkLogPresentationEntry {
796 const title = item.title?.trim() || null;
797 const common = {
798 ...extractToolActivityPresentation(item),
799 id: item.id,
800 createdAt,
801 label: summary,
802 tone: itemWorkLogTone(item),
803 itemType: item.type,
804 toolLifecycleStatus: itemLifecycleStatus(item),
805 structuredPayload: item,
806 ...(item.type === "user_input_request" && item.questionAnswer
807 ? { questionAnswer: item.questionAnswer }
808 : {}),
809 } as const;
810
811 switch (item.type) {
812 case "reasoning":
813 return { ...common, ...(item.text ? { detail: item.text } : {}) };
814 case "command_execution":
815 return {
816 ...common,
817 command: item.input,
818 rawCommand: item.input,
819 toolTitle:
820 title ?? resolve(msg("Command", { $context: "noun, a shell command the agent ran" })),
821 toolData: item,
822 };
823 case "file_change":
824 return {
825 ...common,
826 changedFiles: item.changes?.length
827 ? item.changes.map((change) => change.path)
828 : [item.fileName],
829 toolTitle: title ?? resolve(msg("File change")),
830 toolData: item,
831 };
832 case "file_search":
833 return {
834 ...common,
835 ...(item.pattern ? { detail: item.pattern } : {}),
836 toolTitle: title ?? resolve(msg("File search")),
837 toolData: item,
838 };
839 case "web_search":
840 return {
841 ...common,
842 ...(item.patterns?.length ? { detail: item.patterns.join(", ") } : {}),
843 toolTitle: title ?? resolve(msg("Web search")),
844 toolData: item,
845 };
846 case "checkpoint":
847 return { ...common, changedFiles: item.files.map((file) => file.path), toolData: item };
848 case "approval_request":
849 return {
850 ...common,
851 ...(item.prompt ? { detail: item.prompt } : {}),
852 requestKind: item.requestKind,
853 toolData: item,
854 };
855 case "dynamic_tool":
856 return {
857 ...common,
858 toolTitle:
859 title ?? item.toolName ?? resolve(msg("Tool", { $context: "noun, an agent tool call" })),
860 toolData: { input: item.input, output: item.output },
861 };
862 default:
863 return { ...common, ...(detail ? { detail } : {}), toolData: item };
864 }
865 }
866
867 export function formatItemFullDetail(
868 row: OrchestrationV2ProjectedTurnItem,
869 item: OrchestrationV2TurnItem,
870 ): string {
871 return JSON.stringify(
872 {
873 visibility: row.visibility,
874 sourceThreadId: row.sourceThreadId,
875 sourceItemId: row.sourceItemId,
876 item: toolItemForDisplay(item),
877 },
878 null,
879 2,
880 );
881 }
882
883 function toFeedActivity(
884 row: OrchestrationV2ProjectedTurnItem,
885 attemptId: RunAttemptId | null,
886 resolve: MessageResolver,
887 ): ThreadFeedActivity {
888 const item = row.item;
889 const toolPresentation = itemToolPresentation(item, resolve);
890 const summary = itemSummary(item, toolPresentation, resolve);
891 const detail = item.type === "notification" ? null : itemPreview(item, resolve);
892 const createdAt = DateTime.formatIso(item.startedAt ?? item.updatedAt);
893 const workEntry = toWorkLogEntry(item, createdAt, summary, detail, resolve);
894 const readPaths =
895 item.type === "dynamic_tool" && toolGroupAction(workEntry) === "read"
896 ? collectToolFilePaths(item)
897 : null;
898 const getFullDetail = memoizeValue(() =>
899 item.type === "proposed_plan"
900 ? item.markdown
901 : readPaths
902 ? readPaths.join("\n") || null
903 : item.type === "notification"
904 ? item.detail?.trim() || null
905 : formatItemFullDetail(row, item),
906 );
907 const getCopyText = memoizeValue(() =>
908 item.type === "proposed_plan"
909 ? `${item.markdown.trimEnd()}\n`
910 : [summary, detail, getFullDetail()]
911 .filter(
912 (value, index, values): value is string =>
913 Boolean(value) && values.indexOf(value) === index,
914 )
915 .join("\n"),
916 );
917 return {
918 id: `${row.visibility}:${row.sourceThreadId}:${row.sourceItemId}`,
919 createdAt,
920 runId: item.runId,
921 attemptId,
922 summary,
923 detail,
924 canExpand:
925 !(item.type === "error" && item.status === "failed") &&
926 (readPaths
927 ? readPaths.length > 0 || turnItemNeedsDetailFetch(item)
928 : turnItemHasDetail(item) || workEntry.questionAnswer !== undefined),
929 fetchesDetail: turnItemNeedsDetailFetch(item),
930 getFullDetail,
931 getCopyText,
932 icon: workEntry.toolSurface ?? itemIcon(item),
933 logo: toolPresentation?.logo ?? null,
934 toolLike: itemIsToolLike(item),
935 prominent: itemIsProminent(item) || (item.type === "error" && item.status === "failed"),
936 status:
937 item.type === "error" && item.failure.class === "usage_limit"
938 ? itemStatus(item)
939 : workEntryDisplayIndicatesToolFailure(workEntry)
940 ? "failure"
941 : itemStatus(item),
942 lifecycleStatus: itemLifecycleStatus(item),
943 workEntry,
944 projectedItem: row,
945 };
946 }
947
948 function singleToolCallLabel(
949 activity: ThreadFeedActivity,
950 expanded: boolean,
951 resolve: MessageResolver,
952 ): string {
953 if (activity.workEntry.itemType === "reasoning")
954 return expanded
955 ? resolve(msg("Thought"))
956 : compactWorkEntryText(activity.workEntry.detail ?? "") || resolve(msg("Thought"));
957 const presentation = resolveWorkEntryToolPresentation(activity.workEntry, "completed", resolve);
958 if (presentation) return presentation.displayName;
959 const command = activity.workEntry.command?.trim();
960 return command ? truncate(command, WORK_LOG_LABEL_MAX_LENGTH) : activity.summary;
961 }
962
963 function isEmptyMessage(entry: RawThreadFeedEntry): boolean {
964 return (
965 entry.type === "message" &&
966 entry.message.text.trim().length === 0 &&
967 entry.message.attachments.length === 0
968 );
969 }
970
971 /**
972 * `onRestart` hears each entry after which no group is open, with the grouped
973 * length so far: the entries before it group the same whatever follows.
974 */
975 function groupAdjacentActivities(
976 entries: ReadonlyArray<RawThreadFeedEntry>,
977 childrenByRun: ReadonlyMap<RunId, ReadonlySet<string>>,
978 onRestart?: (entryIndex: number, groupedLength: number) => void,
979 ): ThreadFeedEntry[] {
980 const grouped: ThreadFeedEntry[] = [];
981 let firstActivityEntry: Extract<RawThreadFeedEntry, { readonly type: "activity" }> | null = null;
982 let openGroupActivities: ThreadFeedActivity[] = [];
983 const flushGroup = () => {
984 if (firstActivityEntry === null) return;
985 const cached = activityGroupsCache.get(firstActivityEntry.activity);
986 if (
987 cached &&
988 cached.activities.length === openGroupActivities.length &&
989 cached.activities.every((activity, index) => activity === openGroupActivities[index])
990 ) {
991 grouped.push(cached);
992 } else {
993 const group: ThreadFeedActivityGroup = {
994 type: "activity-group",
995 id: firstActivityEntry.id,
996 createdAt: firstActivityEntry.createdAt,
997 runId: firstActivityEntry.runId,
998 activities: openGroupActivities,
999 };
1000 activityGroupsCache.set(firstActivityEntry.activity, group);
1001 grouped.push(group);
1002 }
1003 firstActivityEntry = null;
1004 openGroupActivities = [];
1005 };
1006
1007 for (let entryIndex = 0; entryIndex < entries.length; entryIndex += 1) {
1008 const entry = entries[entryIndex]!;
1009 if (entry.type === "activity") {
1010 const item = entry.activity.projectedItem.item;
1011 if (
1012 item.type === "dynamic_tool" &&
1013 item.runId !== null &&
1014 (item.status === "running" || item.status === "completed") &&
1015 resolveT3McpToolDefinition(item.toolName)?.summaryAction === "delegate" &&
1016 !workEntryDisplayIndicatesToolFailure(entry.activity.workEntry)
1017 ) {
1018 const output = compactDynamicToolOutput(item.output);
1019 if (
1020 !output?.isError &&
1021 output?.taskId !== undefined &&
1022 childrenByRun.get(item.runId)?.has(output.taskId)
1023 )
1024 continue;
1025 }
1026 }
1027 if (isEmptyMessage(entry)) {
1028 continue;
1029 }
1030
1031 if (entry.type !== "activity") {
1032 flushGroup();
1033 grouped.push(entry);
1034 onRestart?.(entryIndex, grouped.length);
1035 continue;
1036 }
1037
1038 const isStandaloneActivity =
1039 entry.activity.workEntry.questionAnswer !== undefined ||
1040 entry.activity.projectedItem.item.type === "compaction" ||
1041 entry.activity.projectedItem.item.type === "handoff" ||
1042 entry.activity.projectedItem.item.type === "notification";
1043 if (
1044 isStandaloneActivity ||
1045 entry.activity.prominent ||
1046 (entry.activity.projectedItem.item.type === "subagent") !==
1047 (firstActivityEntry?.activity.projectedItem.item.type === "subagent") ||
1048 firstActivityEntry?.runId !== entry.runId ||
1049 (entry.activity.projectedItem.item.type === "subagent" &&
1050 firstActivityEntry?.activity.projectedItem.item.providerTurnId !==
1051 entry.activity.projectedItem.item.providerTurnId) ||
1052 (entry.activity.projectedItem.item.type !== "subagent" &&
1053 firstActivityEntry?.activity.attemptId !== entry.activity.attemptId)
1054 ) {
1055 flushGroup();
1056 }
1057 firstActivityEntry ??= entry;
1058 openGroupActivities.push(entry.activity);
1059 if (isStandaloneActivity || entry.activity.prominent) {
1060 flushGroup();
1061 }
1062 }
1063 flushGroup();
1064 return grouped;
1065 }
1066
1067 function computeElapsedMs(startIso: string, endIso: string): number | null {
1068 const start = Date.parse(startIso);
1069 const end = Date.parse(endIso);
1070 return Number.isFinite(start) && Number.isFinite(end) ? Math.max(0, end - start) : null;
1071 }
1072
1073 function maxIsoTimestamp(left: string | null, right: string | null): string | null {
1074 if (left === null) return right;
1075 if (right === null) return left;
1076 return Date.parse(right) > Date.parse(left) ? right : left;
1077 }
1078
1079 function unsettledRunId(latestRun: ThreadFeedLatestRun | null): RunId | null {
1080 return threadFeedRunIsUnsettled(latestRun) ? latestRun.runId : null;
1081 }
1082
1083 export function threadFeedRunIsUnsettled(
1084 run: ThreadFeedLatestRun | null,
1085 ): run is ThreadFeedLatestRun {
1086 if (run === null || run.status === "queued") return false;
1087 return (
1088 run.completedAt === null ||
1089 run.status === "preparing" ||
1090 run.status === "starting" ||
1091 run.status === "running" ||
1092 run.status === "waiting"
1093 );
1094 }
1095
1096 function threadFeedActivityIsVisible(
1097 activity: Pick<ThreadFeedActivity, "prominent" | "status" | "toolLike"> &
1098 Partial<Pick<ThreadFeedActivity, "lifecycleStatus">>,
1099 ): boolean {
1100 return (
1101 activity.prominent ||
1102 activity.lifecycleStatus === "stopped" ||
1103 activity.lifecycleStatus === "declined" ||
1104 activity.lifecycleStatus === "idle" ||
1105 !(activity.toolLike && activity.status === "neutral")
1106 );
1107 }
1108
1109 interface ThreadFeedRunFold {
1110 readonly deferredWorkItemIds?: ReadonlyArray<string>;
1111 readonly runId: RunId;
1112 readonly createdAt: string;
1113 readonly hiddenEntryIds: ReadonlySet<string>;
1114 readonly label: string;
1115 }
1116
1117 export function failedFeedRunIds(
1118 feed: ReadonlyArray<ThreadFeedEntry>,
1119 latestRun: ThreadFeedLatestRun | null,
1120 ) {
1121 const failed = new Set<RunId>();
1122 if (latestRun?.status === "failed") failed.add(latestRun.runId);
1123 for (const entry of feed) {
1124 if (entry.type !== "activity-group") continue;
1125 for (const activity of entry.activities) {
1126 const item = activity.projectedItem.item;
1127 if (
1128 item.type === "error" &&
1129 item.status === "failed" &&
1130 item.parentItemId === null &&
1131 item.runId !== null
1132 )
1133 failed.add(item.runId);
1134 }
1135 }
1136 return failed;
1137 }
1138
1139 /**
1140 * The key a run fold uses for the message `entryId`: its run, or for an
1141 * imported message with no run, the runless key of the user message before
1142 * it, or the segment after its run's last steer when `presented` shows that
1143 * fold. Null for user messages, which never fold.
1144 */
1145 export function messageFoldRunId(
1146 feed: ReadonlyArray<ThreadFeedEntry>,
1147 entryId: string,
1148 presented: ReadonlyArray<{ readonly type: string; readonly runId?: RunId | null }>,
1149 ): RunId | null {
1150 let runlessKey: RunId | null = null;
1151 const lastSteerIdByRunId = new Map<RunId, string>();
1152 for (const entry of feed) {
1153 if (entry.type !== "message") continue;
1154 if (entry.message.role === "user") {
1155 if (entry.id === entryId) return null;
1156 if (isSteerMessage(entry.message) && entry.message.runId != null) {
1157 lastSteerIdByRunId.set(entry.message.runId, entry.id);
1158 }
1159 runlessKey = entry.message.runId == null ? RunId.make(`runless:${entry.id}`) : null;
1160 } else if (entry.id === entryId) {
1161 const runId = entry.message.runId ?? runlessKey;
1162 const steerId = runId === null ? undefined : lastSteerIdByRunId.get(runId);
1163 if (runId === null || steerId === undefined) return runId;
1164 // Tool visibility can drop all output before the steer, leaving no split.
1165 const steerKey = steerFoldRunId(runId, steerId);
1166 return presented.some((row) => row.type === "run-fold" && row.runId === steerKey)
1167 ? steerKey
1168 : runId;
1169 }
1170 }
1171 return null;
1172 }
1173
1174 function steerFoldRunId(runId: RunId, steerEntryId: string): RunId {
1175 return RunId.make(`${runId}:steer:${steerEntryId}`);
1176 }
1177
1178 function feedEntryFoldRunId(entry: ThreadFeedEntry, runlessKey: RunId | null): RunId | null {
1179 if (entry.type === "message") {
1180 return entry.message.role === "assistant" ? (entry.message.runId ?? runlessKey) : null;
1181 }
1182 return entry.type === "activity-group" ||
1183 entry.type === "html-render" ||
1184 entry.type === "sent-message" ||
1185 entry.type === "mcp-app"
1186 ? (entry.runId ?? runlessKey)
1187 : null;
1188 }
1189
1190 function finalAnswerIds(feed: ReadonlyArray<ThreadFeedEntry>): ReadonlySet<MessageId> {
1191 const ids = new Set<MessageId>();
1192 for (const entry of feed) {
1193 if (
1194 entry.type === "message" &&
1195 entry.message.role === "assistant" &&
1196 entry.message.projectedItem?.item.type === "assistant_message" &&
1197 entry.message.projectedItem.item.phase === "final_answer"
1198 ) {
1199 ids.add(entry.message.id);
1200 }
1201 }
1202 return ids;
1203 }
1204
1205 function deriveThreadFeedRunFolds(
1206 feed: ReadonlyArray<ThreadFeedEntry>,
1207 latestRun: ThreadFeedLatestRun | null,
1208 runlessWorkActive: boolean,
1209 feedFailedRunIds: ReadonlySet<RunId>,
1210 resolve: MessageResolver,
1211 ): ReadonlyMap<string, ThreadFeedRunFold> {
1212 const terminalAssistantMessageIdByRun = new Map<RunId, string>();
1213 const retainedAnswerIds = finalAnswerIds(feed);
1214 const interruptedRunIds = new Set<RunId>();
1215 const failedRunIds = new Set(feedFailedRunIds);
1216 const promptIndexByRunId = new Map<RunId, number>();
1217 for (const [index, entry] of feed.entries()) {
1218 if (
1219 entry.type !== "message" ||
1220 entry.message.role !== "user" ||
1221 entry.message.inputIntent === "steer" ||
1222 entry.message.inputIntent === "promoted_queued_to_steer"
1223 ) {
1224 continue;
1225 }
1226 const runId = entry.message.runId;
1227 if (runId != null && !promptIndexByRunId.has(runId)) promptIndexByRunId.set(runId, index);
1228 }
1229 const groupsByRunId = new Map<
1230 RunId,
1231 {
1232 entries: ThreadFeedEntry[];
1233 startBoundary: string | null;
1234 /** Each steer after the run has output starts a segment at this index into `entries`. */
1235 steerSegments: Array<{ startIndex: number; steer: ThreadFeedEntry }>;
1236 }
1237 >();
1238 let runlessKey: RunId | null = null;
1239 let responseKey: RunId | null = null;
1240 let pendingUserBoundary: string | null = null;
1241 for (const [index, entry] of feed.entries()) {
1242 if (entry.type === "message" && entry.message.role === "user") {
1243 const steerGroup =
1244 isSteerMessage(entry.message) && entry.message.runId != null
1245 ? groupsByRunId.get(entry.message.runId)
1246 : undefined;
1247 if (steerGroup && steerGroup.entries.length > 0) {
1248 // Back-to-back steers split once, after the last of them.
1249 if (steerGroup.steerSegments.at(-1)?.startIndex === steerGroup.entries.length) {
1250 steerGroup.steerSegments.pop();
1251 }
1252 steerGroup.steerSegments.push({ startIndex: steerGroup.entries.length, steer: entry });
1253 }
1254 pendingUserBoundary = entry.message.createdAt;
1255 runlessKey = entry.message.runId == null ? RunId.make(`runless:${entry.id}`) : null;
1256 responseKey = entry.message.runId ?? runlessKey;
1257 continue;
1258 }
1259 const ownRunId = feedEntryFoldRunId(entry, runlessKey);
1260 if (!ownRunId) continue;
1261 // Resumed subagents keep their original turn position and fold, leaving later run folds under their own prompts.
1262 const runId =
1263 responseKey !== null && (promptIndexByRunId.get(ownRunId) ?? -1) > index
1264 ? responseKey
1265 : ownRunId;
1266 let group = groupsByRunId.get(runId);
1267 if (!group) {
1268 group = { entries: [], startBoundary: pendingUserBoundary, steerSegments: [] };
1269 pendingUserBoundary = null;
1270 groupsByRunId.set(runId, group);
1271 }
1272 group.entries.push(entry);
1273 if (entry.type === "message") {
1274 terminalAssistantMessageIdByRun.set(runId, entry.id);
1275 }
1276 if (entry.type !== "activity-group") continue;
1277 for (const activity of entry.activities) {
1278 const item = activity.projectedItem.item;
1279 if (item.type === "run_interrupt_result") interruptedRunIds.add(runId);
1280 if (
1281 runId === runlessKey &&
1282 item.type === "error" &&
1283 item.status === "failed" &&
1284 item.parentItemId === null
1285 ) {
1286 failedRunIds.add(runId);
1287 }
1288 }
1289 }
1290
1291 const activeRunId = unsettledRunId(latestRun);
1292 const foldsByAnchorId = new Map<string, ThreadFeedRunFold>();
1293 for (const [runId, group] of groupsByRunId) {
1294 if (
1295 runId === activeRunId ||
1296 (runlessWorkActive && runId === runlessKey) ||
1297 interruptedRunIds.has(runId) ||
1298 failedRunIds.has(runId) ||
1299 group.entries.some((entry) => entry.type === "message" && entry.message.streaming)
1300 ) {
1301 continue;
1302 }
1303 const terminalAssistantId = terminalAssistantMessageIdByRun.get(runId);
1304 // Folded dividers lose their place in the turn, so only the latest stays visible.
1305 const visibleCompactionId = group.entries.findLast(
1306 (entry) => entry.type === "activity-group" && isContextCompactionActivityGroup(entry),
1307 )?.id;
1308 const hiddenEntryIds = new Set(
1309 group.entries
1310 .filter(
1311 (entry) =>
1312 entry.id !== terminalAssistantId &&
1313 !(entry.type === "message" && retainedAnswerIds.has(entry.message.id)) &&
1314 entry.id !== visibleCompactionId &&
1315 !staysOutOfFold(entry),
1316 )
1317 .map((entry) => entry.id),
1318 );
1319 const firstEntry = group.entries[0];
1320 const lastEntry = group.entries.at(-1);
1321 if (!firstEntry || !lastEntry) continue;
1322 const hidesNonCompactionWork = (entries: ReadonlyArray<ThreadFeedEntry>) =>
1323 entries.some(
1324 (entry) =>
1325 hiddenEntryIds.has(entry.id) &&
1326 !(entry.type === "activity-group" && isContextCompactionActivityGroup(entry)),
1327 );
1328 if (!hidesNonCompactionWork(group.entries)) continue;
1329 const terminalEntry = terminalAssistantId
1330 ? group.entries.find((entry) => entry.id === terminalAssistantId)
1331 : null;
1332 const latestRunMatches = latestRun?.runId === runId;
1333 const lastEntryEnd =
1334 lastEntry.type === "message" ? lastEntry.message.updatedAt : lastEntry.createdAt;
1335 const elapsedMs =
1336 latestRunMatches && latestRun.startedAt && latestRun.completedAt
1337 ? computeElapsedMs(latestRun.startedAt, latestRun.completedAt)
1338 : computeElapsedMs(
1339 group.startBoundary ?? firstEntry.createdAt,
1340 maxIsoTimestamp(
1341 terminalEntry?.type === "message" ? terminalEntry.message.updatedAt : null,
1342 lastEntryEnd,
1343 ) ?? lastEntryEnd,
1344 );
1345 const duration = elapsedMs === null ? null : formatDuration(elapsedMs, resolve);
1346 const interrupted =
1347 latestRunMatches && (latestRun.status === "interrupted" || latestRun.status === "cancelled");
1348 const label = interrupted
1349 ? duration
1350 ? resolve(msg("You stopped after {duration}", { duration }))
1351 : resolve(msg("You stopped this response"))
1352 : duration
1353 ? resolve(msg("Worked for {duration}", { duration }))
1354 : resolve(msg("Worked"));
1355 // The top row keeps the whole turn's time. Work after a steer folds under
1356 // its own row below that steer, keyed apart so each segment opens alone.
1357 const segments = [
1358 {
1359 runId,
1360 entries: group.entries.slice(0, group.steerSegments[0]?.startIndex),
1361 label,
1362 },
1363 ...group.steerSegments.map(({ startIndex, steer }, index) => {
1364 const entries = group.entries.slice(startIndex, group.steerSegments[index + 1]?.startIndex);
1365 const segmentMs = computeElapsedMs(
1366 steer.createdAt,
1367 entries
1368 .map((entry) => (entry.type === "message" ? entry.message.updatedAt : entry.createdAt))
1369 .reduce<string | null>(maxIsoTimestamp, null) ?? steer.createdAt,
1370 );
1371 return {
1372 runId: steerFoldRunId(runId, steer.id),
1373 entries,
1374 label:
1375 segmentMs !== null
1376 ? resolve(
1377 msg("Continued for {duration}", { duration: formatDuration(segmentMs, resolve) }),
1378 )
1379 : resolve(msg("Continued")),
1380 };
1381 }),
1382 ];
1383 for (const segment of segments) {
1384 const firstHiddenEntry = segment.entries.find((entry) => hiddenEntryIds.has(entry.id));
1385 if (!firstHiddenEntry || !hidesNonCompactionWork(segment.entries)) continue;
1386 const deferredWorkItemIds = segment.entries.flatMap((entry) =>
1387 entry.type === "activity-group"
1388 ? entry.activities.flatMap((activity) =>
1389 activity.projectedItem.item.deferredWork
1390 ? [String(activity.projectedItem.sourceItemId)]
1391 : [],
1392 )
1393 : [],
1394 );
1395 foldsByAnchorId.set(firstHiddenEntry.id, {
1396 ...(deferredWorkItemIds.length > 0 ? { deferredWorkItemIds } : {}),
1397 runId: segment.runId,
1398 createdAt: firstHiddenEntry.createdAt,
1399 hiddenEntryIds: new Set(
1400 segment.entries.flatMap((entry) => (hiddenEntryIds.has(entry.id) ? [entry.id] : [])),
1401 ),
1402 label: segment.label,
1403 });
1404 }
1405 }
1406 const covered = new Set(
1407 [...foldsByAnchorId.values()].flatMap((fold) => [...fold.hiddenEntryIds]),
1408 );
1409 for (const entry of feed) {
1410 if (entry.type !== "activity-group" || covered.has(entry.id)) continue;
1411 const deferredWorkItemIds = entry.activities.flatMap((activity) =>
1412 activity.projectedItem.item.deferredWork ? [String(activity.projectedItem.sourceItemId)] : [],
1413 );
1414 if (deferredWorkItemIds.length === 0) continue;
1415 foldsByAnchorId.set(entry.id, {
1416 runId: RunId.make(`deferred-work:${entry.id}`),
1417 createdAt: entry.createdAt,
1418 hiddenEntryIds: new Set([entry.id]),
1419 label: resolve(msg("Earlier work")),
1420 deferredWorkItemIds,
1421 });
1422 }
1423 return foldsByAnchorId;
1424 }
1425
1426 const supersededReasoningGroups = new WeakMap<ThreadFeedActivityGroup, ThreadFeedActivityGroup>();
1427 const trailingReasoningGroups = new WeakMap<ThreadFeedActivityGroup, ThreadFeedActivityGroup>();
1428
1429 function settleSupersededReasoning(
1430 entry: Exclude<
1431 ThreadFeedEntry,
1432 { readonly type: "run-fold" | "work-toggle" | "thinking" | "viewed-images" }
1433 >,
1434 tail: boolean,
1435 ) {
1436 if (entry.type !== "activity-group") return entry;
1437 const cache = tail ? trailingReasoningGroups : supersededReasoningGroups;
1438 const cached = cache.get(entry);
1439 if (cached) return cached;
1440 const activities = entry.activities.map((activity, index) =>
1441 activity.workEntry.itemType === "reasoning" &&
1442 activity.lifecycleStatus === "inProgress" &&
1443 (!tail || index < entry.activities.length - 1)
1444 ? {
1445 ...activity,
1446 lifecycleStatus: "completed" as const,
1447 status: "success" as const,
1448 workEntry: { ...activity.workEntry, toolLifecycleStatus: "completed" as const },
1449 }
1450 : activity,
1451 );
1452 const settled = activities.some((activity, index) => activity !== entry.activities[index])
1453 ? { ...entry, activities }
1454 : entry;
1455 cache.set(entry, settled);
1456 return settled;
1457 }
1458
1459 interface ThreadFeedPresentationBuild {
1460 readonly feed: ReadonlyArray<ThreadFeedEntry>;
1461 readonly latestRun: ThreadFeedLatestRun | null;
1462 readonly expandedRunIds: ReadonlySet<RunId>;
1463 readonly expandedWorkGroupIds: ReadonlySet<string>;
1464 readonly activeWorkStartedAt: string | null;
1465 readonly runlessWorkActive: boolean;
1466 readonly display: ThreadFeedDisplay;
1467 readonly locale: string | undefined;
1468 readonly rows: ReadonlyArray<ThreadFeedEntry>;
1469 /** Feed entry `entry` is a user message whose rows start at `rowsLength`. */
1470 readonly restarts: ReadonlyArray<{ readonly entry: number; readonly rowsLength: number }>;
1471 /** Where each run's entries begin, so a reused prefix never shares a run with the rest. */
1472 readonly firstEntryByRun: ReadonlyMap<RunId, number>;
1473 }
1474
1475 function latestRunsEqual(left: ThreadFeedLatestRun | null, right: ThreadFeedLatestRun | null) {
1476 return (
1477 left === right ||
1478 (left !== null &&
1479 right !== null &&
1480 left.runId === right.runId &&
1481 left.status === right.status &&
1482 left.startedAt === right.startedAt &&
1483 left.completedAt === right.completedAt &&
1484 left.turnEnded === right.turnEnded &&
1485 left.providerStartingLabel === right.providerStartingLabel &&
1486 left.providerStartingLabelMsg === right.providerStartingLabelMsg)
1487 );
1488 }
1489
1490 /** Rows a fold leaves in view; the live fold skips them too, so settling keeps its place. */
1491 function staysOutOfFold(entry: ThreadFeedEntry): boolean {
1492 return (
1493 entry.type === "html-render" ||
1494 entry.type === "sent-message" ||
1495 entry.type === "mcp-app" ||
1496 (entry.type === "activity-group" &&
1497 entry.activities.some(
1498 (activity) =>
1499 activity.prominent ||
1500 activity.workEntry.questionAnswer !== undefined ||
1501 activity.projectedItem.item.type === "notification" ||
1502 activity.projectedItem.item.type === "handoff" ||
1503 // A child still working outlives its settled launching run;
1504 // its group stays visible while any member is live.
1505 isLiveSubagentTurnItem(activity.projectedItem.item),
1506 ))
1507 );
1508 }
1509
1510 function feedEntryRunId(entry: ThreadFeedEntry): RunId | null {
1511 return entry.type === "message" ? (entry.message.runId ?? null) : entry.runId;
1512 }
1513
1514 function isUserMessageEntry(entry: ThreadFeedEntry | undefined): boolean {
1515 return entry?.type === "message" && entry.message.role === "user";
1516 }
1517
1518 /**
1519 * A user message starts every fold and is never hidden or grouped, so the
1520 * rows before it depend only on the entries before it, their runs, and the
1521 * shared inputs. Returns the user message entry to restart from, or null to
1522 * present the whole feed.
1523 */
1524 function presentationRestart(
1525 previous: ThreadFeedPresentationBuild | null,
1526 feed: ReadonlyArray<ThreadFeedEntry>,
1527 latestRun: ThreadFeedLatestRun | null,
1528 expandedRunIds: ReadonlySet<RunId>,
1529 expandedWorkGroupIds: ReadonlySet<string>,
1530 activeWorkStartedAt: string | null,
1531 runlessWorkActive: boolean,
1532 display: ThreadFeedDisplay,
1533 locale: string | undefined,
1534 ): { readonly entry: number; readonly rowsLength: number; readonly index: number } | null {
1535 if (
1536 previous === null ||
1537 previous.locale !== locale ||
1538 !latestRunsEqual(previous.latestRun, latestRun) ||
1539 previous.activeWorkStartedAt !== activeWorkStartedAt ||
1540 previous.runlessWorkActive !== runlessWorkActive ||
1541 previous.display.toolCallVisibility !== display.toolCallVisibility ||
1542 previous.display.revealedMessageId !== display.revealedMessageId ||
1543 !setsEqual(previous.expandedRunIds, expandedRunIds) ||
1544 !setsEqual(previous.expandedWorkGroupIds, expandedWorkGroupIds)
1545 ) {
1546 return null;
1547 }
1548 const firstChanged = firstChangedIndex(previous.feed, feed);
1549 let index = previous.restarts.length - 1;
1550 while (index >= 0 && previous.restarts[index]!.entry > firstChanged) index -= 1;
1551 const restart = previous.restarts[index];
1552 if (restart === undefined || !isUserMessageEntry(feed[restart.entry])) return null;
1553 for (let entryIndex = restart.entry; entryIndex < feed.length; entryIndex += 1) {
1554 const runId = feedEntryRunId(feed[entryIndex]!);
1555 const firstEntry = runId === null ? undefined : previous.firstEntryByRun.get(runId);
1556 if (firstEntry !== undefined && firstEntry < restart.entry) return null;
1557 }
1558 return { ...restart, index };
1559 }
1560
1561 const visibleActivityGroups = new WeakMap<
1562 ThreadFeedActivityGroup,
1563 { readonly visibility: ToolCallVisibility; readonly group: ThreadFeedActivityGroup | null }
1564 >();
1565
1566 function zenKeepsActivity(activity: ThreadFeedActivity): boolean {
1567 const item = activity.projectedItem.item;
1568 return (
1569 activity.prominent ||
1570 activity.workEntry.questionAnswer !== undefined ||
1571 item.type === "compaction" ||
1572 item.type === "handoff" ||
1573 item.type === "notification" ||
1574 (item.type === "error" && item.status !== "completed")
1575 );
1576 }
1577
1578 function activityGroupForVisibility(
1579 entry: ThreadFeedActivityGroup,
1580 visibility: ToolCallVisibility,
1581 ): ThreadFeedActivityGroup | null {
1582 const cached = visibleActivityGroups.get(entry);
1583 if (cached?.visibility === visibility) return cached.group;
1584 const activities = entry.activities.filter((activity) =>
1585 visibility === "zen"
1586 ? zenKeepsActivity(activity)
1587 : !workEntryHiddenByToolCallVisibility(activity.workEntry, visibility),
1588 );
1589 const group =
1590 activities.length === 0
1591 ? null
1592 : activities.length === entry.activities.length
1593 ? entry
1594 : { ...entry, activities };
1595 visibleActivityGroups.set(entry, { visibility, group });
1596 return group;
1597 }
1598
1599 function isSteerMessage(message: ThreadFeedMessage): boolean {
1600 return (
1601 message.role === "user" &&
1602 (message.inputIntent === "steer" || message.inputIntent === "promoted_queued_to_steer")
1603 );
1604 }
1605
1606 function startsResponse(entry: ThreadFeedEntry): boolean {
1607 return (
1608 (entry.type === "message" && entry.message.role === "user" && !isSteerMessage(entry.message)) ||
1609 (entry.type === "activity-group" &&
1610 entry.activities.some((activity) => activity.projectedItem.item.type === "notification"))
1611 );
1612 }
1613
1614 function zenAnswerMessageIds(
1615 feed: ReadonlyArray<ThreadFeedEntry>,
1616 start: number,
1617 answering: boolean,
1618 answeringRunId: RunId | null,
1619 ): ReadonlySet<MessageId> {
1620 const replies: Array<{ readonly message: ThreadFeedMessage; readonly index: number }> = [];
1621 const lastReplyByResponse = new Map<string, MessageId>();
1622 const keptAnswers = new Set(finalAnswerIds(feed));
1623 let userMessages = 0;
1624 let awaitingReply = false;
1625 let candidate: MessageId | null = null;
1626 let answeringFrom = answering ? start : feed.length;
1627 for (let index = start; index < feed.length; index += 1) {
1628 const entry = feed[index]!;
1629 if (
1630 entry.type === "activity-group" &&
1631 entry.activities.every((activity) => activity.workEntry.itemType === "reasoning")
1632 ) {
1633 continue;
1634 }
1635 const reply =
1636 entry.type === "message" && entry.message.role === "assistant" ? entry.message : null;
1637 if (candidate !== null && reply !== null) keptAnswers.add(candidate);
1638 candidate = null;
1639 if (answering && startsResponse(entry)) answeringFrom = index + 1;
1640 if (entry.type === "message" && entry.message.role === "user") {
1641 userMessages += 1;
1642 awaitingReply = isSteerMessage(entry.message);
1643 } else if (reply !== null) {
1644 replies.push({ message: reply, index });
1645 lastReplyByResponse.set(reply.runId ?? `runless:${userMessages}`, reply.id);
1646 if (awaitingReply) {
1647 candidate = reply.id;
1648 awaitingReply = false;
1649 }
1650 }
1651 }
1652 const terminal = new Set(lastReplyByResponse.values());
1653 return new Set(
1654 replies
1655 .filter(
1656 ({ message, index }) =>
1657 keptAnswers.has(message.id) ||
1658 (terminal.has(message.id) &&
1659 index < answeringFrom &&
1660 (answeringRunId === null || message.runId !== answeringRunId)),
1661 )
1662 .map(({ message }) => message.id),
1663 );
1664 }
1665
1666 function liveAnswerPreview(feed: ReadonlyArray<ThreadFeedEntry>): string | null {
1667 for (let index = feed.length - 1; index >= 0; index -= 1) {
1668 const entry = feed[index]!;
1669 if (startsResponse(entry)) return null;
1670 const texts =
1671 entry.type === "message"
1672 ? entry.message.role === "assistant"
1673 ? [entry.message.text]
1674 : []
1675 : entry.type === "activity-group"
1676 ? entry.activities
1677 .filter((activity) => activity.workEntry.itemType === "reasoning")
1678 .map((activity) => activity.workEntry.detail ?? "")
1679 : [];
1680 for (let textIndex = texts.length - 1; textIndex >= 0; textIndex -= 1) {
1681 const line = compactWorkEntryText(liveThoughtLine(texts[textIndex]!));
1682 if (line !== "") return line;
1683 }
1684 }
1685 return null;
1686 }
1687
1688 export interface ThreadFeedDisplay {
1689 readonly toolCallVisibility: ToolCallVisibility;
1690 readonly revealedMessageId: MessageId | null;
1691 }
1692
1693 const DEFAULT_THREAD_FEED_DISPLAY: ThreadFeedDisplay = {
1694 toolCallVisibility: "showAll",
1695 revealedMessageId: null,
1696 };
1697
1698 export function deriveThreadFeedPresentation(
1699 feed: ReadonlyArray<ThreadFeedEntry>,
1700 latestRun: ThreadFeedLatestRun | null,
1701 expandedRunIds: ReadonlySet<RunId>,
1702 expandedWorkGroupIds: ReadonlySet<string> = new Set(),
1703 activeWorkStartedAt: string | null = null,
1704 runlessWorkActive = false,
1705 cache?: ThreadFeedCache,
1706 display: ThreadFeedDisplay = DEFAULT_THREAD_FEED_DISPLAY,
1707 resolve: MessageResolver = m,
1708 locale?: string,
1709 ): ThreadFeedEntry[] {
1710 const previous = cache?.presentation ?? null;
1711 const restart = presentationRestart(
1712 previous,
1713 feed,
1714 latestRun,
1715 expandedRunIds,
1716 expandedWorkGroupIds,
1717 activeWorkStartedAt,
1718 runlessWorkActive,
1719 display,
1720 locale,
1721 );
1722 const start = restart?.entry ?? 0;
1723 const result: ThreadFeedEntry[] =
1724 restart === null ? [] : previous!.rows.slice(0, restart.rowsLength);
1725 const restarts = restart === null ? [] : previous!.restarts.slice(0, restart.index);
1726 const firstEntryByRun = new Map<RunId, number>();
1727 if (restart !== null) {
1728 for (const [runId, entry] of previous!.firstEntryByRun) {
1729 if (entry < start) firstEntryByRun.set(runId, entry);
1730 }
1731 }
1732 const tailStart = result.length;
1733 const lastEntryByRun = new Map<RunId, number>();
1734
1735 const retainedFeed: Array<
1736 Exclude<
1737 ThreadFeedEntry,
1738 { readonly type: "run-fold" | "work-toggle" | "thinking" | "viewed-images" }
1739 >
1740 > = [];
1741 const retainedFeedIndices: number[] = [];
1742 const { toolCallVisibility, revealedMessageId } = display;
1743 const isWorking = activeWorkStartedAt !== null && latestRun?.status !== "preparing";
1744 const activeRunId = unsettledRunId(latestRun);
1745 const zen = toolCallVisibility === "zen";
1746 const answering = isWorking && latestRun?.turnEnded !== true;
1747 const zenAnswerIds = zen
1748 ? zenAnswerMessageIds(feed, start, answering, answering ? activeRunId : null)
1749 : null;
1750 for (let index = start; index < feed.length; index += 1) {
1751 let entry = feed[index]!;
1752 if (
1753 entry.type === "run-fold" ||
1754 entry.type === "work-toggle" ||
1755 entry.type === "thinking" ||
1756 entry.type === "viewed-images"
1757 )
1758 continue;
1759 const runId = feedEntryRunId(entry);
1760 if (runId !== null) {
1761 if (!firstEntryByRun.has(runId)) firstEntryByRun.set(runId, index);
1762 lastEntryByRun.set(runId, index);
1763 }
1764 if (entry.type === "activity-group" && toolCallVisibility !== "showAll") {
1765 const shown = activityGroupForVisibility(entry, toolCallVisibility);
1766 if (shown === null) continue;
1767 entry = shown;
1768 } else if (
1769 zenAnswerIds !== null &&
1770 entry.type === "message" &&
1771 entry.message.role === "assistant" &&
1772 entry.message.id !== revealedMessageId &&
1773 !zenAnswerIds.has(entry.message.id)
1774 ) {
1775 continue;
1776 }
1777 retainedFeed.push(entry);
1778 retainedFeedIndices.push(index);
1779 }
1780 const sourceFeed = retainedFeed.map((entry, index) =>
1781 settleSupersededReasoning(entry, index === retainedFeed.length - 1),
1782 );
1783 const failedRunIds = failedFeedRunIds(sourceFeed, latestRun);
1784 const activeTailGroup = sourceFeed.at(-1);
1785 // A bare `/compact` turn is the compaction itself: its compaction row stands in for the prompt
1786 // and the live activity row. An answered "compact before continuing?" question folds into the
1787 // compaction it asked for.
1788 const compactionCommandRunIds = new Set<RunId>();
1789 const compactionItemRunIds = new Set<RunId>();
1790 for (const entry of feed) {
1791 if (
1792 entry.type === "message" &&
1793 entry.message.runId !== null &&
1794 isCompactionCommandMessage(entry.message)
1795 ) {
1796 compactionCommandRunIds.add(entry.message.runId);
1797 } else if (
1798 entry.type === "activity-group" &&
1799 entry.runId !== null &&
1800 isContextCompactionActivityGroup(entry)
1801 ) {
1802 compactionItemRunIds.add(entry.runId);
1803 }
1804 }
1805 const foldsByAnchorId = zen
1806 ? new Map<string, ThreadFeedRunFold>()
1807 : deriveThreadFeedRunFolds(
1808 sourceFeed,
1809 latestRun,
1810 isWorking && runlessWorkActive,
1811 failedRunIds,
1812 resolve,
1813 );
1814 const collapsedEntryIds = new Set<string>();
1815 for (const fold of foldsByAnchorId.values()) {
1816 if (!expandedRunIds.has(fold.runId)) {
1817 for (const entryId of fold.hiddenEntryIds) collapsedEntryIds.add(entryId);
1818 }
1819 }
1820 // The working run's fold row shows its live timer where "Worked for" lands once it settles.
1821 // Zen never folds, so it keeps only the Thinking row.
1822 // Runless work folds under its prompt's key once it settles, so the live row takes that key.
1823 const runlessPrompt =
1824 activeRunId === null && runlessWorkActive
1825 ? sourceFeed.findLast((entry) => isUserMessageEntry(entry) && feedEntryRunId(entry) === null)
1826 : undefined;
1827 const liveRunId =
1828 activeRunId ?? (runlessPrompt ? RunId.make(`runless:${runlessPrompt.id}`) : null);
1829 const liveFold =
1830 !zen &&
1831 isWorking &&
1832 activeWorkStartedAt !== null &&
1833 liveRunId !== null &&
1834 !compactionCommandRunIds.has(liveRunId)
1835 ? liveRunFoldRow(liveRunId, activeWorkStartedAt, resolve)
1836 : null;
1837 let liveFoldPlaced = false;
1838 // Earlier turns can hold the run's own items (a subagent it continued), so wait for its prompt.
1839 let liveFoldReady =
1840 liveFold !== null &&
1841 activeRunId !== null &&
1842 !sourceFeed.some((entry) => isUserMessageEntry(entry) && feedEntryRunId(entry) === activeRunId);
1843 for (let sourceIndex = 0; sourceIndex < sourceFeed.length; sourceIndex += 1) {
1844 const entry = sourceFeed[sourceIndex]!;
1845 const feedIndex = retainedFeedIndices[sourceIndex]!;
1846 if (liveFold !== null && !liveFoldPlaced && feedEntryRunId(entry) === activeRunId) {
1847 if (isUserMessageEntry(entry)) {
1848 liveFoldReady = activeRunId !== null || entry === runlessPrompt;
1849 } else if (
1850 liveFoldReady &&
1851 !staysOutOfFold(entry) &&
1852 !(entry.type === "activity-group" && isContextCompactionActivityGroup(entry))
1853 ) {
1854 result.push(liveFold);
1855 liveFoldPlaced = true;
1856 }
1857 }
1858 if (isUserMessageEntry(entry)) {
1859 restarts.push({ entry: feedIndex, rowsLength: result.length });
1860 }
1861 const isActiveTailGroup =
1862 isWorking &&
1863 (activeRunId !== null || runlessWorkActive) &&
1864 entry.type === "activity-group" &&
1865 activeTailGroup?.type === "activity-group" &&
1866 activeTailGroup.id === entry.id &&
1867 entry.runId === activeRunId;
1868 const fold = foldsByAnchorId.get(entry.id);
1869 if (fold) {
1870 const expanded = expandedRunIds.has(fold.runId);
1871 let row = runFoldRowsCache.get(entry);
1872 if (
1873 !row ||
1874 row.runId !== fold.runId ||
1875 row.createdAt !== fold.createdAt ||
1876 row.label !== fold.label ||
1877 row.expanded !== expanded ||
1878 row.deferredWorkItemIds?.join("|") !== fold.deferredWorkItemIds?.join("|")
1879 ) {
1880 row = {
1881 type: "run-fold",
1882 id: `run-fold:${fold.runId}`,
1883 ...(fold.deferredWorkItemIds ? { deferredWorkItemIds: fold.deferredWorkItemIds } : {}),
1884 createdAt: fold.createdAt,
1885 runId: fold.runId,
1886 label: fold.label,
1887 expanded,
1888 };
1889 runFoldRowsCache.set(entry, row);
1890 }
1891 result.push(row);
1892 }
1893 if (
1894 (entry.type === "message" &&
1895 entry.message.runId !== null &&
1896 compactionItemRunIds.has(entry.message.runId) &&
1897 isCompactionCommandMessage(entry.message)) ||
1898 (entry.type === "activity-group" &&
1899 entry.runId !== null &&
1900 compactionItemRunIds.has(entry.runId) &&
1901 isResumeCompactionAnswerGroup(entry))
1902 ) {
1903 continue;
1904 }
1905 if (!collapsedEntryIds.has(entry.id)) {
1906 if (
1907 entry.type === "activity-group" &&
1908 entry.runId !== null &&
1909 failedRunIds.has(entry.runId)
1910 ) {
1911 let rows = failedActivityGroupsCache.get(entry);
1912 if (!rows) {
1913 rows =
1914 entry.activities.length === 1
1915 ? [entry]
1916 : entry.activities.map((activity) => ({
1917 type: "activity-group" as const,
1918 id: activity.id,
1919 createdAt: activity.createdAt,
1920 runId: activity.runId,
1921 activities: [activity],
1922 }));
1923 failedActivityGroupsCache.set(entry, rows);
1924 }
1925 result.push(...rows);
1926 continue;
1927 }
1928 appendPresentedFeedEntry(
1929 result,
1930 entry,
1931 expandedWorkGroupIds,
1932 activeRunId,
1933 isWorking,
1934 isActiveTailGroup,
1935 resolve,
1936 locale,
1937 );
1938 }
1939 }
1940 if (liveFold !== null && !liveFoldPlaced) result.push(liveFold);
1941 if (
1942 isWorking &&
1943 activeWorkStartedAt !== null &&
1944 latestRun?.turnEnded !== true &&
1945 (activeRunId === null || !compactionCommandRunIds.has(activeRunId)) &&
1946 !result.some(
1947 (row) =>
1948 row.id === LIVE_ACTIVITY_ROW_ID ||
1949 (row.type === "activity-group" &&
1950 isContextCompactionActivityGroup(row) &&
1951 row.runId === activeRunId &&
1952 row.activities[0]?.projectedItem.item.status === "running"),
1953 )
1954 ) {
1955 const waitingOn = activeRunId === null ? 0 : runningSubagentsAtRunTail(feed, activeRunId);
1956 result.push(
1957 thinkingRow(
1958 activeWorkStartedAt,
1959 activeRunId,
1960 waitingOn > 0
1961 ? waitingOnSubagentsLabel(waitingOn, resolve)
1962 : zen
1963 ? liveAnswerPreview(feed)
1964 : null,
1965 latestRun?.providerStartingLabelMsg === undefined
1966 ? latestRun?.providerStartingLabel
1967 : resolve(latestRun.providerStartingLabelMsg),
1968 ),
1969 );
1970 }
1971 const checkpointByRunId = new Map<RunId, ThreadCheckpointSummary>();
1972 for (const entry of sourceFeed) {
1973 if (entry.type === "message" && entry.message.checkpointSummary) {
1974 checkpointByRunId.set(entry.message.checkpointSummary.runId, entry.message.checkpointSummary);
1975 }
1976 }
1977 const workRowByRunId = new Map<RunId, number>();
1978 for (let index = tailStart; index < result.length; index += 1) {
1979 const row = result[index]!;
1980 if (
1981 (row.type === "run-fold" || row.type === "work-toggle") &&
1982 row.runId !== null &&
1983 checkpointByRunId.has(row.runId) &&
1984 (row.type === "run-fold" || !workRowByRunId.has(row.runId))
1985 ) {
1986 workRowByRunId.set(row.runId, index);
1987 }
1988 }
1989 for (const [runId, index] of workRowByRunId) {
1990 result[index] = { ...result[index]!, checkpointSummary: checkpointByRunId.get(runId)! };
1991 }
1992 for (let index = tailStart; index < result.length; index += 1) {
1993 const row = result[index]!;
1994 if (
1995 row.type !== "message" ||
1996 !row.message.checkpointSummary ||
1997 !workRowByRunId.has(row.message.checkpointSummary.runId)
1998 )
1999 continue;
2000 const message = { ...row.message };
2001 delete message.checkpointSummary;
2002 result[index] = { ...row, message };
2003 }
2004 // Reused rows are final: the user message after them never continues a work log.
2005 for (let index = tailStart; index < result.length; index += 1) {
2006 const row = result[index]!;
2007 if (!isWorkLogFeedRow(row) || !isWorkLogFeedRow(result[index + 1])) continue;
2008 let continued = continuedWorkLogRows.get(row);
2009 if (!continued) {
2010 continued = { ...row, continuesWorkLog: true };
2011 continuedWorkLogRows.set(row, continued);
2012 }
2013 result[index] = continued;
2014 }
2015 // A run that crosses a user message made the rows before it from entries
2016 // after it, so a later build cannot restart there even once those entries
2017 // are gone. Only runs of this build's own entries can cross its restarts.
2018 const crossings = Array.from({ length: feed.length - start + 1 }, () => 0);
2019 for (const [runId, last] of lastEntryByRun) {
2020 const first = firstEntryByRun.get(runId)!;
2021 if (first >= last) continue;
2022 crossings[first - start + 1]! += 1;
2023 crossings[last - start + 1]! -= 1;
2024 }
2025 let crossingRuns = 0;
2026 let crossingIndex = 0;
2027 const cleanRestarts = restarts.filter((candidate) => {
2028 if (candidate.entry < start) return true;
2029 while (crossingIndex <= candidate.entry - start) {
2030 crossingRuns += crossings[crossingIndex]!;
2031 crossingIndex += 1;
2032 }
2033 return crossingRuns === 0;
2034 });
2035 if (cache) {
2036 cache.presentation = {
2037 feed,
2038 latestRun,
2039 expandedRunIds,
2040 expandedWorkGroupIds,
2041 activeWorkStartedAt,
2042 runlessWorkActive,
2043 display,
2044 locale,
2045 rows: result,
2046 restarts: cleanRestarts,
2047 firstEntryByRun,
2048 };
2049 }
2050 return result;
2051 }
2052
2053 const continuedWorkLogRows = new WeakMap<ThreadFeedEntry, ThreadFeedEntry>();
2054
2055 function isWorkLogFeedRow(row: ThreadFeedEntry | undefined): boolean {
2056 return (
2057 row !== undefined &&
2058 (row.type === "work-toggle" ||
2059 row.type === "thinking" ||
2060 (row.type === "activity-group" &&
2061 !isContextCompactionActivityGroup(row) &&
2062 !isContextHandoffActivityGroup(row) &&
2063 row.activities.every(
2064 (activity) =>
2065 !activity.prominent &&
2066 activity.projectedItem.item.type !== "notification" &&
2067 activity.projectedItem.item.type !== "subagent",
2068 )))
2069 );
2070 }
2071
2072 export const LIVE_ACTIVITY_ROW_ID = "live-activity-row";
2073
2074 /** Reads the feed before tool visibility filters it, so hidden newer parent work still counts. */
2075 function runningSubagentsAtRunTail(feed: ReadonlyArray<ThreadFeedEntry>, runId: RunId): number {
2076 let running = 0;
2077 for (let index = feed.length - 1; index >= 0; index -= 1) {
2078 const entry = feed[index]!;
2079 if (entry.type !== "activity-group" || entry.runId !== runId) break;
2080 const items = entry.activities.map((activity) => activity.projectedItem.item);
2081 if (items.some((item) => item.type !== "subagent")) break;
2082 running += items.filter(isLiveSubagentTurnItem).length;
2083 }
2084 return running;
2085 }
2086
2087 let cachedLiveRunFoldRow: Extract<ThreadFeedEntry, { readonly type: "run-fold" }> | null = null;
2088
2089 function liveRunFoldRow(runId: RunId, startedAt: string, resolve: MessageResolver) {
2090 const label = resolve(msg("Working"));
2091 if (
2092 cachedLiveRunFoldRow?.runId !== runId ||
2093 cachedLiveRunFoldRow.workingSince !== startedAt ||
2094 cachedLiveRunFoldRow.label !== label
2095 ) {
2096 cachedLiveRunFoldRow = {
2097 type: "run-fold",
2098 id: `run-fold:${runId}`,
2099 createdAt: startedAt,
2100 runId,
2101 label,
2102 expanded: false,
2103 workingSince: startedAt,
2104 };
2105 }
2106 return cachedLiveRunFoldRow;
2107 }
2108
2109 function thinkingRow(
2110 createdAt: string,
2111 runId: RunId | null,
2112 label: string | null,
2113 providerStartingLabel: string | undefined,
2114 ) {
2115 if (
2116 cachedThinkingRow?.createdAt !== createdAt ||
2117 cachedThinkingRow.runId !== runId ||
2118 (cachedThinkingRow.label ?? null) !== label ||
2119 cachedThinkingRow.providerStartingLabel !== providerStartingLabel
2120 ) {
2121 cachedThinkingRow = {
2122 type: "thinking",
2123 id: LIVE_ACTIVITY_ROW_ID,
2124 createdAt,
2125 runId,
2126 ...(label === null ? {} : { label }),
2127 ...(providerStartingLabel === undefined ? {} : { providerStartingLabel }),
2128 };
2129 }
2130 return cachedThinkingRow;
2131 }
2132
2133 function appendPresentedFeedEntry(
2134 result: ThreadFeedEntry[],
2135 entry: Exclude<
2136 ThreadFeedEntry,
2137 { readonly type: "run-fold" | "work-toggle" | "thinking" | "viewed-images" }
2138 >,
2139 expandedWorkGroupIds: ReadonlySet<string>,
2140 activeRunId: RunId | null,
2141 isWorking: boolean,
2142 activeTail: boolean,
2143 resolve: MessageResolver,
2144 locale: string | undefined,
2145 ): void {
2146 if (entry.type !== "activity-group") {
2147 result.push(entry);
2148 return;
2149 }
2150 if (
2151 isContextCompactionActivityGroup(entry) ||
2152 isContextHandoffActivityGroup(entry) ||
2153 isUserInputActivityGroup(entry) ||
2154 entry.activities[0]?.projectedItem.item.type === "subagent"
2155 ) {
2156 result.push(entry);
2157 return;
2158 }
2159
2160 let cached = presentedActivityGroupsCache.get(entry);
2161 if (
2162 !cached ||
2163 cached.activeRunId !== activeRunId ||
2164 cached.isWorking !== isWorking ||
2165 cached.activeTail !== activeTail ||
2166 cached.locale !== locale ||
2167 cached.rows.some(
2168 (row) => row.type === "work-toggle" && expandedWorkGroupIds.has(row.groupId) !== row.expanded,
2169 )
2170 ) {
2171 const rows: ThreadFeedEntry[] = [];
2172 appendActivityGroupRows(
2173 rows,
2174 entry,
2175 expandedWorkGroupIds,
2176 activeRunId,
2177 isWorking,
2178 activeTail,
2179 resolve,
2180 );
2181 cached = { activeRunId, isWorking, activeTail, locale, rows };
2182 presentedActivityGroupsCache.set(entry, cached);
2183 }
2184 for (const row of cached.rows) {
2185 result.push(row);
2186 }
2187 }
2188
2189 function appendActivityGroupRows(
2190 result: ThreadFeedEntry[],
2191 entry: ThreadFeedActivityGroup,
2192 expandedWorkGroupIds: ReadonlySet<string>,
2193 activeRunId: RunId | null,
2194 isWorking: boolean,
2195 activeTail: boolean,
2196 resolve: MessageResolver,
2197 ): void {
2198 const groupAnchorIdByActivityId = new Map<string, string>();
2199 let groupAnchorId: string | null = null;
2200 for (const activity of entry.activities) {
2201 const item = activity.projectedItem.item;
2202 if (activity.prominent || (item.type === "error" && item.status === "failed")) {
2203 groupAnchorId = null;
2204 continue;
2205 }
2206 groupAnchorId ??= activity.id;
2207 groupAnchorIdByActivityId.set(activity.id, groupAnchorId);
2208 }
2209 const activities = entry.activities.filter(
2210 (activity) =>
2211 threadFeedActivityIsVisible(activity) ||
2212 (isWorking && activity.lifecycleStatus === "inProgress" && activity.runId === activeRunId),
2213 );
2214 if (activities.length === 0) {
2215 return;
2216 }
2217
2218 let groupableRun: ThreadFeedActivity[] = [];
2219 const flushGroupableRun = (isTrailingRun: boolean) => {
2220 if (groupableRun.length === 0) return;
2221 const groupId = `work-group:${groupAnchorIdByActivityId.get(groupableRun[0]!.id) ?? groupableRun[0]!.id}`;
2222 appendToolGroupRows(
2223 result,
2224 entry,
2225 groupableRun,
2226 groupId,
2227 expandedWorkGroupIds,
2228 activeRunId,
2229 isWorking,
2230 activeTail && isTrailingRun,
2231 resolve,
2232 );
2233 const paths = workEntriesViewedImagePaths(groupableRun.map((activity) => activity.workEntry));
2234 if (paths.length > 0) {
2235 result.push({
2236 type: "viewed-images",
2237 id: `${groupId}:viewed-images`,
2238 createdAt: groupableRun[0]!.createdAt,
2239 runId: groupableRun[0]!.runId,
2240 paths,
2241 });
2242 }
2243 groupableRun = [];
2244 };
2245 for (const activity of activities) {
2246 const item = activity.projectedItem.item;
2247 const severeProviderError = item.type === "error" && item.status === "failed";
2248 if (!activity.prominent && !severeProviderError && item.type !== "notification") {
2249 groupableRun.push(activity);
2250 continue;
2251 }
2252 flushGroupableRun(false);
2253 result.push({
2254 type: "activity-group",
2255 id: activity.id,
2256 createdAt: activity.createdAt,
2257 runId: activity.runId,
2258 activities: [activity],
2259 });
2260 }
2261 flushGroupableRun(true);
2262 }
2263
2264 function appendToolGroupRows(
2265 result: ThreadFeedEntry[],
2266 sourceGroup: Extract<ThreadFeedEntry, { readonly type: "activity-group" }>,
2267 activities: ReadonlyArray<ThreadFeedActivity>,
2268 groupId: string,
2269 expandedWorkGroupIds: ReadonlySet<string>,
2270 activeRunId: RunId | null,
2271 isWorking: boolean,
2272 activeTail: boolean,
2273 resolve: MessageResolver,
2274 ): void {
2275 const expanded = expandedWorkGroupIds.has(groupId);
2276 const latestActiveActivity = activities.findLast(
2277 (activity) =>
2278 isWorking && activity.lifecycleStatus === "inProgress" && activity.runId === activeRunId,
2279 );
2280 const active = latestActiveActivity !== undefined;
2281 const live = activeTail || active;
2282 const latestActivity = latestActiveActivity ?? activities.at(-1)!;
2283 const shimmer = activeTail && (active || latestActivity.status === "success");
2284 const singleActivity = activities.length === 1 ? latestActivity : null;
2285 const groupSummary = summarizeToolGroup(
2286 activities.map((activity) => activity.workEntry),
2287 resolve,
2288 );
2289 const latestThought =
2290 live && !expanded
2291 ? activities.findLast(
2292 (activity) =>
2293 activity.workEntry.itemType === "reasoning" &&
2294 (activity.workEntry.detail?.trim() ?? "") !== "",
2295 )?.workEntry.detail
2296 : undefined;
2297 const thought = latestThought ? compactWorkEntryText(liveThoughtLine(latestThought)) : "";
2298 const summary = live
2299 ? (expanded || thought) && latestActivity.workEntry.itemType === "reasoning"
2300 ? latestActivity.lifecycleStatus === "inProgress"
2301 ? resolve(msg("Thinking"))
2302 : resolve(msg("Thought"))
2303 : liveToolActivitySummary(latestActivity, live, resolve)
2304 : singleActivity !== null &&
2305 singleActivity.toolLike &&
2306 toolGroupAction(singleActivity.workEntry) !== "edit"
2307 ? singleToolCallLabel(singleActivity, expanded, resolve)
2308 : singleActivity !== null && !singleActivity.toolLike
2309 ? singleActivity.workEntry.label
2310 : groupSummary.summary;
2311 const id = shimmer ? LIVE_ACTIVITY_ROW_ID : `${live ? "work-live" : "work-toggle"}:${groupId}`;
2312 // Lone calls replace the header and disclose directly; lone thoughts retain the header to show text on expansion.
2313 if (singleActivity !== null && singleActivity.workEntry.itemType !== "reasoning") {
2314 result.push({
2315 type: "activity-group",
2316 id,
2317 createdAt: singleActivity.createdAt,
2318 runId: singleActivity.runId,
2319 activities: [{ ...singleActivity, live: shimmer, groupStandIn: { groupId, label: summary } }],
2320 // No trailing margin lets Thinking or a growing group replace the row without shifting the feed.
2321 continuesWorkLog: true,
2322 });
2323 return;
2324 }
2325 const primarySourceActivity = activities.find(
2326 (activity) => activity.workEntry.toolSource !== undefined,
2327 );
2328 const primarySourceKey = primarySourceActivity?.workEntry.toolSource?.key;
2329 const primarySourceIcon = primarySourceKey
2330 ? (activities.find(
2331 (activity) =>
2332 activity.workEntry.toolSource?.key === primarySourceKey &&
2333 activity.workEntry.toolIcon !== undefined,
2334 )?.workEntry.toolIcon ?? primarySourceActivity?.workEntry.toolSource?.icon)
2335 : undefined;
2336 const groupToolSurface =
2337 primarySourceActivity?.workEntry.toolSurface ??
2338 latestActivity.workEntry.toolSurface ??
2339 activities.findLast((activity) => activity.workEntry.toolSurface !== undefined)?.workEntry
2340 .toolSurface;
2341 const groupToolIcon =
2342 primarySourceIcon ??
2343 latestActivity.workEntry.toolIcon ??
2344 activities.findLast((activity) => activity.workEntry.toolIcon !== undefined)?.workEntry
2345 .toolIcon;
2346 const summaryToolIcon = live
2347 ? resolveWorkEntryToolPresentation(latestActivity.workEntry, undefined, resolve)?.icon
2348 : undefined;
2349 result.push({
2350 type: "work-toggle",
2351 id,
2352 createdAt: sourceGroup.createdAt,
2353 runId: sourceGroup.runId,
2354 groupId,
2355 hiddenCount: activities.length,
2356 expanded,
2357 summary,
2358 summaryKind: toolGroupSummaryKind(
2359 (live ? [latestActivity] : activities).map((activity) => activity.workEntry),
2360 ),
2361 ...(groupToolSurface ? { toolSurface: groupToolSurface } : {}),
2362 ...(groupToolIcon ? { toolIcon: groupToolIcon } : {}),
2363 ...(summaryToolIcon ? { summaryToolIcon } : {}),
2364 ...(thought ? { thought } : {}),
2365 hasFailure: (() => {
2366 const lastToolLike = activities.findLast((activity) => activity.toolLike);
2367 return (
2368 lastToolLike !== undefined && workEntryDisplayIndicatesToolFailure(lastToolLike.workEntry)
2369 );
2370 })(),
2371 live,
2372 shimmer,
2373 });
2374 if (!expanded) return;
2375 result.push({
2376 type: "activity-group",
2377 id: `work-details:${groupId}`,
2378 createdAt: activities[0]!.createdAt,
2379 runId: activities[0]!.runId,
2380 activities: activities.map((activity) => ({
2381 ...activity,
2382 groupedToolDetail: true,
2383 live:
2384 isWorking &&
2385 activity.id === latestActivity.id &&
2386 activity.lifecycleStatus === "inProgress" &&
2387 activity.runId === activeRunId,
2388 })),
2389 });
2390 }
2391
2392 function liveToolActivitySummary(
2393 activity: ThreadFeedActivity,
2394 presentTense: boolean,
2395 resolve: MessageResolver,
2396 ): string {
2397 const status = liveActivityToolStatus(activity.lifecycleStatus, presentTense);
2398 if (activity.workEntry.itemType === "reasoning") {
2399 return compactWorkEntryText(
2400 activity.workEntry.detail?.trim() ||
2401 (status === "inProgress" ? resolve(msg("Thinking")) : resolve(msg("Thought"))),
2402 );
2403 }
2404 const presentation = resolveWorkEntryToolPresentation(
2405 { ...activity.workEntry, toolLifecycleStatus: status },
2406 undefined,
2407 resolve,
2408 );
2409 if (presentation) return presentation.displayName;
2410 const command = activity.workEntry.command?.trim();
2411 if (command) {
2412 const program = commandProgramName(command);
2413 if (program === null || program === undefined) {
2414 return status === "inProgress"
2415 ? resolve(msg("Running command"))
2416 : status === "failed"
2417 ? resolve(msg("Failed command"))
2418 : status === "declined"
2419 ? resolve(msg("Declined command"))
2420 : status === "stopped"
2421 ? resolve(msg("Stopped command"))
2422 : resolve(msg("Ran command"));
2423 }
2424 return status === "inProgress"
2425 ? resolve(msg("Running {program}", { program }))
2426 : status === "failed"
2427 ? resolve(msg("Failed {program}", { program }))
2428 : status === "declined"
2429 ? resolve(msg("Declined {program}", { program }))
2430 : status === "stopped"
2431 ? resolve(msg("Stopped {program}", { program }))
2432 : resolve(msg("Ran {program}", { program }));
2433 }
2434 return (
2435 commandlessCommandLabel(activity.workEntry, status, resolve) ??
2436 compactWorkEntryText(activity.detail ?? activity.summary)
2437 );
2438 }
2439
2440 interface ThreadFeedBuild {
2441 readonly rows: ReadonlyArray<OrchestrationV2ProjectedTurnItem>;
2442 readonly locale: string | undefined;
2443 readonly attempts: ReadonlyArray<OrchestrationV2RunAttempt> | undefined;
2444 readonly nodes: ReadonlyArray<OrchestrationV2ExecutionNode> | undefined;
2445 readonly checkpointSummaries: ReadonlyArray<ThreadCheckpointSummary> | undefined;
2446 readonly foldedAnswerRunIdByMessageId: ReadonlyMap<string, RunId | null>;
2447 readonly delegatedChildrenByRun: ReadonlyMap<RunId, ReadonlySet<string>>;
2448 readonly feed: ReadonlyArray<ThreadFeedEntry>;
2449 /** Grouping is empty before `row`: the rows before it produced `feed.slice(0, feedLength)`. */
2450 readonly restarts: ReadonlyArray<{ readonly row: number; readonly feedLength: number }>;
2451 }
2452
2453 /**
2454 * Keep one cache per on-screen feed across renders to reuse unchanged prefixes during streaming.
2455 * Sharing it between threads would make their results evict each other.
2456 */
2457 export interface ThreadFeedCache {
2458 feedBuild: ThreadFeedBuild | null;
2459 presentation: ThreadFeedPresentationBuild | null;
2460 }
2461
2462 export function createThreadFeedCache(): ThreadFeedCache {
2463 return { feedBuild: null, presentation: null };
2464 }
2465
2466 function setsEqual<T>(left: ReadonlySet<T>, right: ReadonlySet<T>): boolean {
2467 if (left.size !== right.size) return false;
2468 for (const value of left) if (!right.has(value)) return false;
2469 return true;
2470 }
2471
2472 // Summaries are re-derived whenever messages change, including streamed text,
2473 // so a new array often holds the same checkpoints.
2474 function checkpointSummariesEqual(
2475 left: ReadonlyArray<ThreadCheckpointSummary> | undefined,
2476 right: ReadonlyArray<ThreadCheckpointSummary> | undefined,
2477 ): boolean {
2478 if (left === right) return true;
2479 if (left === undefined || right === undefined || left.length !== right.length) return false;
2480 return left.every((summary, index) => {
2481 const other = right[index]!;
2482 return (
2483 summary.checkpointId === other.checkpointId &&
2484 summary.scopeId === other.scopeId &&
2485 summary.runId === other.runId &&
2486 summary.checkpointTurnCount === other.checkpointTurnCount &&
2487 summary.checkpointRef === other.checkpointRef &&
2488 summary.completedAt === other.completedAt &&
2489 summary.status === other.status &&
2490 summary.files === other.files &&
2491 summary.assistantMessageId === other.assistantMessageId
2492 );
2493 });
2494 }
2495
2496 function mapsEqual<K, V>(left: ReadonlyMap<K, V>, right: ReadonlyMap<K, V>): boolean {
2497 if (left.size !== right.size) return false;
2498 for (const [key, value] of left) {
2499 if (!right.has(key) || right.get(key) !== value) return false;
2500 }
2501 return true;
2502 }
2503
2504 function setMapsEqual<K, V>(
2505 left: ReadonlyMap<K, ReadonlySet<V>>,
2506 right: ReadonlyMap<K, ReadonlySet<V>>,
2507 ): boolean {
2508 if (left.size !== right.size) return false;
2509 for (const [key, values] of left) {
2510 const other = right.get(key);
2511 if (other === undefined || !setsEqual(values, other)) return false;
2512 }
2513 return true;
2514 }
2515
2516 /** Index of the first entry that differs, or the shorter length when one extends the other. */
2517 function firstChangedIndex<T>(previous: ReadonlyArray<T>, next: ReadonlyArray<T>): number {
2518 const limit = Math.min(previous.length, next.length);
2519 let index = 0;
2520 while (index < limit && previous[index] === next[index]) index += 1;
2521 return index;
2522 }
2523
2524 export function buildThreadFeed(
2525 visibleTurnItems: ReadonlyArray<OrchestrationV2ProjectedTurnItem>,
2526 options?: {
2527 readonly anchoredMessages?: ReadonlyArray<LocalThreadMessage>;
2528 readonly attempts?: ReadonlyArray<OrchestrationV2RunAttempt>;
2529 readonly nodes?: ReadonlyArray<OrchestrationV2ExecutionNode>;
2530 readonly checkpointSummaries?: ReadonlyArray<ThreadCheckpointSummary>;
2531 readonly cache?: ThreadFeedCache;
2532 readonly resolve?: MessageResolver;
2533 /** Keys the caches; text comes from `resolve`. */
2534 readonly locale?: string;
2535 },
2536 ): ThreadFeedEntry[] {
2537 const anchoredMessages = options?.anchoredMessages ?? [];
2538 const resolve = options?.resolve ?? m;
2539 const locale = options?.locale;
2540 const attemptByRootNodeId = new Map(
2541 (options?.attempts ?? []).map((attempt) => [attempt.rootNodeId, attempt] as const),
2542 );
2543 const nodeById = new Map((options?.nodes ?? []).map((node) => [node.id, node] as const));
2544 const resolveAttemptId = (item: OrchestrationV2TurnItem): RunAttemptId | null => {
2545 if (item.nodeId === null || item.runId === null) return null;
2546 let nodeId: OrchestrationV2ExecutionNode["id"] | null = item.nodeId;
2547 const visited = new Set<OrchestrationV2ExecutionNode["id"]>();
2548 while (nodeId !== null && !visited.has(nodeId)) {
2549 visited.add(nodeId);
2550 const directAttempt = attemptByRootNodeId.get(nodeId);
2551 if (directAttempt?.runId === item.runId) return directAttempt.id;
2552 const node = nodeById.get(nodeId);
2553 if (node === undefined) return null;
2554 const rootAttempt = attemptByRootNodeId.get(node.rootNodeId);
2555 if (rootAttempt?.runId === item.runId) return rootAttempt.id;
2556 nodeId = node.parentNodeId;
2557 }
2558 return null;
2559 };
2560 // Thread-wide facts that change rows anywhere in the feed. A cached prefix
2561 // is reused only while these match the build that produced it.
2562 // An answer that started a later run stays a normal message at that run's position.
2563 const foldedAnswerRunIdByMessageId = new Map<string, RunId | null>();
2564 const delegatedChildrenByRun = new Map<RunId, Set<string>>();
2565 for (const { item } of visibleTurnItems) {
2566 if (item.type === "user_input_request" && item.questionAnswer) {
2567 foldedAnswerRunIdByMessageId.set(`async-answer:${item.questionAnswer.requestId}`, item.runId);
2568 } else if (item.type === "subagent" && item.origin === "app_owned" && item.runId !== null) {
2569 const children = delegatedChildrenByRun.get(item.runId) ?? new Set<string>();
2570 children.add(item.subagentId);
2571 delegatedChildrenByRun.set(item.runId, children);
2572 }
2573 }
2574
2575 const cache = options?.cache;
2576 const previous = cache?.feedBuild ?? null;
2577 let restartIndex = -1;
2578 if (
2579 previous !== null &&
2580 anchoredMessages.length === 0 &&
2581 previous.locale === locale &&
2582 previous.attempts === options?.attempts &&
2583 previous.nodes === options?.nodes &&
2584 checkpointSummariesEqual(previous.checkpointSummaries, options?.checkpointSummaries) &&
2585 mapsEqual(previous.foldedAnswerRunIdByMessageId, foldedAnswerRunIdByMessageId) &&
2586 setMapsEqual(previous.delegatedChildrenByRun, delegatedChildrenByRun)
2587 ) {
2588 const firstChanged = firstChangedIndex(previous.rows, visibleTurnItems);
2589 restartIndex = previous.restarts.length - 1;
2590 while (restartIndex >= 0 && previous.restarts[restartIndex]!.row > firstChanged) {
2591 restartIndex -= 1;
2592 }
2593 }
2594 const restart = restartIndex === -1 ? null : previous!.restarts[restartIndex]!;
2595 const prefix = restart === null ? [] : previous!.feed.slice(0, restart.feedLength);
2596 const restarts = restart === null ? [] : previous!.restarts.slice(0, restartIndex + 1);
2597
2598 const entries: RawThreadFeedEntry[] = [];
2599 const entryRows: number[] = [];
2600 // A stopped compaction's own row already says it stopped. A `/compact` run stopped
2601 // before its provider started has no such row, so it keeps the interrupted one.
2602 const compactPromptRunIds = new Set<RunId>();
2603 const compactedRunIds = new Set<RunId>();
2604 for (const { item } of visibleTurnItems) {
2605 if (item.runId === null) continue;
2606 if (item.type === "user_message" && isCompactionCommandMessage({ role: "user", ...item })) {
2607 compactPromptRunIds.add(item.runId);
2608 } else if (item.type === "compaction") {
2609 compactedRunIds.add(item.runId);
2610 }
2611 }
2612 for (let index = restart?.row ?? 0; index < visibleTurnItems.length; index += 1) {
2613 const row = visibleTurnItems[index]!;
2614 const item = row.item;
2615 if (turnItemIsWorkspacePreparation(item) && !item.deferredWork) continue;
2616 if (item.type === "todo_list" || item.type === "checkpoint") continue;
2617 if (
2618 item.type === "user_message" &&
2619 item.inputIntent === "queued_turn" &&
2620 item.status === "pending"
2621 )
2622 continue;
2623 if (
2624 item.type === "user_message" &&
2625 foldedAnswerRunIdByMessageId.get(item.messageId) === item.runId
2626 )
2627 continue;
2628 if (
2629 item.type === "run_interrupt_request" ||
2630 (item.type === "run_interrupt_result" &&
2631 item.runId !== null &&
2632 compactPromptRunIds.has(item.runId) &&
2633 compactedRunIds.has(item.runId))
2634 ) {
2635 continue;
2636 }
2637 const attemptId = resolveAttemptId(item);
2638 const cached = projectedEntriesCache.get(row);
2639 if (cached?.attemptId === attemptId && cached.locale === locale) {
2640 for (const entry of cached.entries) {
2641 entries.push(entry);
2642 entryRows.push(index);
2643 }
2644 continue;
2645 }
2646 const createdAt = DateTime.formatIso(item.startedAt ?? item.updatedAt);
2647 const render =
2648 item.type === "dynamic_tool" && item.status === "completed"
2649 ? htmlRenderFromToolItem(item)
2650 : undefined;
2651 if (render) {
2652 const entry: RawThreadFeedEntry = {
2653 type: "html-render",
2654 id: `html-render:${row.visibility}:${row.sourceThreadId}:${row.sourceItemId}`,
2655 createdAt,
2656 runId: item.runId,
2657 render,
2658 };
2659 projectedEntriesCache.set(row, { attemptId, locale, entries: [entry] });
2660 entries.push(entry);
2661 entryRows.push(index);
2662 continue;
2663 }
2664 const sentMessage =
2665 item.type === "dynamic_tool" && item.status === "completed"
2666 ? sentMessageFromToolItem(item)
2667 : undefined;
2668 if (sentMessage !== undefined) {
2669 const entry: RawThreadFeedEntry = {
2670 type: "sent-message",
2671 id: `sent-message:${row.visibility}:${row.sourceThreadId}:${row.sourceItemId}`,
2672 createdAt,
2673 runId: item.runId,
2674 text: sentMessage,
2675 };
2676 projectedEntriesCache.set(row, { attemptId, locale, entries: [entry] });
2677 entries.push(entry);
2678 entryRows.push(index);
2679 continue;
2680 }
2681 if (item.type === "user_message" || item.type === "assistant_message") {
2682 const updatedAt = DateTime.formatIso(item.updatedAt);
2683 const entry: RawThreadFeedEntry = {
2684 type: "message",
2685 id: item.messageId,
2686 createdAt,
2687 message: {
2688 id: item.messageId,
2689 role: item.type === "user_message" ? "user" : "assistant",
2690 text: item.text,
2691 ...(item.type === "user_message" && item.context ? { context: item.context } : {}),
2692 attachments: item.attachments ?? [],
2693 runId: item.runId,
2694 streaming: item.type === "assistant_message" && item.streaming,
2695 ...(item.type === "user_message"
2696 ? {
2697 inputIntent: item.inputIntent,
2698 createdBy: item.createdBy,
2699 creationSource: item.creationSource,
2700 ...(item.scheduledTaskId ? { scheduledTaskId: item.scheduledTaskId } : {}),
2701 ...(item.senderThreadId ? { senderThreadId: item.senderThreadId } : {}),
2702 ...(item.linkedSender ? { linkedSender: item.linkedSender } : {}),
2703 ...(item.idleCompaction ? { idleCompaction: item.idleCompaction } : {}),
2704 }
2705 : {}),
2706 visibility: row.visibility,
2707 sourceThreadId: row.sourceThreadId,
2708 createdAt,
2709 updatedAt,
2710 projectedItem: row,
2711 },
2712 };
2713 projectedEntriesCache.set(row, { attemptId, locale, entries: [entry] });
2714 entries.push(entry);
2715 entryRows.push(index);
2716 continue;
2717 }
2718 const activity = toFeedActivity(row, attemptId, resolve);
2719 const rowEntries: RawThreadFeedEntry[] = [
2720 { type: "activity", id: activity.id, createdAt, runId: item.runId, activity },
2721 ];
2722 // The card follows its tool activity: a feed restart resumes after a row's last entry.
2723 const app = item.type === "dynamic_tool" ? mcpAppFromToolItem(item) : undefined;
2724 if (app) {
2725 rowEntries.push({
2726 type: "mcp-app",
2727 id: `mcp-app:${row.visibility}:${row.sourceThreadId}:${row.sourceItemId}`,
2728 createdAt,
2729 runId: item.runId,
2730 sourceThreadId: row.sourceThreadId,
2731 itemId: row.sourceItemId,
2732 revision: turnItemDetailRevision(item),
2733 app,
2734 });
2735 }
2736 projectedEntriesCache.set(row, { attemptId, locale, entries: rowEntries });
2737 for (const entry of rowEntries) {
2738 entries.push(entry);
2739 entryRows.push(index);
2740 }
2741 }
2742 const retainedMessageIds = new Set([
2743 ...foldedAnswerRunIdByMessageId.keys(),
2744 ...entries.flatMap((entry) => (entry.type === "message" ? [entry.id] : [])),
2745 ]);
2746 const appendLocalMessage = (message: LocalThreadMessage): RawThreadFeedEntry => {
2747 const cached = localMessageEntriesCache.get(message);
2748 if (cached) return cached;
2749 const entry: Extract<RawThreadFeedEntry, { readonly type: "message" }> = {
2750 type: "message",
2751 id: message.id,
2752 createdAt: message.createdAt,
2753 message: {
2754 id: message.id,
2755 role: message.role === "assistant" ? "assistant" : "user",
2756 text: message.text,
2757 ...(message.context ? { context: message.context } : {}),
2758 attachments: message.attachments ?? [],
2759 runId: null,
2760 streaming: message.streaming,
2761 visibility: "local",
2762 sourceThreadId: ThreadId.make("local-feedback"),
2763 createdAt: message.createdAt,
2764 updatedAt: message.updatedAt,
2765 },
2766 };
2767 localMessageEntriesCache.set(message, entry);
2768 return entry;
2769 };
2770 for (const message of anchoredMessages) {
2771 if (retainedMessageIds.has(message.id)) continue;
2772 retainedMessageIds.add(message.id);
2773 const entry = appendLocalMessage(message);
2774 const insertionIndex = entries.findIndex(
2775 (candidate) => candidate.createdAt > message.createdAt,
2776 );
2777 if (insertionIndex === -1) entries.push(entry);
2778 else entries.splice(insertionIndex, 0, entry);
2779 }
2780 const checkpointByMessageId = new Map(
2781 (options?.checkpointSummaries ?? [])
2782 .filter((checkpoint) => checkpoint.status === "ready" && checkpoint.files.length > 0)
2783 .map((checkpoint) => [checkpoint.assistantMessageId, checkpoint]),
2784 );
2785 const grouped = groupAdjacentActivities(
2786 entries.map((entry) => {
2787 if (entry.type !== "message" || entry.message.role !== "assistant") return entry;
2788 const checkpointSummary = checkpointByMessageId.get(entry.message.id);
2789 if (!checkpointSummary || checkpointSummary.runId !== entry.message.runId) return entry;
2790 return { ...entry, message: { ...entry.message, checkpointSummary } };
2791 }),
2792 delegatedChildrenByRun,
2793 // Anchored messages shift entries away from their rows; such a build is not reused.
2794 anchoredMessages.length > 0
2795 ? undefined
2796 : (entryIndex, groupedLength) =>
2797 restarts.push({
2798 row: entryRows[entryIndex]! + 1,
2799 feedLength: prefix.length + groupedLength,
2800 }),
2801 );
2802 const feed = prefix.length === 0 ? grouped : prefix.concat(grouped);
2803 if (cache) {
2804 cache.feedBuild =
2805 anchoredMessages.length > 0
2806 ? null
2807 : {
2808 rows: visibleTurnItems,
2809 locale,
2810 attempts: options?.attempts,
2811 nodes: options?.nodes,
2812 checkpointSummaries: options?.checkpointSummaries,
2813 foldedAnswerRunIdByMessageId,
2814 delegatedChildrenByRun,
2815 feed,
2816 restarts,
2817 };
2818 }
2819 return feed;
2820 }