Open History to see the last commit
1import type {
2 ThreadPendingApproval,
3 ThreadPendingUserInput,
4 ThreadUserInputQuestion,
5} from "@t3tools/client-runtime/state/thread-requests";
6import { turnItemIsWorkspacePreparation } from "@t3tools/client-runtime/state/turn-item-presentation";
7import { extractToolActivityPresentation } from "@t3tools/client-runtime/work-log/tool-presentation";
8import { commandProgramName } from "@t3tools/client-runtime/work-log/command-label";
9import {
10 workEntryDisplayIndicatesToolFailure,
11 liveActivityToolStatus,
12 toolGroupAction,
13 resolveWorkEntryToolPresentation,
14 summarizeToolGroup,
15 toolGroupSummaryKind,
16 type ToolGroupSummaryKind,
17 type WorkLogPresentationEntry,
18 type WorkLogToolLifecycleStatus,
19} from "@t3tools/client-runtime/work-log/presentation";
20import {
21 resolveT3McpToolPresentation,
22 type T3McpToolLogo,
23 type T3McpToolPresentation,
24} from "@t3tools/shared/t3McpToolPresentation";
25import type {
26 ChatAttachment,
27 MessageId,
28 OrchestrationV2Actor,
29 OrchestrationV2CreationSource,
30 OrchestrationV2ExecutionNode,
31 OrchestrationMessage,
32 OrchestrationV2ProjectedTurnItem,
33 OrchestrationV2RunAttempt,
34 OrchestrationV2RunStatus,
35 OrchestrationV2TurnItem,
36 OrchestrationV2UserMessageInputIntent,
37 RunId,
38 RunAttemptId,
39} from "@t3tools/contracts";
40import { ThreadId } from "@t3tools/contracts";
41import { formatDuration } from "@t3tools/shared/orchestrationTiming";
42import * as DateTime from "effect/DateTime";
43
44export type PendingApproval = ThreadPendingApproval;
45export type PendingUserInput = ThreadPendingUserInput;
46
47export interface PendingUserInputDraftAnswer {
48 readonly selectedOptionValues?: ReadonlyArray<string>;
49 readonly customAnswer?: string;
50}
51
52export interface ThreadFeedActivity {
53 readonly id: string;
54 readonly createdAt: string;
55 readonly runId: RunId | null;
56 readonly attemptId: RunAttemptId | null;
57 readonly summary: string;
58 readonly detail: string | null;
59 readonly canExpand: boolean;
60 readonly getFullDetail: () => string | null;
61 readonly getCopyText: () => string;
62 readonly icon:
63 | "agent"
64 | "alert"
65 | "browser"
66 | "computer"
67 | "check"
68 | "command"
69 | "edit"
70 | "eye"
71 | "globe"
72 | "hammer"
73 | "message"
74 | "warning"
75 | "wrench"
76 | "zap";
77 readonly logo: T3McpToolLogo | null;
78 readonly toolLike: boolean;
79 readonly prominent: boolean;
80 readonly status: "success" | "failure" | "neutral" | null;
81 readonly lifecycleStatus: WorkLogToolLifecycleStatus;
82 readonly workEntry: WorkLogPresentationEntry;
83 readonly groupedToolDetail?: boolean;
84 readonly live?: boolean;
85 readonly projectedItem: OrchestrationV2ProjectedTurnItem;
86}
87
88export interface ThreadFeedMessage {
89 readonly id: MessageId;
90 readonly role: "user" | "assistant";
91 readonly text: string;
92 readonly attachments: ReadonlyArray<ChatAttachment>;
93 readonly runId: RunId | null;
94 readonly streaming: boolean;
95 readonly inputIntent?: OrchestrationV2UserMessageInputIntent;
96 readonly createdBy?: OrchestrationV2Actor;
97 readonly creationSource?: OrchestrationV2CreationSource;
98 readonly visibility: OrchestrationV2ProjectedTurnItem["visibility"];
99 readonly sourceThreadId: ThreadId;
100 readonly createdAt: string;
101 readonly updatedAt: string;
102 readonly projectedItem?: OrchestrationV2ProjectedTurnItem;
103}
104
105type RawThreadFeedEntry =
106 | {
107 readonly type: "message";
108 readonly id: string;
109 readonly createdAt: string;
110 readonly message: ThreadFeedMessage;
111 }
112 | {
113 readonly type: "activity";
114 readonly id: string;
115 readonly createdAt: string;
116 readonly runId: RunId | null;
117 readonly activity: ThreadFeedActivity;
118 };
119
120export type ThreadFeedEntry =
121 | Extract<RawThreadFeedEntry, { type: "message" }>
122 | {
123 readonly type: "activity-group";
124 readonly id: string;
125 readonly createdAt: string;
126 readonly runId: RunId | null;
127 readonly activities: ReadonlyArray<ThreadFeedActivity>;
128 }
129 | {
130 readonly type: "work-toggle";
131 readonly id: string;
132 readonly createdAt: string;
133 readonly runId: RunId | null;
134 readonly groupId: string;
135 readonly hiddenCount: number;
136 readonly expanded: boolean;
137 readonly summary: string;
138 readonly summaryKind: ToolGroupSummaryKind;
139 readonly toolSurface?: WorkLogPresentationEntry["toolSurface"];
140 readonly toolIcon?: WorkLogPresentationEntry["toolIcon"];
141 readonly summaryToolIcon?: "browser" | "t3-code";
142 readonly hasFailure: boolean;
143 readonly live: boolean;
144 readonly shimmer: boolean;
145 }
146 | {
147 readonly type: "run-fold";
148 readonly id: string;
149 readonly createdAt: string;
150 readonly runId: RunId;
151 readonly label: string;
152 readonly expanded: boolean;
153 };
154
155export interface ThreadFeedLatestRun {
156 readonly runId: RunId;
157 readonly status: OrchestrationV2RunStatus;
158 readonly startedAt: string | null;
159 readonly completedAt: string | null;
160}
161
162type ThreadFeedActivityGroup = Extract<ThreadFeedEntry, { readonly type: "activity-group" }>;
163
164// Immutable source rows let retained history keep its identities while the active item streams.
165const projectedEntriesCache = new WeakMap<
166 OrchestrationV2ProjectedTurnItem,
167 {
168 readonly attemptId: RunAttemptId | null;
169 readonly entry: RawThreadFeedEntry;
170 }
171>();
172const localMessageEntriesCache = new WeakMap<
173 OrchestrationMessage,
174 Extract<RawThreadFeedEntry, { readonly type: "message" }>
175>();
176const activityGroupsCache = new WeakMap<ThreadFeedActivity, ThreadFeedActivityGroup>();
177const presentedActivityGroupsCache = new WeakMap<
178 ThreadFeedActivityGroup,
179 {
180 readonly activeRunId: RunId | null;
181 readonly isWorking: boolean;
182 readonly activeTail: boolean;
183 readonly rows: ReadonlyArray<ThreadFeedEntry>;
184 }
185>();
186const runFoldRowsCache = new WeakMap<
187 ThreadFeedEntry,
188 Extract<ThreadFeedEntry, { readonly type: "run-fold" }>
189>();
190
191export function isContextCompactionActivityGroup(entry: ThreadFeedActivityGroup): boolean {
192 return (
193 entry.activities.length === 1 && entry.activities[0]?.projectedItem.item.type === "compaction"
194 );
195}
196
197function normalizeDraftAnswer(value: string | undefined): string | null {
198 if (typeof value !== "string") return null;
199 const trimmed = value.trim();
200 return trimmed.length > 0 ? trimmed : null;
201}
202
203function resolvePendingUserInputOptionValue(
204 question: ThreadUserInputQuestion,
205 value: string,
206): string | null {
207 if (question.options.some((option) => option.value === value)) {
208 return value;
209 }
210
211 const label = value.trim();
212 return label.length > 0 &&
213 question.options.some((option) => option.value === undefined && option.label.trim() === label)
214 ? label
215 : null;
216}
217
218function normalizeSelectedOptionValues(
219 question: ThreadUserInputQuestion,
220 value: ReadonlyArray<string> | undefined,
221): ReadonlyArray<string> {
222 if (!Array.isArray(value)) {
223 return [];
224 }
225
226 return Array.from(
227 new Set(
228 value
229 .map((entry) => resolvePendingUserInputOptionValue(question, entry))
230 .filter((entry): entry is string => entry !== null),
231 ),
232 );
233}
234
235function resolvePendingUserInputAnswer(
236 question: ThreadUserInputQuestion,
237 draft: PendingUserInputDraftAnswer | undefined,
238): string | ReadonlyArray<string> | null {
239 const customAnswer =
240 question.allowCustomAnswer === false ? null : normalizeDraftAnswer(draft?.customAnswer);
241 if (customAnswer) {
242 return customAnswer;
243 }
244
245 const selectedOptionValues = normalizeSelectedOptionValues(question, draft?.selectedOptionValues);
246 if (question.multiSelect) {
247 return selectedOptionValues.length > 0 ? selectedOptionValues : null;
248 }
249 return selectedOptionValues[0] ?? null;
250}
251
252function capitalizePhrase(value: string): string {
253 const trimmed = value.trim();
254 return trimmed.length === 0 ? value : `${trimmed.charAt(0).toUpperCase()}${trimmed.slice(1)}`;
255}
256
257function memoizeValue<T>(build: () => T): () => T {
258 let value: T;
259 let initialized = false;
260 return () => {
261 if (!initialized) {
262 value = build();
263 initialized = true;
264 }
265 return value;
266 };
267}
268
269function itemIsToolLike(item: OrchestrationV2TurnItem): boolean {
270 return (
271 item.type === "reasoning" ||
272 item.type === "command_execution" ||
273 item.type === "file_change" ||
274 item.type === "file_search" ||
275 item.type === "web_search" ||
276 item.type === "approval_request" ||
277 item.type === "user_input_request" ||
278 item.type === "dynamic_tool" ||
279 item.type === "subagent"
280 );
281}
282
283function itemIsProminent(item: OrchestrationV2TurnItem): boolean {
284 return (
285 item.type === "fork" ||
286 item.type === "thread_created" ||
287 item.type === "subagent" ||
288 item.type === "system_notice"
289 );
290}
291
292function itemStatus(item: OrchestrationV2TurnItem): ThreadFeedActivity["status"] {
293 if (item.type === "error") {
294 if (item.status === "failed") return "failure";
295 return item.status === "completed" ? "success" : "neutral";
296 }
297 if (!itemIsToolLike(item)) return null;
298 if (item.status === "failed") return "failure";
299 return item.status === "completed" ? "success" : "neutral";
300}
301
302function itemLifecycleStatus(item: OrchestrationV2TurnItem): WorkLogToolLifecycleStatus {
303 switch (item.status) {
304 case "pending":
305 case "running":
306 case "waiting":
307 return "inProgress";
308 case "idle":
309 return "idle";
310 case "completed":
311 return "completed";
312 case "failed":
313 return "failed";
314 case "cancelled":
315 case "interrupted":
316 return "stopped";
317 }
318}
319
320function itemWorkLogTone(item: OrchestrationV2TurnItem): WorkLogPresentationEntry["tone"] {
321 if (item.type === "error") return "info";
322 if (item.type === "reasoning") return "thinking";
323 switch (item.type) {
324 case "command_execution":
325 case "file_change":
326 case "file_search":
327 case "web_search":
328 case "dynamic_tool":
329 case "subagent":
330 return "tool";
331 default:
332 return "info";
333 }
334}
335
336function itemIcon(item: OrchestrationV2TurnItem): ThreadFeedActivity["icon"] {
337 switch (item.type) {
338 case "reasoning":
339 return "agent";
340 case "command_execution":
341 return "command";
342 case "file_change":
343 return "edit";
344 case "file_search":
345 return "eye";
346 case "web_search":
347 return "globe";
348 case "approval_request":
349 case "user_input_request":
350 case "user_message":
351 case "assistant_message":
352 return "message";
353 case "dynamic_tool":
354 return "wrench";
355 case "subagent":
356 return "hammer";
357 case "run_interrupt_request":
358 case "run_interrupt_result":
359 case "system_notice":
360 return "warning";
361 case "error":
362 return "alert";
363 case "checkpoint":
364 case "proposed_plan":
365 case "todo_list":
366 return "check";
367 case "compaction":
368 case "handoff":
369 case "fork":
370 case "thread_created":
371 return "zap";
372 }
373}
374
375function itemToolPresentation(item: OrchestrationV2TurnItem): T3McpToolPresentation | null {
376 if (item.type !== "dynamic_tool") {
377 return null;
378 }
379 return resolveT3McpToolPresentation(item.toolName) ?? resolveT3McpToolPresentation(item.title);
380}
381
382function itemSummary(
383 item: OrchestrationV2TurnItem,
384 toolPresentation: T3McpToolPresentation | null = null,
385): string {
386 if (item.type === "system_notice") return item.message;
387 const title = item.title?.trim();
388 if (title) return toolPresentation?.displayName ?? capitalizePhrase(title);
389 switch (item.type) {
390 case "reasoning":
391 return "Thinking";
392 case "command_execution":
393 return "Command";
394 case "file_change":
395 return `Changed ${item.fileName}`;
396 case "file_search":
397 return "Searched files";
398 case "web_search":
399 return "Searched the web";
400 case "approval_request":
401 return "Approval requested";
402 case "user_input_request":
403 return "Input requested";
404 case "checkpoint":
405 return "Checkpoint captured";
406 case "run_interrupt_request":
407 return "Interrupt requested";
408 case "run_interrupt_result":
409 return "Run interrupted";
410 case "error":
411 return "Provider error";
412 case "compaction":
413 return "Context compacted";
414 case "handoff":
415 return "Context handed off";
416 case "fork":
417 return "Thread forked";
418 case "thread_created":
419 return "Thread created";
420 case "subagent":
421 return "Subagent";
422 case "dynamic_tool":
423 return toolPresentation?.displayName ?? item.toolName ?? "Tool call";
424 case "proposed_plan":
425 return "Proposed plan";
426 case "todo_list":
427 return "Plan updated";
428 case "user_message":
429 return "User message";
430 case "assistant_message":
431 return "Assistant message";
432 }
433}
434
435function itemPreview(item: OrchestrationV2TurnItem): string | null {
436 switch (item.type) {
437 case "reasoning":
438 return item.text || null;
439 case "command_execution":
440 return item.input || null;
441 case "file_change":
442 return item.fileName;
443 case "file_search":
444 return item.pattern ?? null;
445 case "web_search":
446 return item.patterns?.join(", ") ?? null;
447 case "approval_request":
448 return item.prompt ?? null;
449 case "user_input_request":
450 return item.questions.map((question) => question.question).join(" · ") || null;
451 case "checkpoint":
452 return item.files.length === 1
453 ? (item.files[0]?.path ?? null)
454 : `${item.files.length} changed files`;
455 case "run_interrupt_request":
456 case "run_interrupt_result":
457 case "system_notice":
458 return item.message || null;
459 case "error":
460 return item.failure.message;
461 case "compaction":
462 case "handoff":
463 return item.summary ?? null;
464 case "fork":
465 case "thread_created":
466 return item.targetThreadId;
467 case "subagent":
468 return item.result ?? item.progress ?? item.prompt;
469 case "dynamic_tool":
470 return null;
471 case "proposed_plan":
472 return item.markdown || null;
473 case "todo_list":
474 return `${item.steps.filter((step) => step.status === "completed").length}/${item.steps.length} completed`;
475 case "user_message":
476 case "assistant_message":
477 return item.text || null;
478 }
479}
480
481function toWorkLogEntry(
482 item: OrchestrationV2TurnItem,
483 createdAt: string,
484 summary: string,
485 detail: string | null,
486): WorkLogPresentationEntry {
487 const title = item.title?.trim() || null;
488 const common = {
489 ...extractToolActivityPresentation(item),
490 id: item.id,
491 createdAt,
492 label: summary,
493 tone: itemWorkLogTone(item),
494 itemType: item.type,
495 toolLifecycleStatus: itemLifecycleStatus(item),
496 structuredPayload: item,
497 } as const;
498
499 switch (item.type) {
500 case "reasoning":
501 return { ...common, ...(item.text ? { detail: item.text } : {}) };
502 case "command_execution":
503 return {
504 ...common,
505 command: item.input,
506 rawCommand: item.input,
507 ...(item.output ? { detail: item.output } : {}),
508 toolTitle: title ?? "Command",
509 toolData: item,
510 };
511 case "file_change":
512 return {
513 ...common,
514 changedFiles: [item.fileName],
515 ...((item.diffStr ?? item.newStr) ? { detail: item.diffStr ?? item.newStr } : {}),
516 toolTitle: title ?? "File change",
517 toolData: item,
518 };
519 case "file_search":
520 return {
521 ...common,
522 ...(item.pattern ? { detail: item.pattern } : {}),
523 toolTitle: title ?? "File search",
524 toolData: item,
525 };
526 case "web_search":
527 return {
528 ...common,
529 ...(item.patterns?.length ? { detail: item.patterns.join(", ") } : {}),
530 toolTitle: title ?? "Web search",
531 toolData: item,
532 };
533 case "checkpoint":
534 return { ...common, changedFiles: item.files.map((file) => file.path), toolData: item };
535 case "approval_request":
536 return {
537 ...common,
538 ...(item.prompt ? { detail: item.prompt } : {}),
539 requestKind: item.requestKind,
540 toolData: item,
541 };
542 case "dynamic_tool":
543 return {
544 ...common,
545 toolTitle: title ?? item.toolName ?? "Tool",
546 toolData: { input: item.input, output: item.output },
547 };
548 default:
549 return { ...common, ...(detail ? { detail } : {}), toolData: item };
550 }
551}
552
553function toFeedActivity(
554 row: OrchestrationV2ProjectedTurnItem,
555 attemptId: RunAttemptId | null,
556): ThreadFeedActivity {
557 const item = row.item;
558 const toolPresentation = itemToolPresentation(item);
559 const summary = itemSummary(item, toolPresentation);
560 const detail = itemPreview(item);
561 const createdAt = DateTime.formatIso(item.startedAt ?? item.updatedAt);
562 const workEntry = toWorkLogEntry(item, createdAt, summary, detail);
563 const getFullDetail = memoizeValue(() =>
564 JSON.stringify(
565 {
566 visibility: row.visibility,
567 sourceThreadId: row.sourceThreadId,
568 sourceItemId: row.sourceItemId,
569 item,
570 },
571 null,
572 2,
573 ),
574 );
575 const getCopyText = memoizeValue(() =>
576 [summary, detail, getFullDetail()]
577 .filter(
578 (value, index, values): value is string =>
579 Boolean(value) && values.indexOf(value) === index,
580 )
581 .join("\n"),
582 );
583 return {
584 id: `${row.visibility}:${row.sourceThreadId}:${row.sourceItemId}`,
585 createdAt,
586 runId: item.runId,
587 attemptId,
588 summary,
589 detail,
590 canExpand: true,
591 getFullDetail,
592 getCopyText,
593 icon: workEntry.toolSurface ?? itemIcon(item),
594 logo: toolPresentation?.logo ?? null,
595 toolLike: itemIsToolLike(item),
596 prominent: itemIsProminent(item),
597 status: itemStatus(item),
598 lifecycleStatus: itemLifecycleStatus(item),
599 workEntry,
600 projectedItem: row,
601 };
602}
603
604function singleToolCallLabel(activity: ThreadFeedActivity): string {
605 const presentation = resolveWorkEntryToolPresentation(activity.workEntry, "completed");
606 if (presentation) return presentation.displayName;
607 const command = activity.workEntry.command?.trim();
608 return command || activity.summary;
609}
610
611function isEmptyMessage(entry: RawThreadFeedEntry): boolean {
612 return (
613 entry.type === "message" &&
614 entry.message.text.trim().length === 0 &&
615 entry.message.attachments.length === 0
616 );
617}
618
619function groupAdjacentActivities(entries: ReadonlyArray<RawThreadFeedEntry>): ThreadFeedEntry[] {
620 const grouped: ThreadFeedEntry[] = [];
621 let firstActivityEntry: Extract<RawThreadFeedEntry, { readonly type: "activity" }> | null = null;
622 let openGroupActivities: ThreadFeedActivity[] = [];
623 const flushGroup = () => {
624 if (firstActivityEntry === null) return;
625 const cached = activityGroupsCache.get(firstActivityEntry.activity);
626 if (
627 cached &&
628 cached.activities.length === openGroupActivities.length &&
629 cached.activities.every((activity, index) => activity === openGroupActivities[index])
630 ) {
631 grouped.push(cached);
632 } else {
633 const group: ThreadFeedActivityGroup = {
634 type: "activity-group",
635 id: firstActivityEntry.id,
636 createdAt: firstActivityEntry.createdAt,
637 runId: firstActivityEntry.runId,
638 activities: openGroupActivities,
639 };
640 activityGroupsCache.set(firstActivityEntry.activity, group);
641 grouped.push(group);
642 }
643 firstActivityEntry = null;
644 openGroupActivities = [];
645 };
646
647 for (const entry of entries) {
648 // Skip empty messages so they don't break activity grouping.
649 if (isEmptyMessage(entry)) {
650 continue;
651 }
652
653 if (entry.type !== "activity") {
654 flushGroup();
655 grouped.push(entry);
656 continue;
657 }
658
659 const isCompaction = entry.activity.projectedItem.item.type === "compaction";
660 if (
661 isCompaction ||
662 entry.activity.prominent ||
663 firstActivityEntry?.runId !== entry.runId ||
664 firstActivityEntry?.activity.attemptId !== entry.activity.attemptId
665 ) {
666 flushGroup();
667 }
668 firstActivityEntry ??= entry;
669 openGroupActivities.push(entry.activity);
670 if (isCompaction || entry.activity.prominent) {
671 flushGroup();
672 }
673 }
674 flushGroup();
675 return grouped;
676}
677
678function computeElapsedMs(startIso: string, endIso: string): number | null {
679 const start = Date.parse(startIso);
680 const end = Date.parse(endIso);
681 return Number.isFinite(start) && Number.isFinite(end) ? Math.max(0, end - start) : null;
682}
683
684function maxIsoTimestamp(left: string | null, right: string | null): string | null {
685 if (left === null) return right;
686 if (right === null) return left;
687 return Date.parse(right) > Date.parse(left) ? right : left;
688}
689
690function unsettledRunId(latestRun: ThreadFeedLatestRun | null): RunId | null {
691 return threadFeedRunIsUnsettled(latestRun) ? latestRun.runId : null;
692}
693
694export function threadFeedRunIsUnsettled(
695 run: ThreadFeedLatestRun | null,
696): run is ThreadFeedLatestRun {
697 if (run === null || run.status === "queued") return false;
698 return (
699 run.completedAt === null ||
700 run.status === "preparing" ||
701 run.status === "starting" ||
702 run.status === "running" ||
703 run.status === "waiting"
704 );
705}
706
707export function threadFeedActivityIsVisible(
708 activity: Pick<ThreadFeedActivity, "prominent" | "status" | "toolLike"> &
709 Partial<Pick<ThreadFeedActivity, "lifecycleStatus">>,
710): boolean {
711 return (
712 activity.prominent ||
713 activity.lifecycleStatus === "stopped" ||
714 activity.lifecycleStatus === "declined" ||
715 activity.lifecycleStatus === "idle" ||
716 !(activity.toolLike && activity.status === "neutral")
717 );
718}
719
720interface ThreadFeedRunFold {
721 readonly runId: RunId;
722 readonly createdAt: string;
723 readonly hiddenEntryIds: ReadonlySet<string>;
724 readonly label: string;
725}
726
727function deriveThreadFeedRunFolds(
728 feed: ReadonlyArray<ThreadFeedEntry>,
729 latestRun: ThreadFeedLatestRun | null,
730): ReadonlyMap<string, ThreadFeedRunFold> {
731 const firstAssistantMessageIdByRun = new Map<RunId, string>();
732 const terminalAssistantMessageIdByRun = new Map<RunId, string>();
733 const interruptedRunIds = new Set<RunId>();
734 for (const entry of feed) {
735 if (entry.type === "message" && entry.message.role === "assistant" && entry.message.runId) {
736 if (!firstAssistantMessageIdByRun.has(entry.message.runId)) {
737 firstAssistantMessageIdByRun.set(entry.message.runId, entry.id);
738 }
739 terminalAssistantMessageIdByRun.set(entry.message.runId, entry.id);
740 }
741 if (
742 entry.type === "activity-group" &&
743 entry.runId !== null &&
744 entry.activities.some(
745 (activity) => activity.projectedItem.item.type === "run_interrupt_result",
746 )
747 ) {
748 interruptedRunIds.add(entry.runId);
749 }
750 }
751
752 const groupsByRunId = new Map<
753 RunId,
754 { entries: ThreadFeedEntry[]; startBoundary: string | null }
755 >();
756 let pendingUserBoundary: string | null = null;
757 for (const entry of feed) {
758 if (entry.type === "message" && entry.message.role === "user") {
759 pendingUserBoundary = entry.message.createdAt;
760 continue;
761 }
762 const runId =
763 entry.type === "message" && entry.message.role === "assistant"
764 ? entry.message.runId
765 : entry.type === "activity-group"
766 ? entry.runId
767 : null;
768 if (!runId) continue;
769 let group = groupsByRunId.get(runId);
770 if (!group) {
771 group = { entries: [], startBoundary: pendingUserBoundary };
772 pendingUserBoundary = null;
773 groupsByRunId.set(runId, group);
774 }
775 group.entries.push(entry);
776 }
777
778 const activeRunId = unsettledRunId(latestRun);
779 const foldsByAnchorId = new Map<string, ThreadFeedRunFold>();
780 for (const [runId, group] of groupsByRunId) {
781 if (
782 runId === activeRunId ||
783 interruptedRunIds.has(runId) ||
784 group.entries.some((entry) => entry.type === "message" && entry.message.streaming)
785 ) {
786 continue;
787 }
788 const firstAssistantId = firstAssistantMessageIdByRun.get(runId);
789 const terminalAssistantId = terminalAssistantMessageIdByRun.get(runId);
790 const hiddenEntryIds = new Set(
791 group.entries
792 .filter(
793 (entry) =>
794 entry.id !== firstAssistantId &&
795 entry.id !== terminalAssistantId &&
796 !(
797 entry.type === "activity-group" &&
798 entry.activities.some((activity) => activity.prominent)
799 ),
800 )
801 .map((entry) => entry.id),
802 );
803 const firstEntry = group.entries[0];
804 const firstHiddenEntry = group.entries.find((entry) => hiddenEntryIds.has(entry.id));
805 const lastEntry = group.entries.at(-1);
806 if (!firstHiddenEntry || !firstEntry || !lastEntry) continue;
807 const hidesNonCompactionWork = group.entries.some(
808 (entry) =>
809 hiddenEntryIds.has(entry.id) &&
810 !(entry.type === "activity-group" && isContextCompactionActivityGroup(entry)),
811 );
812 if (!hidesNonCompactionWork) continue;
813 const terminalEntry = terminalAssistantId
814 ? group.entries.find((entry) => entry.id === terminalAssistantId)
815 : null;
816 const latestRunMatches = latestRun?.runId === runId;
817 const lastEntryEnd =
818 lastEntry.type === "message" ? lastEntry.message.updatedAt : lastEntry.createdAt;
819 const elapsedMs =
820 latestRunMatches && latestRun.startedAt && latestRun.completedAt
821 ? computeElapsedMs(latestRun.startedAt, latestRun.completedAt)
822 : computeElapsedMs(
823 group.startBoundary ?? firstEntry.createdAt,
824 maxIsoTimestamp(
825 terminalEntry?.type === "message" ? terminalEntry.message.updatedAt : null,
826 lastEntryEnd,
827 ) ?? lastEntryEnd,
828 );
829 const duration = elapsedMs === null ? null : formatDuration(elapsedMs);
830 const interrupted =
831 latestRunMatches && (latestRun.status === "interrupted" || latestRun.status === "cancelled");
832 foldsByAnchorId.set(firstHiddenEntry.id, {
833 runId,
834 createdAt: firstHiddenEntry.createdAt,
835 hiddenEntryIds,
836 label: interrupted
837 ? duration
838 ? `You stopped after ${duration}`
839 : "You stopped this response"
840 : duration
841 ? `Worked for ${duration}`
842 : "Worked",
843 });
844 }
845 return foldsByAnchorId;
846}
847
848export function deriveThreadFeedPresentation(
849 feed: ReadonlyArray<ThreadFeedEntry>,
850 latestRun: ThreadFeedLatestRun | null,
851 expandedRunIds: ReadonlySet<RunId>,
852 expandedWorkGroupIds: ReadonlySet<string> = new Set(),
853 activeWorkStartedAt: string | null = null,
854): ThreadFeedEntry[] {
855 const sourceFeed = feed.filter(
856 (entry) => entry.type !== "run-fold" && entry.type !== "work-toggle",
857 );
858 const activeTailGroup = sourceFeed.at(-1);
859 const foldsByAnchorId = deriveThreadFeedRunFolds(sourceFeed, latestRun);
860 const activeRunId = unsettledRunId(latestRun);
861 const isWorking = activeWorkStartedAt !== null;
862 const collapsedEntryIds = new Set<string>();
863 for (const fold of foldsByAnchorId.values()) {
864 if (!expandedRunIds.has(fold.runId)) {
865 for (const entryId of fold.hiddenEntryIds) collapsedEntryIds.add(entryId);
866 }
867 }
868 const result: ThreadFeedEntry[] = [];
869 for (const entry of sourceFeed) {
870 const isActiveTailGroup =
871 isWorking &&
872 activeRunId !== null &&
873 entry.type === "activity-group" &&
874 activeTailGroup?.type === "activity-group" &&
875 activeTailGroup.id === entry.id &&
876 entry.runId === activeRunId;
877 const fold = foldsByAnchorId.get(entry.id);
878 if (fold) {
879 const expanded = expandedRunIds.has(fold.runId);
880 let row = runFoldRowsCache.get(entry);
881 if (
882 !row ||
883 row.runId !== fold.runId ||
884 row.createdAt !== fold.createdAt ||
885 row.label !== fold.label ||
886 row.expanded !== expanded
887 ) {
888 row = {
889 type: "run-fold",
890 id: `run-fold:${fold.runId}`,
891 createdAt: fold.createdAt,
892 runId: fold.runId,
893 label: fold.label,
894 expanded,
895 };
896 runFoldRowsCache.set(entry, row);
897 }
898 result.push(row);
899 }
900 if (!collapsedEntryIds.has(entry.id)) {
901 appendPresentedFeedEntry(
902 result,
903 entry,
904 expandedWorkGroupIds,
905 activeRunId,
906 isWorking,
907 isActiveTailGroup,
908 );
909 }
910 }
911 return result;
912}
913
914function appendPresentedFeedEntry(
915 result: ThreadFeedEntry[],
916 entry: Exclude<ThreadFeedEntry, { readonly type: "run-fold" | "work-toggle" }>,
917 expandedWorkGroupIds: ReadonlySet<string>,
918 activeRunId: RunId | null,
919 isWorking: boolean,
920 activeTail: boolean,
921): void {
922 if (entry.type !== "activity-group") {
923 result.push(entry);
924 return;
925 }
926 if (isContextCompactionActivityGroup(entry)) {
927 result.push(entry);
928 return;
929 }
930
931 let cached = presentedActivityGroupsCache.get(entry);
932 if (
933 !cached ||
934 cached.activeRunId !== activeRunId ||
935 cached.isWorking !== isWorking ||
936 cached.activeTail !== activeTail ||
937 cached.rows.some(
938 (row) => row.type === "work-toggle" && expandedWorkGroupIds.has(row.groupId) !== row.expanded,
939 )
940 ) {
941 const rows: ThreadFeedEntry[] = [];
942 appendActivityGroupRows(rows, entry, expandedWorkGroupIds, activeRunId, isWorking, activeTail);
943 cached = { activeRunId, isWorking, activeTail, rows };
944 presentedActivityGroupsCache.set(entry, cached);
945 }
946 for (const row of cached.rows) {
947 result.push(row);
948 }
949}
950
951function appendActivityGroupRows(
952 result: ThreadFeedEntry[],
953 entry: ThreadFeedActivityGroup,
954 expandedWorkGroupIds: ReadonlySet<string>,
955 activeRunId: RunId | null,
956 isWorking: boolean,
957 activeTail: boolean,
958): void {
959 const groupAnchorIdByActivityId = new Map<string, string>();
960 let groupAnchorId: string | null = null;
961 for (const activity of entry.activities) {
962 const item = activity.projectedItem.item;
963 if (activity.prominent || (item.type === "error" && item.status === "failed")) {
964 groupAnchorId = null;
965 continue;
966 }
967 groupAnchorId ??= activity.id;
968 groupAnchorIdByActivityId.set(activity.id, groupAnchorId);
969 }
970 const activities = entry.activities.filter(
971 (activity) =>
972 threadFeedActivityIsVisible(activity) ||
973 (isWorking && activity.lifecycleStatus === "inProgress" && activity.runId === activeRunId),
974 );
975 if (activities.length === 0) {
976 return;
977 }
978
979 let groupableRun: ThreadFeedActivity[] = [];
980 const flushGroupableRun = (isTrailingRun: boolean) => {
981 if (groupableRun.length === 0) return;
982 appendToolGroupRows(
983 result,
984 entry,
985 groupableRun,
986 `work-group:${groupAnchorIdByActivityId.get(groupableRun[0]!.id) ?? groupableRun[0]!.id}`,
987 expandedWorkGroupIds,
988 activeRunId,
989 isWorking,
990 activeTail && isTrailingRun,
991 );
992 groupableRun = [];
993 };
994 for (const activity of activities) {
995 const item = activity.projectedItem.item;
996 const severeProviderError = item.type === "error" && item.status === "failed";
997 if (!activity.prominent && !severeProviderError) {
998 groupableRun.push(activity);
999 continue;
1000 }
1001 flushGroupableRun(false);
1002 result.push({
1003 type: "activity-group",
1004 id: activity.id,
1005 createdAt: activity.createdAt,
1006 runId: activity.runId,
1007 activities: [activity],
1008 });
1009 }
1010 flushGroupableRun(true);
1011}
1012
1013function appendToolGroupRows(
1014 result: ThreadFeedEntry[],
1015 sourceGroup: Extract<ThreadFeedEntry, { readonly type: "activity-group" }>,
1016 activities: ReadonlyArray<ThreadFeedActivity>,
1017 groupId: string,
1018 expandedWorkGroupIds: ReadonlySet<string>,
1019 activeRunId: RunId | null,
1020 isWorking: boolean,
1021 activeTail: boolean,
1022): void {
1023 const expanded = expandedWorkGroupIds.has(groupId);
1024 const latestInProgressActivity = activities.findLast(
1025 (activity) =>
1026 isWorking && activity.lifecycleStatus === "inProgress" && activity.runId === activeRunId,
1027 );
1028 const live = activeTail || latestInProgressActivity !== undefined;
1029 const latestActivity = latestInProgressActivity ?? activities.at(-1)!;
1030 const singleActivity = activities.length === 1 ? latestActivity : null;
1031 const groupSummary = summarizeToolGroup(activities.map((activity) => activity.workEntry));
1032 const summary = live
1033 ? liveToolActivitySummary(latestActivity, live)
1034 : singleActivity !== null &&
1035 singleActivity.toolLike &&
1036 toolGroupAction(singleActivity.workEntry) !== "edit"
1037 ? singleToolCallLabel(singleActivity)
1038 : singleActivity !== null && !singleActivity.toolLike
1039 ? singleActivity.workEntry.label
1040 : groupSummary.summary;
1041 const primarySourceActivity = activities.find(
1042 (activity) => activity.workEntry.toolSource !== undefined,
1043 );
1044 const primarySourceKey = primarySourceActivity?.workEntry.toolSource?.key;
1045 const primarySourceIcon = primarySourceKey
1046 ? (activities.find(
1047 (activity) =>
1048 activity.workEntry.toolSource?.key === primarySourceKey &&
1049 activity.workEntry.toolIcon !== undefined,
1050 )?.workEntry.toolIcon ?? primarySourceActivity?.workEntry.toolSource?.icon)
1051 : undefined;
1052 const groupToolSurface =
1053 primarySourceActivity?.workEntry.toolSurface ??
1054 latestActivity.workEntry.toolSurface ??
1055 activities.findLast((activity) => activity.workEntry.toolSurface !== undefined)?.workEntry
1056 .toolSurface;
1057 const groupToolIcon =
1058 primarySourceIcon ??
1059 latestActivity.workEntry.toolIcon ??
1060 activities.findLast((activity) => activity.workEntry.toolIcon !== undefined)?.workEntry
1061 .toolIcon;
1062 const summaryToolIcon = live
1063 ? resolveWorkEntryToolPresentation(latestActivity.workEntry)?.icon
1064 : singleActivity !== null &&
1065 singleActivity.toolLike &&
1066 toolGroupAction(singleActivity.workEntry) !== "edit"
1067 ? resolveWorkEntryToolPresentation(singleActivity.workEntry, "completed")?.icon
1068 : undefined;
1069 result.push({
1070 type: "work-toggle",
1071 id: `${live ? "work-live" : "work-toggle"}:${groupId}`,
1072 createdAt: sourceGroup.createdAt,
1073 runId: sourceGroup.runId,
1074 groupId,
1075 hiddenCount: activities.length,
1076 expanded,
1077 summary,
1078 summaryKind: toolGroupSummaryKind(
1079 (live ? [latestActivity] : activities).map((activity) => activity.workEntry),
1080 ),
1081 ...(groupToolSurface ? { toolSurface: groupToolSurface } : {}),
1082 ...(groupToolIcon ? { toolIcon: groupToolIcon } : {}),
1083 ...(summaryToolIcon ? { summaryToolIcon } : {}),
1084 hasFailure: (() => {
1085 const lastToolLike = activities.findLast((activity) => activity.toolLike);
1086 return (
1087 lastToolLike !== undefined && workEntryDisplayIndicatesToolFailure(lastToolLike.workEntry)
1088 );
1089 })(),
1090 live,
1091 shimmer:
1092 isWorking &&
1093 latestActivity.lifecycleStatus === "inProgress" &&
1094 latestActivity.runId === activeRunId,
1095 });
1096 if (!expanded) return;
1097 result.push({
1098 type: "activity-group",
1099 id: `work-details:${groupId}`,
1100 createdAt: activities[0]!.createdAt,
1101 runId: activities[0]!.runId,
1102 activities: activities.map((activity) => ({
1103 ...activity,
1104 groupedToolDetail: true,
1105 live:
1106 isWorking &&
1107 activity.id === latestActivity.id &&
1108 activity.lifecycleStatus === "inProgress" &&
1109 activity.runId === activeRunId,
1110 })),
1111 });
1112}
1113
1114function liveToolActivitySummary(activity: ThreadFeedActivity, presentTense: boolean): string {
1115 const status = liveActivityToolStatus(activity.lifecycleStatus, presentTense);
1116 const presentation = resolveWorkEntryToolPresentation({
1117 ...activity.workEntry,
1118 toolLifecycleStatus: status,
1119 });
1120 if (presentation) return presentation.displayName;
1121 const command = activity.workEntry.command?.trim();
1122 if (command) {
1123 const program = commandProgramName(command);
1124 const verb =
1125 status === "inProgress"
1126 ? "Running"
1127 : status === "failed"
1128 ? "Failed"
1129 : status === "declined"
1130 ? "Declined"
1131 : status === "stopped"
1132 ? "Stopped"
1133 : "Ran";
1134 return `${verb} ${program ?? "command"}`;
1135 }
1136 return activity.detail ?? activity.summary;
1137}
1138
1139export function setPendingUserInputCustomAnswer(
1140 question: ThreadUserInputQuestion,
1141 draft: PendingUserInputDraftAnswer | undefined,
1142 customAnswer: string,
1143): PendingUserInputDraftAnswer {
1144 if (question.allowCustomAnswer === false) {
1145 return draft ?? {};
1146 }
1147
1148 const selectedOptionValues =
1149 customAnswer.trim().length > 0
1150 ? undefined
1151 : normalizeSelectedOptionValues(question, draft?.selectedOptionValues);
1152 return {
1153 customAnswer,
1154 ...(selectedOptionValues && selectedOptionValues.length > 0 ? { selectedOptionValues } : {}),
1155 };
1156}
1157
1158export function isPendingUserInputOptionSelected(
1159 question: ThreadUserInputQuestion,
1160 draft: PendingUserInputDraftAnswer | undefined,
1161 optionValue: string,
1162): boolean {
1163 if (question.allowCustomAnswer !== false && normalizeDraftAnswer(draft?.customAnswer)) {
1164 return false;
1165 }
1166
1167 const resolvedOptionValue = resolvePendingUserInputOptionValue(question, optionValue);
1168 return (
1169 resolvedOptionValue !== null &&
1170 normalizeSelectedOptionValues(question, draft?.selectedOptionValues).includes(
1171 resolvedOptionValue,
1172 )
1173 );
1174}
1175
1176export function togglePendingUserInputOptionSelection(
1177 question: ThreadUserInputQuestion,
1178 draft: PendingUserInputDraftAnswer | undefined,
1179 optionValue: string,
1180): PendingUserInputDraftAnswer {
1181 const resolvedOptionValue = resolvePendingUserInputOptionValue(question, optionValue);
1182 if (resolvedOptionValue === null) {
1183 return draft ?? {};
1184 }
1185
1186 if (question.multiSelect) {
1187 const selectedOptionValues = normalizeSelectedOptionValues(
1188 question,
1189 draft?.selectedOptionValues,
1190 );
1191 const nextSelectedOptionValues = selectedOptionValues.includes(resolvedOptionValue)
1192 ? selectedOptionValues.filter((value) => value !== resolvedOptionValue)
1193 : [...selectedOptionValues, resolvedOptionValue];
1194
1195 return {
1196 customAnswer: "",
1197 ...(nextSelectedOptionValues.length > 0
1198 ? { selectedOptionValues: nextSelectedOptionValues }
1199 : {}),
1200 };
1201 }
1202
1203 return {
1204 customAnswer: "",
1205 selectedOptionValues: [resolvedOptionValue],
1206 };
1207}
1208
1209export function buildPendingUserInputAnswers(
1210 questions: ReadonlyArray<ThreadUserInputQuestion>,
1211 draftAnswers: Record<string, PendingUserInputDraftAnswer>,
1212): Record<string, string | ReadonlyArray<string>> | null {
1213 const answers: Record<string, string | ReadonlyArray<string>> = {};
1214
1215 for (const question of questions) {
1216 const answer = resolvePendingUserInputAnswer(question, draftAnswers[question.id]);
1217 if (answer === null) {
1218 return null;
1219 }
1220 answers[question.id] = answer;
1221 }
1222
1223 return answers;
1224}
1225
1226/**
1227 * Projects the server-authored visible sequence into mobile row presentation.
1228 * It deliberately preserves the incoming order and never rebuilds chat from
1229 * separate message, plan, or work-entry collections.
1230 */
1231export function buildThreadFeed(
1232 visibleTurnItems: ReadonlyArray<OrchestrationV2ProjectedTurnItem>,
1233 options?: {
1234 readonly localMessages?: ReadonlyArray<OrchestrationMessage>;
1235 readonly anchoredMessages?: ReadonlyArray<OrchestrationMessage>;
1236 readonly attempts?: ReadonlyArray<OrchestrationV2RunAttempt>;
1237 readonly nodes?: ReadonlyArray<OrchestrationV2ExecutionNode>;
1238 },
1239): ThreadFeedEntry[] {
1240 const entries: RawThreadFeedEntry[] = [];
1241 const attemptByRootNodeId = new Map(
1242 (options?.attempts ?? []).map((attempt) => [attempt.rootNodeId, attempt] as const),
1243 );
1244 const nodeById = new Map((options?.nodes ?? []).map((node) => [node.id, node] as const));
1245 const resolveAttemptId = (item: OrchestrationV2TurnItem): RunAttemptId | null => {
1246 if (item.nodeId === null || item.runId === null) return null;
1247 let nodeId: OrchestrationV2ExecutionNode["id"] | null = item.nodeId;
1248 const visited = new Set<OrchestrationV2ExecutionNode["id"]>();
1249 while (nodeId !== null && !visited.has(nodeId)) {
1250 visited.add(nodeId);
1251 const directAttempt = attemptByRootNodeId.get(nodeId);
1252 if (directAttempt?.runId === item.runId) return directAttempt.id;
1253 const node = nodeById.get(nodeId);
1254 if (node === undefined) return null;
1255 const rootAttempt = attemptByRootNodeId.get(node.rootNodeId);
1256 if (rootAttempt?.runId === item.runId) return rootAttempt.id;
1257 nodeId = node.parentNodeId;
1258 }
1259 return null;
1260 };
1261 for (const row of visibleTurnItems) {
1262 const item = row.item;
1263 if (turnItemIsWorkspacePreparation(item)) continue;
1264 if (item.type === "todo_list") continue;
1265 // Match the web timeline: only the terminal interrupt result is useful to
1266 // users; the preceding request is transient bookkeeping.
1267 if (item.type === "run_interrupt_request") {
1268 continue;
1269 }
1270 const attemptId = resolveAttemptId(item);
1271 const cached = projectedEntriesCache.get(row);
1272 if (cached?.attemptId === attemptId) {
1273 entries.push(cached.entry);
1274 continue;
1275 }
1276 const createdAt = DateTime.formatIso(item.startedAt ?? item.updatedAt);
1277 if (item.type === "user_message" || item.type === "assistant_message") {
1278 const updatedAt = DateTime.formatIso(item.updatedAt);
1279 const entry: RawThreadFeedEntry = {
1280 type: "message",
1281 id: item.messageId,
1282 createdAt,
1283 message: {
1284 id: item.messageId,
1285 role: item.type === "user_message" ? "user" : "assistant",
1286 text: item.text,
1287 attachments: item.attachments ?? [],
1288 runId: item.runId,
1289 streaming: item.type === "assistant_message" && item.streaming,
1290 ...(item.type === "user_message"
1291 ? {
1292 inputIntent: item.inputIntent,
1293 createdBy: item.createdBy,
1294 creationSource: item.creationSource,
1295 }
1296 : {}),
1297 visibility: row.visibility,
1298 sourceThreadId: row.sourceThreadId,
1299 createdAt,
1300 updatedAt,
1301 projectedItem: row,
1302 },
1303 };
1304 projectedEntriesCache.set(row, { attemptId, entry });
1305 entries.push(entry);
1306 continue;
1307 }
1308 const activity = toFeedActivity(row, attemptId);
1309 const entry: RawThreadFeedEntry = {
1310 type: "activity",
1311 id: activity.id,
1312 createdAt,
1313 runId: item.runId,
1314 activity,
1315 };
1316 projectedEntriesCache.set(row, { attemptId, entry });
1317 entries.push(entry);
1318 }
1319 const retainedMessageIds = new Set(
1320 entries.flatMap((entry) => (entry.type === "message" ? [entry.id] : [])),
1321 );
1322 const appendLocalMessage = (message: OrchestrationMessage): RawThreadFeedEntry => {
1323 const cached = localMessageEntriesCache.get(message);
1324 if (cached) return cached;
1325 const entry: Extract<RawThreadFeedEntry, { readonly type: "message" }> = {
1326 type: "message",
1327 id: message.id,
1328 createdAt: message.createdAt,
1329 message: {
1330 id: message.id,
1331 role: message.role === "assistant" ? "assistant" : "user",
1332 text: message.text,
1333 attachments: message.attachments ?? [],
1334 runId: null,
1335 streaming: message.streaming,
1336 visibility: "local",
1337 sourceThreadId: ThreadId.make("local-feedback"),
1338 createdAt: message.createdAt,
1339 updatedAt: message.updatedAt,
1340 },
1341 };
1342 localMessageEntriesCache.set(message, entry);
1343 return entry;
1344 };
1345 for (const message of options?.anchoredMessages ?? []) {
1346 if (retainedMessageIds.has(message.id)) continue;
1347 retainedMessageIds.add(message.id);
1348 const entry = appendLocalMessage(message);
1349 const insertionIndex = entries.findIndex(
1350 (candidate) => candidate.createdAt > message.createdAt,
1351 );
1352 if (insertionIndex === -1) entries.push(entry);
1353 else entries.splice(insertionIndex, 0, entry);
1354 }
1355 for (const message of options?.localMessages ?? []) {
1356 if (retainedMessageIds.has(message.id)) continue;
1357 retainedMessageIds.add(message.id);
1358 entries.push(appendLocalMessage(message));
1359 }
1360 return groupAdjacentActivities(entries);
1361}