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

V2ItemInspector.tsx

424 lines14.8 KB

1import type {
2 EnvironmentId,
3 OrchestrationV2ProjectedTurnItem,
4 RunId,
5 ThreadId,
6} from "@t3tools/contracts";
7import {
8 toolCallLines,
9 turnItemDetailRevision,
10 turnItemNeedsDetailFetch,
11 turnItemOutputImages,
12 turnItemOutputText,
13} from "@t3tools/client-runtime/work-log/item-detail";
14import { ExternalLinkIcon, GitBranchIcon, RotateCcwIcon } from "lucide-react";
15import { memo, Suspense, use, useMemo } from "react";
16​
17import { useTheme } from "../../hooks/useTheme";
18import { cn } from "../../lib/utils";
19import { resolveDiffThemeName } from "../../lib/diffRendering";
20import { getSyntaxHighlighterPromise } from "../../lib/syntaxHighlighting";
21import { useTurnItemDetail } from "../../state/queries";
22import { useV2ItemSupport } from "../../state/v2ItemSupport";
23import { formatWorkspaceRelativePath } from "../../filePathDisplay";
24import { Button } from "../ui/button";
25import ChatMarkdown, { ChatMarkdownAssetImage } from "../ChatMarkdown";
26import { RenderErrorBoundary } from "../RenderErrorBoundary";
27import { resolveExternalWebLinkHref } from "./externalLinkContextMenu";
28import type { ExpandedImagePreview } from "./ExpandedImagePreview";
29import { ShellCommandBlock } from "./ShellCommandBlock";
30​
31interface V2ItemInspectorProps {
32 readonly projectedItem: OrchestrationV2ProjectedTurnItem;
33 readonly environmentId: EnvironmentId;
34 readonly cwd?: string | undefined;
35 readonly workspaceRoot?: string | undefined;
36 readonly onOpenThread: (threadId: ThreadId) => void;
37 readonly onOpenTurnDiff: (runId: RunId, filePath?: string) => void;
38 readonly onRollbackCheckpoint?: (input: {
39 readonly checkpointId: string;
40 readonly scopeId: string;
41 }) => void;
42 readonly onImageExpand?: ((preview: ExpandedImagePreview) => void) | undefined;
44​
45function JsonTokens({ text }: { readonly text: string }) {
46 const { resolvedTheme } = useTheme();
47 const highlighter = use(getSyntaxHighlighterPromise("json"));
48 const { tokens } = useMemo(
49 () =>
50 highlighter.codeToTokens(text, { lang: "json", theme: resolveDiffThemeName(resolvedTheme) }),
51 [highlighter, text, resolvedTheme],
52 );
53 return tokens.flatMap((line, lineIndex) => [
54 lineIndex > 0 ? "\n" : "",
55 ...line.map((token) => (
56 <span key={token.offset} style={{ color: token.color }}>
57 {token.content}
58 </span>
59 )),
60 ]);
62​
63const monoClassName =
64 "font-mono text-(length:--font-size-code,var(--text-2xs)) leading-relaxed whitespace-pre-wrap break-words select-text";
65​
66function StructuredValue({
67 value,
68 highlightJson = false,
69}: {
70 readonly value: unknown;
71 readonly highlightJson?: boolean;
72}) {
73 const text = typeof value === "string" ? value : JSON.stringify(value, null, 2);
74 const isJson = useMemo(() => {
75 if (!highlightJson || !text) return false;
76 try {
77 JSON.parse(text);
78 return true;
79 } catch {
80 return false;
81 }
82 }, [highlightJson, text]);
83 if (!text) return null;
84 return (
85 <pre className={cn("max-h-80 overflow-auto text-muted-foreground", monoClassName)}>
86 {isJson ? (
87 <RenderErrorBoundary fallback={text}>
88 <Suspense fallback={text}>
89 <JsonTokens text={text} />
90 </Suspense>
91 </RenderErrorBoundary>
92 ) : (
93 text
94 )}
95 </pre>
96 );
98​
99/**
100 * The item behind a projected row, with the output the timeline withheld
101 * fetched while the row is open.
102 */
103function useFetchedTurnItem(
104 projectedItem: OrchestrationV2ProjectedTurnItem,
105 environmentId: EnvironmentId,
106) {
107 const wireItem = projectedItem.item;
108 const fetches = turnItemNeedsDetailFetch(wireItem);
109 const detail = useTurnItemDetail(
110 fetches
111 ? {
112 environmentId,
113 threadId: projectedItem.sourceThreadId,
114 itemId: projectedItem.sourceItemId,
115 revision: turnItemDetailRevision(wireItem),
116 }
117 : null,
118 );
119 const fetchedItem = detail.data?.item;
120 const item = fetchedItem?.type === wireItem.type ? fetchedItem : wireItem;
121 return {
122 item,
123 output: {
124 output: turnItemOutputText(item),
125 images: turnItemOutputImages(item),
126 environmentId,
127 pending: item === wireItem && detail.isPending,
128 error:
129 item !== wireItem
130 ? null
131 : detail.data?.item === null
132 ? "Output is no longer available."
133 : detail.error,
134 empty: fetches && item !== wireItem,
135 },
136 };
138​
139interface ToolOutputState {
140 readonly output: string | null;
141 readonly images: ReturnType<typeof turnItemOutputImages>;
142 readonly environmentId: EnvironmentId;
143 readonly pending: boolean;
144 readonly error: string | null;
145 readonly empty: boolean;
146 readonly onImageExpand?: ((preview: ExpandedImagePreview) => void) | undefined;
148​
149function ToolOutput(props: ToolOutputState) {
150 const images = props.images.map((resource) => (
151 <ChatMarkdownAssetImage
152 key={resource.index}
153 environmentId={props.environmentId}
154 resource={resource}
155 alt="Tool output image"
156 maxHeightRem={16}
157 onImageExpand={props.onImageExpand}
158 />
159 ));
160 const text = props.output ? (
161 <div className="max-h-80 overflow-auto text-muted-foreground">{props.output}</div>
162 ) : props.pending ? (
163 <div className="text-muted-foreground italic">Loading output…</div>
164 ) : props.error ? (
165 <div className="text-destructive">Couldn&apos;t load output: {props.error}</div>
166 ) : props.empty && images.length === 0 ? (
167 <div className="text-muted-foreground italic">No output.</div>
168 ) : null;
169 return (
170 <>
171 {images}
172 {text}
173 </>
174 );
176​
177/** Fetched output for rows that show their own plain text instead of the inspector. */
178export function FetchedToolOutput(props: {
179 readonly projectedItem: OrchestrationV2ProjectedTurnItem;
180 readonly environmentId: EnvironmentId;
181 readonly onImageExpand?: ((preview: ExpandedImagePreview) => void) | undefined;
182}) {
183 const { output } = useFetchedTurnItem(props.projectedItem, props.environmentId);
184 return (
185 <div className={cn("mt-1.5 space-y-1.5", monoClassName)}>
186 <ToolOutput {...output} onImageExpand={props.onImageExpand} />
187 </div>
188 );
190​
191/** A tool call's body: the call itself in the foreground, its result muted below. */
192function ToolCallBody(
193 props: ToolOutputState & {
194 readonly command?: string;
195 readonly args?: unknown;
196 readonly exitCode?: number | undefined;
197 },
198) {
199 const call = toolCallLines({ command: props.command, args: props.args });
200 return (
201 <div className={cn("space-y-1.5", monoClassName)}>
202 {call.command ? <ShellCommandBlock command={call.command} /> : null}
203 {call.args ? (
204 <div className="text-foreground/85">
205 {call.args.map(([key, value]) => (
206 <div key={key}>
207 <span className="text-muted-foreground">{key} </span>
208 {value}
209 </div>
210 ))}
211 </div>
212 ) : null}
213 {call.argsText ? <StructuredValue value={call.argsText} highlightJson /> : null}
214 <ToolOutput {...props} />
215 {props.exitCode !== undefined && props.exitCode !== 0 ? (
216 <div className="text-destructive">exit {props.exitCode}</div>
217 ) : null}
218 </div>
219 );
221​
222export const V2ItemInspector = memo(function V2ItemInspector(props: V2ItemInspectorProps) {
223 const fetched = useFetchedTurnItem(props.projectedItem, props.environmentId);
224 const item = fetched.item;
225 const outputState = fetched.output;
226 const support = useV2ItemSupport({
227 environmentId: props.environmentId,
228 sourceThreadId: props.projectedItem.sourceThreadId,
229 sourceItemId: props.projectedItem.sourceItemId,
230 });
231 return (
232 <div className="space-y-2 text-xs" data-v2-item-inspector={item.type}>
233 {item.type === "reasoning" && item.text ? (
234 <div className="rounded-md border border-border/45 bg-muted/15 p-2 italic text-muted-foreground">
235 <ChatMarkdown
236 text={item.text}
237 cwd={props.cwd}
238 threadRef={{
239 environmentId: props.environmentId,
240 threadId: props.projectedItem.sourceThreadId,
241 }}
242 lineBreaks
243 />
244 </div>
245 ) : null}
246​
247 {item.type === "command_execution" ? (
248 <ToolCallBody
249 command={item.input}
250 exitCode={item.exitCode}
251 {...outputState}
252 onImageExpand={props.onImageExpand}
253 />
254 ) : null}
255​
256 {item.type === "file_change" ? (
257 <div className="space-y-2">
258 <div className="flex flex-wrap items-center gap-2">
259 <span className="font-mono text-muted-foreground">
260 {formatWorkspaceRelativePath(item.fileName, props.workspaceRoot)}
261 </span>
262 {item.additions !== undefined || item.deletions !== undefined ? (
263 <span>
264 <span className="text-success">+{item.additions ?? 0}</span>{" "}
265 <span className="text-destructive">-{item.deletions ?? 0}</span>
266 </span>
267 ) : null}
268 {item.runId !== null ? (
269 <Button
270 size="xs"
271 variant="outline"
272 onClick={() => props.onOpenTurnDiff(item.runId!, item.fileName)}
273 >
274 Open diff
275 </Button>
276 ) : null}
277 </div>
278 {item.status === "failed" && item.diffStr?.trim() ? (
279 <StructuredValue value={item.diffStr} />
280 ) : null}
281 {item.changes !== undefined && item.changes.length > 0 ? (
282 <ul className="space-y-1 font-mono text-muted-foreground">
283 {item.changes.map((change, index) => (
284 <li key={`${change.operation}:${change.path}:${index}`}>
285 {change.operation} {change.oldPath ? `${change.oldPath} → ` : ""}
286 {formatWorkspaceRelativePath(change.path, props.workspaceRoot)}
287 {change.fileType || change.mimeType
288 ? ` (${[change.fileType, change.mimeType].filter(Boolean).join(", ")})`
289 : ""}
290 </li>
291 ))}
292 </ul>
293 ) : null}
294 </div>
295 ) : null}
296​
297 {item.type === "file_search" && item.pattern?.trim() ? (
298 <div className={cn("text-foreground/85", monoClassName)}>{item.pattern}</div>
299 ) : null}
300​
301 {item.type === "web_search" && item.patterns?.length ? (
302 <div className={cn("text-foreground/85", monoClassName)}>{item.patterns.join("\n")}</div>
303 ) : null}
304​
305 {item.type === "file_search" && item.results?.length ? (
306 <ul className="space-y-1">
307 {item.results.map((result) => (
308 <li key={JSON.stringify(result)}>
309 <span className="font-mono text-foreground/80">
310 {formatWorkspaceRelativePath(result.fileName, props.workspaceRoot)}
311 {result.line === undefined ? "" : `:${result.line}`}
312 {result.column === undefined ? "" : `:${result.column}`}
313 </span>
314 {result.preview ? (
315 <p className="mt-0.5 whitespace-pre-wrap text-muted-foreground">{result.preview}</p>
316 ) : null}
317 </li>
318 ))}
319 </ul>
320 ) : null}
321​
322 {item.type === "web_search" && item.results?.length ? (
323 <ul className="space-y-1.5">
324 {item.results.map((result) => {
325 const safeHref = resolveExternalWebLinkHref(result.url);
326 return (
327 <li key={JSON.stringify(result)}>
328 {safeHref ? (
329 <a
330 href={safeHref}
331 target="_blank"
332 rel="noreferrer"
333 className="inline-flex items-center gap-1 font-medium text-foreground hover:underline"
334 >
335 {result.title ?? result.url}
336 <ExternalLinkIcon className="size-3" />
337 </a>
338 ) : (
339 <p className="font-medium text-foreground">
340 {result.title ?? result.url ?? "Search result"}
341 </p>
342 )}
343 {result.snippet ? <p className="text-muted-foreground">{result.snippet}</p> : null}
344 </li>
345 );
346 })}
347 </ul>
348 ) : null}
349​
350 {item.type === "dynamic_tool" ? (
351 <ToolCallBody args={item.input} {...outputState} onImageExpand={props.onImageExpand} />
352 ) : null}
353​
354 {item.type === "approval_request" ? <StructuredValue value={item.prompt} /> : null}
355 {item.type === "user_input_request" ? (
356 <StructuredValue value={item.questions.map((question) => question.question).join("\n\n")} />
357 ) : null}
358 {item.type === "notification" ? <StructuredValue value={item.detail} /> : null}
359 {item.type === "system_notice" ? <StructuredValue value={item.message} /> : null}
360 {item.type === "error" ? <StructuredValue value={item.failure.message} /> : null}
361 {item.type === "proposed_plan" ? <StructuredValue value={item.markdown} /> : null}
362 {item.type === "todo_list" ? (
363 <StructuredValue
364 value={item.steps
365 .map((step) => `${step.status === "completed" ? "✓" : "○"} ${step.text}`)
366 .join("\n")}
367 />
368 ) : null}
369​
370 {item.type === "checkpoint" ? (
371 <div className="flex flex-wrap items-center gap-2">
372 <span className="text-muted-foreground">
373 {support.checkpoint?.status ?? item.status} · {item.files.length} files
374 </span>
375 {props.onRollbackCheckpoint && support.checkpoint?.status === "ready" ? (
376 <Button
377 size="xs"
378 variant="outline"
379 onClick={() =>
380 props.onRollbackCheckpoint?.({
381 checkpointId: item.checkpointId,
382 scopeId: item.scopeId,
383 })
384 }
385 >
386 <RotateCcwIcon className="size-3" />
387 Roll back
388 </Button>
389 ) : null}
390 </div>
391 ) : null}
392​
393 {item.type === "fork" ? (
394 <Button size="xs" variant="outline" onClick={() => props.onOpenThread(item.targetThreadId)}>
395 <GitBranchIcon className="size-3" />
396 Open fork
397 </Button>
398 ) : null}
399​
400 {item.type === "subagent" && item.childThreadId !== null ? (
401 <Button size="xs" variant="outline" onClick={() => props.onOpenThread(item.childThreadId!)}>
402 Open subagent thread
403 </Button>
404 ) : null}
405​
406 {item.type === "handoff" ? (
407 <div className="space-y-1 text-muted-foreground">
408 <p>
409 {item.fromProviderInstanceIds.join(", ")} → {item.toProviderInstanceId}
410 </p>
411 <p>
412 {item.strategy.replaceAll("_", " ")} · {support.contextHandoff?.status ?? item.status}
413 </p>
414 {support.contextTransfer ? (
415 <p>
416 Transfer {support.contextTransfer.type.replaceAll("_", " ")} ·{" "}
417 {support.contextTransfer.status}
418 </p>
419 ) : null}
420 </div>
421 ) : null}
422 </div>
423 );
424});