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