Open History to see the last commit
1import { useCallback, useRef, useState } from 'react'
2import { createFileRoute } from '@tanstack/react-router'
3import { fetchServerSentEvents, useChat } from '@tanstack/ai-react'
4import type { ToolCallPart } from '@tanstack/ai'
5import {
6 SCENARIO_LIST,
7 admitRescue,
8 assignEnclosure,
9 finalizeAdoption,
10 getScenario,
11 logFieldSighting,
12 printCertificate,
13 printIntakeTag,
14 scheduleVetCheck,
15 shareAdoptionStory,
16} from '@/lib/interrupt-scenario-tools'
17import type { ResolutionConfig } from '@/lib/interrupt-scenario-tools'
18import { parseAimockPort } from '@/lib/devtools-test'
19
20/**
21 * Interrupt playground — deterministic e2e host for every wildlife interrupt
22 * scenario (server/client boolean, shared payload, branch payload, edited
23 * args, generic, batch). Mirrors the /tools-test selectors so the shared
24 * helpers apply, and adds per-item cancel, generic resolve/cancel, and root
25 * batch controls (resolveInterrupts / cancelInterrupts).
26 */
27
28interface InterruptEvent {
29 timestamp: number
30 type:
31 | 'approval-granted'
32 | 'approval-denied'
33 | 'approval-cancelled'
34 | 'generic-resolved'
35 | 'generic-cancelled'
36 | 'execution-complete'
37 | 'custom-event'
38 toolName: string
39 interruptId?: string
40 details?: string
41}
42
43/** Loose interrupt view — the harness drives a mixed set, so it deliberately
44 * uses the untyped surface instead of the per-tool typed overloads. */
45interface LooseInterrupt {
46 kind: string
47 id?: string
48 interruptId?: string
49 toolCallId?: string
50 toolName?: string
51 status?: string
52 resolveInterrupt: (arg1?: unknown, arg2?: unknown) => void
53 cancel: () => void
54}
55
56function InterruptsTestPage() {
57 const { testId, aimockPort, scenario: initialScenario } = Route.useSearch()
58 const [scenario, setScenario] = useState(initialScenario || 'admit')
59 const [events, setEvents] = useState<Array<InterruptEvent>>([])
60 const [testComplete, setTestComplete] = useState(false)
61 const responded = useRef<Set<string>>(new Set())
62
63 const addEvent = useCallback((event: Omit<InterruptEvent, 'timestamp'>) => {
64 setEvents((prev) => [...prev, { ...event, timestamp: Date.now() }])
65 }, [])
66
67 // Client tools. Server tools get bare `.client()` stubs so the
68 // InterruptManager hydrates their pause as `tool-approval` (schema hashes
69 // must match the server). Client tools get echoing executors so approval is
70 // observable in the event log / messages.
71 const clientTools = useRef([
72 admitRescue.client(),
73 scheduleVetCheck.client(),
74 finalizeAdoption.client(),
75 assignEnclosure.client(),
76 printIntakeTag.client(async ({ animal }) => {
77 addEvent({
78 type: 'execution-complete',
79 toolName: 'printIntakeTag',
80 details: animal,
81 })
82 return { tag: `tag_${animal.toLowerCase()}` }
83 }),
84 logFieldSighting.client(async ({ species, location }) => {
85 addEvent({
86 type: 'execution-complete',
87 toolName: 'logFieldSighting',
88 details: `${species}@${location}`,
89 })
90 return { sightingId: `sighting_${species.toLowerCase()}` }
91 }),
92 shareAdoptionStory.client(async ({ animal }) => {
93 addEvent({
94 type: 'execution-complete',
95 toolName: 'shareAdoptionStory',
96 details: animal,
97 })
98 return { url: `https://sanctuary.example/${animal.toLowerCase()}` }
99 }),
100 printCertificate.client(async ({ animal, adopter, date }) => {
101 addEvent({
102 type: 'execution-complete',
103 toolName: 'printCertificate',
104 // Echo the (possibly edited) args so the edited-args spec can assert.
105 details: `${animal}|${adopter}|${date}`,
106 })
107 return { certificate: `cert_${animal.toLowerCase()}_${date}` }
108 }),
109 ]).current
110
111 const {
112 messages,
113 sendMessage,
114 isLoading,
115 stop,
116 clear,
117 interrupts,
118 resolveInterrupts,
119 cancelInterrupts,
120 error,
121 } = useChat({
122 threadId: `interrupts-test-${scenario}`,
123 connection: fetchServerSentEvents('/api/interrupts-test'),
124 forwardedProps: { scenario, testId, aimockPort },
125 tools: clientTools,
126 onFinish: () => setTestComplete(true),
127 onCustomEvent: (eventType: string, data: unknown) =>
128 addEvent({
129 type: 'custom-event',
130 toolName: eventType,
131 details: JSON.stringify(data),
132 }),
133 })
134
135 const loose = interrupts as unknown as ReadonlyArray<LooseInterrupt>
136 const pendingApprovals = loose.filter(
137 (i) => i.kind === 'tool-approval' && i.status === 'pending',
138 )
139 const pendingGeneric = loose.filter(
140 (i) => i.kind === 'generic' && i.status === 'pending',
141 )
142
143 const scenarioDef = getScenario(scenario)
144
145 const configForTool = (toolName?: string): ResolutionConfig => {
146 if (scenarioDef?.resolutionByTool && toolName) {
147 return scenarioDef.resolutionByTool[toolName] ?? {}
148 }
149 return scenarioDef?.resolution ?? {}
150 }
151
152 const once = (key: string | undefined): boolean => {
153 if (!key || responded.current.has(key)) return false
154 responded.current.add(key)
155 return true
156 }
157
158 const approve = (item: LooseInterrupt) => {
159 if (!once(item.interruptId ?? item.id)) return
160 const cfg = configForTool(item.toolName)
161 const options: { editedArgs?: unknown; payload?: unknown } = {}
162 if (cfg.editedArgs) options.editedArgs = cfg.editedArgs
163 if (cfg.approvePayload) options.payload = cfg.approvePayload
164 addEvent({
165 type: 'approval-granted',
166 toolName: item.toolName ?? '',
167 interruptId: item.interruptId,
168 })
169 item.resolveInterrupt(true, options)
170 }
171
172 const deny = (item: LooseInterrupt) => {
173 if (!once(item.interruptId ?? item.id)) return
174 const cfg = configForTool(item.toolName)
175 const options: { payload?: unknown } = {}
176 if (cfg.denyPayload) options.payload = cfg.denyPayload
177 addEvent({
178 type: 'approval-denied',
179 toolName: item.toolName ?? '',
180 interruptId: item.interruptId,
181 })
182 item.resolveInterrupt(false, options)
183 }
184
185 const cancel = (item: LooseInterrupt) => {
186 if (!once(item.interruptId ?? item.id)) return
187 addEvent({
188 type: 'approval-cancelled',
189 toolName: item.toolName ?? '',
190 interruptId: item.interruptId,
191 })
192 item.cancel()
193 }
194
195 const resolveGeneric = (item: LooseInterrupt) => {
196 if (!once(item.interruptId ?? item.id)) return
197 addEvent({
198 type: 'generic-resolved',
199 toolName: 'generic',
200 interruptId: item.interruptId,
201 })
202 item.resolveInterrupt(scenarioDef?.resolution?.approvePayload ?? {})
203 }
204
205 const cancelGeneric = (item: LooseInterrupt) => {
206 if (!once(item.interruptId ?? item.id)) return
207 addEvent({
208 type: 'generic-cancelled',
209 toolName: 'generic',
210 interruptId: item.interruptId,
211 })
212 item.cancel()
213 }
214
215 // Root batch controls.
216 const approveAll = () => {
217 for (const i of pendingApprovals) once(i.interruptId ?? i.id)
218 addEvent({ type: 'approval-granted', toolName: 'batch' })
219 resolveInterrupts(true)
220 }
221 const denyAll = () => {
222 for (const i of pendingApprovals) once(i.interruptId ?? i.id)
223 addEvent({ type: 'approval-denied', toolName: 'batch' })
224 resolveInterrupts(false)
225 }
226 const cancelAll = () => {
227 for (const i of pendingApprovals) once(i.interruptId ?? i.id)
228 addEvent({ type: 'approval-cancelled', toolName: 'batch' })
229 cancelInterrupts()
230 }
231 const resolveAllMixed = () => {
232 for (const i of pendingApprovals) once(i.interruptId ?? i.id)
233 addEvent({ type: 'approval-granted', toolName: 'batch-mixed' })
234 resolveInterrupts((raw: unknown) => {
235 const item = raw as LooseInterrupt
236 const cfg = configForTool(item.toolName)
237 const options: { editedArgs?: unknown; payload?: unknown } = {}
238 if (cfg.editedArgs) options.editedArgs = cfg.editedArgs
239 if (cfg.approvePayload) options.payload = cfg.approvePayload
240 item.resolveInterrupt(true, options)
241 return undefined
242 })
243 }
244
245 const handleRun = useCallback(() => {
246 setEvents([])
247 setTestComplete(false)
248 responded.current.clear()
249 sendMessage(`[${scenario}] run test`)
250 }, [scenario, sendMessage])
251
252 const toolCalls: Array<ToolCallPart> = messages.flatMap((msg) =>
253 msg.parts.filter(
254 (p): p is Extract<typeof p, { type: 'tool-call' }> =>
255 p.type === 'tool-call',
256 ),
257 )
258
259 // Server tool results can arrive as separate `tool-result` parts rather than
260 // on the tool-call part; index them by tool-call id so a spec can read the
261 // executed output (this is how the edited-args scenarios are observed).
262 const toolResults = new Map<string, unknown>()
263 for (const msg of messages) {
264 for (const part of msg.parts) {
265 if (part.type === 'tool-result') {
266 const p = part as {
267 toolCallId: string
268 content?: unknown
269 output?: unknown
270 }
271 toolResults.set(p.toolCallId, p.output ?? p.content)
272 }
273 }
274 }
275 const outputFor = (tc: ToolCallPart) => tc.output ?? toolResults.get(tc.id)
276
277 const count = (type: InterruptEvent['type']) =>
278 events.filter((e) => e.type === type).length
279
280 return (
281 <div
282 style={{
283 display: 'flex',
284 flexDirection: 'column',
285 padding: '20px',
286 fontFamily: 'system-ui, sans-serif',
287 color: '#e2e8f0',
288 }}
289 >
290 <h1 style={{ marginTop: 0 }}>Interrupt Playground</h1>
291
292 <div style={{ marginBottom: '20px' }}>
293 <label htmlFor="scenario-select" style={{ fontWeight: 'bold' }}>
294 Scenario:{' '}
295 </label>
296 <select
297 id="scenario-select"
298 value={scenario}
299 onChange={(e) => setScenario(e.target.value)}
300 style={{
301 padding: '8px',
302 backgroundColor: '#1e293b',
303 color: '#e2e8f0',
304 border: '1px solid #475569',
305 borderRadius: '4px',
306 }}
307 >
308 {SCENARIO_LIST.map((s) => (
309 <option key={s.id} value={s.id}>
310 {s.label}
311 </option>
312 ))}
313 </select>
314 {testComplete && (
315 <span
316 id="test-complete-indicator"
317 style={{ marginLeft: '10px', color: '#28a745', fontWeight: 'bold' }}
318 >
319 ✓ Test Complete
320 </span>
321 )}
322 </div>
323
324 {error && (
325 <div
326 id="error-display"
327 style={{
328 padding: '10px',
329 background: 'rgba(220, 53, 69, 0.15)',
330 border: '1px solid rgba(220, 53, 69, 0.4)',
331 borderRadius: '4px',
332 marginBottom: '10px',
333 color: '#f8a4a4',
334 }}
335 >
336 Error: {error.message}
337 </div>
338 )}
339
340 <div style={{ display: 'flex', gap: '10px', marginBottom: '20px' }}>
341 <button id="run-test-button" onClick={handleRun} disabled={isLoading}>
342 Run Test
343 </button>
344 {isLoading && (
345 <button id="stop-button" onClick={stop}>
346 Stop
347 </button>
348 )}
349 <button id="clear-button" onClick={clear}>
350 Clear
351 </button>
352 </div>
353
354 {/* Tool-approval interrupts */}
355 {pendingApprovals.length > 0 && (
356 <div id="approval-section" style={sectionStyle('#ffc107')}>
357 <h3 style={{ margin: '0 0 10px 0' }}>
358 Pending Approvals (
359 <span id="pending-approval-count">{pendingApprovals.length}</span>)
360 </h3>
361 {pendingApprovals.map((item) => {
362 const key = item.toolCallId ?? item.interruptId ?? item.id ?? ''
363 return (
364 <div
365 key={key}
366 className="approval-request"
367 data-tool-name={item.toolName}
368 data-interrupt-id={item.interruptId}
369 style={{ display: 'flex', gap: '8px', marginBottom: '8px' }}
370 >
371 <span>
372 <strong>{item.toolName}</strong>
373 </span>
374 <button
375 id={`approve-${key}`}
376 className="approve-button"
377 onClick={() => approve(item)}
378 >
379 Approve
380 </button>
381 <button
382 id={`deny-${key}`}
383 className="deny-button"
384 onClick={() => deny(item)}
385 >
386 Deny
387 </button>
388 <button
389 id={`cancel-${key}`}
390 className="cancel-button"
391 onClick={() => cancel(item)}
392 >
393 Cancel
394 </button>
395 </div>
396 )
397 })}
398
399 {/* Root batch controls */}
400 <div style={{ display: 'flex', gap: '8px', marginTop: '10px' }}>
401 <button id="resolve-all-approve" onClick={approveAll}>
402 Approve All
403 </button>
404 <button id="resolve-all-deny" onClick={denyAll}>
405 Deny All
406 </button>
407 <button id="cancel-all" onClick={cancelAll}>
408 Cancel All
409 </button>
410 <button id="resolve-all-mixed" onClick={resolveAllMixed}>
411 Resolve All (mixed)
412 </button>
413 </div>
414 </div>
415 )}
416
417 {/* Generic interrupts */}
418 {pendingGeneric.length > 0 && (
419 <div id="generic-section" style={sectionStyle('#8b5cf6')}>
420 <h3 style={{ margin: '0 0 10px 0' }}>
421 Generic Interrupts (
422 <span id="pending-generic-count">{pendingGeneric.length}</span>)
423 </h3>
424 {pendingGeneric.map((item) => {
425 const key = item.interruptId ?? item.id ?? ''
426 return (
427 <div
428 key={key}
429 className="generic-request"
430 data-interrupt-id={item.interruptId}
431 style={{ display: 'flex', gap: '8px', marginBottom: '8px' }}
432 >
433 <button
434 id={`resolve-generic-${key}`}
435 className="resolve-generic-button"
436 onClick={() => resolveGeneric(item)}
437 >
438 Resolve
439 </button>
440 <button
441 id={`cancel-generic-${key}`}
442 className="cancel-generic-button"
443 onClick={() => cancelGeneric(item)}
444 >
445 Cancel
446 </button>
447 </div>
448 )
449 })}
450 </div>
451 )}
452
453 {/* Messages JSON for assertions */}
454 <div
455 id="messages-json"
456 style={{
457 overflow: 'auto',
458 maxHeight: '40vh',
459 padding: '10px',
460 backgroundColor: 'rgba(15, 23, 42, 0.6)',
461 border: '1px solid rgba(100, 116, 139, 0.3)',
462 borderRadius: '4px',
463 fontFamily: 'monospace',
464 fontSize: '12px',
465 color: '#94a3b8',
466 }}
467 >
468 <pre
469 id="messages-json-content"
470 style={{ margin: 0, whiteSpace: 'pre-wrap', wordBreak: 'break-word' }}
471 >
472 {JSON.stringify(messages, null, 2)}
473 </pre>
474 </div>
475
476 {/* Hidden metadata for assertions */}
477 <div
478 id="test-metadata"
479 style={{ display: 'none' }}
480 data-scenario={scenario}
481 data-is-loading={isLoading.toString()}
482 data-test-complete={testComplete.toString()}
483 data-tool-call-count={toolCalls.length}
484 data-pending-approval-count={pendingApprovals.length}
485 data-pending-generic-count={pendingGeneric.length}
486 data-interrupt-count={loose.length}
487 data-interrupt-kinds={loose.map((i) => i.kind).join(',')}
488 data-complete-tool-count={
489 toolCalls.filter(
490 (tc) =>
491 tc.state === 'approval-responded' || outputFor(tc) !== undefined,
492 ).length
493 }
494 data-event-count={events.length}
495 data-approval-granted-count={count('approval-granted')}
496 data-approval-denied-count={count('approval-denied')}
497 data-approval-cancelled-count={count('approval-cancelled')}
498 data-generic-resolved-count={count('generic-resolved')}
499 data-generic-cancelled-count={count('generic-cancelled')}
500 data-execution-complete-count={count('execution-complete')}
501 data-has-error={(!!error).toString()}
502 data-error-message={error?.message || ''}
503 />
504
505 <script
506 id="event-log-json"
507 type="application/json"
508 dangerouslySetInnerHTML={{ __html: JSON.stringify(events) }}
509 />
510 <script
511 id="tool-calls-json"
512 type="application/json"
513 dangerouslySetInnerHTML={{
514 __html: JSON.stringify(
515 toolCalls.map((tc) => ({
516 id: tc.id,
517 name: tc.name,
518 state: tc.state,
519 output: outputFor(tc),
520 })),
521 ),
522 }}
523 />
524 </div>
525 )
526}
527
528function sectionStyle(accent: string) {
529 return {
530 marginBottom: '20px',
531 padding: '15px',
532 backgroundColor: `${accent}22`,
533 borderRadius: '4px',
534 border: `1px solid ${accent}66`,
535 } as const
536}
537
538export const Route = createFileRoute('/interrupts-test')({
539 component: InterruptsTestPage,
540 validateSearch: (search: Record<string, unknown>) => {
541 return {
542 testId: typeof search.testId === 'string' ? search.testId : undefined,
543 aimockPort: parseAimockPort(search.aimockPort),
544 scenario:
545 typeof search.scenario === 'string' ? search.scenario : undefined,
546 }
547 },
548})