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