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