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