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

V2ItemInspector.tsx

432 lines15.3 KB

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