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: Array<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: Array<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 connection: fetchServerSentEvents('/api/sandbox-triage'),
387 body: {
388 harness,
389 provider,
390 issueUrl,
391 threadId,
392 keepAlive,
393 useSubscription: canUseSubscription && useSubscription,
394 ...(harness === 'grok' ? { grokModel, grokProtocol, grokTransport } : {}),
395 },
396 onCustomEvent: (eventType, data) => {
397 if (data === null || typeof data !== 'object') return
398 if (
399 eventType === 'file.changed' &&
400 'diff' in data &&
401 typeof data.diff === 'string'
402 ) {
403 const diff = data.diff
404 const path =
405 'path' in data && typeof data.path === 'string' ? data.path : '.'
406 setFileEvents((prev) => [...prev, { path, diff }])
407 return
408 }
409 // Code-mode progress, bridged from inside the sandbox.
410 if (eventType === 'code_mode:execution_started') {
411 const chars =
412 'codeLength' in data && typeof data.codeLength === 'number'
413 ? ` (${data.codeLength} chars)`
414 : ''
415 setCodeModeLines((prev) => [
416 ...prev,
417 { kind: 'start', text: `executing TypeScript${chars}…` },
418 ])
419 return
420 }
421 if (eventType === 'code_mode:console') {
422 const level =
423 'level' in data && typeof data.level === 'string' ? data.level : 'log'
424 const message =
425 'message' in data && typeof data.message === 'string'
426 ? data.message
427 : JSON.stringify(data)
428 setCodeModeLines((prev) => [
429 ...prev,
430 { kind: 'console', level, text: message },
431 ])
432 }
433 },
434 })
435
436 // Live elapsed timer while a run is in flight — makes a long, quiet step
437 // (e.g. a code-mode execution) visibly "still running", not hung.
438 const [elapsed, setElapsed] = useState(0)
439 useEffect(() => {
440 if (!isLoading) return
441 const startedAt = Date.now()
442 setElapsed(0)
443 const id = setInterval(
444 () => setElapsed(Math.floor((Date.now() - startedAt) / 1000)),
445 1000,
446 )
447 return () => clearInterval(id)
448 }, [isLoading])
449
450 const canRun = useMemo(
451 () => /\/issues\/\d+/.test(issueUrl) && !isLoading,
452 [issueUrl, isLoading],
453 )
454
455 // A run finished (not loading, no error) but the last message is still the
456 // user's — the agent streamed no assistant content. Surfaces the otherwise
457 // invisible "completed with zero output" case.
458 const noOutput = !isLoading && !error && messages.at(-1)?.role === 'user'
459
460 function run() {
461 if (!canRun) return
462 setFileEvents([])
463 setCodeModeLines([])
464 sendMessage(`Triage ${issueUrl}`)
465 }
466
467 const elapsedLabel = `${Math.floor(elapsed / 60)}:${String(elapsed % 60).padStart(2, '0')}`
468
469 return (
470 <div className="flex flex-col h-screen bg-gray-900 text-white">
471 <header className="flex items-center gap-3 border-b border-indigo-500/10 bg-gray-900/80 px-4 py-3 backdrop-blur-sm">
472 <Github className="w-5 h-5 text-indigo-400" />
473 <span className="font-semibold">Sandbox Issue Triage</span>
474 <span className="text-xs text-gray-500">
475 clone a repo · investigate · root-cause
476 </span>
477 </header>
478
479 <div className="border-b border-indigo-500/10 bg-gray-900/60 px-4 py-3 flex flex-wrap items-center gap-3">
480 <select
481 value={harness}
482 onChange={(e) => setHarness(e.target.value as HarnessName)}
483 disabled={isLoading}
484 className="rounded-lg border border-indigo-500/20 bg-gray-800 px-3 py-2 text-sm"
485 >
486 {Object.entries(HARNESSES).map(([name, spec]) => (
487 <option key={name} value={name}>
488 {spec.label}
489 </option>
490 ))}
491 </select>
492 <select
493 value={provider}
494 onChange={(e) => setProvider(e.target.value as ProviderName)}
495 disabled={isLoading}
496 className="rounded-lg border border-indigo-500/20 bg-gray-800 px-3 py-2 text-sm"
497 >
498 {Object.entries(PROVIDERS).map(([name, spec]) => (
499 <option key={name} value={name}>
500 {spec.label}
501 </option>
502 ))}
503 </select>
504 {harness === 'grok' && (
505 <>
506 <select
507 value={grokModel}
508 onChange={(e) => {
509 if (isGrokModel(e.target.value)) {
510 setGrokModel(e.target.value)
511 }
512 }}
513 disabled={isLoading}
514 title="Grok Build model"
515 className="rounded-lg border border-indigo-500/20 bg-gray-800 px-3 py-2 text-sm"
516 >
517 {GROK_MODEL_OPTIONS.map((o) => (
518 <option key={o.value} value={o.value}>
519 {o.label}
520 </option>
521 ))}
522 </select>
523 <select
524 value={grokProtocol}
525 onChange={(e) => {
526 if (isGrokProtocol(e.target.value)) {
527 setGrokProtocol(e.target.value)
528 }
529 }}
530 disabled={isLoading}
531 title="Grok Build wire protocol"
532 className="rounded-lg border border-indigo-500/20 bg-gray-800 px-3 py-2 text-sm"
533 >
534 {GROK_PROTOCOL_OPTIONS.map((o) => (
535 <option key={o.value} value={o.value}>
536 {o.label}
537 </option>
538 ))}
539 </select>
540 {grokProtocol === 'acp' && (
541 <select
542 value={grokTransport}
543 onChange={(e) => {
544 if (isGrokTransport(e.target.value)) {
545 setGrokTransport(e.target.value)
546 }
547 }}
548 disabled={isLoading}
549 title="ACP transport (auto picks stdio vs WebSocket)"
550 className="rounded-lg border border-indigo-500/20 bg-gray-800 px-3 py-2 text-sm"
551 >
552 {GROK_TRANSPORT_OPTIONS.map((o) => (
553 <option key={o.value} value={o.value}>
554 {o.label}
555 </option>
556 ))}
557 </select>
558 )}
559 </>
560 )}
561 <input
562 value={issueUrl}
563 onChange={(e) => setIssueUrl(e.target.value)}
564 disabled={isLoading}
565 placeholder="https://github.com/owner/repo/issues/123"
566 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"
567 onKeyDown={(e) => {
568 if (e.key === 'Enter') run()
569 }}
570 />
571 <label
572 className="flex items-center gap-1.5 text-xs text-gray-400 select-none"
573 title="By default the sandbox is destroyed after the run (success, error, or stop). Check to keep it alive."
574 >
575 <input
576 type="checkbox"
577 checked={keepAlive}
578 onChange={(e) => setKeepAlive(e.target.checked)}
579 disabled={isLoading}
580 />
581 keep sandbox
582 </label>
583 <label
584 className={`flex items-center gap-1.5 text-xs select-none ${
585 canUseSubscription ? 'text-gray-400' : 'text-gray-600'
586 }`}
587 title={
588 canUseSubscription
589 ? 'Use your logged-in Claude Code subscription instead of the API key (no API billing). Requires `claude login` on the host.'
590 : 'Only available for Claude Code on the Local process provider.'
591 }
592 >
593 <input
594 type="checkbox"
595 checked={canUseSubscription && useSubscription}
596 onChange={(e) => setUseSubscription(e.target.checked)}
597 disabled={isLoading || !canUseSubscription}
598 />
599 use my subscription
600 </label>
601 {isLoading ? (
602 <button
603 onClick={stop}
604 className="flex items-center gap-2 rounded-lg bg-red-600 px-4 py-2 text-sm font-medium hover:bg-red-700"
605 >
606 <Square className="w-4 h-4 fill-current" /> Stop
607 <span className="font-mono tabular-nums text-red-100/80">
608 {elapsedLabel}
609 </span>
610 </button>
611 ) : (
612 <button
613 onClick={run}
614 disabled={!canRun}
615 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"
616 >
617 <Play className="w-4 h-4" /> Triage
618 </button>
619 )}
620 </div>
621
622 {error && (
623 <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">
624 <AlertTriangle className="mt-0.5 h-4 w-4 shrink-0 text-red-400" />
625 <div className="min-w-0">
626 <div className="font-medium text-red-300">Run failed</div>
627 <pre className="mt-1 whitespace-pre-wrap break-words font-mono text-xs text-red-200/90">
628 {error.message}
629 </pre>
630 </div>
631 </div>
632 )}
633 {noOutput && (
634 <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">
635 <AlertTriangle className="mt-0.5 h-4 w-4 shrink-0 text-amber-400" />
636 <span>
637 The run finished but the agent produced no output. Check the dev
638 server logs for details (e.g. a sandbox or CLI error).
639 </span>
640 </div>
641 )}
642
643 <div className="flex-1 flex flex-col max-w-4xl mx-auto w-full overflow-hidden">
644 <Messages
645 messages={messages}
646 waiting={sandboxWaitKind(isLoading, messages)}
647 />
648 </div>
649 <CodeModeStrip lines={codeModeLines} />
650 <FileEventsStrip events={fileEvents} />
651 </div>
652 )
653}