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