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

threadActivity.ts

1,110 lines34.2 KB

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 { commandProgramName } from "@t3tools/client-runtime/work-log/command-label";
8import {
9 summarizeToolGroup,
10 toolGroupSummaryKind,
11 type ToolGroupSummaryKind,
12 type WorkLogPresentationEntry,
13 type WorkLogToolLifecycleStatus,
14} from "@t3tools/client-runtime/work-log/presentation";
15import {
16 resolveT3McpToolPresentation,
17 type T3McpToolLogo,
18 type T3McpToolPresentation,
19} from "@t3tools/shared/t3McpToolPresentation";
20import type {
21 ChatAttachment,
22 MessageId,
23 OrchestrationV2Actor,
24 OrchestrationV2CreationSource,
25 OrchestrationV2ExecutionNode,
26 OrchestrationMessage,
27 OrchestrationV2ProjectedTurnItem,
28 OrchestrationV2RunAttempt,
29 OrchestrationV2RunStatus,
30 OrchestrationV2TurnItem,
31 OrchestrationV2UserMessageInputIntent,
32 RunId,
33 RunAttemptId,
34} from "@t3tools/contracts";
35import { ThreadId } from "@t3tools/contracts";
36import { formatDuration } from "@t3tools/shared/orchestrationTiming";
37import * as DateTime from "effect/DateTime";
38​
39export type PendingApproval = ThreadPendingApproval;
40export type PendingUserInput = ThreadPendingUserInput;
41​
42export interface PendingUserInputDraftAnswer {
43 readonly selectedOptionLabels?: ReadonlyArray<string>;
44 readonly customAnswer?: string;
46​
47export interface ThreadFeedActivity {
48 readonly id: string;
49 readonly createdAt: string;
50 readonly runId: RunId | null;
51 readonly attemptId: RunAttemptId | null;
52 readonly summary: string;
53 readonly detail: string | null;
54 readonly canExpand: boolean;
55 readonly getFullDetail: () => string | null;
56 readonly getCopyText: () => string;
57 readonly icon:
58 | "agent"
59 | "alert"
60 | "check"
61 | "command"
62 | "edit"
63 | "eye"
64 | "globe"
65 | "hammer"
66 | "message"
67 | "warning"
68 | "wrench"
69 | "zap";
70 readonly logo: T3McpToolLogo | null;
71 readonly toolLike: boolean;
72 readonly prominent: boolean;
73 readonly status: "success" | "failure" | "neutral" | null;
74 readonly lifecycleStatus: WorkLogToolLifecycleStatus;
75 readonly workEntry: WorkLogPresentationEntry;
76 readonly groupedToolDetail?: boolean;
77 readonly live?: boolean;
78 readonly projectedItem: OrchestrationV2ProjectedTurnItem;
80​
81export interface ThreadFeedMessage {
82 readonly id: MessageId;
83 readonly role: "user" | "assistant";
84 readonly text: string;
85 readonly attachments: ReadonlyArray<ChatAttachment>;
86 readonly runId: RunId | null;
87 readonly streaming: boolean;
88 readonly inputIntent?: OrchestrationV2UserMessageInputIntent;
89 readonly createdBy?: OrchestrationV2Actor;
90 readonly creationSource?: OrchestrationV2CreationSource;
91 readonly visibility: OrchestrationV2ProjectedTurnItem["visibility"];
92 readonly sourceThreadId: ThreadId;
93 readonly createdAt: string;
94 readonly updatedAt: string;
95 readonly projectedItem?: OrchestrationV2ProjectedTurnItem;
97​
98type RawThreadFeedEntry =
99 | {
100 readonly type: "message";
101 readonly id: string;
102 readonly createdAt: string;
103 readonly message: ThreadFeedMessage;
104 }
105 | {
106 readonly type: "activity";
107 readonly id: string;
108 readonly createdAt: string;
109 readonly runId: RunId | null;
110 readonly activity: ThreadFeedActivity;
111 };
112​
113export type ThreadFeedEntry =
114 | Extract<RawThreadFeedEntry, { type: "message" }>
115 | {
116 readonly type: "activity-group";
117 readonly id: string;
118 readonly createdAt: string;
119 readonly runId: RunId | null;
120 readonly activities: ReadonlyArray<ThreadFeedActivity>;
121 }
122 | {
123 readonly type: "work-toggle";
124 readonly id: string;
125 readonly createdAt: string;
126 readonly runId: RunId | null;
127 readonly groupId: string;
128 readonly hiddenCount: number;
129 readonly expanded: boolean;
130 readonly summary: string;
131 readonly summaryKind: ToolGroupSummaryKind;
132 readonly hasFailure: boolean;
133 readonly live: boolean;
134 readonly shimmer: boolean;
135 }
136 | {
137 readonly type: "run-fold";
138 readonly id: string;
139 readonly createdAt: string;
140 readonly runId: RunId;
141 readonly label: string;
142 readonly expanded: boolean;
143 };
144​
145export interface ThreadFeedLatestRun {
146 readonly runId: RunId;
147 readonly status: OrchestrationV2RunStatus;
148 readonly startedAt: string | null;
149 readonly completedAt: string | null;
151​
152function normalizeDraftAnswer(value: string | undefined): string | null {
153 if (typeof value !== "string") return null;
154 const trimmed = value.trim();
155 return trimmed.length > 0 ? trimmed : null;
157​
158function normalizeSelectedOptionLabels(
159 value: ReadonlyArray<string> | undefined,
160): ReadonlyArray<string> {
161 if (!Array.isArray(value)) {
162 return [];
163 }
164​
165 return Array.from(
166 new Set(value.map((entry) => entry.trim()).filter((entry) => entry.length > 0)),
167 );
169​
170function resolvePendingUserInputAnswer(
171 question: ThreadUserInputQuestion,
172 draft: PendingUserInputDraftAnswer | undefined,
173): string | ReadonlyArray<string> | null {
174 const customAnswer = normalizeDraftAnswer(draft?.customAnswer);
175 if (customAnswer) {
176 return customAnswer;
177 }
178​
179 const selectedOptionLabels = normalizeSelectedOptionLabels(draft?.selectedOptionLabels);
180 if (question.multiSelect) {
181 return selectedOptionLabels.length > 0 ? selectedOptionLabels : null;
182 }
183 return selectedOptionLabels[0] ?? null;
185​
186function capitalizePhrase(value: string): string {
187 const trimmed = value.trim();
188 return trimmed.length === 0 ? value : `${trimmed.charAt(0).toUpperCase()}${trimmed.slice(1)}`;
190​
191function memoizeValue<T>(build: () => T): () => T {
192 let value: T;
193 let initialized = false;
194 return () => {
195 if (!initialized) {
196 value = build();
197 initialized = true;
198 }
199 return value;
200 };
202​
203function itemIsToolLike(item: OrchestrationV2TurnItem): boolean {
204 return (
205 item.type === "reasoning" ||
206 item.type === "command_execution" ||
207 item.type === "file_change" ||
208 item.type === "file_search" ||
209 item.type === "web_search" ||
210 item.type === "approval_request" ||
211 item.type === "user_input_request" ||
212 item.type === "dynamic_tool" ||
213 item.type === "subagent"
214 );
216​
217function itemIsProminent(item: OrchestrationV2TurnItem): boolean {
218 return item.type === "fork" || item.type === "thread_created" || item.type === "subagent";
220​
221function itemStatus(item: OrchestrationV2TurnItem): ThreadFeedActivity["status"] {
222 if (item.type === "error") {
223 if (item.status === "failed") return "failure";
224 return item.status === "completed" ? "success" : "neutral";
225 }
226 if (!itemIsToolLike(item)) return null;
227 if (item.status === "failed") return "failure";
228 return item.status === "completed" ? "success" : "neutral";
230​
231function itemLifecycleStatus(item: OrchestrationV2TurnItem): WorkLogToolLifecycleStatus {
232 switch (item.status) {
233 case "pending":
234 case "running":
235 case "waiting":
236 return "inProgress";
237 case "completed":
238 return "completed";
239 case "failed":
240 return "failed";
241 case "cancelled":
242 case "interrupted":
243 return "stopped";
244 }
246​
247function itemWorkLogTone(item: OrchestrationV2TurnItem): WorkLogPresentationEntry["tone"] {
248 if (item.type === "error") return "info";
249 if (item.type === "reasoning") return "thinking";
250 switch (item.type) {
251 case "command_execution":
252 case "file_change":
253 case "file_search":
254 case "web_search":
255 case "dynamic_tool":
256 case "subagent":
257 return "tool";
258 default:
259 return "info";
260 }
262​
263function itemIcon(item: OrchestrationV2TurnItem): ThreadFeedActivity["icon"] {
264 switch (item.type) {
265 case "reasoning":
266 return "agent";
267 case "command_execution":
268 return "command";
269 case "file_change":
270 return "edit";
271 case "file_search":
272 return "eye";
273 case "web_search":
274 return "globe";
275 case "approval_request":
276 case "user_input_request":
277 case "user_message":
278 case "assistant_message":
279 return "message";
280 case "dynamic_tool":
281 return "wrench";
282 case "subagent":
283 return "hammer";
284 case "run_interrupt_request":
285 case "run_interrupt_result":
286 return "warning";
287 case "error":
288 return "alert";
289 case "checkpoint":
290 case "proposed_plan":
291 case "todo_list":
292 return "check";
293 case "compaction":
294 case "handoff":
295 case "fork":
296 case "thread_created":
297 return "zap";
298 }
300​
301function itemToolPresentation(item: OrchestrationV2TurnItem): T3McpToolPresentation | null {
302 if (item.type !== "dynamic_tool") {
303 return null;
304 }
305 return resolveT3McpToolPresentation(item.toolName) ?? resolveT3McpToolPresentation(item.title);
307​
308function itemSummary(
309 item: OrchestrationV2TurnItem,
310 toolPresentation: T3McpToolPresentation | null = null,
311): string {
312 const title = item.title?.trim();
313 if (title) return toolPresentation?.displayName ?? capitalizePhrase(title);
314 switch (item.type) {
315 case "reasoning":
316 return "Thinking";
317 case "command_execution":
318 return "Command";
319 case "file_change":
320 return `Changed ${item.fileName}`;
321 case "file_search":
322 return "Searched files";
323 case "web_search":
324 return "Searched the web";
325 case "approval_request":
326 return "Approval requested";
327 case "user_input_request":
328 return "Input requested";
329 case "checkpoint":
330 return "Checkpoint captured";
331 case "run_interrupt_request":
332 return "Interrupt requested";
333 case "run_interrupt_result":
334 return "Run interrupted";
335 case "error":
336 return "Provider error";
337 case "compaction":
338 return "Context compacted";
339 case "handoff":
340 return "Context handed off";
341 case "fork":
342 return "Thread forked";
343 case "thread_created":
344 return "Thread created";
345 case "subagent":
346 return "Subagent";
347 case "dynamic_tool":
348 return toolPresentation?.displayName ?? item.toolName ?? "Tool call";
349 case "proposed_plan":
350 return "Proposed plan";
351 case "todo_list":
352 return "Plan updated";
353 case "user_message":
354 return "User message";
355 case "assistant_message":
356 return "Assistant message";
357 }
359​
360function itemPreview(item: OrchestrationV2TurnItem): string | null {
361 switch (item.type) {
362 case "reasoning":
363 return item.text || null;
364 case "command_execution":
365 return item.input || null;
366 case "file_change":
367 return item.fileName;
368 case "file_search":
369 return item.pattern ?? null;
370 case "web_search":
371 return item.patterns?.join(", ") ?? null;
372 case "approval_request":
373 return item.prompt ?? null;
374 case "user_input_request":
375 return item.questions.map((question) => question.question).join(" · ") || null;
376 case "checkpoint":
377 return item.files.length === 1
378 ? (item.files[0]?.path ?? null)
379 : `${item.files.length} changed files`;
380 case "run_interrupt_request":
381 case "run_interrupt_result":
382 return item.message || null;
383 case "error":
384 return item.failure.message;
385 case "compaction":
386 case "handoff":
387 return item.summary ?? null;
388 case "fork":
389 case "thread_created":
390 return item.targetThreadId;
391 case "subagent":
392 return item.result ?? item.progress ?? item.prompt;
393 case "dynamic_tool":
394 return null;
395 case "proposed_plan":
396 return item.markdown || null;
397 case "todo_list":
398 return `${item.steps.filter((step) => step.status === "completed").length}/${item.steps.length} completed`;
399 case "user_message":
400 case "assistant_message":
401 return item.text || null;
402 }
404​
405function toWorkLogEntry(
406 item: OrchestrationV2TurnItem,
407 createdAt: string,
408 summary: string,
409 detail: string | null,
410): WorkLogPresentationEntry {
411 const title = item.title?.trim() || null;
412 const common = {
413 id: item.id,
414 createdAt,
415 label: summary,
416 tone: itemWorkLogTone(item),
417 itemType: item.type,
418 toolLifecycleStatus: itemLifecycleStatus(item),
419 structuredPayload: item,
420 } as const;
421​
422 switch (item.type) {
423 case "reasoning":
424 return { ...common, ...(item.text ? { detail: item.text } : {}) };
425 case "command_execution":
426 return {
427 ...common,
428 command: item.input,
429 rawCommand: item.input,
430 ...(item.output ? { detail: item.output } : {}),
431 toolTitle: title ?? "Command",
432 toolData: item,
433 };
434 case "file_change":
435 return {
436 ...common,
437 changedFiles: [item.fileName],
438 ...((item.diffStr ?? item.newStr) ? { detail: item.diffStr ?? item.newStr } : {}),
439 toolTitle: title ?? "File change",
440 toolData: item,
441 };
442 case "file_search":
443 return {
444 ...common,
445 ...(item.pattern ? { detail: item.pattern } : {}),
446 toolTitle: title ?? "File search",
447 toolData: item,
448 };
449 case "web_search":
450 return {
451 ...common,
452 ...(item.patterns?.length ? { detail: item.patterns.join(", ") } : {}),
453 toolTitle: title ?? "Web search",
454 toolData: item,
455 };
456 case "checkpoint":
457 return { ...common, changedFiles: item.files.map((file) => file.path), toolData: item };
458 case "approval_request":
459 return {
460 ...common,
461 ...(item.prompt ? { detail: item.prompt } : {}),
462 requestKind: item.requestKind,
463 toolData: item,
464 };
465 case "dynamic_tool":
466 return {
467 ...common,
468 toolTitle: title ?? item.toolName ?? "Tool",
469 toolData: { input: item.input, output: item.output },
470 };
471 default:
472 return { ...common, ...(detail ? { detail } : {}), toolData: item };
473 }
475​
476function toFeedActivity(
477 row: OrchestrationV2ProjectedTurnItem,
478 attemptId: RunAttemptId | null,
479): ThreadFeedActivity {
480 const item = row.item;
481 const toolPresentation = itemToolPresentation(item);
482 const summary = itemSummary(item, toolPresentation);
483 const detail = itemPreview(item);
484 const createdAt = DateTime.formatIso(item.startedAt ?? item.updatedAt);
485 const workEntry = toWorkLogEntry(item, createdAt, summary, detail);
486 const getFullDetail = memoizeValue(() =>
487 JSON.stringify(
488 {
489 visibility: row.visibility,
490 sourceThreadId: row.sourceThreadId,
491 sourceItemId: row.sourceItemId,
492 item,
493 },
494 null,
495 2,
496 ),
497 );
498 const getCopyText = memoizeValue(() =>
499 [summary, detail, getFullDetail()]
500 .filter(
501 (value, index, values): value is string =>
502 Boolean(value) && values.indexOf(value) === index,
503 )
504 .join("\n"),
505 );
506 return {
507 id: `${row.visibility}:${row.sourceThreadId}:${row.sourceItemId}`,
508 createdAt,
509 runId: item.runId,
510 attemptId,
511 summary,
512 detail,
513 canExpand: true,
514 getFullDetail,
515 getCopyText,
516 icon: itemIcon(item),
517 logo: toolPresentation?.logo ?? null,
518 toolLike: itemIsToolLike(item),
519 prominent: itemIsProminent(item),
520 status: itemStatus(item),
521 lifecycleStatus: itemLifecycleStatus(item),
522 workEntry,
523 projectedItem: row,
524 };
526​
527function isEmptyMessage(entry: RawThreadFeedEntry): boolean {
528 return (
529 entry.type === "message" &&
530 entry.message.text.trim().length === 0 &&
531 entry.message.attachments.length === 0
532 );
534​
535function groupAdjacentActivities(entries: ReadonlyArray<RawThreadFeedEntry>): ThreadFeedEntry[] {
536 const grouped: ThreadFeedEntry[] = [];
537 // Mutable backing array for the trailing group so appending an activity is
538 // O(1) instead of re-copying the group (which made this loop quadratic on
539 // long tool runs). The array is only mutated while it is the trailing group.
540 let openGroupActivities: ThreadFeedActivity[] | null = null;
541 let openGroupRunId: string | null = null;
542 let openGroupAttemptId: string | null = null;
543 let openGroupHasProminent = false;
544​
545 for (const entry of entries) {
546 if (isEmptyMessage(entry)) continue;
547 if (entry.type !== "activity") {
548 grouped.push(entry);
549 openGroupActivities = null;
550 continue;
551 }
552​
553 if (
554 openGroupActivities !== null &&
555 openGroupRunId === entry.runId &&
556 openGroupAttemptId === entry.activity.attemptId &&
557 !entry.activity.prominent &&
558 !openGroupHasProminent
559 ) {
560 openGroupActivities.push(entry.activity);
561 continue;
562 }
563​
564 openGroupActivities = [entry.activity];
565 openGroupRunId = entry.runId;
566 openGroupAttemptId = entry.activity.attemptId;
567 openGroupHasProminent = entry.activity.prominent === true;
568 grouped.push({
569 type: "activity-group",
570 id: entry.id,
571 createdAt: entry.createdAt,
572 runId: entry.runId,
573 activities: openGroupActivities,
574 });
575 }
576 return grouped;
578​
579function computeElapsedMs(startIso: string, endIso: string): number | null {
580 const start = Date.parse(startIso);
581 const end = Date.parse(endIso);
582 return Number.isFinite(start) && Number.isFinite(end) ? Math.max(0, end - start) : null;
584​
585function maxIsoTimestamp(left: string | null, right: string | null): string | null {
586 if (left === null) return right;
587 if (right === null) return left;
588 return Date.parse(right) > Date.parse(left) ? right : left;
590​
591function unsettledRunId(latestRun: ThreadFeedLatestRun | null): RunId | null {
592 return threadFeedRunIsUnsettled(latestRun) ? latestRun.runId : null;
594​
595export function threadFeedRunIsUnsettled(
596 run: ThreadFeedLatestRun | null,
597): run is ThreadFeedLatestRun {
598 if (run === null || run.status === "queued") return false;
599 return (
600 run.completedAt === null ||
601 run.status === "preparing" ||
602 run.status === "starting" ||
603 run.status === "running" ||
604 run.status === "waiting"
605 );
607​
608export function threadFeedActivityIsVisible(
609 activity: Pick<ThreadFeedActivity, "prominent" | "status" | "toolLike">,
610): boolean {
611 return activity.prominent || !(activity.toolLike && activity.status === "neutral");
613​
614interface ThreadFeedRunFold {
615 readonly runId: RunId;
616 readonly createdAt: string;
617 readonly hiddenEntryIds: ReadonlySet<string>;
618 readonly label: string;
620​
621function deriveThreadFeedRunFolds(
622 feed: ReadonlyArray<ThreadFeedEntry>,
623 latestRun: ThreadFeedLatestRun | null,
624): ReadonlyMap<string, ThreadFeedRunFold> {
625 const terminalAssistantMessageIdByRun = new Map<RunId, string>();
626 const interruptedRunIds = new Set<RunId>();
627 for (const entry of feed) {
628 if (entry.type === "message" && entry.message.role === "assistant" && entry.message.runId) {
629 terminalAssistantMessageIdByRun.set(entry.message.runId, entry.id);
630 }
631 if (
632 entry.type === "activity-group" &&
633 entry.runId !== null &&
634 entry.activities.some(
635 (activity) => activity.projectedItem.item.type === "run_interrupt_result",
636 )
637 ) {
638 interruptedRunIds.add(entry.runId);
639 }
640 }
641​
642 const groupsByRunId = new Map<
643 RunId,
644 { entries: ThreadFeedEntry[]; startBoundary: string | null }
645 >();
646 let pendingUserBoundary: string | null = null;
647 for (const entry of feed) {
648 if (entry.type === "message" && entry.message.role === "user") {
649 pendingUserBoundary = entry.message.createdAt;
650 continue;
651 }
652 const runId =
653 entry.type === "message" && entry.message.role === "assistant"
654 ? entry.message.runId
655 : entry.type === "activity-group"
656 ? entry.runId
657 : null;
658 if (!runId) continue;
659 let group = groupsByRunId.get(runId);
660 if (!group) {
661 group = { entries: [], startBoundary: pendingUserBoundary };
662 pendingUserBoundary = null;
663 groupsByRunId.set(runId, group);
664 }
665 group.entries.push(entry);
666 }
667​
668 const activeRunId = unsettledRunId(latestRun);
669 const foldsByAnchorId = new Map<string, ThreadFeedRunFold>();
670 for (const [runId, group] of groupsByRunId) {
671 if (
672 runId === activeRunId ||
673 interruptedRunIds.has(runId) ||
674 group.entries.some((entry) => entry.type === "message" && entry.message.streaming)
675 ) {
676 continue;
677 }
678 const terminalAssistantId = terminalAssistantMessageIdByRun.get(runId);
679 const hiddenEntryIds = new Set(
680 group.entries
681 .filter(
682 (entry) =>
683 entry.id !== terminalAssistantId &&
684 !(
685 entry.type === "activity-group" &&
686 entry.activities.some((activity) => activity.prominent)
687 ),
688 )
689 .map((entry) => entry.id),
690 );
691 const firstEntry = group.entries[0];
692 const lastEntry = group.entries.at(-1);
693 if (hiddenEntryIds.size === 0 || !firstEntry || !lastEntry) continue;
694 const terminalEntry = terminalAssistantId
695 ? group.entries.find((entry) => entry.id === terminalAssistantId)
696 : null;
697 const latestRunMatches = latestRun?.runId === runId;
698 const lastEntryEnd =
699 lastEntry.type === "message" ? lastEntry.message.updatedAt : lastEntry.createdAt;
700 const elapsedMs =
701 latestRunMatches && latestRun.startedAt && latestRun.completedAt
702 ? computeElapsedMs(latestRun.startedAt, latestRun.completedAt)
703 : computeElapsedMs(
704 group.startBoundary ?? firstEntry.createdAt,
705 maxIsoTimestamp(
706 terminalEntry?.type === "message" ? terminalEntry.message.updatedAt : null,
707 lastEntryEnd,
708 ) ?? lastEntryEnd,
709 );
710 const duration = elapsedMs === null ? null : formatDuration(elapsedMs);
711 const interrupted =
712 latestRunMatches && (latestRun.status === "interrupted" || latestRun.status === "cancelled");
713 foldsByAnchorId.set(firstEntry.id, {
714 runId,
715 createdAt: firstEntry.createdAt,
716 hiddenEntryIds,
717 label: interrupted
718 ? duration
719 ? `You stopped after ${duration}`
720 : "You stopped this response"
721 : duration
722 ? `Worked for ${duration}`
723 : "Worked",
724 });
725 }
726 return foldsByAnchorId;
728​
729export function deriveThreadFeedPresentation(
730 feed: ReadonlyArray<ThreadFeedEntry>,
731 latestRun: ThreadFeedLatestRun | null,
732 expandedRunIds: ReadonlySet<RunId>,
733 expandedWorkGroupIds: ReadonlySet<string> = new Set(),
734 activeWorkStartedAt: string | null = null,
735): ThreadFeedEntry[] {
736 const sourceFeed = feed.filter(
737 (entry) => entry.type !== "run-fold" && entry.type !== "work-toggle",
738 );
739 const activeTailGroup = sourceFeed.at(-1);
740 const foldsByAnchorId = deriveThreadFeedRunFolds(sourceFeed, latestRun);
741 const activeRunId = unsettledRunId(latestRun);
742 const isWorking = activeWorkStartedAt !== null;
743 const collapsedEntryIds = new Set<string>();
744 for (const fold of foldsByAnchorId.values()) {
745 if (!expandedRunIds.has(fold.runId)) {
746 for (const entryId of fold.hiddenEntryIds) collapsedEntryIds.add(entryId);
747 }
748 }
749 const result: ThreadFeedEntry[] = [];
750 for (const entry of sourceFeed) {
751 const isActiveTailGroup =
752 isWorking &&
753 activeRunId !== null &&
754 entry.type === "activity-group" &&
755 activeTailGroup?.type === "activity-group" &&
756 activeTailGroup.id === entry.id &&
757 entry.runId === activeRunId;
758 const fold = foldsByAnchorId.get(entry.id);
759 if (fold) {
760 result.push({
761 type: "run-fold",
762 id: `run-fold:${fold.runId}`,
763 createdAt: fold.createdAt,
764 runId: fold.runId,
765 label: fold.label,
766 expanded: expandedRunIds.has(fold.runId),
767 });
768 }
769 if (!collapsedEntryIds.has(entry.id)) {
770 appendPresentedFeedEntry(
771 result,
772 entry,
773 expandedWorkGroupIds,
774 activeRunId,
775 isWorking,
776 isActiveTailGroup,
777 );
778 }
779 }
780 return result;
782​
783function appendPresentedFeedEntry(
784 result: ThreadFeedEntry[],
785 entry: Exclude<ThreadFeedEntry, { readonly type: "run-fold" | "work-toggle" }>,
786 expandedWorkGroupIds: ReadonlySet<string>,
787 activeRunId: RunId | null,
788 isWorking: boolean,
789 activeTail: boolean,
790): void {
791 if (entry.type !== "activity-group") {
792 result.push(entry);
793 return;
794 }
795​
796 const groupAnchorIdByActivityId = new Map<string, string>();
797 let groupAnchorId: string | null = null;
798 for (const activity of entry.activities) {
799 const item = activity.projectedItem.item;
800 if (activity.prominent || (item.type === "error" && item.status === "failed")) {
801 groupAnchorId = null;
802 continue;
803 }
804 groupAnchorId ??= activity.id;
805 groupAnchorIdByActivityId.set(activity.id, groupAnchorId);
806 }
807 const activities = entry.activities.filter(
808 (activity) =>
809 threadFeedActivityIsVisible(activity) ||
810 (isWorking && activity.lifecycleStatus === "inProgress" && activity.runId === activeRunId),
811 );
812 if (activities.length === 0) {
813 return;
814 }
815​
816 let groupableRun: ThreadFeedActivity[] = [];
817 const flushGroupableRun = (isTrailingRun: boolean) => {
818 if (groupableRun.length === 0) return;
819 appendToolGroupRows(
820 result,
821 entry,
822 groupableRun,
823 `work-group:${groupAnchorIdByActivityId.get(groupableRun[0]!.id) ?? groupableRun[0]!.id}`,
824 expandedWorkGroupIds,
825 activeRunId,
826 isWorking,
827 activeTail && isTrailingRun,
828 );
829 groupableRun = [];
830 };
831 for (const activity of activities) {
832 const item = activity.projectedItem.item;
833 const severeProviderError = item.type === "error" && item.status === "failed";
834 if (!activity.prominent && !severeProviderError) {
835 groupableRun.push(activity);
836 continue;
837 }
838 flushGroupableRun(false);
839 result.push({
840 type: "activity-group",
841 id: activity.id,
842 createdAt: activity.createdAt,
843 runId: activity.runId,
844 activities: [activity],
845 });
846 }
847 flushGroupableRun(true);
849​
850function appendToolGroupRows(
851 result: ThreadFeedEntry[],
852 sourceGroup: Extract<ThreadFeedEntry, { readonly type: "activity-group" }>,
853 activities: ReadonlyArray<ThreadFeedActivity>,
854 groupId: string,
855 expandedWorkGroupIds: ReadonlySet<string>,
856 activeRunId: RunId | null,
857 isWorking: boolean,
858 activeTail: boolean,
859): void {
860 const expanded = expandedWorkGroupIds.has(groupId);
861 const latestInProgressActivity = activities.findLast(
862 (activity) =>
863 isWorking && activity.lifecycleStatus === "inProgress" && activity.runId === activeRunId,
864 );
865 const live = activeTail || latestInProgressActivity !== undefined;
866 const latestActivity = activeTail
867 ? activities.at(-1)!
868 : (latestInProgressActivity ?? activities.at(-1)!);
869 const groupSummary = summarizeToolGroup(activities.map((activity) => activity.workEntry));
870 const summary = live
871 ? liveToolActivitySummary(latestActivity)
872 : activities.length === 1 && !activities[0]!.toolLike
873 ? activities[0]!.workEntry.label
874 : groupSummary.summary;
875 result.push({
876 type: "work-toggle",
877 id: `${live ? "work-live" : "work-toggle"}:${groupId}`,
878 createdAt: sourceGroup.createdAt,
879 runId: sourceGroup.runId,
880 groupId,
881 hiddenCount: activities.length,
882 expanded,
883 summary,
884 summaryKind: toolGroupSummaryKind(
885 (live ? [latestActivity] : activities).map((activity) => activity.workEntry),
886 ),
887 hasFailure: groupSummary.hasFailure,
888 live,
889 shimmer:
890 isWorking &&
891 latestActivity.lifecycleStatus === "inProgress" &&
892 latestActivity.runId === activeRunId,
893 });
894 if (!expanded) return;
895 for (const activity of activities) {
896 result.push({
897 type: "activity-group",
898 id: activity.id,
899 createdAt: activity.createdAt,
900 runId: activity.runId,
901 activities: [
902 {
903 ...activity,
904 groupedToolDetail: true,
905 live:
906 isWorking &&
907 activity.id === latestActivity.id &&
908 activity.lifecycleStatus === "inProgress" &&
909 activity.runId === activeRunId,
910 },
911 ],
912 });
913 }
915​
916function liveToolActivitySummary(activity: ThreadFeedActivity): string {
917 const command = activity.workEntry.command?.trim();
918 if (command) {
919 const program = commandProgramName(command);
920 return program ? `Running ${program}` : "Running command";
921 }
922 return activity.detail ?? activity.summary;
924export function setPendingUserInputCustomAnswer(
925 draft: PendingUserInputDraftAnswer | undefined,
926 customAnswer: string,
927): PendingUserInputDraftAnswer {
928 const selectedOptionLabels =
929 customAnswer.trim().length > 0
930 ? undefined
931 : normalizeSelectedOptionLabels(draft?.selectedOptionLabels);
932 return {
933 customAnswer,
934 ...(selectedOptionLabels && selectedOptionLabels.length > 0 ? { selectedOptionLabels } : {}),
935 };
937​
938export function isPendingUserInputOptionSelected(
939 draft: PendingUserInputDraftAnswer | undefined,
940 optionLabel: string,
941): boolean {
942 if (normalizeDraftAnswer(draft?.customAnswer)) {
943 return false;
944 }
945​
946 return normalizeSelectedOptionLabels(draft?.selectedOptionLabels).includes(optionLabel.trim());
948​
949export function togglePendingUserInputOptionSelection(
950 question: ThreadUserInputQuestion,
951 draft: PendingUserInputDraftAnswer | undefined,
952 optionLabel: string,
953): PendingUserInputDraftAnswer {
954 const normalizedOptionLabel = optionLabel.trim();
955​
956 if (question.multiSelect) {
957 const selectedOptionLabels = normalizeSelectedOptionLabels(draft?.selectedOptionLabels);
958 const nextSelectedOptionLabels = selectedOptionLabels.includes(normalizedOptionLabel)
959 ? selectedOptionLabels.filter((label) => label !== normalizedOptionLabel)
960 : [...selectedOptionLabels, normalizedOptionLabel];
961​
962 return {
963 customAnswer: "",
964 ...(nextSelectedOptionLabels.length > 0
965 ? { selectedOptionLabels: nextSelectedOptionLabels }
966 : {}),
967 };
968 }
969​
970 return {
971 customAnswer: "",
972 selectedOptionLabels: [normalizedOptionLabel],
973 };
975​
976export function buildPendingUserInputAnswers(
977 questions: ReadonlyArray<ThreadUserInputQuestion>,
978 draftAnswers: Record<string, PendingUserInputDraftAnswer>,
979): Record<string, string | ReadonlyArray<string>> | null {
980 const answers: Record<string, string | ReadonlyArray<string>> = {};
981​
982 for (const question of questions) {
983 const answer = resolvePendingUserInputAnswer(question, draftAnswers[question.id]);
984 if (!answer) {
985 return null;
986 }
987 answers[question.id] = answer;
988 }
989 return answers;
991​
992/**
993 * Projects the server-authored visible sequence into mobile row presentation.
994 * It deliberately preserves the incoming order and never rebuilds chat from
995 * separate message, plan, or work-entry collections.
996 */
997export function buildThreadFeed(
998 visibleTurnItems: ReadonlyArray<OrchestrationV2ProjectedTurnItem>,
999 options?: {
1000 readonly localMessages?: ReadonlyArray<OrchestrationMessage>;
1001 readonly anchoredMessages?: ReadonlyArray<OrchestrationMessage>;
1002 readonly attempts?: ReadonlyArray<OrchestrationV2RunAttempt>;
1003 readonly nodes?: ReadonlyArray<OrchestrationV2ExecutionNode>;
1004 },
1005): ThreadFeedEntry[] {
1006 const entries: RawThreadFeedEntry[] = [];
1007 const attemptByRootNodeId = new Map(
1008 (options?.attempts ?? []).map((attempt) => [attempt.rootNodeId, attempt] as const),
1009 );
1010 const nodeById = new Map((options?.nodes ?? []).map((node) => [node.id, node] as const));
1011 const resolveAttemptId = (item: OrchestrationV2TurnItem): RunAttemptId | null => {
1012 if (item.nodeId === null || item.runId === null) return null;
1013 let nodeId: OrchestrationV2ExecutionNode["id"] | null = item.nodeId;
1014 const visited = new Set<OrchestrationV2ExecutionNode["id"]>();
1015 while (nodeId !== null && !visited.has(nodeId)) {
1016 visited.add(nodeId);
1017 const directAttempt = attemptByRootNodeId.get(nodeId);
1018 if (directAttempt?.runId === item.runId) return directAttempt.id;
1019 const node = nodeById.get(nodeId);
1020 if (node === undefined) return null;
1021 const rootAttempt = attemptByRootNodeId.get(node.rootNodeId);
1022 if (rootAttempt?.runId === item.runId) return rootAttempt.id;
1023 nodeId = node.parentNodeId;
1025 return null;
1026 };
1027 for (const row of visibleTurnItems) {
1028 const item = row.item;
1029 if (turnItemIsWorkspacePreparation(item)) continue;
1030 // Match the web timeline: only the terminal interrupt result is useful to
1031 // users; the preceding request is transient bookkeeping.
1032 if (item.type === "run_interrupt_request") {
1033 continue;
1035 const createdAt = DateTime.formatIso(item.startedAt ?? item.updatedAt);
1036 if (item.type === "user_message" || item.type === "assistant_message") {
1037 const updatedAt = DateTime.formatIso(item.updatedAt);
1038 entries.push({
1039 type: "message",
1040 id: item.messageId,
1041 createdAt,
1042 message: {
1043 id: item.messageId,
1044 role: item.type === "user_message" ? "user" : "assistant",
1045 text: item.text,
1046 attachments: item.type === "user_message" ? item.attachments : [],
1047 runId: item.runId,
1048 streaming: item.type === "assistant_message" && item.streaming,
1049 ...(item.type === "user_message"
1050 ? {
1051 inputIntent: item.inputIntent,
1052 createdBy: item.createdBy,
1053 creationSource: item.creationSource,
1055 : {}),
1056 visibility: row.visibility,
1057 sourceThreadId: row.sourceThreadId,
1058 createdAt,
1059 updatedAt,
1060 projectedItem: row,
1061 },
1062 });
1063 continue;
1065 const activity = toFeedActivity(row, resolveAttemptId(item));
1066 entries.push({
1067 type: "activity",
1068 id: activity.id,
1069 createdAt,
1070 runId: item.runId,
1071 activity,
1072 });
1074 const retainedMessageIds = new Set(
1075 entries.flatMap((entry) => (entry.type === "message" ? [entry.id] : [])),
1076 );
1077 const appendLocalMessage = (message: OrchestrationMessage): RawThreadFeedEntry => ({
1078 type: "message",
1079 id: message.id,
1080 createdAt: message.createdAt,
1081 message: {
1082 id: message.id,
1083 role: message.role === "assistant" ? "assistant" : "user",
1084 text: message.text,
1085 attachments: message.attachments ?? [],
1086 runId: null,
1087 streaming: message.streaming,
1088 visibility: "local",
1089 sourceThreadId: ThreadId.make("local-feedback"),
1090 createdAt: message.createdAt,
1091 updatedAt: message.updatedAt,
1092 },
1093 });
1094 for (const message of options?.anchoredMessages ?? []) {
1095 if (retainedMessageIds.has(message.id)) continue;
1096 retainedMessageIds.add(message.id);
1097 const entry = appendLocalMessage(message);
1098 const insertionIndex = entries.findIndex(
1099 (candidate) => candidate.createdAt > message.createdAt,
1100 );
1101 if (insertionIndex === -1) entries.push(entry);
1102 else entries.splice(insertionIndex, 0, entry);
1104 for (const message of options?.localMessages ?? []) {
1105 if (retainedMessageIds.has(message.id)) continue;
1106 retainedMessageIds.add(message.id);
1107 entries.push(appendLocalMessage(message));
1109 return groupAdjacentActivities(entries);