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

threadActivity.ts

1,469 lines47.5 KB

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