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

threadActivity.ts

691 lines20.6 KB

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