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

threadActivity.ts

593 lines17.9 KB

1import type {
2 ThreadPendingApproval,
3 ThreadPendingUserInput,
4 ThreadUserInputQuestion,
5} from "@t3tools/client-runtime/state/thread-requests";
6import type {
7 ChatAttachment,
8 MessageId,
9 OrchestrationV2Actor,
10 OrchestrationV2CreationSource,
11 OrchestrationV2ProjectedTurnItem,
12 OrchestrationV2RunStatus,
13 OrchestrationV2TurnItem,
14 OrchestrationV2UserMessageInputIntent,
15 RunId,
16 ThreadId,
17} from "@t3tools/contracts";
18import { formatDuration } from "@t3tools/shared/orchestrationTiming";
19import * as DateTime from "effect/DateTime";
20​
21export type PendingApproval = ThreadPendingApproval;
22export type PendingUserInput = ThreadPendingUserInput;
23​
24export interface PendingUserInputDraftAnswer {
25 readonly selectedOptionLabel?: string;
26 readonly customAnswer?: string;
28​
29export interface ThreadFeedActivity {
30 readonly id: string;
31 readonly createdAt: string;
32 readonly runId: RunId | null;
33 readonly summary: string;
34 readonly detail: string | null;
35 readonly fullDetail: string | null;
36 readonly copyText: string;
37 readonly icon:
38 | "agent"
39 | "alert"
40 | "check"
41 | "command"
42 | "edit"
43 | "eye"
44 | "globe"
45 | "hammer"
46 | "message"
47 | "warning"
48 | "wrench"
49 | "zap";
50 readonly toolLike: boolean;
51 readonly prominent: boolean;
52 readonly status: "success" | "failure" | "neutral" | null;
53 readonly projectedItem: OrchestrationV2ProjectedTurnItem;
55​
56export interface ThreadFeedMessage {
57 readonly id: MessageId;
58 readonly role: "user" | "assistant";
59 readonly text: string;
60 readonly attachments: ReadonlyArray<ChatAttachment>;
61 readonly runId: RunId | null;
62 readonly streaming: boolean;
63 readonly inputIntent?: OrchestrationV2UserMessageInputIntent;
64 readonly createdBy?: OrchestrationV2Actor;
65 readonly creationSource?: OrchestrationV2CreationSource;
66 readonly visibility: OrchestrationV2ProjectedTurnItem["visibility"];
67 readonly sourceThreadId: ThreadId;
68 readonly createdAt: string;
69 readonly updatedAt: string;
70 readonly projectedItem: OrchestrationV2ProjectedTurnItem;
72​
73type RawThreadFeedEntry =
74 | {
75 readonly type: "message";
76 readonly id: string;
77 readonly createdAt: string;
78 readonly message: ThreadFeedMessage;
79 }
80 | {
81 readonly type: "activity";
82 readonly id: string;
83 readonly createdAt: string;
84 readonly runId: RunId | null;
85 readonly activity: ThreadFeedActivity;
86 };
87​
88export type ThreadFeedEntry =
89 | Extract<RawThreadFeedEntry, { type: "message" }>
90 | {
91 readonly type: "activity-group";
92 readonly id: string;
93 readonly createdAt: string;
94 readonly runId: RunId | null;
95 readonly activities: ReadonlyArray<ThreadFeedActivity>;
96 }
97 | {
98 readonly type: "run-fold";
99 readonly id: string;
100 readonly createdAt: string;
101 readonly runId: RunId;
102 readonly label: string;
103 readonly expanded: boolean;
104 };
105​
106export interface ThreadFeedLatestRun {
107 readonly runId: RunId;
108 readonly status: OrchestrationV2RunStatus;
109 readonly startedAt: string | null;
110 readonly completedAt: string | null;
112​
113function normalizeDraftAnswer(value: string | undefined): string | null {
114 if (typeof value !== "string") return null;
115 const trimmed = value.trim();
116 return trimmed.length > 0 ? trimmed : null;
118​
119function resolvePendingUserInputAnswer(
120 draft: PendingUserInputDraftAnswer | undefined,
121): string | null {
122 return (
123 normalizeDraftAnswer(draft?.customAnswer) ?? normalizeDraftAnswer(draft?.selectedOptionLabel)
124 );
126​
127function capitalizePhrase(value: string): string {
128 const trimmed = value.trim();
129 return trimmed.length === 0 ? value : `${trimmed.charAt(0).toUpperCase()}${trimmed.slice(1)}`;
131​
132function itemIsToolLike(item: OrchestrationV2TurnItem): boolean {
133 return (
134 item.type === "reasoning" ||
135 item.type === "command_execution" ||
136 item.type === "file_change" ||
137 item.type === "file_search" ||
138 item.type === "web_search" ||
139 item.type === "approval_request" ||
140 item.type === "user_input_request" ||
141 item.type === "dynamic_tool" ||
142 item.type === "subagent" ||
143 item.type === "error"
144 );
146​
147function itemIsProminent(item: OrchestrationV2TurnItem): boolean {
148 return item.type === "fork" || item.type === "thread_created" || item.type === "subagent";
150​
151function itemStatus(item: OrchestrationV2TurnItem): ThreadFeedActivity["status"] {
152 if (!itemIsToolLike(item)) return null;
153 if (item.type === "error" || item.status === "failed") return "failure";
154 return item.status === "completed" ? "success" : "neutral";
156​
157function itemIcon(item: OrchestrationV2TurnItem): ThreadFeedActivity["icon"] {
158 switch (item.type) {
159 case "reasoning":
160 return "agent";
161 case "command_execution":
162 return "command";
163 case "file_change":
164 return "edit";
165 case "file_search":
166 return "eye";
167 case "web_search":
168 return "globe";
169 case "approval_request":
170 case "user_input_request":
171 case "user_message":
172 case "assistant_message":
173 return "message";
174 case "dynamic_tool":
175 return "wrench";
176 case "subagent":
177 return "hammer";
178 case "run_interrupt_request":
179 case "run_interrupt_result":
180 return "warning";
181 case "error":
182 return "alert";
183 case "checkpoint":
184 case "proposed_plan":
185 case "todo_list":
186 return "check";
187 case "compaction":
188 case "handoff":
189 case "fork":
190 case "thread_created":
191 return "zap";
192 }
194​
195function itemSummary(item: OrchestrationV2TurnItem): string {
196 const title = item.title?.trim();
197 if (title) return capitalizePhrase(title);
198 switch (item.type) {
199 case "reasoning":
200 return "Thinking";
201 case "command_execution":
202 return "Command";
203 case "file_change":
204 return `Changed ${item.fileName}`;
205 case "file_search":
206 return "Searched files";
207 case "web_search":
208 return "Searched the web";
209 case "approval_request":
210 return "Approval requested";
211 case "user_input_request":
212 return "Input requested";
213 case "checkpoint":
214 return "Checkpoint captured";
215 case "run_interrupt_request":
216 return "Interrupt requested";
217 case "run_interrupt_result":
218 return "Run interrupted";
219 case "error":
220 return "Provider error";
221 case "compaction":
222 return "Context compacted";
223 case "handoff":
224 return "Context handed off";
225 case "fork":
226 return "Thread forked";
227 case "thread_created":
228 return "Thread created";
229 case "subagent":
230 return "Subagent";
231 case "dynamic_tool":
232 return item.toolName ?? "Tool call";
233 case "proposed_plan":
234 return "Proposed plan";
235 case "todo_list":
236 return "Plan updated";
237 case "user_message":
238 return "User message";
239 case "assistant_message":
240 return "Assistant message";
241 }
243​
244function itemPreview(item: OrchestrationV2TurnItem): string | null {
245 switch (item.type) {
246 case "reasoning":
247 return item.text || null;
248 case "command_execution":
249 return item.input || null;
250 case "file_change":
251 return item.fileName;
252 case "file_search":
253 return item.pattern ?? null;
254 case "web_search":
255 return item.patterns?.join(", ") ?? null;
256 case "approval_request":
257 return item.prompt ?? null;
258 case "user_input_request":
259 return item.questions.map((question) => question.question).join(" · ") || null;
260 case "checkpoint":
261 return item.files.length === 1
262 ? (item.files[0]?.path ?? null)
263 : `${item.files.length} changed files`;
264 case "run_interrupt_request":
265 case "run_interrupt_result":
266 return item.message || null;
267 case "error":
268 return item.failure.message;
269 case "compaction":
270 case "handoff":
271 return item.summary ?? null;
272 case "fork":
273 case "thread_created":
274 return item.targetThreadId;
275 case "subagent":
276 return item.result ?? item.progress ?? item.prompt;
277 case "dynamic_tool":
278 return null;
279 case "proposed_plan":
280 return item.markdown || null;
281 case "todo_list":
282 return `${item.steps.filter((step) => step.status === "completed").length}/${item.steps.length} completed`;
283 case "user_message":
284 case "assistant_message":
285 return item.text || null;
286 }
288​
289function toFeedActivity(row: OrchestrationV2ProjectedTurnItem): ThreadFeedActivity {
290 const item = row.item;
291 const summary = itemSummary(item);
292 const detail = itemPreview(item);
293 const fullDetail = JSON.stringify(
294 {
295 visibility: row.visibility,
296 sourceThreadId: row.sourceThreadId,
297 sourceItemId: row.sourceItemId,
298 item,
299 },
300 null,
301 2,
302 );
303 return {
304 id: `${row.visibility}:${row.sourceThreadId}:${row.sourceItemId}`,
305 createdAt: DateTime.formatIso(item.startedAt ?? item.updatedAt),
306 runId: item.runId,
307 summary,
308 detail,
309 fullDetail,
310 icon: itemIcon(item),
311 copyText: [summary, detail, fullDetail]
312 .filter(
313 (value, index, values): value is string =>
314 Boolean(value) && values.indexOf(value) === index,
315 )
316 .join("\n"),
317 toolLike: itemIsToolLike(item),
318 prominent: itemIsProminent(item),
319 status: itemStatus(item),
320 projectedItem: row,
321 };
323​
324function isEmptyMessage(entry: RawThreadFeedEntry): boolean {
325 return (
326 entry.type === "message" &&
327 entry.message.text.trim().length === 0 &&
328 entry.message.attachments.length === 0
329 );
331​
332function groupAdjacentActivities(entries: ReadonlyArray<RawThreadFeedEntry>): ThreadFeedEntry[] {
333 const grouped: ThreadFeedEntry[] = [];
334 for (const entry of entries) {
335 if (isEmptyMessage(entry)) continue;
336 if (entry.type !== "activity") {
337 grouped.push(entry);
338 continue;
339 }
340 const previous = grouped.at(-1);
341 if (
342 previous?.type === "activity-group" &&
343 previous.runId === entry.runId &&
344 !entry.activity.prominent &&
345 !previous.activities.some((activity) => activity.prominent)
346 ) {
347 grouped[grouped.length - 1] = {
348 ...previous,
349 activities: [...previous.activities, entry.activity],
350 };
351 continue;
352 }
353 grouped.push({
354 type: "activity-group",
355 id: entry.id,
356 createdAt: entry.createdAt,
357 runId: entry.runId,
358 activities: [entry.activity],
359 });
360 }
361 return grouped;
363​
364function computeElapsedMs(startIso: string, endIso: string): number | null {
365 const start = Date.parse(startIso);
366 const end = Date.parse(endIso);
367 return Number.isFinite(start) && Number.isFinite(end) ? Math.max(0, end - start) : null;
369​
370function maxIsoTimestamp(left: string | null, right: string | null): string | null {
371 if (left === null) return right;
372 if (right === null) return left;
373 return Date.parse(right) > Date.parse(left) ? right : left;
375​
376function unsettledRunId(latestRun: ThreadFeedLatestRun | null): RunId | null {
377 if (!latestRun) return null;
378 return latestRun.completedAt === null ||
379 latestRun.status === "preparing" ||
380 latestRun.status === "starting" ||
381 latestRun.status === "running" ||
382 latestRun.status === "waiting"
383 ? latestRun.runId
384 : null;
386​
387interface ThreadFeedRunFold {
388 readonly runId: RunId;
389 readonly createdAt: string;
390 readonly hiddenEntryIds: ReadonlySet<string>;
391 readonly label: string;
393​
394function deriveThreadFeedRunFolds(
395 feed: ReadonlyArray<ThreadFeedEntry>,
396 latestRun: ThreadFeedLatestRun | null,
397): ReadonlyMap<string, ThreadFeedRunFold> {
398 const terminalAssistantMessageIdByRun = new Map<RunId, string>();
399 for (const entry of feed) {
400 if (entry.type === "message" && entry.message.role === "assistant" && entry.message.runId) {
401 terminalAssistantMessageIdByRun.set(entry.message.runId, entry.id);
402 }
403 }
404​
405 const groupsByRunId = new Map<
406 RunId,
407 { entries: ThreadFeedEntry[]; startBoundary: string | null }
408 >();
409 let pendingUserBoundary: string | null = null;
410 for (const entry of feed) {
411 if (entry.type === "message" && entry.message.role === "user") {
412 pendingUserBoundary = entry.message.createdAt;
413 continue;
414 }
415 const runId =
416 entry.type === "message" && entry.message.role === "assistant"
417 ? entry.message.runId
418 : entry.type === "activity-group"
419 ? entry.runId
420 : null;
421 if (!runId) continue;
422 let group = groupsByRunId.get(runId);
423 if (!group) {
424 group = { entries: [], startBoundary: pendingUserBoundary };
425 pendingUserBoundary = null;
426 groupsByRunId.set(runId, group);
427 }
428 group.entries.push(entry);
429 }
430​
431 const activeRunId = unsettledRunId(latestRun);
432 const foldsByAnchorId = new Map<string, ThreadFeedRunFold>();
433 for (const [runId, group] of groupsByRunId) {
434 if (
435 runId === activeRunId ||
436 group.entries.some((entry) => entry.type === "message" && entry.message.streaming)
437 ) {
438 continue;
439 }
440 const terminalAssistantId = terminalAssistantMessageIdByRun.get(runId);
441 const hiddenEntryIds = new Set(
442 group.entries
443 .filter(
444 (entry) =>
445 entry.id !== terminalAssistantId &&
446 !(
447 entry.type === "activity-group" &&
448 entry.activities.some((activity) => activity.prominent)
449 ),
450 )
451 .map((entry) => entry.id),
452 );
453 const firstEntry = group.entries[0];
454 const lastEntry = group.entries.at(-1);
455 if (hiddenEntryIds.size === 0 || !firstEntry || !lastEntry) continue;
456 const terminalEntry = terminalAssistantId
457 ? group.entries.find((entry) => entry.id === terminalAssistantId)
458 : null;
459 const latestRunMatches = latestRun?.runId === runId;
460 const lastEntryEnd =
461 lastEntry.type === "message" ? lastEntry.message.updatedAt : lastEntry.createdAt;
462 const elapsedMs =
463 latestRunMatches && latestRun.startedAt && latestRun.completedAt
464 ? computeElapsedMs(latestRun.startedAt, latestRun.completedAt)
465 : computeElapsedMs(
466 group.startBoundary ?? firstEntry.createdAt,
467 maxIsoTimestamp(
468 terminalEntry?.type === "message" ? terminalEntry.message.updatedAt : null,
469 lastEntryEnd,
470 ) ?? lastEntryEnd,
471 );
472 const duration = elapsedMs === null ? null : formatDuration(elapsedMs);
473 const interrupted =
474 latestRunMatches && (latestRun.status === "interrupted" || latestRun.status === "cancelled");
475 foldsByAnchorId.set(firstEntry.id, {
476 runId,
477 createdAt: firstEntry.createdAt,
478 hiddenEntryIds,
479 label: interrupted
480 ? duration
481 ? `You stopped after ${duration}`
482 : "You stopped this response"
483 : duration
484 ? `Worked for ${duration}`
485 : "Worked",
486 });
487 }
488 return foldsByAnchorId;
490​
491export function deriveThreadFeedPresentation(
492 feed: ReadonlyArray<ThreadFeedEntry>,
493 latestRun: ThreadFeedLatestRun | null,
494 expandedRunIds: ReadonlySet<RunId>,
495): ThreadFeedEntry[] {
496 const sourceFeed = feed.filter((entry) => entry.type !== "run-fold");
497 const foldsByAnchorId = deriveThreadFeedRunFolds(sourceFeed, latestRun);
498 const collapsedEntryIds = new Set<string>();
499 for (const fold of foldsByAnchorId.values()) {
500 if (!expandedRunIds.has(fold.runId)) {
501 for (const entryId of fold.hiddenEntryIds) collapsedEntryIds.add(entryId);
502 }
503 }
504 const result: ThreadFeedEntry[] = [];
505 for (const entry of sourceFeed) {
506 const fold = foldsByAnchorId.get(entry.id);
507 if (fold) {
508 result.push({
509 type: "run-fold",
510 id: `run-fold:${fold.runId}`,
511 createdAt: fold.createdAt,
512 runId: fold.runId,
513 label: fold.label,
514 expanded: expandedRunIds.has(fold.runId),
515 });
516 }
517 if (!collapsedEntryIds.has(entry.id)) result.push(entry);
518 }
519 return result;
521​
522export function setPendingUserInputCustomAnswer(
523 draft: PendingUserInputDraftAnswer | undefined,
524 customAnswer: string,
525): PendingUserInputDraftAnswer {
526 const selectedOptionLabel =
527 customAnswer.trim().length > 0 ? undefined : draft?.selectedOptionLabel;
528 return { customAnswer, ...(selectedOptionLabel ? { selectedOptionLabel } : {}) };
530​
531export function buildPendingUserInputAnswers(
532 questions: ReadonlyArray<ThreadUserInputQuestion>,
533 draftAnswers: Record<string, PendingUserInputDraftAnswer>,
534): Record<string, string> | null {
535 const answers: Record<string, string> = {};
536 for (const question of questions) {
537 const answer = resolvePendingUserInputAnswer(draftAnswers[question.id]);
538 if (!answer) return null;
539 answers[question.id] = answer;
540 }
541 return answers;
543​
544/**
545 * Projects the server-authored visible sequence into mobile row presentation.
546 * It deliberately preserves the incoming order and never rebuilds chat from
547 * separate message, plan, or work-entry collections.
548 */
549export function buildThreadFeed(
550 visibleTurnItems: ReadonlyArray<OrchestrationV2ProjectedTurnItem>,
551): ThreadFeedEntry[] {
552 const entries = visibleTurnItems.map((row): RawThreadFeedEntry => {
553 const item = row.item;
554 const createdAt = DateTime.formatIso(item.startedAt ?? item.updatedAt);
555 if (item.type === "user_message" || item.type === "assistant_message") {
556 const updatedAt = DateTime.formatIso(item.updatedAt);
557 return {
558 type: "message",
559 id: item.messageId,
560 createdAt,
561 message: {
562 id: item.messageId,
563 role: item.type === "user_message" ? "user" : "assistant",
564 text: item.text,
565 attachments: item.type === "user_message" ? item.attachments : [],
566 runId: item.runId,
567 streaming: item.type === "assistant_message" && item.streaming,
568 ...(item.type === "user_message"
569 ? {
570 inputIntent: item.inputIntent,
571 createdBy: item.createdBy,
572 creationSource: item.creationSource,
573 }
574 : {}),
575 visibility: row.visibility,
576 sourceThreadId: row.sourceThreadId,
577 createdAt,
578 updatedAt,
579 projectedItem: row,
580 },
581 };
582 }
583 const activity = toFeedActivity(row);
584 return {
585 type: "activity",
586 id: activity.id,
587 createdAt,
588 runId: item.runId,
589 activity,
590 };
591 });
592 return groupAdjacentActivities(entries);