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

threadActivity.ts

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