Open History to see the last commit
1import { useEffect, useMemo, useRef, useState } from 'react'
2import { createFileRoute } from '@tanstack/react-router'
3import {
4 AlertTriangle,
5 FileText,
6 Github,
7 Play,
8 Server,
9 Square,
10 Terminal,
11} from 'lucide-react'
12import ReactMarkdown from 'react-markdown'
13import rehypeHighlight from 'rehype-highlight'
14import rehypeRaw from 'rehype-raw'
15import rehypeSanitize from 'rehype-sanitize'
16import remarkGfm from 'remark-gfm'
17import { fetchServerSentEvents, useChat } from '@tanstack/ai-react'
18import {
19 GROK_MODEL_OPTIONS,
20 GROK_PROTOCOL_OPTIONS,
21 GROK_TRANSPORT_OPTIONS,
22 HARNESSES,
23 PROVIDERS,
24 isGrokModel,
25 isGrokProtocol,
26 isGrokTransport,
27 parseVerdict,
28} from '../sandbox-triage-options'
29import type {
30 GrokBuildModel,
31 GrokBuildProtocol,
32 GrokTransport,
33 HarnessName,
34 ProviderName,
35 Verdict,
36} from '../sandbox-triage-options'
37import type { UIMessage } from '@tanstack/ai-react'
38
39export const Route = createFileRoute('/sandboxes')({
40 component: SandboxesPage,
41})
42
43// ---------------------------------------------------------------------------
44// VerdictChip
45// ---------------------------------------------------------------------------
46
47const VERDICT_STYLES: Record<Verdict, { label: string; cls: string }> = {
48 relevant: {
49 label: 'Relevant',
50 cls: 'bg-emerald-500/20 text-emerald-300 border-emerald-500/40',
51 },
52 'not-relevant': {
53 label: 'Not relevant',
54 cls: 'bg-gray-500/20 text-gray-300 border-gray-500/40',
55 },
56 uncertain: {
57 label: 'Uncertain',
58 cls: 'bg-amber-500/20 text-amber-300 border-amber-500/40',
59 },
60}
61
62function VerdictChip({ verdict }: { verdict: Verdict }) {
63 const s = VERDICT_STYLES[verdict]
64 return (
65 <span
66 className={`inline-block rounded-full border px-3 py-1 text-xs font-medium ${s.cls}`}
67 >
68 {s.label}
69 </span>
70 )
71}
72
73// ---------------------------------------------------------------------------
74// FileEventsStrip — fed by the file.changed custom event (git diff string)
75// ---------------------------------------------------------------------------
76
77interface FileChangedEvent {
78 path: string
79 diff: string
80}
81
82function FileEventsStrip({ events }: { events: Array<FileChangedEvent> }) {
83 if (events.length === 0) return null
84 return (
85 <div className="border-t border-indigo-500/10 bg-gray-900/60 px-4 py-2 text-xs font-mono text-gray-400">
86 <div className="mb-1 flex items-center gap-1 text-indigo-300">
87 <FileText className="w-3 h-3" /> changed files
88 </div>
89 {events.map((e, i) => (
90 <div key={`${e.path}-${i}`} className="mt-1">
91 <div className="text-indigo-200 mb-0.5">{e.path}</div>
92 <pre className="overflow-x-auto max-h-40 overflow-y-auto whitespace-pre text-gray-400 bg-gray-800/50 rounded p-2">
93 {e.diff}
94 </pre>
95 </div>
96 ))}
97 </div>
98 )
99}
100
101// ---------------------------------------------------------------------------
102// CodeModeStrip — live log from code-mode (execute_typescript) custom events,
103// bridged back from inside the sandbox via the tool bridge.
104// ---------------------------------------------------------------------------
105
106interface CodeModeLine {
107 kind: 'start' | 'console'
108 level?: string
109 text: string
110}
111
112const LEVEL_CLS: Record<string, string> = {
113 error: 'text-red-300',
114 warn: 'text-amber-300',
115 info: 'text-sky-300',
116 log: 'text-gray-300',
117}
118
119function CodeModeStrip({ lines }: { lines: Array<CodeModeLine> }) {
120 if (lines.length === 0) return null
121 return (
122 <div className="border-t border-violet-500/10 bg-gray-900/60 px-4 py-2 text-xs font-mono">
123 <div className="mb-1 flex items-center gap-1 text-violet-300">
124 <Terminal className="w-3 h-3" /> code mode
125 </div>
126 <pre className="overflow-x-auto max-h-40 overflow-y-auto whitespace-pre-wrap bg-gray-800/50 rounded p-2">
127 {lines.map((line, i) =>
128 line.kind === 'start' ? (
129 <div key={i} className="text-violet-200">
130 ▶ {line.text}
131 </div>
132 ) : (
133 <div
134 key={i}
135 className={LEVEL_CLS[line.level ?? 'log'] ?? 'text-gray-300'}
136 >
137 {line.text}
138 </div>
139 ),
140 )}
141 </pre>
142 </div>
143 )
144}
145
146// ---------------------------------------------------------------------------
147// ToolCall — copied verbatim from sandbox-web/src/routes/index.tsx
148// ---------------------------------------------------------------------------
149
150function ToolCall({
151 name,
152 args,
153 output,
154}: {
155 name: string
156 args: string
157 output?: unknown
158}) {
159 let parsedArgs: unknown = args
160 try {
161 parsedArgs = JSON.parse(args)
162 } catch {
163 // leave as the raw string
164 }
165 const running = output === undefined
166 return (
167 <div className="mt-3 rounded-lg border border-indigo-500/30 bg-indigo-900/10 overflow-hidden">
168 <div className="flex items-center gap-2 px-3 py-2 bg-indigo-900/20 text-indigo-300 text-sm">
169 {running ? (
170 <div className="w-4 h-4 border-2 border-indigo-400 border-t-transparent rounded-full animate-spin" />
171 ) : (
172 <div className="w-4 h-4 rounded-full bg-indigo-500/50" />
173 )}
174 <span className="font-mono font-medium">{name}</span>
175 </div>
176 <pre className="px-3 py-2 text-xs text-gray-300 overflow-x-auto max-h-40 overflow-y-auto">
177 {typeof parsedArgs === 'string'
178 ? parsedArgs
179 : JSON.stringify(parsedArgs, null, 2)}
180 </pre>
181 {output !== undefined && (
182 <pre className="px-3 pb-3 text-xs text-gray-400 border-t border-indigo-500/20 overflow-x-auto max-h-40 overflow-y-auto">
183 {typeof output === 'string'
184 ? output
185 : JSON.stringify(output, null, 2)}
186 </pre>
187 )}
188 </div>
189 )
190}
191
192// ---------------------------------------------------------------------------
193// SandboxWaiting — aligned with sandbox-web/src/routes/index.tsx
194// ---------------------------------------------------------------------------
195
196type SandboxWaitKind = 'boot' | 'continue'
197
198function SandboxWaiting({ kind }: { kind: SandboxWaitKind }) {
199 const headline = kind === 'boot' ? 'Starting sandbox…' : 'Agent is working…'
200 const detail =
201 kind === 'boot'
202 ? 'starting the sandbox container and coding agent. The first message takes a moment.'
203 : 'resuming the sandbox and continuing the conversation.'
204 return (
205 <div className="p-4">
206 <div className="flex items-start gap-4">
207 <div className="w-8 h-8 rounded-lg flex items-center justify-center bg-linear-to-r from-indigo-500 to-violet-600 shrink-0">
208 <Server className="w-4 h-4 text-white" />
209 </div>
210 <div className="flex items-center gap-3 rounded-lg border border-indigo-500/30 bg-indigo-900/10 px-4 py-3">
211 <div className="w-4 h-4 border-2 border-indigo-400 border-t-transparent rounded-full animate-spin" />
212 <p className="text-sm">
213 <span className="font-medium text-indigo-200">{headline}</span>{' '}
214 <span className="text-gray-400">{detail}</span>
215 </p>
216 </div>
217 </div>
218 </div>
219 )
220}
221
222function sandboxWaitKind(
223 isLoading: boolean,
224 messages: ReadonlyArray<UIMessage>,
225): SandboxWaitKind | false {
226 if (
227 !isLoading ||
228 messages.length === 0 ||
229 messages[messages.length - 1].role !== 'user'
230 ) {
231 return false
232 }
233 return messages.some((m) => m.role === 'assistant') ? 'continue' : 'boot'
234}
235
236// ---------------------------------------------------------------------------
237// Messages — adapted from sandbox-web/src/routes/index.tsx:
238// - drops exposePreview / PreviewLink branch
239// - computes verdict per assistant message and renders VerdictChip
240// ---------------------------------------------------------------------------
241
242function Messages({
243 messages,
244 waiting,
245}: {
246 messages: ReadonlyArray<UIMessage>
247 waiting: SandboxWaitKind | false
248}) {
249 const containerRef = useRef<HTMLDivElement>(null)
250 useEffect(() => {
251 if (containerRef.current) {
252 containerRef.current.scrollTop = containerRef.current.scrollHeight
253 }
254 }, [messages, waiting])
255
256 if (!messages.length) {
257 return (
258 <div className="flex-1 flex items-center justify-center px-6 text-center text-gray-500">
259 <p className="max-w-md">
260 Pick a harness and provider, paste a GitHub issue URL, and click
261 Triage — the agent clones the repo into a sandbox and investigates
262 read-only, streaming tool calls live.
263 </p>
264 </div>
265 )
266 }
267
268 return (
269 <div
270 ref={containerRef}
271 className="flex-1 overflow-y-auto px-4 py-4"
272 style={{ scrollbarWidth: 'thin' }}
273 >
274 {messages.map((message) => {
275 const results = new Map<string, string>()
276 for (const part of message.parts) {
277 if (part.type === 'tool-result') {
278 results.set(
279 part.toolCallId,
280 typeof part.content === 'string'
281 ? part.content
282 : JSON.stringify(part.content),
283 )
284 }
285 }
286
287 // Compute verdict for assistant messages by joining all text parts.
288 const verdict =
289 message.role === 'assistant'
290 ? parseVerdict(
291 message.parts
292 .flatMap((p) => (p.type === 'text' ? [p.content] : []))
293 .join('\n'),
294 )
295 : null
296
297 return (
298 <div
299 key={message.id}
300 className={`p-4 rounded-lg mb-2 ${
301 message.role === 'assistant'
302 ? 'bg-linear-to-r from-indigo-500/5 to-violet-600/5'
303 : 'bg-transparent'
304 }`}
305 >
306 <div className="flex items-start gap-4">
307 <div
308 className={`w-8 h-8 rounded-lg flex items-center justify-center text-sm font-medium text-white shrink-0 ${
309 message.role === 'assistant'
310 ? 'bg-linear-to-r from-indigo-500 to-violet-600'
311 : 'bg-gray-700'
312 }`}
313 >
314 {message.role === 'assistant' ? 'AI' : 'U'}
315 </div>
316 <div className="flex-1 min-w-0">
317 {verdict && (
318 <div className="mb-2">
319 <VerdictChip verdict={verdict} />
320 </div>
321 )}
322 {message.parts.map((part, index) => {
323 if (part.type === 'text' && part.content) {
324 return (
325 <div key={`text-${index}`} className="markdown-content">
326 <ReactMarkdown
327 remarkPlugins={[remarkGfm]}
328 rehypePlugins={[
329 rehypeRaw,
330 rehypeSanitize,
331 rehypeHighlight,
332 ]}
333 >
334 {part.content}
335 </ReactMarkdown>
336 </div>
337 )
338 }
339 if (part.type === 'tool-call') {
340 const resultContent = results.get(part.id)
341 const output = part.output ?? resultContent
342 return (
343 <ToolCall
344 key={part.id}
345 name={part.name}
346 args={part.arguments}
347 output={output}
348 />
349 )
350 }
351 return null
352 })}
353 </div>
354 </div>
355 </div>
356 )
357 })}
358 {waiting && <SandboxWaiting kind={waiting} />}
359 </div>
360 )
361}
362
363// ---------------------------------------------------------------------------
364// SandboxesPage
365// ---------------------------------------------------------------------------
366
367function SandboxesPage() {
368 const [threadId] = useState(() => crypto.randomUUID())
369 const [harness, setHarness] = useState<HarnessName>('grok')
370 const [provider, setProvider] = useState<ProviderName>('docker')
371 const [issueUrl, setIssueUrl] = useState(
372 'https://github.com/TanStack/ai/issues/859',
373 )
374 const [fileEvents, setFileEvents] = useState<Array<FileChangedEvent>>([])
375 const [codeModeLines, setCodeModeLines] = useState<Array<CodeModeLine>>([])
376 const [keepAlive, setKeepAlive] = useState(false)
377 const [useSubscription, setUseSubscription] = useState(false)
378 const [grokModel, setGrokModel] = useState<GrokBuildModel>('composer-2.5')
379 const [grokProtocol, setGrokProtocol] = useState<GrokBuildProtocol>('acp')
380 const [grokTransport, setGrokTransport] = useState<GrokTransport>('auto')
381
382 // Subscription auth only applies to Claude Code on the local-process provider.
383 const canUseSubscription = provider === 'local' && harness === 'claude-code'
384
385 const { messages, sendMessage, isLoading, stop, error } = useChat({
386 threadId,
387 connection: fetchServerSentEvents('/api/sandbox-triage'),
388 forwardedProps: {
389 harness,
390 provider,
391 issueUrl,
392 threadId,
393 keepAlive,
394 useSubscription: canUseSubscription && useSubscription,
395 ...(harness === 'grok' ? { grokModel, grokProtocol, grokTransport } : {}),
396 },
397 onCustomEvent: (eventType, data) => {
398 if (data === null || typeof data !== 'object') return
399 if (
400 eventType === 'file.changed' &&
401 'diff' in data &&
402 typeof data.diff === 'string'
403 ) {
404 const diff = data.diff
405 const path =
406 'path' in data && typeof data.path === 'string' ? data.path : '.'
407 setFileEvents((prev) => [...prev, { path, diff }])
408 return
409 }
410 // Code-mode progress, bridged from inside the sandbox.
411 if (eventType === 'code_mode:execution_started') {
412 const chars =
413 'codeLength' in data && typeof data.codeLength === 'number'
414 ? ` (${data.codeLength} chars)`
415 : ''
416 setCodeModeLines((prev) => [
417 ...prev,
418 { kind: 'start', text: `executing TypeScript${chars}…` },
419 ])
420 return
421 }
422 if (eventType === 'code_mode:console') {
423 const level =
424 'level' in data && typeof data.level === 'string' ? data.level : 'log'
425 const message =
426 'message' in data && typeof data.message === 'string'
427 ? data.message
428 : JSON.stringify(data)
429 setCodeModeLines((prev) => [
430 ...prev,
431 { kind: 'console', level, text: message },
432 ])
433 }
434 },
435 })
436
437 // Live elapsed timer while a run is in flight — makes a long, quiet step
438 // (e.g. a code-mode execution) visibly "still running", not hung.
439 const [elapsed, setElapsed] = useState(0)
440 useEffect(() => {
441 if (!isLoading) return
442 const startedAt = Date.now()
443 setElapsed(0)
444 const id = setInterval(
445 () => setElapsed(Math.floor((Date.now() - startedAt) / 1000)),
446 1000,
447 )
448 return () => clearInterval(id)
449 }, [isLoading])
450
451 const canRun = useMemo(
452 () => /\/issues\/\d+/.test(issueUrl) && !isLoading,
453 [issueUrl, isLoading],
454 )
455
456 // A run finished (not loading, no error) but the last message is still the
457 // user's — the agent streamed no assistant content. Surfaces the otherwise
458 // invisible "completed with zero output" case.
459 const noOutput = !isLoading && !error && messages.at(-1)?.role === 'user'
460
461 function run() {
462 if (!canRun) return
463 setFileEvents([])
464 setCodeModeLines([])
465 sendMessage(`Triage ${issueUrl}`)
466 }
467
468 const elapsedLabel = `${Math.floor(elapsed / 60)}:${String(elapsed % 60).padStart(2, '0')}`
469
470 return (
471 <div className="flex flex-col h-screen bg-gray-900 text-white">
472 <header className="flex items-center gap-3 border-b border-indigo-500/10 bg-gray-900/80 px-4 py-3 backdrop-blur-sm">
473 <Github className="w-5 h-5 text-indigo-400" />
474 <span className="font-semibold">Sandbox Issue Triage</span>
475 <span className="text-xs text-gray-500">
476 clone a repo · investigate · root-cause
477 </span>
478 </header>
479
480 <div className="border-b border-indigo-500/10 bg-gray-900/60 px-4 py-3 flex flex-wrap items-center gap-3">
481 <select
482 value={harness}
483 onChange={(e) => setHarness(e.target.value as HarnessName)}
484 disabled={isLoading}
485 className="rounded-lg border border-indigo-500/20 bg-gray-800 px-3 py-2 text-sm"
486 >
487 {Object.entries(HARNESSES).map(([name, spec]) => (
488 <option key={name} value={name}>
489 {spec.label}
490 </option>
491 ))}
492 </select>
493 <select
494 value={provider}
495 onChange={(e) => setProvider(e.target.value as ProviderName)}
496 disabled={isLoading}
497 className="rounded-lg border border-indigo-500/20 bg-gray-800 px-3 py-2 text-sm"
498 >
499 {Object.entries(PROVIDERS).map(([name, spec]) => (
500 <option key={name} value={name}>
501 {spec.label}
502 </option>
503 ))}
504 </select>
505 {harness === 'grok' && (
506 <>
507 <select
508 value={grokModel}
509 onChange={(e) => {
510 if (isGrokModel(e.target.value)) {
511 setGrokModel(e.target.value)
512 }
513 }}
514 disabled={isLoading}
515 title="Grok Build model"
516 className="rounded-lg border border-indigo-500/20 bg-gray-800 px-3 py-2 text-sm"
517 >
518 {GROK_MODEL_OPTIONS.map((o) => (
519 <option key={o.value} value={o.value}>
520 {o.label}
521 </option>
522 ))}
523 </select>
524 <select
525 value={grokProtocol}
526 onChange={(e) => {
527 if (isGrokProtocol(e.target.value)) {
528 setGrokProtocol(e.target.value)
529 }
530 }}
531 disabled={isLoading}
532 title="Grok Build wire protocol"
533 className="rounded-lg border border-indigo-500/20 bg-gray-800 px-3 py-2 text-sm"
534 >
535 {GROK_PROTOCOL_OPTIONS.map((o) => (
536 <option key={o.value} value={o.value}>
537 {o.label}
538 </option>
539 ))}
540 </select>
541 {grokProtocol === 'acp' && (
542 <select
543 value={grokTransport}
544 onChange={(e) => {
545 if (isGrokTransport(e.target.value)) {
546 setGrokTransport(e.target.value)
547 }
548 }}
549 disabled={isLoading}
550 title="ACP transport (auto picks stdio vs WebSocket)"
551 className="rounded-lg border border-indigo-500/20 bg-gray-800 px-3 py-2 text-sm"
552 >
553 {GROK_TRANSPORT_OPTIONS.map((o) => (
554 <option key={o.value} value={o.value}>
555 {o.label}
556 </option>
557 ))}
558 </select>
559 )}
560 </>
561 )}
562 <input
563 value={issueUrl}
564 onChange={(e) => setIssueUrl(e.target.value)}
565 disabled={isLoading}
566 placeholder="https://github.com/owner/repo/issues/123"
567 className="flex-1 min-w-[18rem] rounded-lg border border-indigo-500/20 bg-gray-800 px-3 py-2 text-sm placeholder-gray-500"
568 onKeyDown={(e) => {
569 if (e.key === 'Enter') run()
570 }}
571 />
572 <label
573 className="flex items-center gap-1.5 text-xs text-gray-400 select-none"
574 title="By default the sandbox is destroyed after the run (success, error, or stop). Check to keep it alive."
575 >
576 <input
577 type="checkbox"
578 checked={keepAlive}
579 onChange={(e) => setKeepAlive(e.target.checked)}
580 disabled={isLoading}
581 />
582 keep sandbox
583 </label>
584 <label
585 className={`flex items-center gap-1.5 text-xs select-none ${
586 canUseSubscription ? 'text-gray-400' : 'text-gray-600'
587 }`}
588 title={
589 canUseSubscription
590 ? 'Use your logged-in Claude Code subscription instead of the API key (no API billing). Requires `claude login` on the host.'
591 : 'Only available for Claude Code on the Local process provider.'
592 }
593 >
594 <input
595 type="checkbox"
596 checked={canUseSubscription && useSubscription}
597 onChange={(e) => setUseSubscription(e.target.checked)}
598 disabled={isLoading || !canUseSubscription}
599 />
600 use my subscription
601 </label>
602 {isLoading ? (
603 <button
604 onClick={stop}
605 className="flex items-center gap-2 rounded-lg bg-red-600 px-4 py-2 text-sm font-medium hover:bg-red-700"
606 >
607 <Square className="w-4 h-4 fill-current" /> Stop
608 <span className="font-mono tabular-nums text-red-100/80">
609 {elapsedLabel}
610 </span>
611 </button>
612 ) : (
613 <button
614 onClick={run}
615 disabled={!canRun}
616 className="flex items-center gap-2 rounded-lg bg-indigo-600 px-4 py-2 text-sm font-medium hover:bg-indigo-700 disabled:opacity-50"
617 >
618 <Play className="w-4 h-4" /> Triage
619 </button>
620 )}
621 </div>
622
623 {error && (
624 <div className="mx-auto mt-3 flex max-w-4xl w-full items-start gap-2 rounded-lg border border-red-500/40 bg-red-900/20 px-4 py-3 text-sm text-red-200">
625 <AlertTriangle className="mt-0.5 h-4 w-4 shrink-0 text-red-400" />
626 <div className="min-w-0">
627 <div className="font-medium text-red-300">Run failed</div>
628 <pre className="mt-1 whitespace-pre-wrap break-words font-mono text-xs text-red-200/90">
629 {error.message}
630 </pre>
631 </div>
632 </div>
633 )}
634 {noOutput && (
635 <div className="mx-auto mt-3 flex max-w-4xl w-full items-start gap-2 rounded-lg border border-amber-500/40 bg-amber-900/20 px-4 py-3 text-sm text-amber-200">
636 <AlertTriangle className="mt-0.5 h-4 w-4 shrink-0 text-amber-400" />
637 <span>
638 The run finished but the agent produced no output. Check the dev
639 server logs for details (e.g. a sandbox or CLI error).
640 </span>
641 </div>
642 )}
643
644 <div className="flex-1 flex flex-col max-w-4xl mx-auto w-full overflow-hidden">
645 <Messages
646 messages={messages}
647 waiting={sandboxWaitKind(isLoading, messages)}
648 />
649 </div>
650 <CodeModeStrip lines={codeModeLines} />
651 <FileEventsStrip events={fileEvents} />
652 </div>
653 )
654}