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

V2ItemInspector.tsx

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