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

V2ItemInspector.tsx

464 lines16.2 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​
113/**
114 * The item behind a projected row, with the output the timeline withheld
115 * fetched while the row is open.
116 */
117function useFetchedTurnItem(
118 projectedItem: OrchestrationV2ProjectedTurnItem,
119 environmentId: EnvironmentId,
120 skip = false,
121) {
122 const wireItem = projectedItem.item;
123 const fetches = !skip && turnItemNeedsDetailFetch(wireItem);
124 const detail = useTurnItemDetail(
125 fetches
126 ? {
127 environmentId,
128 threadId: projectedItem.sourceThreadId,
129 itemId: projectedItem.sourceItemId,
130 revision: turnItemDetailRevision(wireItem),
131 }
132 : null,
133 );
134 const fetchedItem = detail.data?.item;
135 const item = fetchedItem?.type === wireItem.type ? fetchedItem : wireItem;
136 return {
137 item,
138 output: {
139 output: turnItemOutputText(item),
140 images: turnItemOutputImages(item),
141 environmentId,
142 pending: item === wireItem && detail.isPending,
143 error:
144 item !== wireItem
145 ? null
146 : detail.data?.item === null
147 ? "Output is no longer available."
148 : detail.error,
149 empty: fetches && item !== wireItem,
150 },
151 };
153​
154interface ToolOutputState {
155 readonly output: string | null;
156 readonly images: ReturnType<typeof turnItemOutputImages>;
157 readonly environmentId: EnvironmentId;
158 readonly pending: boolean;
159 readonly error: string | null;
160 readonly empty: boolean;
161 readonly onImageExpand?: ((preview: ExpandedImagePreview) => void) | undefined;
163​
164function ToolOutput(props: ToolOutputState) {
165 const images = props.images.map((resource) => (
166 <ChatMarkdownAssetImage
167 key={resource.index}
168 environmentId={props.environmentId}
169 resource={resource}
170 alt="Tool output image"
171 maxHeightRem={16}
172 onImageExpand={props.onImageExpand}
173 />
174 ));
175 const text = props.output ? (
176 <div className="max-h-80 overflow-auto text-muted-foreground">{props.output}</div>
177 ) : props.pending ? (
178 <div className="text-muted-foreground italic">Loading output…</div>
179 ) : props.error ? (
180 <div className="text-destructive">Couldn&apos;t load output: {props.error}</div>
181 ) : props.empty && images.length === 0 ? (
182 <div className="text-muted-foreground italic">No output.</div>
183 ) : null;
184 return (
185 <>
186 {images}
187 {text}
188 </>
189 );
191​
192/** Fetched output for rows that show their own plain text instead of the inspector. */
193export function FetchedToolOutput(props: {
194 readonly projectedItem: OrchestrationV2ProjectedTurnItem;
195 readonly environmentId: EnvironmentId;
196 readonly onImageExpand?: ((preview: ExpandedImagePreview) => void) | undefined;
197}) {
198 const { output } = useFetchedTurnItem(props.projectedItem, props.environmentId);
199 return (
200 <div className={cn("mt-1.5 space-y-1.5", monoClassName)}>
201 <ToolOutput {...output} onImageExpand={props.onImageExpand} />
202 </div>
203 );
205​
206/** A tool call's body: the call itself in the foreground, its result muted below. */
207function ToolCallBody(
208 props: ToolOutputState & {
209 readonly command?: string;
210 readonly args?: unknown;
211 readonly toolName?: string | null;
212 readonly exitCode?: number | undefined;
213 /** Replaces the fetched output, e.g. with a command's live output. */
214 readonly outputSlot?: ReactNode;
215 },
216) {
217 const call = toolCallLines({ command: props.command, args: props.args });
218 return (
219 <div className={cn("space-y-1.5", monoClassName)}>
220 {call.command ? <ShellCommandBlock command={call.command} /> : null}
221 {call.args ? (
222 <div className="text-foreground/85">
223 {call.args.map(([key, value]) => (
224 <div key={key}>
225 <span className="text-muted-foreground">{key} </span>
226 {key === "code" && isJavaScriptReplTool(props.toolName) ? (
227 <StructuredValue value={value} language="typescript" />
228 ) : (
229 value
230 )}
231 </div>
232 ))}
233 </div>
234 ) : null}
235 {call.argsText ? <StructuredValue value={call.argsText} highlightJson /> : null}
236 {props.outputSlot ?? <ToolOutput {...props} />}
237 {props.exitCode !== undefined && props.exitCode !== 0 ? (
238 <div className="text-destructive">exit {props.exitCode}</div>
239 ) : null}
240 </div>
241 );
243​
244export const V2ItemInspector = memo(function V2ItemInspector(props: V2ItemInspectorProps) {
245 // Command rows stream their output, including the final output, from the server.
246 const streamsOutput =
247 useCommandOutputStreaming(props.environmentId) &&
248 props.projectedItem.item.type === "command_execution";
249 const fetched = useFetchedTurnItem(props.projectedItem, props.environmentId, streamsOutput);
250 const item = fetched.item;
251 const outputState = fetched.output;
252 const support = useV2ItemSupport({
253 environmentId: props.environmentId,
254 sourceThreadId: props.projectedItem.sourceThreadId,
255 sourceItemId: props.projectedItem.sourceItemId,
256 });
257 return (
258 <div className="space-y-2 text-xs" data-v2-item-inspector={item.type}>
259 {item.type === "reasoning" && item.text ? (
260 <div className="rounded-md border border-border/45 bg-muted/15 p-2 italic text-muted-foreground">
261 <ChatMarkdown
262 text={item.text}
263 cwd={props.cwd}
264 threadRef={{
265 environmentId: props.environmentId,
266 threadId: props.projectedItem.sourceThreadId,
267 }}
268 lineBreaks
269 />
270 </div>
271 ) : null}
272​
273 {item.type === "command_execution" ? (
274 <ToolCallBody
275 command={item.input}
276 exitCode={item.exitCode}
277 {...outputState}
278 onImageExpand={props.onImageExpand}
279 outputSlot={
280 streamsOutput ? (
281 <CommandOutputPanel
282 environmentId={props.environmentId}
283 threadId={props.projectedItem.sourceThreadId}
284 itemId={props.projectedItem.sourceItemId}
285 />
286 ) : undefined
287 }
288 />
289 ) : null}
290​
291 {item.type === "file_change" ? (
292 <div className="space-y-2">
293 <div className="flex flex-wrap items-center gap-2">
294 <span className="font-mono text-muted-foreground">
295 {formatWorkspaceRelativePath(item.fileName, props.workspaceRoot)}
296 </span>
297 {item.additions !== undefined || item.deletions !== undefined ? (
298 <span>
299 <span className="text-success">+{formatDiffCount(item.additions ?? 0)}</span>{" "}
300 <span className="text-destructive">-{formatDiffCount(item.deletions ?? 0)}</span>
301 </span>
302 ) : null}
303 {item.runId !== null ? (
304 <Button
305 size="xs"
306 variant="outline"
307 onClick={() => props.onOpenTurnDiff(item.runId!, item.fileName)}
308 >
309 Open diff
310 </Button>
311 ) : null}
312 </div>
313 {item.status === "failed" && item.diffStr?.trim() ? (
314 <StructuredValue value={item.diffStr} />
315 ) : null}
316 {item.changes !== undefined && item.changes.length > 0 ? (
317 <ul className="space-y-1 font-mono text-muted-foreground">
318 {item.changes.map((change, index) => (
319 <li key={`${change.operation}:${change.path}:${index}`}>
320 {change.operation} {change.oldPath ? `${change.oldPath} → ` : ""}
321 {formatWorkspaceRelativePath(change.path, props.workspaceRoot)}
322 {change.fileType || change.mimeType
323 ? ` (${[change.fileType, change.mimeType].filter(Boolean).join(", ")})`
324 : ""}
325 </li>
326 ))}
327 </ul>
328 ) : null}
329 </div>
330 ) : null}
331​
332 {item.type === "file_search" && item.pattern?.trim() ? (
333 <div className={cn("text-foreground/85", monoClassName)}>{item.pattern}</div>
334 ) : null}
335​
336 {item.type === "web_search" && item.patterns?.length ? (
337 <div className={cn("text-foreground/85", monoClassName)}>{item.patterns.join("\n")}</div>
338 ) : null}
339​
340 {item.type === "file_search" && item.results?.length ? (
341 <ul className="space-y-1">
342 {item.results.map((result) => (
343 <li key={JSON.stringify(result)}>
344 <span className="font-mono text-foreground/80">
345 {formatWorkspaceRelativePath(result.fileName, props.workspaceRoot)}
346 {result.line === undefined ? "" : `:${result.line}`}
347 {result.column === undefined ? "" : `:${result.column}`}
348 </span>
349 {result.preview ? (
350 <p className="mt-0.5 whitespace-pre-wrap text-muted-foreground">{result.preview}</p>
351 ) : null}
352 </li>
353 ))}
354 </ul>
355 ) : null}
356​
357 {item.type === "web_search" && item.results?.length ? (
358 <ul className="space-y-1.5">
359 {item.results.map((result) => {
360 const safeHref = resolveExternalWebLinkHref(result.url);
361 return (
362 <li key={JSON.stringify(result)}>
363 {safeHref ? (
364 <a
365 href={safeHref}
366 target="_blank"
367 rel="noreferrer"
368 className="inline-flex items-center gap-1 font-medium text-foreground hover:underline"
369 >
370 {result.title ?? result.url}
371 <ExternalLinkIcon className="size-3" />
372 </a>
373 ) : (
374 <p className="font-medium text-foreground">
375 {result.title ?? result.url ?? "Search result"}
376 </p>
377 )}
378 {result.snippet ? <p className="text-muted-foreground">{result.snippet}</p> : null}
379 </li>
380 );
381 })}
382 </ul>
383 ) : null}
384​
385 {item.type === "dynamic_tool" ? (
386 <ToolCallBody
387 toolName={item.toolName}
388 args={item.input}
389 {...outputState}
390 onImageExpand={props.onImageExpand}
391 />
392 ) : null}
393​
394 {item.type === "approval_request" ? <StructuredValue value={item.prompt} /> : null}
395 {item.type === "user_input_request" ? (
396 <StructuredValue value={item.questions.map((question) => question.question).join("\n\n")} />
397 ) : null}
398 {item.type === "notification" ? <StructuredValue value={item.detail} /> : null}
399 {item.type === "system_notice" ? <StructuredValue value={item.message} /> : null}
400 {item.type === "error" ? <StructuredValue value={item.failure.message} /> : null}
401 {item.type === "proposed_plan" ? <StructuredValue value={item.markdown} /> : null}
402 {item.type === "todo_list" ? (
403 <StructuredValue
404 value={item.steps
405 .map((step) => `${step.status === "completed" ? "✓" : "○"} ${step.text}`)
406 .join("\n")}
407 />
408 ) : null}
409​
410 {item.type === "checkpoint" ? (
411 <div className="flex flex-wrap items-center gap-2">
412 <span className="text-muted-foreground">
413 {support.checkpoint?.status ?? item.status} · {item.files.length} files
414 </span>
415 {props.onRollbackCheckpoint && support.checkpoint?.status === "ready" ? (
416 <Button
417 size="xs"
418 variant="outline"
419 onClick={() =>
420 props.onRollbackCheckpoint?.({
421 checkpointId: item.checkpointId,
422 scopeId: item.scopeId,
423 })
424 }
425 >
426 <RotateCcwIcon className="size-3" />
427 Roll back
428 </Button>
429 ) : null}
430 </div>
431 ) : null}
432​
433 {item.type === "fork" ? (
434 <Button size="xs" variant="outline" onClick={() => props.onOpenThread(item.targetThreadId)}>
435 <GitBranchIcon className="size-3" />
436 Open fork
437 </Button>
438 ) : null}
439​
440 {item.type === "subagent" && item.childThreadId !== null ? (
441 <Button size="xs" variant="outline" onClick={() => props.onOpenThread(item.childThreadId!)}>
442 Open subagent thread
443 </Button>
444 ) : null}
445​
446 {item.type === "handoff" ? (
447 <div className="space-y-1 text-muted-foreground">
448 <p>
449 {item.fromProviderInstanceIds.join(", ")} → {item.toProviderInstanceId}
450 </p>
451 <p>
452 {item.strategy.replaceAll("_", " ")} · {support.contextHandoff?.status ?? item.status}
453 </p>
454 {support.contextTransfer ? (
455 <p>
456 Transfer {support.contextTransfer.type.replaceAll("_", " ")} ·{" "}
457 {support.contextTransfer.status}
458 </p>
459 ) : null}
460 </div>
461 ) : null}
462 </div>
463 );
464});