Skip to content
Source
Sign inSign up
TanStack/ai
Open History to see the last commit

sandboxes-durable.tsx

961 lines34.9 KB

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-durable')({
40 component: SandboxesPage,
41})
42​
43/**
44 * The thread INDEX (which threads exist, and their titles) is small app state and
45 * lives in localStorage. The transcripts themselves live on the SERVER, one per
46 * thread id — this list is only how the UI enumerates and labels them. Same split
47 * as `/persistent-chat`.
48 *
49 * A stable id per thread is not cosmetic here: it is the whole mechanism. The
50 * server stores the run and transcript under it, and `useChat` hydrates by it on
51 * mount. `/sandboxes` mints a fresh uuid per mount, which is correct there (each
52 * visit is a one-off triage) and would make durability untestable here.
53 */
54const THREADS_KEY = 'sandboxes-durable:threads'
55​
56interface Thread {
57 id: string
58 title: string
60​
61function loadThreads(): Array<Thread> {
62 if (typeof window === 'undefined') return []
63 try {
64 const raw = window.localStorage.getItem(THREADS_KEY)
65 const parsed: unknown = raw ? JSON.parse(raw) : null
66 return Array.isArray(parsed) ? (parsed as Array<Thread>) : []
67 } catch {
68 return []
69 }
71​
72function newThread(): Thread {
73 return { id: `thread-${crypto.randomUUID()}`, title: 'New triage' }
75​
76/**
77 * One connection instance for every thread. `useChat` keys both the hydration GET
78 * (`?threadId`) and the run itself on the thread id, so switching threads reuses
79 * this without rebuilding it.
80 */
81const connection = fetchServerSentEvents('/api/sandbox-triage-durable')
82​
83/** Per-thread run state, as the sidebar shows it. */
84interface ThreadStatus {
85 status: 'running' | 'idle' | 'unknown'
86 detached?: boolean
88​
89/**
90 * Poll per-thread run status for the sidebar.
91 *
92 * Server-owned on purpose: a run keeps going while nobody watches, so the only
93 * truthful source for "is this thread busy?" is the run store — never client
94 * state, which by definition knows nothing about the threads you are not looking
95 * at. One request covers every thread (`?statuses=a,b,c`).
96 */
97/** Cadence while at least one run is going. */
98const STATUS_POLL_ACTIVE_MS = 2500
99/** Cadence when every thread is idle — the usual case, so keep it cheap. */
100const STATUS_POLL_IDLE_MS = 30_000
101​
102function useThreadStatuses(ids: Array<string>): Record<string, ThreadStatus> {
103 const [statuses, setStatuses] = useState<Record<string, ThreadStatus>>({})
104 // Join into a primitive so the effect re-runs when the SET changes, not on
105 // every render (a new array identity each time would poll in a loop).
106 const key = ids.join(',')
107 // Read inside the loop so the cadence can change without tearing the loop down
108 // and restarting it.
109 const anyRunningRef = useRef(false)
110​
111 useEffect(() => {
112 if (key === '') return
113 let cancelled = false
114 let timer: ReturnType<typeof setTimeout> | undefined
115 const controller = new AbortController()
116​
117 const poll = async () => {
118 try {
119 const res = await fetch(
120 `/api/sandbox-triage-durable?statuses=${encodeURIComponent(key)}`,
121 { signal: controller.signal },
122 )
123 if (!res.ok) return
124 const json: unknown = await res.json()
125 if (cancelled || json === null || typeof json !== 'object') return
126 const next = json as Record<string, ThreadStatus>
127 setStatuses(next)
128 anyRunningRef.current = Object.values(next).some(
129 (s) => s.status === 'running',
130 )
131 } catch {
132 // A failed poll leaves the previous chips in place — a transient blip
133 // must not make every thread flash to "unknown".
134 } finally {
135 // SELF-SCHEDULING, and only after the previous poll settled. Two reasons,
136 // both seen in a real session with 16 threads in this list:
137 //
138 // 1. A fixed `setInterval` kept firing while everything was idle and every
139 // run had finished — one request every 2.5s forever, each making the
140 // server run one `findActiveRun` per thread. It backs right off now.
141 // 2. `setInterval` does not wait for the previous request. When the page
142 // was short of connections the polls STACKED, which is what made the
143 // network tab look like a flood of the same URL. Scheduling from
144 // `finally` means at most one poll is ever in flight.
145 if (!cancelled) {
146 timer = setTimeout(
147 () => void poll(),
148 anyRunningRef.current ? STATUS_POLL_ACTIVE_MS : STATUS_POLL_IDLE_MS,
149 )
150 }
151 }
152 }
153​
154 void poll()
155 return () => {
156 cancelled = true
157 controller.abort()
158 if (timer !== undefined) clearTimeout(timer)
159 }
160 }, [key])
161​
162 return statuses
164​
165function StatusDot({ status }: { status: ThreadStatus | undefined }) {
166 if (status?.status === 'running') {
167 return (
168 <span
169 title={
170 status.detached ? 'running (detached — nobody attached)' : 'running'
171 }
172 className={`inline-block h-2 w-2 shrink-0 rounded-full bg-emerald-400 ${
173 status.detached ? '' : 'animate-pulse'
174 }`}
175 />
176 )
177 }
178 return (
179 <span
180 title={status?.status === 'unknown' ? 'status unavailable' : 'idle'}
181 className="inline-block h-2 w-2 shrink-0 rounded-full bg-slate-600"
182 />
183 )
185​
186// ---------------------------------------------------------------------------
187// VerdictChip
188// ---------------------------------------------------------------------------
189​
190const VERDICT_STYLES: Record<Verdict, { label: string; cls: string }> = {
191 relevant: {
192 label: 'Relevant',
193 cls: 'bg-emerald-500/20 text-emerald-300 border-emerald-500/40',
194 },
195 'not-relevant': {
196 label: 'Not relevant',
197 cls: 'bg-gray-500/20 text-gray-300 border-gray-500/40',
198 },
199 uncertain: {
200 label: 'Uncertain',
201 cls: 'bg-amber-500/20 text-amber-300 border-amber-500/40',
202 },
204​
205function VerdictChip({ verdict }: { verdict: Verdict }) {
206 const s = VERDICT_STYLES[verdict]
207 return (
208 <span
209 className={`inline-block rounded-full border px-3 py-1 text-xs font-medium ${s.cls}`}
210 >
211 {s.label}
212 </span>
213 )
215​
216// ---------------------------------------------------------------------------
217// FileEventsStrip — fed by the file.changed custom event (git diff string)
218// ---------------------------------------------------------------------------
219​
220interface FileChangedEvent {
221 path: string
222 diff: string
224​
225function FileEventsStrip({ events }: { events: Array<FileChangedEvent> }) {
226 if (events.length === 0) return null
227 return (
228 <div className="border-t border-indigo-500/10 bg-gray-900/60 px-4 py-2 text-xs font-mono text-gray-400">
229 <div className="mb-1 flex items-center gap-1 text-indigo-300">
230 <FileText className="w-3 h-3" /> changed files
231 </div>
232 {events.map((e, i) => (
233 <div key={`${e.path}-${i}`} className="mt-1">
234 <div className="text-indigo-200 mb-0.5">{e.path}</div>
235 <pre className="overflow-x-auto max-h-40 overflow-y-auto whitespace-pre text-gray-400 bg-gray-800/50 rounded p-2">
236 {e.diff}
237 </pre>
238 </div>
239 ))}
240 </div>
241 )
243​
244// ---------------------------------------------------------------------------
245// CodeModeStrip — live log from code-mode (execute_typescript) custom events,
246// bridged back from inside the sandbox via the tool bridge.
247// ---------------------------------------------------------------------------
248​
249interface CodeModeLine {
250 kind: 'start' | 'console'
251 level?: string
252 text: string
254​
255const LEVEL_CLS: Record<string, string> = {
256 error: 'text-red-300',
257 warn: 'text-amber-300',
258 info: 'text-sky-300',
259 log: 'text-gray-300',
261​
262function CodeModeStrip({ lines }: { lines: Array<CodeModeLine> }) {
263 if (lines.length === 0) return null
264 return (
265 <div className="border-t border-violet-500/10 bg-gray-900/60 px-4 py-2 text-xs font-mono">
266 <div className="mb-1 flex items-center gap-1 text-violet-300">
267 <Terminal className="w-3 h-3" /> code mode
268 </div>
269 <pre className="overflow-x-auto max-h-40 overflow-y-auto whitespace-pre-wrap bg-gray-800/50 rounded p-2">
270 {lines.map((line, i) =>
271 line.kind === 'start' ? (
272 <div key={i} className="text-violet-200">
273 ▶ {line.text}
274 </div>
275 ) : (
276 <div
277 key={i}
278 className={LEVEL_CLS[line.level ?? 'log'] ?? 'text-gray-300'}
279 >
280 {line.text}
281 </div>
282 ),
283 )}
284 </pre>
285 </div>
286 )
288​
289// ---------------------------------------------------------------------------
290// ToolCall — copied verbatim from sandbox-web/src/routes/index.tsx
291// ---------------------------------------------------------------------------
292​
293function ToolCall({
294 name,
295 args,
296 output,
297}: {
298 name: string
299 args: string
300 output?: unknown
301}) {
302 let parsedArgs: unknown = args
303 try {
304 parsedArgs = JSON.parse(args)
305 } catch {
306 // leave as the raw string
307 }
308 const running = output === undefined
309 return (
310 <div className="mt-3 rounded-lg border border-indigo-500/30 bg-indigo-900/10 overflow-hidden">
311 <div className="flex items-center gap-2 px-3 py-2 bg-indigo-900/20 text-indigo-300 text-sm">
312 {running ? (
313 <div className="w-4 h-4 border-2 border-indigo-400 border-t-transparent rounded-full animate-spin" />
314 ) : (
315 <div className="w-4 h-4 rounded-full bg-indigo-500/50" />
316 )}
317 <span className="font-mono font-medium">{name}</span>
318 </div>
319 <pre className="px-3 py-2 text-xs text-gray-300 overflow-x-auto max-h-40 overflow-y-auto">
320 {typeof parsedArgs === 'string'
321 ? parsedArgs
322 : JSON.stringify(parsedArgs, null, 2)}
323 </pre>
324 {output !== undefined && (
325 <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">
326 {typeof output === 'string'
327 ? output
328 : JSON.stringify(output, null, 2)}
329 </pre>
330 )}
331 </div>
332 )
334​
335// ---------------------------------------------------------------------------
336// SandboxWaiting — aligned with sandbox-web/src/routes/index.tsx
337// ---------------------------------------------------------------------------
338​
339type SandboxWaitKind = 'boot' | 'continue'
340​
341function SandboxWaiting({ kind }: { kind: SandboxWaitKind }) {
342 const headline = kind === 'boot' ? 'Starting sandbox…' : 'Agent is working…'
343 const detail =
344 kind === 'boot'
345 ? 'starting the sandbox container and coding agent. The first message takes a moment.'
346 : 'resuming the sandbox and continuing the conversation.'
347 return (
348 <div className="p-4">
349 <div className="flex items-start gap-4">
350 <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">
351 <Server className="w-4 h-4 text-white" />
352 </div>
353 <div className="flex items-center gap-3 rounded-lg border border-indigo-500/30 bg-indigo-900/10 px-4 py-3">
354 <div className="w-4 h-4 border-2 border-indigo-400 border-t-transparent rounded-full animate-spin" />
355 <p className="text-sm">
356 <span className="font-medium text-indigo-200">{headline}</span>{' '}
357 <span className="text-gray-400">{detail}</span>
358 </p>
359 </div>
360 </div>
361 </div>
362 )
364​
365/**
366 * `isLoading` alone cannot answer this after a tab switch.
367 *
368 * A sandboxed run spends its first minutes inside `withSandbox`'s `ensure` —
369 * creating the sandbox, cloning the repo — and emits NOTHING until that finishes.
370 * A client returning in that window hydrates the transcript (which ends with the
371 * user's message) but has no stream to be "loading" from, so `isLoading` is false
372 * and the pane rendered empty: the run looked lost even though it was healthy and
373 * still working.
374 *
375 * `hasActiveRun` is the server's answer to the same question — `findActiveRun` on
376 * the run record — so the waiting state survives leaving and re-entering the
377 * thread. Either signal is sufficient: `isLoading` covers the tab that started the
378 * run, `hasActiveRun` covers every tab that comes back to it.
379 */
380export function sandboxWaitKind(
381 isLoading: boolean,
382 hasActiveRun: boolean,
383 messages: ReadonlyArray<UIMessage>,
384): SandboxWaitKind | false {
385 // "Nothing has come back for the current turn yet." An EMPTY transcript counts,
386 // and that is the case this used to get wrong: chat persistence saves the pending
387 // user turn from `onStart`, which — like the run record — runs after every
388 // middleware `setup`, so throughout the minutes a sandbox takes to build the
389 // hydration response is literally `{ messages: [], activeRun: { runId } }`.
390 // Requiring a message therefore hid the waiting state for exactly the window it
391 // exists to cover, and a returning tab rendered an empty pane.
392 const nothingYet =
393 messages.length === 0 || messages[messages.length - 1].role === 'user'
394 if (!nothingYet) return false
395 // `isLoading` covers the tab that started the run; `hasActiveRun` (the server's
396 // `findActiveRun`) covers every tab that comes back to it.
397 if (!isLoading && !hasActiveRun) return false
398 return messages.some((m) => m.role === 'assistant') ? 'continue' : 'boot'
400​
401// ---------------------------------------------------------------------------
402// Messages — adapted from sandbox-web/src/routes/index.tsx:
403// - drops exposePreview / PreviewLink branch
404// - computes verdict per assistant message and renders VerdictChip
405// ---------------------------------------------------------------------------
406​
407function Messages({
408 messages,
409 waiting,
410}: {
411 messages: ReadonlyArray<UIMessage>
412 waiting: SandboxWaitKind | false
413}) {
414 const containerRef = useRef<HTMLDivElement>(null)
415 useEffect(() => {
416 if (containerRef.current) {
417 containerRef.current.scrollTop = containerRef.current.scrollHeight
418 }
419 }, [messages, waiting])
420​
421 if (!messages.length) {
422 // A run can be in flight with NO messages: chat persistence saves the pending
423 // user turn from `onStart`, which runs after every middleware `setup`, so for
424 // the minutes a sandbox takes to build the hydration response is
425 // `{ messages: [], activeRun: { runId } }`. Returning the empty-state hint here
426 // unconditionally made the waiting panel unreachable in exactly that window —
427 // a tab coming back to a healthy, still-booting run was told to start one.
428 if (waiting) return <SandboxWaiting kind={waiting} />
429 return (
430 <div className="flex-1 flex items-center justify-center px-6 text-center text-gray-500">
431 <p className="max-w-md">
432 Pick a harness and provider, paste a GitHub issue URL, and click
433 Triage — the agent clones the repo into a sandbox and investigates
434 read-only, streaming tool calls live.
435 </p>
436 </div>
437 )
438 }
439​
440 return (
441 <div
442 ref={containerRef}
443 className="flex-1 overflow-y-auto px-4 py-4"
444 style={{ scrollbarWidth: 'thin' }}
445 >
446 {messages.map((message) => {
447 const results = new Map<string, string>()
448 for (const part of message.parts) {
449 if (part.type === 'tool-result') {
450 results.set(
451 part.toolCallId,
452 typeof part.content === 'string'
453 ? part.content
454 : JSON.stringify(part.content),
455 )
456 }
457 }
458​
459 // Compute verdict for assistant messages by joining all text parts.
460 const verdict =
461 message.role === 'assistant'
462 ? parseVerdict(
463 message.parts
464 .flatMap((p) => (p.type === 'text' ? [p.content] : []))
465 .join('\n'),
466 )
467 : null
468​
469 return (
470 <div
471 key={message.id}
472 className={`p-4 rounded-lg mb-2 ${
473 message.role === 'assistant'
474 ? 'bg-linear-to-r from-indigo-500/5 to-violet-600/5'
475 : 'bg-transparent'
476 }`}
477 >
478 <div className="flex items-start gap-4">
479 <div
480 className={`w-8 h-8 rounded-lg flex items-center justify-center text-sm font-medium text-white shrink-0 ${
481 message.role === 'assistant'
482 ? 'bg-linear-to-r from-indigo-500 to-violet-600'
483 : 'bg-gray-700'
484 }`}
485 >
486 {message.role === 'assistant' ? 'AI' : 'U'}
487 </div>
488 <div className="flex-1 min-w-0">
489 {verdict && (
490 <div className="mb-2">
491 <VerdictChip verdict={verdict} />
492 </div>
493 )}
494 {message.parts.map((part, index) => {
495 if (part.type === 'text' && part.content) {
496 return (
497 <div key={`text-${index}`} className="markdown-content">
498 <ReactMarkdown
499 remarkPlugins={[remarkGfm]}
500 rehypePlugins={[
501 rehypeRaw,
502 rehypeSanitize,
503 rehypeHighlight,
504 ]}
505 >
506 {part.content}
507 </ReactMarkdown>
508 </div>
509 )
510 }
511 if (part.type === 'tool-call') {
512 const resultContent = results.get(part.id)
513 const output = part.output ?? resultContent
514 return (
515 <ToolCall
516 key={part.id}
517 name={part.name}
518 args={part.arguments}
519 output={output}
520 />
521 )
522 }
523 return null
524 })}
525 </div>
526 </div>
527 </div>
528 )
529 })}
530 {waiting && <SandboxWaiting kind={waiting} />}
531 </div>
532 )
534​
535// ---------------------------------------------------------------------------
536// SandboxesPage
537// ---------------------------------------------------------------------------
538​
539/**
540 * Thread list + the active thread's pane. ChatGPT-shaped on purpose: the point of
541 * durable runs is that a conversation outlives the tab, which is only observable
542 * if you can leave a thread and come back to it.
543 */
544function SandboxesPage() {
545 const [threads, setThreads] = useState<Array<Thread>>([])
546 const [activeId, setActiveId] = useState<string | null>(null)
547 const [hydrated, setHydrated] = useState(false)
548​
549 // localStorage is unavailable during SSR, so the first render is empty on both
550 // sides (no hydration mismatch) and the index loads in an effect.
551 useEffect(() => {
552 const loaded = loadThreads()
553 if (loaded.length === 0) {
554 const first = newThread()
555 setThreads([first])
556 setActiveId(first.id)
557 } else {
558 setThreads(loaded)
559 setActiveId(loaded[0]!.id)
560 }
561 setHydrated(true)
562 }, [])
563​
564 useEffect(() => {
565 if (!hydrated) return
566 window.localStorage.setItem(THREADS_KEY, JSON.stringify(threads))
567 }, [threads, hydrated])
568​
569 // Server-owned run state for every thread in the list, not just the open one.
570 const statuses = useThreadStatuses(threads.map((t) => t.id))
571​
572 const createThread = () => {
573 const thread = newThread()
574 setThreads((prev) => [thread, ...prev])
575 setActiveId(thread.id)
576 }
577​
578 // Label a thread by the issue it triaged, so the sidebar is readable. A no-op
579 // once the thread has a real title, so it never churns state.
580 const titleThread = (id: string, title: string) => {
581 setThreads((prev) => {
582 const current = prev.find((t) => t.id === id)
583 if (!current || current.title !== 'New triage') return prev
584 return prev.map((t) => (t.id === id ? { ...t, title } : t))
585 })
586 }
587​
588 return (
589 <div className="flex h-screen bg-slate-950 text-slate-100">
590 <aside className="flex w-64 shrink-0 flex-col gap-2 border-r border-slate-800 p-3">
591 <button
592 type="button"
593 onClick={createThread}
594 className="rounded-md bg-cyan-600 px-3 py-2 text-sm font-medium text-white hover:bg-cyan-500"
595 >
596 + New triage
597 </button>
598 <div className="flex flex-col gap-1 overflow-y-auto">
599 {threads.map((thread) => {
600 const status = statuses[thread.id]
601 return (
602 <button
603 key={thread.id}
604 type="button"
605 onClick={() => setActiveId(thread.id)}
606 title={thread.id}
607 className={`flex items-center gap-2 rounded-md px-3 py-2 text-left text-sm ${
608 thread.id === activeId
609 ? 'bg-slate-800 text-white'
610 : 'text-slate-400 hover:bg-slate-900'
611 }`}
612 >
613 <StatusDot status={status} />
614 <span className="min-w-0 flex-1 truncate">{thread.title}</span>
615 {status?.status === 'running' ? (
616 <span className="shrink-0 text-[10px] uppercase tracking-wide text-emerald-400">
617 {status.detached ? 'detached' : 'running'}
618 </span>
619 ) : null}
620 </button>
621 )
622 })}
623 </div>
624 <p className="mt-auto text-[11px] leading-snug text-slate-500">
625 Transcripts live on the server, one per thread id. This list is just
626 the index. Start a run, then refresh or switch threads and come back —
627 the run keeps going and you rejoin it mid-stream.
628 </p>
629 </aside>
630​
631 <div className="min-w-0 flex-1 overflow-y-auto">
632 {activeId ? (
633 // Keyed by threadId: a fresh instance mounts per thread and hydrates
634 // that thread from the server. Nothing to wire beyond the id.
635 <TriagePane
636 key={activeId}
637 threadId={activeId}
638 // The same server-owned status the sidebar dot uses. Passed down so a
639 // thread re-entered while its sandbox is still booting shows the
640 // waiting state instead of an empty pane — the run emits nothing until
641 // `ensure` finishes, so the client cannot infer it from the stream.
642 hasActiveRun={statuses[activeId]?.status === 'running'}
643 onIssue={(title) => titleThread(activeId, title)}
644 />
645 ) : null}
646 </div>
647 </div>
648 )
650​
651function TriagePane({
652 threadId,
653 hasActiveRun,
654 onIssue,
655}: {
656 threadId: string
657 hasActiveRun: boolean
658 onIssue: (title: string) => void
659}) {
660 const [harness, setHarness] = useState<HarnessName>('grok')
661 const [provider, setProvider] = useState<ProviderName>('docker')
662 const [issueUrl, setIssueUrl] = useState(
663 'https://github.com/TanStack/ai/issues/859',
664 )
665 const [fileEvents, setFileEvents] = useState<Array<FileChangedEvent>>([])
666 const [codeModeLines, setCodeModeLines] = useState<Array<CodeModeLine>>([])
667 const [keepAlive, setKeepAlive] = useState(false)
668 const [useSubscription, setUseSubscription] = useState(false)
669 const [grokModel, setGrokModel] = useState<GrokBuildModel>('composer-2.5')
670 const [grokProtocol, setGrokProtocol] = useState<GrokBuildProtocol>('acp')
671 const [grokTransport, setGrokTransport] = useState<GrokTransport>('auto')
672​
673 // Subscription auth only applies to Claude Code on the local-process provider.
674 const canUseSubscription = provider === 'local' && harness === 'claude-code'
675​
676 const { messages, sendMessage, isLoading, stop, error } = useChat({
677 // TOP-LEVEL, not just in `body`. This is the id `useChat` hydrates by and the
678 // id the server stores the run and transcript under. Passing it only inside
679 // `body` (as `/sandboxes` does, where nothing rejoins) leaves the client
680 // hydrating a different, auto-generated thread than the one the server wrote
681 // — so a refresh finds nothing and the conversation looks wiped.
682 threadId,
683 connection,
684 // Server-authoritative: keep no transcript and no run pointer client-side.
685 // On mount `useChat` calls the route's GET itself (keyed by threadId), gets
686 // the stored transcript plus a cursor to any in-flight run, and tails that
687 // run through the replay branch. This flag plus a stable `threadId` is the
688 // whole of what makes a refresh resume.
689 persistence: true,
690 forwardedProps: {
691 harness,
692 provider,
693 issueUrl,
694 keepAlive,
695 useSubscription: canUseSubscription && useSubscription,
696 ...(harness === 'grok' ? { grokModel, grokProtocol, grokTransport } : {}),
697 },
698 onCustomEvent: (eventType, data) => {
699 if (data === null || typeof data !== 'object') return
700 if (
701 eventType === 'file.changed' &&
702 'diff' in data &&
703 typeof data.diff === 'string'
704 ) {
705 const diff = data.diff
706 const path =
707 'path' in data && typeof data.path === 'string' ? data.path : '.'
708 setFileEvents((prev) => [...prev, { path, diff }])
709 return
710 }
711 // Code-mode progress, bridged from inside the sandbox.
712 if (eventType === 'code_mode:execution_started') {
713 const chars =
714 'codeLength' in data && typeof data.codeLength === 'number'
715 ? ` (${data.codeLength} chars)`
716 : ''
717 setCodeModeLines((prev) => [
718 ...prev,
719 { kind: 'start', text: `executing TypeScript${chars}…` },
720 ])
721 return
722 }
723 if (eventType === 'code_mode:console') {
724 const level =
725 'level' in data && typeof data.level === 'string' ? data.level : 'log'
726 const message =
727 'message' in data && typeof data.message === 'string'
728 ? data.message
729 : JSON.stringify(data)
730 setCodeModeLines((prev) => [
731 ...prev,
732 { kind: 'console', level, text: message },
733 ])
734 }
735 },
736 })
737​
738 // Live elapsed timer while a run is in flight — makes a long, quiet step
739 // (e.g. a code-mode execution) visibly "still running", not hung.
740 const [elapsed, setElapsed] = useState(0)
741 useEffect(() => {
742 if (!isLoading) return
743 const startedAt = Date.now()
744 setElapsed(0)
745 const id = setInterval(
746 () => setElapsed(Math.floor((Date.now() - startedAt) / 1000)),
747 1000,
748 )
749 return () => clearInterval(id)
750 }, [isLoading])
751​
752 const canRun = useMemo(
753 () => /\/issues\/\d+/.test(issueUrl) && !isLoading,
754 [issueUrl, isLoading],
755 )
756​
757 // A run finished (not loading, no error) but the last message is still the
758 // user's — the agent streamed no assistant content. Surfaces the otherwise
759 // invisible "completed with zero output" case.
760 const noOutput = !isLoading && !error && messages.at(-1)?.role === 'user'
761​
762 function run() {
763 if (!canRun) return
764 setFileEvents([])
765 setCodeModeLines([])
766 // Label the thread by what it triaged (`TanStack/ai#859`), so the sidebar
767 // reads like a conversation list rather than a column of uuids.
768 const match = /github\.com\/([^/]+\/[^/]+)\/issues\/(\d+)/.exec(issueUrl)
769 onIssue(match ? `${match[1]}#${match[2]}` : issueUrl)
770 sendMessage(`Triage ${issueUrl}`)
771 }
772​
773 const elapsedLabel = `${Math.floor(elapsed / 60)}:${String(elapsed % 60).padStart(2, '0')}`
774​
775 return (
776 // `min-h-full`, not `h-screen`: this pane now lives inside the page's own
777 // full-height flex shell, and a second viewport-height box would scroll twice.
778 <div className="flex min-h-full flex-col bg-gray-900 text-white">
779 <header className="flex items-center gap-3 border-b border-indigo-500/10 bg-gray-900/80 px-4 py-3 backdrop-blur-sm">
780 <Github className="w-5 h-5 text-indigo-400" />
781 <span className="font-semibold">Sandbox Issue Triage</span>
782 <span className="text-xs text-gray-500">
783 clone a repo · investigate · root-cause
784 </span>
785 </header>
786​
787 <div className="border-b border-indigo-500/10 bg-gray-900/60 px-4 py-3 flex flex-wrap items-center gap-3">
788 <select
789 value={harness}
790 onChange={(e) => setHarness(e.target.value as HarnessName)}
791 disabled={isLoading}
792 className="rounded-lg border border-indigo-500/20 bg-gray-800 px-3 py-2 text-sm"
793 >
794 {Object.entries(HARNESSES).map(([name, spec]) => (
795 <option key={name} value={name}>
796 {spec.label}
797 </option>
798 ))}
799 </select>
800 <select
801 value={provider}
802 onChange={(e) => setProvider(e.target.value as ProviderName)}
803 disabled={isLoading}
804 className="rounded-lg border border-indigo-500/20 bg-gray-800 px-3 py-2 text-sm"
805 >
806 {Object.entries(PROVIDERS).map(([name, spec]) => (
807 <option key={name} value={name}>
808 {spec.label}
809 </option>
810 ))}
811 </select>
812 {harness === 'grok' && (
813 <>
814 <select
815 value={grokModel}
816 onChange={(e) => {
817 if (isGrokModel(e.target.value)) {
818 setGrokModel(e.target.value)
819 }
820 }}
821 disabled={isLoading}
822 title="Grok Build model"
823 className="rounded-lg border border-indigo-500/20 bg-gray-800 px-3 py-2 text-sm"
824 >
825 {GROK_MODEL_OPTIONS.map((o) => (
826 <option key={o.value} value={o.value}>
827 {o.label}
828 </option>
829 ))}
830 </select>
831 <select
832 value={grokProtocol}
833 onChange={(e) => {
834 if (isGrokProtocol(e.target.value)) {
835 setGrokProtocol(e.target.value)
836 }
837 }}
838 disabled={isLoading}
839 title="Grok Build wire protocol"
840 className="rounded-lg border border-indigo-500/20 bg-gray-800 px-3 py-2 text-sm"
841 >
842 {GROK_PROTOCOL_OPTIONS.map((o) => (
843 <option key={o.value} value={o.value}>
844 {o.label}
845 </option>
846 ))}
847 </select>
848 {grokProtocol === 'acp' && (
849 <select
850 value={grokTransport}
851 onChange={(e) => {
852 if (isGrokTransport(e.target.value)) {
853 setGrokTransport(e.target.value)
854 }
855 }}
856 disabled={isLoading}
857 title="ACP transport (auto picks stdio vs WebSocket)"
858 className="rounded-lg border border-indigo-500/20 bg-gray-800 px-3 py-2 text-sm"
859 >
860 {GROK_TRANSPORT_OPTIONS.map((o) => (
861 <option key={o.value} value={o.value}>
862 {o.label}
863 </option>
864 ))}
865 </select>
866 )}
867 </>
868 )}
869 <input
870 value={issueUrl}
871 onChange={(e) => setIssueUrl(e.target.value)}
872 disabled={isLoading}
873 placeholder="https://github.com/owner/repo/issues/123"
874 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"
875 onKeyDown={(e) => {
876 if (e.key === 'Enter') run()
877 }}
878 />
879 <label
880 className="flex items-center gap-1.5 text-xs text-gray-400 select-none"
881 title="By default the sandbox is destroyed after the run (success, error, or stop). Check to keep it alive."
882 >
883 <input
884 type="checkbox"
885 checked={keepAlive}
886 onChange={(e) => setKeepAlive(e.target.checked)}
887 disabled={isLoading}
888 />
889 keep sandbox
890 </label>
891 <label
892 className={`flex items-center gap-1.5 text-xs select-none ${
893 canUseSubscription ? 'text-gray-400' : 'text-gray-600'
894 }`}
895 title={
896 canUseSubscription
897 ? 'Use your logged-in Claude Code subscription instead of the API key (no API billing). Requires `claude login` on the host.'
898 : 'Only available for Claude Code on the Local process provider.'
899 }
900 >
901 <input
902 type="checkbox"
903 checked={canUseSubscription && useSubscription}
904 onChange={(e) => setUseSubscription(e.target.checked)}
905 disabled={isLoading || !canUseSubscription}
906 />
907 use my subscription
908 </label>
909 {isLoading ? (
910 <button
911 onClick={stop}
912 className="flex items-center gap-2 rounded-lg bg-red-600 px-4 py-2 text-sm font-medium hover:bg-red-700"
913 >
914 <Square className="w-4 h-4 fill-current" /> Stop
915 <span className="font-mono tabular-nums text-red-100/80">
916 {elapsedLabel}
917 </span>
918 </button>
919 ) : (
920 <button
921 onClick={run}
922 disabled={!canRun}
923 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"
924 >
925 <Play className="w-4 h-4" /> Triage
926 </button>
927 )}
928 </div>
929​
930 {error && (
931 <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">
932 <AlertTriangle className="mt-0.5 h-4 w-4 shrink-0 text-red-400" />
933 <div className="min-w-0">
934 <div className="font-medium text-red-300">Run failed</div>
935 <pre className="mt-1 whitespace-pre-wrap break-words font-mono text-xs text-red-200/90">
936 {error.message}
937 </pre>
938 </div>
939 </div>
940 )}
941 {noOutput && (
942 <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">
943 <AlertTriangle className="mt-0.5 h-4 w-4 shrink-0 text-amber-400" />
944 <span>
945 The run finished but the agent produced no output. Check the dev
946 server logs for details (e.g. a sandbox or CLI error).
947 </span>
948 </div>
949 )}
950​
951 <div className="flex-1 flex flex-col max-w-4xl mx-auto w-full overflow-hidden">
952 <Messages
953 messages={messages}
954 waiting={sandboxWaitKind(isLoading, hasActiveRun, messages)}
955 />
956 </div>
957 <CodeModeStrip lines={codeModeLines} />
958 <FileEventsStrip events={fileEvents} />
959 </div>
960 )