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