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

threadActivityInspector.ts

309 lines9.7 KB

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