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

threadActivityInspector.ts

304 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): ThreadActivityInspectorModel {
77 const row = activity.projectedItem;
78 const item = row.item;
79 const fields: ThreadActivityInspectorField[] = [
80 { label: "Item", value: item.type.replaceAll("_", " ") },
81 { label: "Status", value: item.status.replaceAll("_", " ") },
82 ];
83 const duration = durationLabel(item.startedAt, item.completedAt);
84 if (duration) fields.push({ label: "Duration", value: duration });
85 if (row.visibility !== "local") fields.push({ label: "Visibility", value: row.visibility });
86 if (support.run) fields.push({ label: "Run", value: support.run.status });
87​
88 const latestAttempt = support.attempts.at(-1);
89 if (latestAttempt) {
90 fields.push({
91 label: "Attempt",
92 value: `${latestAttempt.attemptOrdinal} · ${latestAttempt.status} · ${latestAttempt.reason.replaceAll("_", " ")}`,
93 });
94 }
95 if (support.node) {
96 fields.push({
97 label: "Node",
98 value: `${support.node.kind.replaceAll("_", " ")} · ${support.node.status}`,
99 });
100 }
101 if (support.providerThread) {
102 fields.push({
103 label: "Provider thread",
104 value: `${support.providerThread.providerInstanceId} · ${support.providerThread.status}`,
105 });
106 }
107 if (support.providerTurn) {
108 fields.push({ label: "Provider turn", value: support.providerTurn.status });
109 }
110 if (support.providerSession) {
111 fields.push({
112 label: "Session",
113 value: `${support.providerSession.status} · ${support.providerSession.model ?? "default model"}`,
114 });
115 fields.push({ label: "Working directory", value: support.providerSession.cwd });
116 }
117 if (support.runtimeRequest) {
118 fields.push({
119 label: "Request",
120 value: `${support.runtimeRequest.status} · ${support.runtimeRequest.responseCapability.type.replaceAll("_", " ")}`,
121 });
122 }
123​
124 const blocks: ThreadActivityInspectorBlock[] = [];
125 const fileLinks: ThreadActivityFileLink[] = [];
126 const webLinks: ThreadActivityWebLink[] = [];
127​
128 if (support.attempts.length > 1) {
129 addBlock(
130 blocks,
131 "Attempt history",
132 support.attempts
133 .map(
134 (attempt) =>
135 `Attempt ${attempt.attemptOrdinal} · ${attempt.status} · ${attempt.reason.replaceAll("_", " ")}`,
136 )
137 .join("\n"),
138 );
139 }
140​
141 switch (item.type) {
142 case "reasoning":
143 addBlock(blocks, "Reasoning", item.text, false);
144 break;
145 case "command_execution":
146 addBlock(blocks, "Command", item.input);
147 addBlock(blocks, "Output", item.output);
148 if (item.exitCode !== undefined) {
149 addBlock(blocks, "Exit", `Process exited with code ${item.exitCode}`);
150 }
151 break;
152 case "file_change":
153 fileLinks.push({ label: item.fileName, path: item.fileName });
154 if (item.additions !== undefined || item.deletions !== undefined) {
155 fields.push({
156 label: "Changes",
157 value: `+${item.additions ?? 0} −${item.deletions ?? 0}`,
158 });
159 }
160 addBlock(blocks, "Patch", item.diffStr);
161 addBlock(blocks, "Before", item.oldStr);
162 addBlock(blocks, "After", item.newStr);
163 break;
164 case "file_search":
165 addBlock(blocks, "Query", item.pattern);
166 for (const result of item.results ?? []) {
167 fileLinks.push({
168 label: result.preview ? `${result.fileName} — ${result.preview}` : result.fileName,
169 path: result.fileName,
170 ...(result.line === undefined ? {} : { line: result.line }),
171 });
172 }
173 break;
174 case "web_search":
175 addBlock(blocks, "Queries", item.patterns?.join("\n"));
176 for (const result of item.results ?? []) {
177 if (result.url) {
178 webLinks.push({
179 label: result.title ?? result.url,
180 url: result.url,
181 });
182 }
183 if (result.snippet)
184 addBlock(blocks, result.title ?? "Search result", result.snippet, false);
185 }
186 break;
187 case "dynamic_tool":
188 addBlock(blocks, "Input", item.input);
189 addBlock(blocks, "Output", item.output);
190 break;
191 case "approval_request":
192 addBlock(blocks, "Prompt", item.prompt, false);
193 break;
194 case "user_input_request":
195 addBlock(
196 blocks,
197 "Questions",
198 item.questions.map((question) => question.question).join("\n"),
199 false,
200 );
201 break;
202 case "checkpoint":
203 addBlock(
204 blocks,
205 "Files",
206 item.files
207 .map((file) => `${file.path} +${file.additions} −${file.deletions} ${file.kind}`)
208 .join("\n"),
209 );
210 break;
211 case "subagent":
212 addBlock(blocks, "Prompt", item.prompt, false);
213 addBlock(blocks, "Progress", support.subagent?.progress ?? item.progress, false);
214 addBlock(blocks, "Result", support.subagent?.result ?? item.result, false);
215 if (support.subagent) {
216 fields.push({
217 label: "Delegated task",
218 value: `${support.subagent.origin.replaceAll("_", " ")} · ${support.subagent.status}`,
219 });
220 }
221 break;
222 case "handoff":
223 addBlock(blocks, "Summary", item.summary, false);
224 fields.push({
225 label: "Handoff",
226 value: `${item.strategy.replaceAll("_", " ")} · ${support.contextHandoff?.status ?? item.status}`,
227 });
228 if (support.contextTransfer) {
229 fields.push({
230 label: "Transfer",
231 value: `${support.contextTransfer.type.replaceAll("_", " ")} · ${support.contextTransfer.status}`,
232 });
233 if (support.contextTransfer.resolution) {
234 fields.push({
235 label: "Context",
236 value: support.contextTransfer.resolution.strategy.replaceAll("_", " "),
237 });
238 }
239 }
240 break;
241 case "error":
242 addBlock(blocks, "Error", item.failure.message, false);
243 if (item.failure.code) fields.push({ label: "Code", value: item.failure.code });
244 if (item.failure.retryable !== null) {
245 fields.push({ label: "Retryable", value: item.failure.retryable ? "yes" : "no" });
246 }
247 break;
248 case "proposed_plan":
249 addBlock(blocks, "Plan", item.markdown, false);
250 break;
251 case "todo_list":
252 addBlock(
253 blocks,
254 "Tasks",
255 item.steps
256 .map((step) => `${step.status === "completed" ? "✓" : "○"} ${step.text}`)
257 .join("\n"),
258 false,
259 );
260 addBlock(blocks, "Explanation", item.explanation, false);
261 break;
262 case "compaction":
263 addBlock(blocks, "Summary", item.summary, false);
264 if (item.beforeTokenCount !== undefined || item.afterTokenCount !== undefined) {
265 fields.push({
266 label: "Context tokens",
267 value: `${item.beforeTokenCount ?? "?"} → ${item.afterTokenCount ?? "?"}`,
268 });
269 }
270 break;
271 case "run_interrupt_request":
272 case "run_interrupt_result":
273 addBlock(blocks, "Message", item.message, false);
274 break;
275 case "fork":
276 case "thread_created":
277 case "user_message":
278 case "assistant_message":
279 break;
280 }
281​
282 const checkpoint = item.type === "checkpoint" ? support.checkpoint : null;
283 return {
284 fields,
285 blocks,
286 fileLinks,
287 webLinks,
288 canRollback: checkpoint?.status === "ready",
289 rollbackTarget:
290 checkpoint?.status === "ready"
291 ? {
292 threadId: row.sourceThreadId,
293 checkpointId: checkpoint.id,
294 scopeId: checkpoint.scopeId,
295 }
296 : null,
297 structuredDetails: formatStructured({
298 visibility: row.visibility,
299 sourceThreadId: row.sourceThreadId,
300 sourceItemId: row.sourceItemId,
301 item,
302 }),
303 };