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 `Changed ${item.fileName}`;
458 case "file_search":
459 return "Searched files";
460 case "web_search":
461 return "Searched the web";
462 case "approval_request":
463 return "Approval requested";
464 case "user_input_request":
465 return "Input requested";
466 case "checkpoint":
467 return "Checkpoint captured";
468 case "run_interrupt_request":
469 return "Interrupt requested";
470 case "run_interrupt_result":
471 return "Run interrupted";
472 case "error":
473 return "Provider error";
474 case "handoff":
475 return "Context handed off";
476 case "fork":
477 return "Thread forked";
478 case "thread_created":
479 return "Thread created";
480 case "subagent":
481 return "Subagent";
482 case "dynamic_tool":
483 return toolPresentation?.displayName ?? item.toolName ?? "Tool call";
484 case "proposed_plan":
485 return "Proposed plan";
486 case "todo_list":
487 return "Plan updated";
488 case "user_message":
489 return "User message";
490 case "assistant_message":
491 return "Assistant message";
492 }
493}
494
495function itemPreview(item: OrchestrationV2TurnItem): string | null {
496 switch (item.type) {
497 case "reasoning":
498 return item.text || null;
499 case "command_execution":
500 return item.input || null;
501 case "file_change":
502 return item.fileName;
503 case "file_search":
504 return item.pattern ?? null;
505 case "web_search":
506 return item.patterns?.join(", ") ?? null;
507 case "approval_request":
508 return item.prompt ?? null;
509 case "user_input_request":
510 return item.questions.map((question) => question.question).join(" · ") || null;
511 case "checkpoint":
512 return item.files.length === 1
513 ? (item.files[0]?.path ?? null)
514 : `${item.files.length} changed files`;
515 case "run_interrupt_request":
516 case "run_interrupt_result":
517 case "system_notice":
518 return item.message || null;
519 case "error":
520 return item.failure.message;
521 case "compaction":
522 case "handoff":
523 return item.summary ?? null;
524 case "fork":
525 case "thread_created":
526 return item.targetThreadId;
527 case "subagent":
528 return item.result ?? item.progress ?? item.prompt;
529 case "dynamic_tool":
530 return null;
531 case "proposed_plan":
532 return item.markdown || null;
533 case "todo_list":
534 return `${item.steps.filter((step) => step.status === "completed").length}/${item.steps.length} completed`;
535 case "user_message":
536 case "assistant_message":
537 return item.text || null;
538 }
539}
540
541function toWorkLogEntry(
542 item: OrchestrationV2TurnItem,
543 createdAt: string,
544 summary: string,
545 detail: string | null,
546): WorkLogPresentationEntry {
547 const title = item.title?.trim() || null;
548 const common = {
549 ...extractToolActivityPresentation(item),
550 id: item.id,
551 createdAt,
552 label: summary,
553 tone: itemWorkLogTone(item),
554 itemType: item.type,
555 toolLifecycleStatus: itemLifecycleStatus(item),
556 structuredPayload: item,
557 ...(item.type === "user_input_request" && item.questionAnswer
558 ? { questionAnswer: item.questionAnswer }
559 : {}),
560 } as const;
561
562 switch (item.type) {
563 case "reasoning":
564 return { ...common, ...(item.text ? { detail: item.text } : {}) };
565 case "command_execution":
566 return {
567 ...common,
568 command: item.input,
569 rawCommand: item.input,
570 toolTitle: title ?? "Command",
571 toolData: item,
572 };
573 case "file_change":
574 return {
575 ...common,
576 changedFiles: [item.fileName],
577 toolTitle: title ?? "File change",
578 toolData: item,
579 };
580 case "file_search":
581 return {
582 ...common,
583 ...(item.pattern ? { detail: item.pattern } : {}),
584 toolTitle: title ?? "File search",
585 toolData: item,
586 };
587 case "web_search":
588 return {
589 ...common,
590 ...(item.patterns?.length ? { detail: item.patterns.join(", ") } : {}),
591 toolTitle: title ?? "Web search",
592 toolData: item,
593 };
594 case "checkpoint":
595 return { ...common, changedFiles: item.files.map((file) => file.path), toolData: item };
596 case "approval_request":
597 return {
598 ...common,
599 ...(item.prompt ? { detail: item.prompt } : {}),
600 requestKind: item.requestKind,
601 toolData: item,
602 };
603 case "dynamic_tool":
604 return {
605 ...common,
606 toolTitle: title ?? item.toolName ?? "Tool",
607 toolData: { input: item.input, output: item.output },
608 };
609 default:
610 return { ...common, ...(detail ? { detail } : {}), toolData: item };
611 }
612}
613
614function toFeedActivity(
615 row: OrchestrationV2ProjectedTurnItem,
616 attemptId: RunAttemptId | null,
617): ThreadFeedActivity {
618 const item = row.item;
619 const toolPresentation = itemToolPresentation(item);
620 const summary = itemSummary(item, toolPresentation);
621 const detail = itemPreview(item);
622 const createdAt = DateTime.formatIso(item.startedAt ?? item.updatedAt);
623 const workEntry = toWorkLogEntry(item, createdAt, summary, detail);
624 const getFullDetail = memoizeValue(() =>
625 JSON.stringify(
626 {
627 visibility: row.visibility,
628 sourceThreadId: row.sourceThreadId,
629 sourceItemId: row.sourceItemId,
630 item: toolItemForDisplay(item),
631 },
632 null,
633 2,
634 ),
635 );
636 const getCopyText = memoizeValue(() =>
637 [summary, detail, getFullDetail()]
638 .filter(
639 (value, index, values): value is string =>
640 Boolean(value) && values.indexOf(value) === index,
641 )
642 .join("\n"),
643 );
644 return {
645 id: `${row.visibility}:${row.sourceThreadId}:${row.sourceItemId}`,
646 createdAt,
647 runId: item.runId,
648 attemptId,
649 summary,
650 detail,
651 canExpand: true,
652 getFullDetail,
653 getCopyText,
654 icon: workEntry.toolSurface ?? itemIcon(item),
655 logo: toolPresentation?.logo ?? null,
656 toolLike: itemIsToolLike(item),
657 prominent: itemIsProminent(item),
658 status: workEntryDisplayIndicatesToolFailure(workEntry) ? "failure" : itemStatus(item),
659 lifecycleStatus: itemLifecycleStatus(item),
660 workEntry,
661 projectedItem: row,
662 };
663}
664
665function singleToolCallLabel(activity: ThreadFeedActivity): string {
666 const presentation = resolveWorkEntryToolPresentation(activity.workEntry, "completed");
667 if (presentation) return presentation.displayName;
668 const command = activity.workEntry.command?.trim();
669 return command || activity.summary;
670}
671
672function isEmptyMessage(entry: RawThreadFeedEntry): boolean {
673 return (
674 entry.type === "message" &&
675 entry.message.text.trim().length === 0 &&
676 entry.message.attachments.length === 0
677 );
678}
679
680function groupAdjacentActivities(entries: ReadonlyArray<RawThreadFeedEntry>): ThreadFeedEntry[] {
681 const grouped: ThreadFeedEntry[] = [];
682 let firstActivityEntry: Extract<RawThreadFeedEntry, { readonly type: "activity" }> | null = null;
683 let openGroupActivities: ThreadFeedActivity[] = [];
684 const flushGroup = () => {
685 if (firstActivityEntry === null) return;
686 const cached = activityGroupsCache.get(firstActivityEntry.activity);
687 if (
688 cached &&
689 cached.activities.length === openGroupActivities.length &&
690 cached.activities.every((activity, index) => activity === openGroupActivities[index])
691 ) {
692 grouped.push(cached);
693 } else {
694 const group: ThreadFeedActivityGroup = {
695 type: "activity-group",
696 id: firstActivityEntry.id,
697 createdAt: firstActivityEntry.createdAt,
698 runId: firstActivityEntry.runId,
699 activities: openGroupActivities,
700 };
701 activityGroupsCache.set(firstActivityEntry.activity, group);
702 grouped.push(group);
703 }
704 firstActivityEntry = null;
705 openGroupActivities = [];
706 };
707
708 for (const entry of entries) {
709 // Skip empty messages so they don't break activity grouping.
710 if (isEmptyMessage(entry)) {
711 continue;
712 }
713
714 if (entry.type !== "activity") {
715 flushGroup();
716 grouped.push(entry);
717 continue;
718 }
719
720 const isCompaction = entry.activity.projectedItem.item.type === "compaction";
721 if (
722 isCompaction ||
723 entry.activity.prominent ||
724 firstActivityEntry?.runId !== entry.runId ||
725 firstActivityEntry?.activity.attemptId !== entry.activity.attemptId
726 ) {
727 flushGroup();
728 }
729 firstActivityEntry ??= entry;
730 openGroupActivities.push(entry.activity);
731 if (isCompaction || entry.activity.prominent) {
732 flushGroup();
733 }
734 }
735 flushGroup();
736 return grouped;
737}
738
739function computeElapsedMs(startIso: string, endIso: string): number | null {
740 const start = Date.parse(startIso);
741 const end = Date.parse(endIso);
742 return Number.isFinite(start) && Number.isFinite(end) ? Math.max(0, end - start) : null;
743}
744
745function maxIsoTimestamp(left: string | null, right: string | null): string | null {
746 if (left === null) return right;
747 if (right === null) return left;
748 return Date.parse(right) > Date.parse(left) ? right : left;
749}
750
751function unsettledRunId(latestRun: ThreadFeedLatestRun | null): RunId | null {
752 return threadFeedRunIsUnsettled(latestRun) ? latestRun.runId : null;
753}
754
755export function threadFeedRunIsUnsettled(
756 run: ThreadFeedLatestRun | null,
757): run is ThreadFeedLatestRun {
758 if (run === null || run.status === "queued") return false;
759 return (
760 run.completedAt === null ||
761 run.status === "preparing" ||
762 run.status === "starting" ||
763 run.status === "running" ||
764 run.status === "waiting"
765 );
766}
767
768export function threadFeedActivityIsVisible(
769 activity: Pick<ThreadFeedActivity, "prominent" | "status" | "toolLike"> &
770 Partial<Pick<ThreadFeedActivity, "lifecycleStatus">>,
771): boolean {
772 return (
773 activity.prominent ||
774 activity.lifecycleStatus === "stopped" ||
775 activity.lifecycleStatus === "declined" ||
776 activity.lifecycleStatus === "idle" ||
777 !(activity.toolLike && activity.status === "neutral")
778 );
779}
780
781interface ThreadFeedRunFold {
782 readonly runId: RunId;
783 readonly createdAt: string;
784 readonly hiddenEntryIds: ReadonlySet<string>;
785 readonly label: string;
786}
787
788function deriveThreadFeedRunFolds(
789 feed: ReadonlyArray<ThreadFeedEntry>,
790 latestRun: ThreadFeedLatestRun | null,
791): ReadonlyMap<string, ThreadFeedRunFold> {
792 const firstAssistantMessageIdByRun = new Map<RunId, string>();
793 const terminalAssistantMessageIdByRun = new Map<RunId, string>();
794 const interruptedRunIds = new Set<RunId>();
795 for (const entry of feed) {
796 if (entry.type === "message" && entry.message.role === "assistant" && entry.message.runId) {
797 if (!firstAssistantMessageIdByRun.has(entry.message.runId)) {
798 firstAssistantMessageIdByRun.set(entry.message.runId, entry.id);
799 }
800 terminalAssistantMessageIdByRun.set(entry.message.runId, entry.id);
801 }
802 if (
803 entry.type === "activity-group" &&
804 entry.runId !== null &&
805 entry.activities.some(
806 (activity) => activity.projectedItem.item.type === "run_interrupt_result",
807 )
808 ) {
809 interruptedRunIds.add(entry.runId);
810 }
811 }
812
813 const groupsByRunId = new Map<
814 RunId,
815 { entries: ThreadFeedEntry[]; startBoundary: string | null }
816 >();
817 let pendingUserBoundary: string | null = null;
818 for (const entry of feed) {
819 if (entry.type === "message" && entry.message.role === "user") {
820 pendingUserBoundary = entry.message.createdAt;
821 continue;
822 }
823 const runId =
824 entry.type === "message" && entry.message.role === "assistant"
825 ? entry.message.runId
826 : entry.type === "activity-group"
827 ? entry.runId
828 : null;
829 if (!runId) continue;
830 let group = groupsByRunId.get(runId);
831 if (!group) {
832 group = { entries: [], startBoundary: pendingUserBoundary };
833 pendingUserBoundary = null;
834 groupsByRunId.set(runId, group);
835 }
836 group.entries.push(entry);
837 }
838
839 const activeRunId = unsettledRunId(latestRun);
840 const foldsByAnchorId = new Map<string, ThreadFeedRunFold>();
841 for (const [runId, group] of groupsByRunId) {
842 if (
843 runId === activeRunId ||
844 interruptedRunIds.has(runId) ||
845 group.entries.some((entry) => entry.type === "message" && entry.message.streaming)
846 ) {
847 continue;
848 }
849 const firstAssistantId = firstAssistantMessageIdByRun.get(runId);
850 const terminalAssistantId = terminalAssistantMessageIdByRun.get(runId);
851 const hiddenEntryIds = new Set(
852 group.entries
853 .filter(
854 (entry) =>
855 entry.id !== firstAssistantId &&
856 entry.id !== terminalAssistantId &&
857 !(
858 entry.type === "activity-group" &&
859 entry.activities.some((activity) => activity.prominent)
860 ),
861 )
862 .map((entry) => entry.id),
863 );
864 const firstEntry = group.entries[0];
865 const firstHiddenEntry = group.entries.find((entry) => hiddenEntryIds.has(entry.id));
866 const lastEntry = group.entries.at(-1);
867 if (!firstHiddenEntry || !firstEntry || !lastEntry) continue;
868 const hidesNonCompactionWork = group.entries.some(
869 (entry) =>
870 hiddenEntryIds.has(entry.id) &&
871 !(entry.type === "activity-group" && isContextCompactionActivityGroup(entry)),
872 );
873 if (!hidesNonCompactionWork) continue;
874 const terminalEntry = terminalAssistantId
875 ? group.entries.find((entry) => entry.id === terminalAssistantId)
876 : null;
877 const latestRunMatches = latestRun?.runId === runId;
878 const lastEntryEnd =
879 lastEntry.type === "message" ? lastEntry.message.updatedAt : lastEntry.createdAt;
880 const elapsedMs =
881 latestRunMatches && latestRun.startedAt && latestRun.completedAt
882 ? computeElapsedMs(latestRun.startedAt, latestRun.completedAt)
883 : computeElapsedMs(
884 group.startBoundary ?? firstEntry.createdAt,
885 maxIsoTimestamp(
886 terminalEntry?.type === "message" ? terminalEntry.message.updatedAt : null,
887 lastEntryEnd,
888 ) ?? lastEntryEnd,
889 );
890 const duration = elapsedMs === null ? null : formatDuration(elapsedMs);
891 const interrupted =
892 latestRunMatches && (latestRun.status === "interrupted" || latestRun.status === "cancelled");
893 foldsByAnchorId.set(firstHiddenEntry.id, {
894 runId,
895 createdAt: firstHiddenEntry.createdAt,
896 hiddenEntryIds,
897 label: interrupted
898 ? duration
899 ? `You stopped after ${duration}`
900 : "You stopped this response"
901 : duration
902 ? `Worked for ${duration}`
903 : "Worked",
904 });
905 }
906 return foldsByAnchorId;
907}
908
909export function deriveThreadFeedPresentation(
910 feed: ReadonlyArray<ThreadFeedEntry>,
911 latestRun: ThreadFeedLatestRun | null,
912 expandedRunIds: ReadonlySet<RunId>,
913 expandedWorkGroupIds: ReadonlySet<string> = new Set(),
914 activeWorkStartedAt: string | null = null,
915): ThreadFeedEntry[] {
916 const sourceFeed = feed.filter(
917 (entry) =>
918 entry.type !== "run-fold" && entry.type !== "work-toggle" && entry.type !== "thinking",
919 );
920 const activeTailGroup = sourceFeed.at(-1);
921 const foldsByAnchorId = deriveThreadFeedRunFolds(sourceFeed, latestRun);
922 const activeRunId = unsettledRunId(latestRun);
923 const isWorking = activeWorkStartedAt !== null;
924 const collapsedEntryIds = new Set<string>();
925 for (const fold of foldsByAnchorId.values()) {
926 if (!expandedRunIds.has(fold.runId)) {
927 for (const entryId of fold.hiddenEntryIds) collapsedEntryIds.add(entryId);
928 }
929 }
930 const result: ThreadFeedEntry[] = [];
931 for (const entry of sourceFeed) {
932 const isActiveTailGroup =
933 isWorking &&
934 activeRunId !== null &&
935 entry.type === "activity-group" &&
936 activeTailGroup?.type === "activity-group" &&
937 activeTailGroup.id === entry.id &&
938 entry.runId === activeRunId;
939 const fold = foldsByAnchorId.get(entry.id);
940 if (fold) {
941 const expanded = expandedRunIds.has(fold.runId);
942 let row = runFoldRowsCache.get(entry);
943 if (
944 !row ||
945 row.runId !== fold.runId ||
946 row.createdAt !== fold.createdAt ||
947 row.label !== fold.label ||
948 row.expanded !== expanded
949 ) {
950 row = {
951 type: "run-fold",
952 id: `run-fold:${fold.runId}`,
953 createdAt: fold.createdAt,
954 runId: fold.runId,
955 label: fold.label,
956 expanded,
957 };
958 runFoldRowsCache.set(entry, row);
959 }
960 result.push(row);
961 }
962 if (!collapsedEntryIds.has(entry.id)) {
963 appendPresentedFeedEntry(
964 result,
965 entry,
966 expandedWorkGroupIds,
967 activeRunId,
968 isWorking,
969 isActiveTailGroup,
970 );
971 }
972 }
973 // Keep exactly one live slot while a run is working. When no tool row can
974 // carry it yet (or the latest call failed), the slot reads "Thinking".
975 if (
976 activeWorkStartedAt !== null &&
977 !result.some(
978 (row) =>
979 (row.type === "work-toggle" && row.shimmer) ||
980 (row.type === "activity-group" &&
981 isContextCompactionActivityGroup(row) &&
982 row.runId === activeRunId &&
983 row.activities[0]?.projectedItem.item.status === "running"),
984 )
985 ) {
986 result.push(thinkingRow(activeWorkStartedAt, activeRunId));
987 }
988 return result;
989}
990
991/** Shared by the trailing live tool row and its Thinking fallback. */
992export const LIVE_ACTIVITY_ROW_ID = "live-activity-row";
993
994function thinkingRow(createdAt: string, runId: RunId | null) {
995 if (cachedThinkingRow?.createdAt !== createdAt || cachedThinkingRow.runId !== runId) {
996 cachedThinkingRow = { type: "thinking", id: LIVE_ACTIVITY_ROW_ID, createdAt, runId };
997 }
998 return cachedThinkingRow;
999}
1000
1001function appendPresentedFeedEntry(
1002 result: ThreadFeedEntry[],
1003 entry: Exclude<ThreadFeedEntry, { readonly type: "run-fold" | "work-toggle" | "thinking" }>,
1004 expandedWorkGroupIds: ReadonlySet<string>,
1005 activeRunId: RunId | null,
1006 isWorking: boolean,
1007 activeTail: boolean,
1008): void {
1009 if (entry.type !== "activity-group") {
1010 result.push(entry);
1011 return;
1012 }
1013 if (isContextCompactionActivityGroup(entry)) {
1014 result.push(entry);
1015 return;
1016 }
1017
1018 let cached = presentedActivityGroupsCache.get(entry);
1019 if (
1020 !cached ||
1021 cached.activeRunId !== activeRunId ||
1022 cached.isWorking !== isWorking ||
1023 cached.activeTail !== activeTail ||
1024 cached.rows.some(
1025 (row) => row.type === "work-toggle" && expandedWorkGroupIds.has(row.groupId) !== row.expanded,
1026 )
1027 ) {
1028 const rows: ThreadFeedEntry[] = [];
1029 appendActivityGroupRows(rows, entry, expandedWorkGroupIds, activeRunId, isWorking, activeTail);
1030 cached = { activeRunId, isWorking, activeTail, rows };
1031 presentedActivityGroupsCache.set(entry, cached);
1032 }
1033 for (const row of cached.rows) {
1034 result.push(row);
1035 }
1036}
1037
1038function appendActivityGroupRows(
1039 result: ThreadFeedEntry[],
1040 entry: ThreadFeedActivityGroup,
1041 expandedWorkGroupIds: ReadonlySet<string>,
1042 activeRunId: RunId | null,
1043 isWorking: boolean,
1044 activeTail: boolean,
1045): void {
1046 const groupAnchorIdByActivityId = new Map<string, string>();
1047 let groupAnchorId: string | null = null;
1048 for (const activity of entry.activities) {
1049 const item = activity.projectedItem.item;
1050 if (activity.prominent || (item.type === "error" && item.status === "failed")) {
1051 groupAnchorId = null;
1052 continue;
1053 }
1054 groupAnchorId ??= activity.id;
1055 groupAnchorIdByActivityId.set(activity.id, groupAnchorId);
1056 }
1057 const activities = entry.activities.filter(
1058 (activity) =>
1059 threadFeedActivityIsVisible(activity) ||
1060 (isWorking && activity.lifecycleStatus === "inProgress" && activity.runId === activeRunId),
1061 );
1062 if (activities.length === 0) {
1063 return;
1064 }
1065
1066 let groupableRun: ThreadFeedActivity[] = [];
1067 const flushGroupableRun = (isTrailingRun: boolean) => {
1068 if (groupableRun.length === 0) return;
1069 appendToolGroupRows(
1070 result,
1071 entry,
1072 groupableRun,
1073 `work-group:${groupAnchorIdByActivityId.get(groupableRun[0]!.id) ?? groupableRun[0]!.id}`,
1074 expandedWorkGroupIds,
1075 activeRunId,
1076 isWorking,
1077 activeTail && isTrailingRun,
1078 );
1079 groupableRun = [];
1080 };
1081 for (const activity of activities) {
1082 const item = activity.projectedItem.item;
1083 const severeProviderError = item.type === "error" && item.status === "failed";
1084 if (!activity.prominent && !severeProviderError) {
1085 groupableRun.push(activity);
1086 continue;
1087 }
1088 flushGroupableRun(false);
1089 result.push({
1090 type: "activity-group",
1091 id: activity.id,
1092 createdAt: activity.createdAt,
1093 runId: activity.runId,
1094 activities: [activity],
1095 });
1096 }
1097 flushGroupableRun(true);
1098}
1099
1100function appendToolGroupRows(
1101 result: ThreadFeedEntry[],
1102 sourceGroup: Extract<ThreadFeedEntry, { readonly type: "activity-group" }>,
1103 activities: ReadonlyArray<ThreadFeedActivity>,
1104 groupId: string,
1105 expandedWorkGroupIds: ReadonlySet<string>,
1106 activeRunId: RunId | null,
1107 isWorking: boolean,
1108 activeTail: boolean,
1109): void {
1110 const expanded = expandedWorkGroupIds.has(groupId);
1111 const latestActiveActivity = activities.findLast(
1112 (activity) =>
1113 isWorking && activity.lifecycleStatus === "inProgress" && activity.runId === activeRunId,
1114 );
1115 const active = latestActiveActivity !== undefined;
1116 const live = activeTail || active;
1117 const latestActivity = latestActiveActivity ?? activities.at(-1)!;
1118 // A successful trailing call remains the live slot until the next activity.
1119 // Failed/stopped calls hand that slot to the Thinking row.
1120 const shimmer = activeTail && (active || latestActivity.status === "success");
1121 const singleActivity = activities.length === 1 ? latestActivity : null;
1122 const groupSummary = summarizeToolGroup(activities.map((activity) => activity.workEntry));
1123 const summary = live
1124 ? liveToolActivitySummary(latestActivity, live)
1125 : singleActivity !== null &&
1126 singleActivity.toolLike &&
1127 toolGroupAction(singleActivity.workEntry) !== "edit"
1128 ? singleToolCallLabel(singleActivity)
1129 : singleActivity !== null && !singleActivity.toolLike
1130 ? singleActivity.workEntry.label
1131 : groupSummary.summary;
1132 const primarySourceActivity = activities.find(
1133 (activity) => activity.workEntry.toolSource !== undefined,
1134 );
1135 const primarySourceKey = primarySourceActivity?.workEntry.toolSource?.key;
1136 const primarySourceIcon = primarySourceKey
1137 ? (activities.find(
1138 (activity) =>
1139 activity.workEntry.toolSource?.key === primarySourceKey &&
1140 activity.workEntry.toolIcon !== undefined,
1141 )?.workEntry.toolIcon ?? primarySourceActivity?.workEntry.toolSource?.icon)
1142 : undefined;
1143 const groupToolSurface =
1144 primarySourceActivity?.workEntry.toolSurface ??
1145 latestActivity.workEntry.toolSurface ??
1146 activities.findLast((activity) => activity.workEntry.toolSurface !== undefined)?.workEntry
1147 .toolSurface;
1148 const groupToolIcon =
1149 primarySourceIcon ??
1150 latestActivity.workEntry.toolIcon ??
1151 activities.findLast((activity) => activity.workEntry.toolIcon !== undefined)?.workEntry
1152 .toolIcon;
1153 const summaryToolIcon = live
1154 ? resolveWorkEntryToolPresentation(latestActivity.workEntry)?.icon
1155 : singleActivity !== null &&
1156 singleActivity.toolLike &&
1157 toolGroupAction(singleActivity.workEntry) !== "edit"
1158 ? resolveWorkEntryToolPresentation(singleActivity.workEntry, "completed")?.icon
1159 : undefined;
1160 result.push({
1161 type: "work-toggle",
1162 id: shimmer ? LIVE_ACTIVITY_ROW_ID : `${live ? "work-live" : "work-toggle"}:${groupId}`,
1163 createdAt: sourceGroup.createdAt,
1164 runId: sourceGroup.runId,
1165 groupId,
1166 hiddenCount: activities.length,
1167 expanded,
1168 summary,
1169 summaryKind: toolGroupSummaryKind(
1170 (live ? [latestActivity] : activities).map((activity) => activity.workEntry),
1171 ),
1172 ...(groupToolSurface ? { toolSurface: groupToolSurface } : {}),
1173 ...(groupToolIcon ? { toolIcon: groupToolIcon } : {}),
1174 ...(summaryToolIcon ? { summaryToolIcon } : {}),
1175 hasFailure: (() => {
1176 const lastToolLike = activities.findLast((activity) => activity.toolLike);
1177 return (
1178 lastToolLike !== undefined && workEntryDisplayIndicatesToolFailure(lastToolLike.workEntry)
1179 );
1180 })(),
1181 live,
1182 shimmer,
1183 });
1184 if (!expanded) return;
1185 result.push({
1186 type: "activity-group",
1187 id: `work-details:${groupId}`,
1188 createdAt: activities[0]!.createdAt,
1189 runId: activities[0]!.runId,
1190 activities: activities.map((activity) => ({
1191 ...activity,
1192 groupedToolDetail: true,
1193 live:
1194 isWorking &&
1195 activity.id === latestActivity.id &&
1196 activity.lifecycleStatus === "inProgress" &&
1197 activity.runId === activeRunId,
1198 })),
1199 });
1200}
1201
1202function liveToolActivitySummary(activity: ThreadFeedActivity, presentTense: boolean): string {
1203 const status = liveActivityToolStatus(activity.lifecycleStatus, presentTense);
1204 const presentation = resolveWorkEntryToolPresentation({
1205 ...activity.workEntry,
1206 toolLifecycleStatus: status,
1207 });
1208 if (presentation) return presentation.displayName;
1209 const command = activity.workEntry.command?.trim();
1210 if (command) {
1211 const program = commandProgramName(command);
1212 const verb =
1213 status === "inProgress"
1214 ? "Running"
1215 : status === "failed"
1216 ? "Failed"
1217 : status === "declined"
1218 ? "Declined"
1219 : status === "stopped"
1220 ? "Stopped"
1221 : "Ran";
1222 return `${verb} ${program ?? "command"}`;
1223 }
1224 return activity.detail ?? activity.summary;
1225}
1226
1227export function setPendingUserInputCustomAnswer(
1228 question: ThreadUserInputQuestion,
1229 draft: PendingUserInputDraftAnswer | undefined,
1230 customAnswer: string,
1231): PendingUserInputDraftAnswer {
1232 if (question.allowCustomAnswer === false) {
1233 return draft ?? {};
1234 }
1235
1236 const selectedOptionValues =
1237 customAnswer.trim().length > 0
1238 ? undefined
1239 : normalizeSelectedOptionValues(question, draft?.selectedOptionValues);
1240 return {
1241 customAnswer,
1242 ...(selectedOptionValues && selectedOptionValues.length > 0 ? { selectedOptionValues } : {}),
1243 };
1244}
1245
1246export function isPendingUserInputOptionSelected(
1247 question: ThreadUserInputQuestion,
1248 draft: PendingUserInputDraftAnswer | undefined,
1249 optionValue: string,
1250): boolean {
1251 if (question.allowCustomAnswer !== false && normalizeDraftAnswer(draft?.customAnswer)) {
1252 return false;
1253 }
1254
1255 const resolvedOptionValue = resolvePendingUserInputOptionValue(question, optionValue);
1256 return (
1257 resolvedOptionValue !== null &&
1258 normalizeSelectedOptionValues(question, draft?.selectedOptionValues).includes(
1259 resolvedOptionValue,
1260 )
1261 );
1262}
1263
1264export function togglePendingUserInputOptionSelection(
1265 question: ThreadUserInputQuestion,
1266 draft: PendingUserInputDraftAnswer | undefined,
1267 optionValue: string,
1268): PendingUserInputDraftAnswer {
1269 const resolvedOptionValue = resolvePendingUserInputOptionValue(question, optionValue);
1270 if (resolvedOptionValue === null) {
1271 return draft ?? {};
1272 }
1273
1274 if (question.multiSelect) {
1275 const selectedOptionValues = normalizeSelectedOptionValues(
1276 question,
1277 draft?.selectedOptionValues,
1278 );
1279 const nextSelectedOptionValues = selectedOptionValues.includes(resolvedOptionValue)
1280 ? selectedOptionValues.filter((value) => value !== resolvedOptionValue)
1281 : [...selectedOptionValues, resolvedOptionValue];
1282
1283 return {
1284 customAnswer: "",
1285 ...(nextSelectedOptionValues.length > 0
1286 ? { selectedOptionValues: nextSelectedOptionValues }
1287 : {}),
1288 };
1289 }
1290
1291 return {
1292 customAnswer: "",
1293 selectedOptionValues: [resolvedOptionValue],
1294 };
1295}
1296
1297export function buildPendingUserInputAnswers(
1298 questions: ReadonlyArray<ThreadUserInputQuestion>,
1299 draftAnswers: Record<string, PendingUserInputDraftAnswer>,
1300): Record<string, string | ReadonlyArray<string>> | null {
1301 const answers: Record<string, string | ReadonlyArray<string>> = {};
1302
1303 for (const question of questions) {
1304 const answer = resolvePendingUserInputAnswer(question, draftAnswers[question.id]);
1305 if (answer === null) {
1306 return null;
1307 }
1308 answers[question.id] = answer;
1309 }
1310
1311 return answers;
1312}
1313
1314/**
1315 * Projects the server-authored visible sequence into mobile row presentation.
1316 * It deliberately preserves the incoming order and never rebuilds chat from
1317 * separate message, plan, or work-entry collections.
1318 */
1319export function buildThreadFeed(
1320 visibleTurnItems: ReadonlyArray<OrchestrationV2ProjectedTurnItem>,
1321 options?: {
1322 readonly localMessages?: ReadonlyArray<OrchestrationMessage>;
1323 readonly anchoredMessages?: ReadonlyArray<OrchestrationMessage>;
1324 readonly attempts?: ReadonlyArray<OrchestrationV2RunAttempt>;
1325 readonly nodes?: ReadonlyArray<OrchestrationV2ExecutionNode>;
1326 },
1327): ThreadFeedEntry[] {
1328 const entries: RawThreadFeedEntry[] = [];
1329 const attemptByRootNodeId = new Map(
1330 (options?.attempts ?? []).map((attempt) => [attempt.rootNodeId, attempt] as const),
1331 );
1332 const nodeById = new Map((options?.nodes ?? []).map((node) => [node.id, node] as const));
1333 const resolveAttemptId = (item: OrchestrationV2TurnItem): RunAttemptId | null => {
1334 if (item.nodeId === null || item.runId === null) return null;
1335 let nodeId: OrchestrationV2ExecutionNode["id"] | null = item.nodeId;
1336 const visited = new Set<OrchestrationV2ExecutionNode["id"]>();
1337 while (nodeId !== null && !visited.has(nodeId)) {
1338 visited.add(nodeId);
1339 const directAttempt = attemptByRootNodeId.get(nodeId);
1340 if (directAttempt?.runId === item.runId) return directAttempt.id;
1341 const node = nodeById.get(nodeId);
1342 if (node === undefined) return null;
1343 const rootAttempt = attemptByRootNodeId.get(node.rootNodeId);
1344 if (rootAttempt?.runId === item.runId) return rootAttempt.id;
1345 nodeId = node.parentNodeId;
1346 }
1347 return null;
1348 };
1349 for (const row of visibleTurnItems) {
1350 const item = row.item;
1351 if (turnItemIsWorkspacePreparation(item)) continue;
1352 if (item.type === "todo_list") continue;
1353 // Match the web timeline: only the terminal interrupt result is useful to
1354 // users; the preceding request is transient bookkeeping.
1355 if (item.type === "run_interrupt_request") {
1356 continue;
1357 }
1358 const attemptId = resolveAttemptId(item);
1359 const cached = projectedEntriesCache.get(row);
1360 if (cached?.attemptId === attemptId) {
1361 entries.push(cached.entry);
1362 continue;
1363 }
1364 const createdAt = DateTime.formatIso(item.startedAt ?? item.updatedAt);
1365 if (item.type === "user_message" || item.type === "assistant_message") {
1366 const updatedAt = DateTime.formatIso(item.updatedAt);
1367 const entry: RawThreadFeedEntry = {
1368 type: "message",
1369 id: item.messageId,
1370 createdAt,
1371 message: {
1372 id: item.messageId,
1373 role: item.type === "user_message" ? "user" : "assistant",
1374 text: item.text,
1375 attachments: item.attachments ?? [],
1376 runId: item.runId,
1377 streaming: item.type === "assistant_message" && item.streaming,
1378 ...(item.type === "user_message"
1379 ? {
1380 inputIntent: item.inputIntent,
1381 createdBy: item.createdBy,
1382 creationSource: item.creationSource,
1383 ...(item.scheduledTaskId ? { scheduledTaskId: item.scheduledTaskId } : {}),
1384 }
1385 : {}),
1386 visibility: row.visibility,
1387 sourceThreadId: row.sourceThreadId,
1388 createdAt,
1389 updatedAt,
1390 projectedItem: row,
1391 },
1392 };
1393 projectedEntriesCache.set(row, { attemptId, entry });
1394 entries.push(entry);
1395 continue;
1396 }
1397 const activity = toFeedActivity(row, attemptId);
1398 const entry: RawThreadFeedEntry = {
1399 type: "activity",
1400 id: activity.id,
1401 createdAt,
1402 runId: item.runId,
1403 activity,
1404 };
1405 projectedEntriesCache.set(row, { attemptId, entry });
1406 entries.push(entry);
1407 }
1408 const retainedMessageIds = new Set(
1409 entries.flatMap((entry) => (entry.type === "message" ? [entry.id] : [])),
1410 );
1411 const appendLocalMessage = (message: OrchestrationMessage): RawThreadFeedEntry => {
1412 const cached = localMessageEntriesCache.get(message);
1413 if (cached) return cached;
1414 const entry: Extract<RawThreadFeedEntry, { readonly type: "message" }> = {
1415 type: "message",
1416 id: message.id,
1417 createdAt: message.createdAt,
1418 message: {
1419 id: message.id,
1420 role: message.role === "assistant" ? "assistant" : "user",
1421 text: message.text,
1422 attachments: message.attachments ?? [],
1423 runId: null,
1424 streaming: message.streaming,
1425 visibility: "local",
1426 sourceThreadId: ThreadId.make("local-feedback"),
1427 createdAt: message.createdAt,
1428 updatedAt: message.updatedAt,
1429 },
1430 };
1431 localMessageEntriesCache.set(message, entry);
1432 return entry;
1433 };
1434 for (const message of options?.anchoredMessages ?? []) {
1435 if (retainedMessageIds.has(message.id)) continue;
1436 retainedMessageIds.add(message.id);
1437 const entry = appendLocalMessage(message);
1438 const insertionIndex = entries.findIndex(
1439 (candidate) => candidate.createdAt > message.createdAt,
1440 );
1441 if (insertionIndex === -1) entries.push(entry);
1442 else entries.splice(insertionIndex, 0, entry);
1443 }
1444 for (const message of options?.localMessages ?? []) {
1445 if (retainedMessageIds.has(message.id)) continue;
1446 retainedMessageIds.add(message.id);
1447 entries.push(appendLocalMessage(message));
1448 }
1449 return groupAdjacentActivities(entries);
1450}