Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

V2ItemInspector.tsx

472 lines16.3 KB

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