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