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

threadActivity.ts

1,469 lines47.4 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 { 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;
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;
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;
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;
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 }>;
187​
188function compactWorkEntryText(value: string): string {
189 return value.replace(/\s+/gu, " ").trim();
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();
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;
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 );
250​
251function isUserInputActivityGroup(entry: ThreadFeedActivityGroup): boolean {
252 return entry.activities.some((activity) => activity.workEntry.questionAnswer !== undefined);
254​
255function normalizeDraftAnswer(value: string | undefined): string | null {
256 if (typeof value !== "string") return null;
257 const trimmed = value.trim();
258 return trimmed.length > 0 ? trimmed : null;
260​
261function resolvePendingUserInputOptionValue(
262 question: ThreadUserInputQuestion,
263 value: string,
264): string | null {
265 if (question.options.some((option) => option.value === value)) {
266 return value;
267 }
268​
269 const label = value.trim();
270 return label.length > 0 &&
271 question.options.some((option) => option.value === undefined && option.label.trim() === label)
272 ? label
273 : null;
275​
276function normalizeSelectedOptionValues(
277 question: ThreadUserInputQuestion,
278 value: ReadonlyArray<string> | undefined,
279): ReadonlyArray<string> {
280 if (!Array.isArray(value)) {
281 return [];
282 }
283​
284 return Array.from(
285 new Set(
286 value
287 .map((entry) => resolvePendingUserInputOptionValue(question, entry))
288 .filter((entry): entry is string => entry !== null),
289 ),
290 );
292​
293function resolvePendingUserInputAnswer(
294 question: ThreadUserInputQuestion,
295 draft: PendingUserInputDraftAnswer | undefined,
296): string | ReadonlyArray<string> | null {
297 if (draft?.attachmentsBlocked) return null;
298 const customAnswer =
299 question.allowCustomAnswer === false ? null : normalizeDraftAnswer(draft?.customAnswer);
300 if (customAnswer) {
301 return customAnswer;
302 }
303​
304 const selectedOptionValues = normalizeSelectedOptionValues(question, draft?.selectedOptionValues);
305 if (question.multiSelect) {
306 return selectedOptionValues.length > 0
307 ? selectedOptionValues
308 : question.allowCustomAnswer !== false && (draft?.attachmentCount ?? 0) > 0
309 ? ""
310 : null;
311 }
312 return (
313 selectedOptionValues[0] ??
314 (question.allowCustomAnswer !== false && (draft?.attachmentCount ?? 0) > 0 ? "" : null)
315 );
317​
318function capitalizePhrase(value: string): string {
319 const trimmed = value.trim();
320 return trimmed.length === 0 ? value : `${trimmed.charAt(0).toUpperCase()}${trimmed.slice(1)}`;
322​
323function memoizeValue<T>(build: () => T): () => T {
324 let value: T;
325 let initialized = false;
326 return () => {
327 if (!initialized) {
328 value = build();
329 initialized = true;
330 }
331 return value;
332 };
334​
335function itemIsToolLike(item: OrchestrationV2TurnItem): boolean {
336 return (
337 item.type === "reasoning" ||
338 item.type === "command_execution" ||
339 item.type === "file_change" ||
340 item.type === "file_search" ||
341 item.type === "web_search" ||
342 item.type === "approval_request" ||
343 item.type === "user_input_request" ||
344 item.type === "dynamic_tool" ||
345 item.type === "subagent"
346 );
348​
349function itemIsProminent(item: OrchestrationV2TurnItem): boolean {
350 return (
351 item.type === "fork" ||
352 item.type === "thread_created" ||
353 item.type === "subagent" ||
354 item.type === "system_notice"
355 );
357​
358function itemStatus(item: OrchestrationV2TurnItem): ThreadFeedActivity["status"] {
359 if (item.type === "notification") return item.outcome === "failed" ? "failure" : null;
360 if (item.type === "error") {
361 if (item.status === "failed") return "failure";
362 return item.status === "completed" ? "success" : "neutral";
363 }
364 if (!itemIsToolLike(item)) return null;
365 if (item.status === "failed") return "failure";
366 return item.status === "completed" ? "success" : "neutral";
368​
369function itemLifecycleStatus(item: OrchestrationV2TurnItem): WorkLogToolLifecycleStatus {
370 switch (item.status) {
371 case "pending":
372 case "running":
373 case "waiting":
374 return "inProgress";
375 case "idle":
376 return "idle";
377 case "completed":
378 return "completed";
379 case "failed":
380 return "failed";
381 case "cancelled":
382 case "interrupted":
383 return "stopped";
384 }
386​
387function itemWorkLogTone(item: OrchestrationV2TurnItem): WorkLogPresentationEntry["tone"] {
388 if (item.type === "error") return "info";
389 if (item.type === "reasoning") return "thinking";
390 switch (item.type) {
391 case "command_execution":
392 case "file_change":
393 case "file_search":
394 case "web_search":
395 case "dynamic_tool":
396 case "subagent":
397 return "tool";
398 default:
399 return "info";
400 }
402​
403function itemIcon(item: OrchestrationV2TurnItem): ThreadFeedActivity["icon"] {
404 if (item.type === "notification") return "zap";
405 switch (item.type) {
406 case "reasoning":
407 return "agent";
408 case "command_execution":
409 return "command";
410 case "file_change":
411 return "edit";
412 case "file_search":
413 return "eye";
414 case "web_search":
415 return "globe";
416 case "approval_request":
417 case "user_input_request":
418 case "user_message":
419 case "assistant_message":
420 return "message";
421 case "dynamic_tool":
422 return "wrench";
423 case "subagent":
424 return "hammer";
425 case "run_interrupt_request":
426 case "run_interrupt_result":
427 case "system_notice":
428 return "warning";
429 case "error":
430 return "alert";
431 case "checkpoint":
432 case "proposed_plan":
433 case "todo_list":
434 return "check";
435 case "compaction":
436 case "handoff":
437 case "fork":
438 case "thread_created":
439 return "zap";
440 }
442​
443function itemToolPresentation(item: OrchestrationV2TurnItem): T3McpToolPresentation | null {
444 if (item.type !== "dynamic_tool") {
445 return null;
446 }
447 return resolveT3McpToolPresentation(item.toolName) ?? resolveT3McpToolPresentation(item.title);
449​
450function itemSummary(
451 item: OrchestrationV2TurnItem,
452 toolPresentation: T3McpToolPresentation | null = null,
453): string {
454 if (item.type === "notification") return item.summary;
455 if (item.type === "system_notice") return item.message;
456 if (item.type === "compaction") return contextCompactionLabel(item);
457 const title = item.title?.trim();
458 if (title) return toolPresentation?.displayName ?? capitalizePhrase(title);
459 switch (item.type) {
460 case "reasoning":
461 return "Thinking";
462 case "command_execution":
463 return "Command";
464 case "file_change":
465 return item.changes !== undefined && item.changes.length > 1
466 ? `Changed ${item.changes.length} files`
467 : `Changed ${item.fileName}`;
468 case "file_search":
469 return "Searched files";
470 case "web_search":
471 return "Searched the web";
472 case "approval_request":
473 return "Approval requested";
474 case "user_input_request":
475 return "Input requested";
476 case "checkpoint":
477 return "Checkpoint captured";
478 case "run_interrupt_request":
479 return "Interrupt requested";
480 case "run_interrupt_result":
481 return "Run interrupted";
482 case "error":
483 return "Provider error";
484 case "handoff":
485 return "Context handed off";
486 case "fork":
487 return "Thread forked";
488 case "thread_created":
489 return "Thread created";
490 case "subagent":
491 return "Subagent";
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);