The best way to control Claude Code, Codex and more from any computer or phone

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