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

threadActivityInspector.ts

308 lines9.6 KB

1import type { V2ItemSupport } from "@t3tools/client-runtime/state/item-support";
2import type { ThreadId } from "@t3tools/contracts";
3import { formatDuration } from "@t3tools/shared/orchestrationTiming";
4import * as DateTime from "effect/DateTime";
5​
6import type { ThreadFeedActivity } from "./threadActivity";
7​
8export interface ThreadActivityInspectorField {
9 readonly label: string;
10 readonly value: string;
12​
13export interface ThreadActivityInspectorBlock {
14 readonly label: string;
15 readonly value: string;
16 readonly monospaced: boolean;
18​
19export interface ThreadActivityFileLink {
20 readonly label: string;
21 readonly path: string;
22 readonly line?: number;
24​
25export interface ThreadActivityWebLink {
26 readonly label: string;
27 readonly url: string;
29​
30export interface ThreadActivityInspectorModel {
31 readonly fields: ReadonlyArray<ThreadActivityInspectorField>;
32 readonly blocks: ReadonlyArray<ThreadActivityInspectorBlock>;
33 readonly fileLinks: ReadonlyArray<ThreadActivityFileLink>;
34 readonly webLinks: ReadonlyArray<ThreadActivityWebLink>;
35 readonly canRollback: boolean;
36 readonly rollbackTarget: {
37 readonly threadId: ThreadId;
38 readonly checkpointId: string;
39 readonly scopeId: string;
40 } | null;
41 readonly structuredDetails: string;
43​
44function formatStructured(value: unknown): string {
45 if (typeof value === "string") return value;
46 try {
47 return JSON.stringify(value, null, 2) ?? String(value);
48 } catch {
49 return String(value);
50 }
52​
53function durationLabel(
54 startedAt: DateTime.Utc | null,
55 completedAt: DateTime.Utc | null,
56): string | null {
57 if (startedAt === null) return null;
58 const start = DateTime.toEpochMillis(startedAt);
59 const end = completedAt === null ? Date.now() : DateTime.toEpochMillis(completedAt);
60 return formatDuration(Math.max(0, end - start));
62​
63function addBlock(
64 blocks: ThreadActivityInspectorBlock[],
65 label: string,
66 value: unknown,
67 monospaced = true,
68): void {
69 if (value === undefined || value === null || value === "") return;
70 blocks.push({ label, value: formatStructured(value), monospaced });
72​
73export function buildThreadActivityInspector(
74 activity: ThreadFeedActivity,
75 support: V2ItemSupport,
76 currentThreadId: ThreadId,
77): ThreadActivityInspectorModel {
78 const row = activity.projectedItem;
79 const item = row.item;
80 const fields: ThreadActivityInspectorField[] = [
81 { label: "Item", value: item.type.replaceAll("_", " ") },
82 { label: "Status", value: item.status.replaceAll("_", " ") },
83 ];
84 const duration = durationLabel(item.startedAt, item.completedAt);
85 if (duration) fields.push({ label: "Duration", value: duration });
86 if (row.visibility !== "local") fields.push({ label: "Visibility", value: row.visibility });
87 if (support.run) fields.push({ label: "Run", value: support.run.status });
88​
89 const latestAttempt = support.attempts.at(-1);
90 if (latestAttempt) {
91 fields.push({
92 label: "Attempt",
93 value: `${latestAttempt.attemptOrdinal} · ${latestAttempt.status} · ${latestAttempt.reason.replaceAll("_", " ")}`,
94 });
95 }
96 if (support.node) {
97 fields.push({
98 label: "Node",
99 value: `${support.node.kind.replaceAll("_", " ")} · ${support.node.status}`,
100 });
101 }
102 if (support.providerThread) {
103 fields.push({
104 label: "Provider thread",
105 value: `${support.providerThread.providerInstanceId} · ${support.providerThread.status}`,
106 });
107 }
108 if (support.providerTurn) {
109 fields.push({ label: "Provider turn", value: support.providerTurn.status });
110 }
111 if (support.providerSession) {
112 fields.push({
113 label: "Session",
114 value: `${support.providerSession.status} · ${support.providerSession.model ?? "default model"}`,
115 });
116 fields.push({ label: "Working directory", value: support.providerSession.cwd });
117 }
118 if (support.runtimeRequest) {
119 fields.push({
120 label: "Request",
121 value: `${support.runtimeRequest.status} · ${support.runtimeRequest.responseCapability.type.replaceAll("_", " ")}`,
122 });
123 }
124​
125 const blocks: ThreadActivityInspectorBlock[] = [];
126 const fileLinks: ThreadActivityFileLink[] = [];
127 const webLinks: ThreadActivityWebLink[] = [];
128​
129 if (support.attempts.length > 1) {
130 addBlock(
131 blocks,
132 "Attempt history",
133 support.attempts
134 .map(
135 (attempt) =>
136 `Attempt ${attempt.attemptOrdinal} · ${attempt.status} · ${attempt.reason.replaceAll("_", " ")}`,
137 )
138 .join("\n"),
139 );
140 }
141​
142 switch (item.type) {
143 case "reasoning":
144 addBlock(blocks, "Reasoning", item.text, false);
145 break;
146 case "command_execution":
147 addBlock(blocks, "Command", item.input);
148 addBlock(blocks, "Output", item.output);
149 if (item.exitCode !== undefined) {
150 addBlock(blocks, "Exit", `Process exited with code ${item.exitCode}`);
151 }
152 break;
153 case "file_change":
154 fileLinks.push({ label: item.fileName, path: item.fileName });
155 if (item.additions !== undefined || item.deletions !== undefined) {
156 fields.push({
157 label: "Changes",
158 value: `+${item.additions ?? 0} −${item.deletions ?? 0}`,
159 });
160 }
161 addBlock(blocks, "Patch", item.diffStr);
162 addBlock(blocks, "Before", item.oldStr);
163 addBlock(blocks, "After", item.newStr);
164 break;
165 case "file_search":
166 addBlock(blocks, "Query", item.pattern);
167 for (const result of item.results ?? []) {
168 fileLinks.push({
169 label: result.preview ? `${result.fileName} — ${result.preview}` : result.fileName,
170 path: result.fileName,
171 ...(result.line === undefined ? {} : { line: result.line }),
172 });
173 }
174 break;
175 case "web_search":
176 addBlock(blocks, "Queries", item.patterns?.join("\n"));
177 for (const result of item.results ?? []) {
178 if (result.url) {
179 webLinks.push({
180 label: result.title ?? result.url,
181 url: result.url,
182 });
183 }
184 if (result.snippet)
185 addBlock(blocks, result.title ?? "Search result", result.snippet, false);
186 }
187 break;
188 case "dynamic_tool":
189 addBlock(blocks, "Input", item.input);
190 addBlock(blocks, "Output", item.output);
191 break;
192 case "approval_request":
193 addBlock(blocks, "Prompt", item.prompt, false);
194 break;
195 case "user_input_request":
196 addBlock(
197 blocks,
198 "Questions",
199 item.questions.map((question) => question.question).join("\n"),
200 false,
201 );
202 break;
203 case "checkpoint":
204 addBlock(
205 blocks,
206 "Files",
207 item.files
208 .map((file) => `${file.path} +${file.additions} −${file.deletions} ${file.kind}`)
209 .join("\n"),
210 );
211 break;
212 case "subagent":
213 addBlock(blocks, "Prompt", item.prompt, false);
214 addBlock(blocks, "Progress", support.subagent?.progress ?? item.progress, false);
215 addBlock(blocks, "Result", support.subagent?.result ?? item.result, false);
216 if (support.subagent) {
217 fields.push({
218 label: "Delegated task",
219 value: `${support.subagent.origin.replaceAll("_", " ")} · ${support.subagent.status}`,
220 });
221 }
222 break;
223 case "handoff":
224 addBlock(blocks, "Summary", item.summary, false);
225 fields.push({
226 label: "Handoff",
227 value: `${item.strategy.replaceAll("_", " ")} · ${support.contextHandoff?.status ?? item.status}`,
228 });
229 if (support.contextTransfer) {
230 fields.push({
231 label: "Transfer",
232 value: `${support.contextTransfer.type.replaceAll("_", " ")} · ${support.contextTransfer.status}`,
233 });
234 if (support.contextTransfer.resolution) {
235 fields.push({
236 label: "Context",
237 value: support.contextTransfer.resolution.strategy.replaceAll("_", " "),
238 });
239 }
240 }
241 break;
242 case "error":
243 addBlock(blocks, "Error", item.failure.message, false);
244 if (item.failure.code) fields.push({ label: "Code", value: item.failure.code });
245 if (item.failure.retryable !== null) {
246 fields.push({ label: "Retryable", value: item.failure.retryable ? "yes" : "no" });
247 }
248 break;
249 case "proposed_plan":
250 addBlock(blocks, "Plan", item.markdown, false);
251 break;
252 case "todo_list":
253 addBlock(
254 blocks,
255 "Tasks",
256 item.steps
257 .map((step) => `${step.status === "completed" ? "✓" : "○"} ${step.text}`)
258 .join("\n"),
259 false,
260 );
261 addBlock(blocks, "Explanation", item.explanation, false);
262 break;
263 case "compaction":
264 addBlock(blocks, "Summary", item.summary, false);
265 if (item.beforeTokenCount !== undefined || item.afterTokenCount !== undefined) {
266 fields.push({
267 label: "Context tokens",
268 value: `${item.beforeTokenCount ?? "?"} → ${item.afterTokenCount ?? "?"}`,
269 });
270 }
271 break;
272 case "run_interrupt_request":
273 case "run_interrupt_result":
274 addBlock(blocks, "Message", item.message, false);
275 break;
276 case "fork":
277 case "thread_created":
278 case "user_message":
279 case "assistant_message":
280 break;
281 }
282​
283 const checkpoint =
284 item.type === "checkpoint" && row.sourceThreadId === currentThreadId
285 ? support.checkpoint
286 : null;
287 return {
288 fields,
289 blocks,
290 fileLinks,
291 webLinks,
292 canRollback: checkpoint?.status === "ready",
293 rollbackTarget:
294 checkpoint?.status === "ready"
295 ? {
296 threadId: row.sourceThreadId,
297 checkpointId: checkpoint.id,
298 scopeId: checkpoint.scopeId,
299 }
300 : null,
301 structuredDetails: formatStructured({
302 visibility: row.visibility,
303 sourceThreadId: row.sourceThreadId,
304 sourceItemId: row.sourceItemId,
305 item,
306 }),
307 };