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

threadActivity.ts

799 lines23.8 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 {
8 resolveT3McpToolPresentation,
9 type T3McpToolLogo,
10 type T3McpToolPresentation,
11} from "@t3tools/shared/t3McpToolPresentation";
12import type {
13 ChatAttachment,
14 MessageId,
15 OrchestrationV2Actor,
16 OrchestrationV2CreationSource,
17 OrchestrationV2ProjectedTurnItem,
18 OrchestrationV2RunStatus,
19 OrchestrationV2TurnItem,
20 OrchestrationV2UserMessageInputIntent,
21 RunId,
22 ThreadId,
23} from "@t3tools/contracts";
24import { formatDuration } from "@t3tools/shared/orchestrationTiming";
25import * as DateTime from "effect/DateTime";
26​
27export type PendingApproval = ThreadPendingApproval;
28export type PendingUserInput = ThreadPendingUserInput;
29​
30const MAX_VISIBLE_WORK_LOG_ENTRIES = 1;
31​
32export interface PendingUserInputDraftAnswer {
33 readonly selectedOptionLabels?: ReadonlyArray<string>;
34 readonly customAnswer?: string;
36​
37export interface ThreadFeedActivity {
38 readonly id: string;
39 readonly createdAt: string;
40 readonly runId: RunId | null;
41 readonly summary: string;
42 readonly detail: string | null;
43 readonly canExpand: boolean;
44 readonly getFullDetail: () => string | null;
45 readonly getCopyText: () => string;
46 readonly icon:
47 | "agent"
48 | "alert"
49 | "check"
50 | "command"
51 | "edit"
52 | "eye"
53 | "globe"
54 | "hammer"
55 | "message"
56 | "warning"
57 | "wrench"
58 | "zap";
59 readonly logo: T3McpToolLogo | null;
60 readonly toolLike: boolean;
61 readonly prominent: boolean;
62 readonly status: "success" | "failure" | "neutral" | null;
63 readonly projectedItem: OrchestrationV2ProjectedTurnItem;
65​
66export interface ThreadFeedMessage {
67 readonly id: MessageId;
68 readonly role: "user" | "assistant";
69 readonly text: string;
70 readonly attachments: ReadonlyArray<ChatAttachment>;
71 readonly runId: RunId | null;
72 readonly streaming: boolean;
73 readonly inputIntent?: OrchestrationV2UserMessageInputIntent;
74 readonly createdBy?: OrchestrationV2Actor;
75 readonly creationSource?: OrchestrationV2CreationSource;
76 readonly visibility: OrchestrationV2ProjectedTurnItem["visibility"];
77 readonly sourceThreadId: ThreadId;
78 readonly createdAt: string;
79 readonly updatedAt: string;
80 readonly projectedItem: OrchestrationV2ProjectedTurnItem;
82​
83type RawThreadFeedEntry =
84 | {
85 readonly type: "message";
86 readonly id: string;
87 readonly createdAt: string;
88 readonly message: ThreadFeedMessage;
89 }
90 | {
91 readonly type: "activity";
92 readonly id: string;
93 readonly createdAt: string;
94 readonly runId: RunId | null;
95 readonly activity: ThreadFeedActivity;
96 };
97​
98export type ThreadFeedEntry =
99 | Extract<RawThreadFeedEntry, { type: "message" }>
100 | {
101 readonly type: "working";
102 readonly id: string;
103 readonly createdAt: string;
104 }
105 | {
106 readonly type: "activity-group";
107 readonly id: string;
108 readonly createdAt: string;
109 readonly runId: RunId | null;
110 readonly activities: ReadonlyArray<ThreadFeedActivity>;
111 }
112 | {
113 readonly type: "work-toggle";
114 readonly id: string;
115 readonly createdAt: string;
116 readonly runId: RunId | null;
117 readonly groupId: string;
118 readonly hiddenCount: number;
119 readonly expanded: boolean;
120 readonly onlyToolActivities: boolean;
121 }
122 | {
123 readonly type: "run-fold";
124 readonly id: string;
125 readonly createdAt: string;
126 readonly runId: RunId;
127 readonly label: string;
128 readonly expanded: boolean;
129 };
130​
131export interface ThreadFeedLatestRun {
132 readonly runId: RunId;
133 readonly status: OrchestrationV2RunStatus;
134 readonly startedAt: string | null;
135 readonly completedAt: string | null;
137​
138function normalizeDraftAnswer(value: string | undefined): string | null {
139 if (typeof value !== "string") return null;
140 const trimmed = value.trim();
141 return trimmed.length > 0 ? trimmed : null;
143​
144function normalizeSelectedOptionLabels(
145 value: ReadonlyArray<string> | undefined,
146): ReadonlyArray<string> {
147 if (!Array.isArray(value)) {
148 return [];
149 }
150​
151 return Array.from(
152 new Set(value.map((entry) => entry.trim()).filter((entry) => entry.length > 0)),
153 );
155​
156function resolvePendingUserInputAnswer(
157 question: ThreadUserInputQuestion,
158 draft: PendingUserInputDraftAnswer | undefined,
159): string | ReadonlyArray<string> | null {
160 const customAnswer = normalizeDraftAnswer(draft?.customAnswer);
161 if (customAnswer) {
162 return customAnswer;
163 }
164​
165 const selectedOptionLabels = normalizeSelectedOptionLabels(draft?.selectedOptionLabels);
166 if (question.multiSelect) {
167 return selectedOptionLabels.length > 0 ? selectedOptionLabels : null;
168 }
169 return selectedOptionLabels[0] ?? null;
171​
172function capitalizePhrase(value: string): string {
173 const trimmed = value.trim();
174 return trimmed.length === 0 ? value : `${trimmed.charAt(0).toUpperCase()}${trimmed.slice(1)}`;
176​
177function memoizeValue<T>(build: () => T): () => T {
178 let value: T;
179 let initialized = false;
180 return () => {
181 if (!initialized) {
182 value = build();
183 initialized = true;
184 }
185 return value;
186 };
188​
189function itemIsToolLike(item: OrchestrationV2TurnItem): boolean {
190 return (
191 item.type === "reasoning" ||
192 item.type === "command_execution" ||
193 item.type === "file_change" ||
194 item.type === "file_search" ||
195 item.type === "web_search" ||
196 item.type === "approval_request" ||
197 item.type === "user_input_request" ||
198 item.type === "dynamic_tool" ||
199 item.type === "subagent" ||
200 item.type === "error"
201 );
203​
204function itemIsProminent(item: OrchestrationV2TurnItem): boolean {
205 return item.type === "fork" || item.type === "thread_created" || item.type === "subagent";
207​
208function itemStatus(item: OrchestrationV2TurnItem): ThreadFeedActivity["status"] {
209 if (!itemIsToolLike(item)) return null;
210 if (item.type === "error" || item.status === "failed") return "failure";
211 return item.status === "completed" ? "success" : "neutral";
213​
214function itemIcon(item: OrchestrationV2TurnItem): ThreadFeedActivity["icon"] {
215 switch (item.type) {
216 case "reasoning":
217 return "agent";
218 case "command_execution":
219 return "command";
220 case "file_change":
221 return "edit";
222 case "file_search":
223 return "eye";
224 case "web_search":
225 return "globe";
226 case "approval_request":
227 case "user_input_request":
228 case "user_message":
229 case "assistant_message":
230 return "message";
231 case "dynamic_tool":
232 return "wrench";
233 case "subagent":
234 return "hammer";
235 case "run_interrupt_request":
236 case "run_interrupt_result":
237 return "warning";
238 case "error":
239 return "alert";
240 case "checkpoint":
241 case "proposed_plan":
242 case "todo_list":
243 return "check";
244 case "compaction":
245 case "handoff":
246 case "fork":
247 case "thread_created":
248 return "zap";
249 }
251​
252function itemToolPresentation(item: OrchestrationV2TurnItem): T3McpToolPresentation | null {
253 if (item.type !== "dynamic_tool") {
254 return null;
255 }
256 return resolveT3McpToolPresentation(item.toolName) ?? resolveT3McpToolPresentation(item.title);
258​
259function itemSummary(
260 item: OrchestrationV2TurnItem,
261 toolPresentation: T3McpToolPresentation | null = null,
262): string {
263 const title = item.title?.trim();
264 if (title) return toolPresentation?.displayName ?? capitalizePhrase(title);
265 switch (item.type) {
266 case "reasoning":
267 return "Thinking";
268 case "command_execution":
269 return "Command";
270 case "file_change":
271 return `Changed ${item.fileName}`;
272 case "file_search":
273 return "Searched files";
274 case "web_search":
275 return "Searched the web";
276 case "approval_request":
277 return "Approval requested";
278 case "user_input_request":
279 return "Input requested";
280 case "checkpoint":
281 return "Checkpoint captured";
282 case "run_interrupt_request":
283 return "Interrupt requested";
284 case "run_interrupt_result":
285 return "Run interrupted";
286 case "error":
287 return "Provider error";
288 case "compaction":
289 return "Context compacted";
290 case "handoff":
291 return "Context handed off";
292 case "fork":
293 return "Thread forked";
294 case "thread_created":
295 return "Thread created";
296 case "subagent":
297 return "Subagent";
298 case "dynamic_tool":
299 return toolPresentation?.displayName ?? item.toolName ?? "Tool call";
300 case "proposed_plan":
301 return "Proposed plan";
302 case "todo_list":
303 return "Plan updated";
304 case "user_message":
305 return "User message";
306 case "assistant_message":
307 return "Assistant message";
308 }
310​
311function itemPreview(item: OrchestrationV2TurnItem): string | null {
312 switch (item.type) {
313 case "reasoning":
314 return item.text || null;
315 case "command_execution":
316 return item.input || null;
317 case "file_change":
318 return item.fileName;
319 case "file_search":
320 return item.pattern ?? null;
321 case "web_search":
322 return item.patterns?.join(", ") ?? null;
323 case "approval_request":
324 return item.prompt ?? null;
325 case "user_input_request":
326 return item.questions.map((question) => question.question).join(" · ") || null;
327 case "checkpoint":
328 return item.files.length === 1
329 ? (item.files[0]?.path ?? null)
330 : `${item.files.length} changed files`;
331 case "run_interrupt_request":
332 case "run_interrupt_result":
333 return item.message || null;
334 case "error":
335 return item.failure.message;
336 case "compaction":
337 case "handoff":
338 return item.summary ?? null;
339 case "fork":
340 case "thread_created":
341 return item.targetThreadId;
342 case "subagent":
343 return item.result ?? item.progress ?? item.prompt;
344 case "dynamic_tool":
345 return null;
346 case "proposed_plan":
347 return item.markdown || null;
348 case "todo_list":
349 return `${item.steps.filter((step) => step.status === "completed").length}/${item.steps.length} completed`;
350 case "user_message":
351 case "assistant_message":
352 return item.text || null;
353 }
355​
356function toFeedActivity(row: OrchestrationV2ProjectedTurnItem): ThreadFeedActivity {
357 const item = row.item;
358 const toolPresentation = itemToolPresentation(item);
359 const summary = itemSummary(item, toolPresentation);
360 const detail = itemPreview(item);
361 const getFullDetail = memoizeValue(() =>
362 JSON.stringify(
363 {
364 visibility: row.visibility,
365 sourceThreadId: row.sourceThreadId,
366 sourceItemId: row.sourceItemId,
367 item,
368 },
369 null,
370 2,
371 ),
372 );
373 const getCopyText = memoizeValue(() =>
374 [summary, detail, getFullDetail()]
375 .filter(
376 (value, index, values): value is string =>
377 Boolean(value) && values.indexOf(value) === index,
378 )
379 .join("\n"),
380 );
381 return {
382 id: `${row.visibility}:${row.sourceThreadId}:${row.sourceItemId}`,
383 createdAt: DateTime.formatIso(item.startedAt ?? item.updatedAt),
384 runId: item.runId,
385 summary,
386 detail,
387 canExpand: true,
388 getFullDetail,
389 getCopyText,
390 icon: itemIcon(item),
391 logo: toolPresentation?.logo ?? null,
392 toolLike: itemIsToolLike(item),
393 prominent: itemIsProminent(item),
394 status: itemStatus(item),
395 projectedItem: row,
396 };
398​
399function isEmptyMessage(entry: RawThreadFeedEntry): boolean {
400 return (
401 entry.type === "message" &&
402 entry.message.text.trim().length === 0 &&
403 entry.message.attachments.length === 0
404 );
406​
407function groupAdjacentActivities(entries: ReadonlyArray<RawThreadFeedEntry>): ThreadFeedEntry[] {
408 const grouped: ThreadFeedEntry[] = [];
409 // Mutable backing array for the trailing group so appending an activity is
410 // O(1) instead of re-copying the group (which made this loop quadratic on
411 // long tool runs). The array is only mutated while it is the trailing group.
412 let openGroupActivities: ThreadFeedActivity[] | null = null;
413 let openGroupRunId: string | null = null;
414 let openGroupHasProminent = false;
415​
416 for (const entry of entries) {
417 if (isEmptyMessage(entry)) continue;
418 if (entry.type !== "activity") {
419 grouped.push(entry);
420 openGroupActivities = null;
421 continue;
422 }
423​
424 if (
425 openGroupActivities !== null &&
426 openGroupRunId === entry.runId &&
427 !entry.activity.prominent &&
428 !openGroupHasProminent
429 ) {
430 openGroupActivities.push(entry.activity);
431 continue;
432 }
433​
434 openGroupActivities = [entry.activity];
435 openGroupRunId = entry.runId;
436 openGroupHasProminent = entry.activity.prominent === true;
437 grouped.push({
438 type: "activity-group",
439 id: entry.id,
440 createdAt: entry.createdAt,
441 runId: entry.runId,
442 activities: openGroupActivities,
443 });
444 }
445 return grouped;
447​
448function computeElapsedMs(startIso: string, endIso: string): number | null {
449 const start = Date.parse(startIso);
450 const end = Date.parse(endIso);
451 return Number.isFinite(start) && Number.isFinite(end) ? Math.max(0, end - start) : null;
453​
454function maxIsoTimestamp(left: string | null, right: string | null): string | null {
455 if (left === null) return right;
456 if (right === null) return left;
457 return Date.parse(right) > Date.parse(left) ? right : left;
459​
460function unsettledRunId(latestRun: ThreadFeedLatestRun | null): RunId | null {
461 return threadFeedRunIsUnsettled(latestRun) ? latestRun.runId : null;
463​
464export function threadFeedRunIsUnsettled(
465 run: ThreadFeedLatestRun | null,
466): run is ThreadFeedLatestRun {
467 return (
468 run !== null &&
469 (run.status === "preparing" ||
470 run.status === "starting" ||
471 run.status === "running" ||
472 run.status === "waiting")
473 );
475​
476interface ThreadFeedRunFold {
477 readonly runId: RunId;
478 readonly createdAt: string;
479 readonly hiddenEntryIds: ReadonlySet<string>;
480 readonly label: string;
482​
483function deriveThreadFeedRunFolds(
484 feed: ReadonlyArray<ThreadFeedEntry>,
485 latestRun: ThreadFeedLatestRun | null,
486): ReadonlyMap<string, ThreadFeedRunFold> {
487 const terminalAssistantMessageIdByRun = new Map<RunId, string>();
488 for (const entry of feed) {
489 if (entry.type === "message" && entry.message.role === "assistant" && entry.message.runId) {
490 terminalAssistantMessageIdByRun.set(entry.message.runId, entry.id);
491 }
492 }
493​
494 const groupsByRunId = new Map<
495 RunId,
496 { entries: ThreadFeedEntry[]; startBoundary: string | null }
497 >();
498 let pendingUserBoundary: string | null = null;
499 for (const entry of feed) {
500 if (entry.type === "message" && entry.message.role === "user") {
501 pendingUserBoundary = entry.message.createdAt;
502 continue;
503 }
504 const runId =
505 entry.type === "message" && entry.message.role === "assistant"
506 ? entry.message.runId
507 : entry.type === "activity-group"
508 ? entry.runId
509 : null;
510 if (!runId) continue;
511 let group = groupsByRunId.get(runId);
512 if (!group) {
513 group = { entries: [], startBoundary: pendingUserBoundary };
514 pendingUserBoundary = null;
515 groupsByRunId.set(runId, group);
516 }
517 group.entries.push(entry);
518 }
519​
520 const activeRunId = unsettledRunId(latestRun);
521 const foldsByAnchorId = new Map<string, ThreadFeedRunFold>();
522 for (const [runId, group] of groupsByRunId) {
523 if (
524 runId === activeRunId ||
525 group.entries.some((entry) => entry.type === "message" && entry.message.streaming)
526 ) {
527 continue;
528 }
529 const terminalAssistantId = terminalAssistantMessageIdByRun.get(runId);
530 const hiddenEntryIds = new Set(
531 group.entries
532 .filter(
533 (entry) =>
534 entry.id !== terminalAssistantId &&
535 !(
536 entry.type === "activity-group" &&
537 entry.activities.some((activity) => activity.prominent)
538 ),
539 )
540 .map((entry) => entry.id),
541 );
542 const firstEntry = group.entries[0];
543 const lastEntry = group.entries.at(-1);
544 if (hiddenEntryIds.size === 0 || !firstEntry || !lastEntry) continue;
545 const terminalEntry = terminalAssistantId
546 ? group.entries.find((entry) => entry.id === terminalAssistantId)
547 : null;
548 const latestRunMatches = latestRun?.runId === runId;
549 const lastEntryEnd =
550 lastEntry.type === "message" ? lastEntry.message.updatedAt : lastEntry.createdAt;
551 const elapsedMs =
552 latestRunMatches && latestRun.startedAt && latestRun.completedAt
553 ? computeElapsedMs(latestRun.startedAt, latestRun.completedAt)
554 : computeElapsedMs(
555 group.startBoundary ?? firstEntry.createdAt,
556 maxIsoTimestamp(
557 terminalEntry?.type === "message" ? terminalEntry.message.updatedAt : null,
558 lastEntryEnd,
559 ) ?? lastEntryEnd,
560 );
561 const duration = elapsedMs === null ? null : formatDuration(elapsedMs);
562 const interrupted =
563 latestRunMatches && (latestRun.status === "interrupted" || latestRun.status === "cancelled");
564 foldsByAnchorId.set(firstEntry.id, {
565 runId,
566 createdAt: firstEntry.createdAt,
567 hiddenEntryIds,
568 label: interrupted
569 ? duration
570 ? `You stopped after ${duration}`
571 : "You stopped this response"
572 : duration
573 ? `Worked for ${duration}`
574 : "Worked",
575 });
576 }
577 return foldsByAnchorId;
579​
580export function deriveThreadFeedPresentation(
581 feed: ReadonlyArray<ThreadFeedEntry>,
582 latestRun: ThreadFeedLatestRun | null,
583 expandedRunIds: ReadonlySet<RunId>,
584 expandedWorkGroupIds: ReadonlySet<string> = new Set(),
585 activeWorkStartedAt: string | null = null,
586): ThreadFeedEntry[] {
587 const sourceFeed = feed.filter(
588 (entry) =>
589 entry.type !== "run-fold" && entry.type !== "work-toggle" && entry.type !== "working",
590 );
591 const foldsByAnchorId = deriveThreadFeedRunFolds(sourceFeed, latestRun);
592 const collapsedEntryIds = new Set<string>();
593 for (const fold of foldsByAnchorId.values()) {
594 if (!expandedRunIds.has(fold.runId)) {
595 for (const entryId of fold.hiddenEntryIds) collapsedEntryIds.add(entryId);
596 }
597 }
598 const result: ThreadFeedEntry[] = [];
599 for (const entry of sourceFeed) {
600 const fold = foldsByAnchorId.get(entry.id);
601 if (fold) {
602 result.push({
603 type: "run-fold",
604 id: `run-fold:${fold.runId}`,
605 createdAt: fold.createdAt,
606 runId: fold.runId,
607 label: fold.label,
608 expanded: expandedRunIds.has(fold.runId),
609 });
610 }
611 if (!collapsedEntryIds.has(entry.id)) {
612 appendPresentedFeedEntry(result, entry, expandedWorkGroupIds);
613 }
614 }
615 if (activeWorkStartedAt !== null) {
616 result.push({
617 type: "working",
618 id: "working-indicator-row",
619 createdAt: activeWorkStartedAt,
620 });
621 }
622 return result;
624​
625function appendPresentedFeedEntry(
626 result: ThreadFeedEntry[],
627 entry: Exclude<ThreadFeedEntry, { readonly type: "run-fold" | "work-toggle" | "working" }>,
628 expandedWorkGroupIds: ReadonlySet<string>,
629): void {
630 if (entry.type !== "activity-group") {
631 result.push(entry);
632 return;
633 }
634​
635 const activities = entry.activities.filter(
636 (activity) => !(activity.toolLike && activity.status === "neutral"),
637 );
638 if (activities.length === 0) {
639 return;
640 }
641 if (activities.length <= MAX_VISIBLE_WORK_LOG_ENTRIES) {
642 result.push({
643 ...entry,
644 activities,
645 });
646 return;
647 }
648​
649 const groupId = entry.id;
650 const expanded = expandedWorkGroupIds.has(groupId);
651 const hiddenCount = activities.length - MAX_VISIBLE_WORK_LOG_ENTRIES;
652 const visibleActivities = expanded ? activities : activities.slice(-MAX_VISIBLE_WORK_LOG_ENTRIES);
653​
654 for (const activity of visibleActivities) {
655 result.push({
656 type: "activity-group",
657 id: activity.id,
658 createdAt: activity.createdAt,
659 runId: activity.runId,
660 activities: [activity],
661 });
662 }
663 result.push({
664 type: "work-toggle",
665 id: `work-toggle:${groupId}`,
666 createdAt: entry.createdAt,
667 runId: entry.runId,
668 groupId,
669 hiddenCount,
670 expanded,
671 onlyToolActivities: activities.every((activity) => activity.toolLike),
672 });
674export function setPendingUserInputCustomAnswer(
675 draft: PendingUserInputDraftAnswer | undefined,
676 customAnswer: string,
677): PendingUserInputDraftAnswer {
678 const selectedOptionLabels =
679 customAnswer.trim().length > 0
680 ? undefined
681 : normalizeSelectedOptionLabels(draft?.selectedOptionLabels);
682 return {
683 customAnswer,
684 ...(selectedOptionLabels && selectedOptionLabels.length > 0 ? { selectedOptionLabels } : {}),
685 };
687​
688export function isPendingUserInputOptionSelected(
689 draft: PendingUserInputDraftAnswer | undefined,
690 optionLabel: string,
691): boolean {
692 if (normalizeDraftAnswer(draft?.customAnswer)) {
693 return false;
694 }
695​
696 return normalizeSelectedOptionLabels(draft?.selectedOptionLabels).includes(optionLabel.trim());
698​
699export function togglePendingUserInputOptionSelection(
700 question: ThreadUserInputQuestion,
701 draft: PendingUserInputDraftAnswer | undefined,
702 optionLabel: string,
703): PendingUserInputDraftAnswer {
704 const normalizedOptionLabel = optionLabel.trim();
705​
706 if (question.multiSelect) {
707 const selectedOptionLabels = normalizeSelectedOptionLabels(draft?.selectedOptionLabels);
708 const nextSelectedOptionLabels = selectedOptionLabels.includes(normalizedOptionLabel)
709 ? selectedOptionLabels.filter((label) => label !== normalizedOptionLabel)
710 : [...selectedOptionLabels, normalizedOptionLabel];
711​
712 return {
713 customAnswer: "",
714 ...(nextSelectedOptionLabels.length > 0
715 ? { selectedOptionLabels: nextSelectedOptionLabels }
716 : {}),
717 };
718 }
719​
720 return {
721 customAnswer: "",
722 selectedOptionLabels: [normalizedOptionLabel],
723 };
725​
726export function buildPendingUserInputAnswers(
727 questions: ReadonlyArray<ThreadUserInputQuestion>,
728 draftAnswers: Record<string, PendingUserInputDraftAnswer>,
729): Record<string, string | ReadonlyArray<string>> | null {
730 const answers: Record<string, string | ReadonlyArray<string>> = {};
731​
732 for (const question of questions) {
733 const answer = resolvePendingUserInputAnswer(question, draftAnswers[question.id]);
734 if (!answer) {
735 return null;
736 }
737 answers[question.id] = answer;
738 }
739 return answers;
741​
742/**
743 * Projects the server-authored visible sequence into mobile row presentation.
744 * It deliberately preserves the incoming order and never rebuilds chat from
745 * separate message, plan, or work-entry collections.
746 */
747export function buildThreadFeed(
748 visibleTurnItems: ReadonlyArray<OrchestrationV2ProjectedTurnItem>,
749): ThreadFeedEntry[] {
750 const entries: RawThreadFeedEntry[] = [];
751 for (const row of visibleTurnItems) {
752 const item = row.item;
753 if (turnItemIsWorkspacePreparation(item)) continue;
754 // Match the web timeline: only the terminal interrupt result is useful to
755 // users; the preceding request is transient bookkeeping.
756 if (item.type === "run_interrupt_request") {
757 continue;
758 }
759 const createdAt = DateTime.formatIso(item.startedAt ?? item.updatedAt);
760 if (item.type === "user_message" || item.type === "assistant_message") {
761 const updatedAt = DateTime.formatIso(item.updatedAt);
762 entries.push({
763 type: "message",
764 id: item.messageId,
765 createdAt,
766 message: {
767 id: item.messageId,
768 role: item.type === "user_message" ? "user" : "assistant",
769 text: item.text,
770 attachments: item.type === "user_message" ? item.attachments : [],
771 runId: item.runId,
772 streaming: item.type === "assistant_message" && item.streaming,
773 ...(item.type === "user_message"
774 ? {
775 inputIntent: item.inputIntent,
776 createdBy: item.createdBy,
777 creationSource: item.creationSource,
778 }
779 : {}),
780 visibility: row.visibility,
781 sourceThreadId: row.sourceThreadId,
782 createdAt,
783 updatedAt,
784 projectedItem: row,
785 },
786 });
787 continue;
788 }
789 const activity = toFeedActivity(row);
790 entries.push({
791 type: "activity",
792 id: activity.id,
793 createdAt,
794 runId: item.runId,
795 activity,
796 });
797 }
798 return groupAdjacentActivities(entries);