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