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

generic-interrupts.tsx

449 lines15.0 KB

1import { useEffect, useRef, useState } from 'react'
2import { createFileRoute } from '@tanstack/react-router'
3import { INTERRUPT_TOOL_RESUMES } from '@tanstack/ai'
4import {
5 fetchServerSentEvents,
6 useChat,
7 type GenericInterrupt,
8 type UseChatReturn,
9} from '@tanstack/ai-react'
10import { Check, RotateCcw, Sparkles, Trash2 } from 'lucide-react'
11import {
12 AUDIENCE_OPTIONS,
13 chooseAudience,
14 inspectPlan,
15 playgroundInterrupts,
16 playgroundScenarios,
17 reviewPlan,
18} from '@/lib/generic-interrupt-playground'
19import type { InterruptToolResume } from '@tanstack/ai'
20import type { PlaygroundScenario } from '@/lib/generic-interrupt-playground'
21​
22export const Route = createFileRoute('/generic-interrupts')({
23 component: GenericInterruptPlayground,
24})
25​
26const clientTools = [inspectPlan.client()] as const
27const connection = fetchServerSentEvents('/api/generic-interrupts')
28​
29type PlaygroundChat = UseChatReturn<
30 typeof clientTools,
31 undefined,
32 typeof playgroundInterrupts
34​
35const POLICY_HELP: Record<InterruptToolResume, string> = {
36 continue: 'The run continues after you resolve the review.',
37 cancel: 'Pending tools are cancelled. Then the run continues.',
38 stop: 'The run ends after you resolve the review.',
40​
41function GenericInterruptPlayground() {
42 const [threadId, setThreadId] = useState(() => crypto.randomUUID())
43 const [active, setActive] = useState<PlaygroundScenario | null>(null)
44 const [policy, setPolicy] = useState<InterruptToolResume>('continue')
45 const [pending, setPending] = useState<string | null>(null)
46 const [decisions, setDecisions] = useState<Array<string>>([])
47 const record = (message: string) =>
48 setDecisions((prev) => [message, ...prev].slice(0, 8))
49​
50 const chat = useChat({
51 threadId,
52 connection,
53 tools: clientTools,
54 interrupts: playgroundInterrupts,
55 forwardedProps: {
56 boundary: active?.boundary ?? 'beforeModel',
57 policy,
58 },
59 })
60​
61 useEffect(() => {
62 if (pending === null) return
63 void chat.sendMessage(pending)
64 setPending(null)
65 // eslint-disable-next-line react-hooks/exhaustive-deps
66 }, [pending])
67​
68 const runScenario = (scenario: PlaygroundScenario) => {
69 setDecisions([])
70 setActive(scenario)
71 setThreadId(crypto.randomUUID())
72 setPending(scenario.message)
73 }
74​
75 return (
76 <main className="min-h-screen bg-gray-900 text-white">
77 <div className="mx-auto grid max-w-6xl gap-6 p-6 lg:grid-cols-[320px_minmax(0,1fr)]">
78 <aside className="space-y-5">
79 <header className="overflow-hidden rounded-2xl border border-gray-700 bg-gray-800 p-5">
80 <p className="text-xs uppercase tracking-wider text-cyan-400">
81 First-party generic interrupts
82 </p>
83 <h1 className="text-3xl font-bold leading-tight">
84 Lifecycle playground
85 </h1>
86 <p className="mt-2 text-sm text-gray-400">
87 Pick a boundary. The run pauses with two typed cards: review the
88 plan, then pick an audience. Resolve both, then the selected
89 policy runs.
90 </p>
91 </header>
92​
93 <section className="space-y-2">
94 <h2 className="flex items-center gap-2 text-xs uppercase tracking-wider text-gray-500">
95 <Sparkles size={14} /> Resume policy
96 </h2>
97 <div
98 className="flex overflow-hidden rounded-lg border border-gray-700"
99 role="radiogroup"
100 aria-label="Resume policy"
101 >
102 {INTERRUPT_TOOL_RESUMES.map((nextPolicy) => (
103 <button
104 key={nextPolicy}
105 type="button"
106 role="radio"
107 aria-checked={policy === nextPolicy}
108 onClick={() => setPolicy(nextPolicy)}
109 className={`flex-1 px-3 py-1 text-sm transition-colors ${
110 policy === nextPolicy
111 ? 'bg-cyan-600 text-white'
112 : 'bg-transparent text-gray-400 hover:text-gray-200'
113 }`}
114 >
115 {nextPolicy}
116 </button>
117 ))}
118 </div>
119 <p className="text-xs text-gray-500">{POLICY_HELP[policy]}</p>
120 <p className="text-xs text-gray-500">
121 If you reject the review, the run stops even when the policy is
122 continue.
123 </p>
124 </section>
125​
126 <section className="space-y-2">
127 <h2 className="text-xs uppercase tracking-wider text-gray-500">
128 Boundaries
129 </h2>
130 <div className="space-y-2">
131 {playgroundScenarios.map((scenario) => (
132 <button
133 key={scenario.id}
134 type="button"
135 onClick={() => runScenario(scenario)}
136 disabled={chat.isLoading || chat.resuming}
137 aria-pressed={active?.id === scenario.id}
138 className={`w-full rounded-lg border p-3 text-left transition-colors enabled:hover:border-cyan-500/50 enabled:hover:bg-gray-800/60 disabled:opacity-50 ${
139 active?.id === scenario.id
140 ? 'border-cyan-500/60 bg-gray-800'
141 : 'border-gray-700 bg-gray-800'
142 }`}
143 >
144 <div className="font-semibold">{scenario.title}</div>
145 <div className="text-xs text-gray-400">{scenario.blurb}</div>
146 </button>
147 ))}
148 </div>
149 </section>
150 </aside>
151​
152 <section className="space-y-4">
153 <div className="rounded-lg border border-gray-700 bg-gray-800 p-3 text-sm text-gray-400">
154 {chat.isLoading || chat.resuming
155 ? `Running ${active?.boundary ?? 'scenario'} with policy ${policy}...`
156 : active
157 ? `Active boundary: ${active.boundary}. Policy: ${policy}.`
158 : 'Pick a boundary on the left to start.'}
159 </div>
160​
161 <Transcript chat={chat} />
162​
163 {chat.interruptErrors.length > 0 ? (
164 <div className="rounded-lg border border-red-500/30 bg-red-500/10 p-3 text-sm text-red-300">
165 {chat.interruptErrors.map((error) => (
166 <div key={error.code}>{error.message}</div>
167 ))}
168 <button
169 type="button"
170 onClick={() => chat.retryInterrupts()}
171 className="mt-2 inline-flex items-center gap-1 rounded-md bg-red-600 px-2 py-1 text-white transition-colors hover:bg-red-700"
172 >
173 <RotateCcw size={13} /> Retry
174 </button>
175 </div>
176 ) : null}
177​
178 {chat.interrupts.filter(isReviewPlan).map((interrupt) => (
179 <ReviewCard
180 key={interrupt.id}
181 interrupt={interrupt}
182 disabled={chat.resuming}
183 record={record}
184 />
185 ))}
186​
187 {chat.interrupts.filter(isChooseAudience).map((interrupt) => (
188 <AudienceCard
189 key={interrupt.id}
190 interrupt={interrupt}
191 disabled={chat.resuming}
192 record={record}
193 />
194 ))}
195​
196 {decisions.length > 0 ? (
197 <div className="rounded-lg border border-gray-700 bg-gray-800/60 p-3">
198 <h2 className="mb-1 text-xs uppercase tracking-wider text-gray-500">
199 Your decisions
200 </h2>
201 <ul className="space-y-1 font-mono text-[11px] text-gray-400">
202 {decisions.map((decision, index) => (
203 <li key={index}>{decision}</li>
204 ))}
205 </ul>
206 </div>
207 ) : null}
208 </section>
209 </div>
210 </main>
211 )
213​
214function isReviewPlan(
215 interrupt: PlaygroundChat['interrupts'][number],
216): interrupt is GenericInterrupt<typeof reviewPlan> {
217 return (
218 interrupt.kind === 'generic' &&
219 'definitionId' in interrupt &&
220 interrupt.definitionId === reviewPlan.id
221 )
223​
224function isChooseAudience(
225 interrupt: PlaygroundChat['interrupts'][number],
226): interrupt is GenericInterrupt<typeof chooseAudience> {
227 return (
228 interrupt.kind === 'generic' &&
229 'definitionId' in interrupt &&
230 interrupt.definitionId === chooseAudience.id
231 )
233​
234function Transcript({ chat }: { chat: PlaygroundChat }) {
235 if (chat.messages.length === 0) {
236 return (
237 <div className="rounded-lg border border-dashed border-gray-700 p-6 text-center text-sm text-gray-500">
238 Pick a boundary on the left to start.
239 </div>
240 )
241 }
242 return (
243 <div className="space-y-2 rounded-lg border border-gray-700 bg-gray-800/60 p-4">
244 {chat.messages.map((message) => (
245 <div key={message.id} className="text-sm">
246 <span className="font-mono text-xs uppercase text-gray-500">
247 {message.role}:{' '}
248 </span>
249 {message.parts.map((part, index) => {
250 if (part.type === 'text') {
251 return <span key={index}>{part.content}</span>
252 }
253 if (part.type === 'tool-call') {
254 return (
255 <div
256 key={index}
257 className="mt-1 rounded-md bg-gray-800 px-2 py-1 font-mono text-[11px] text-gray-300"
258 >
259 {part.name}({JSON.stringify(part.input ?? part.arguments)})
260 {part.output !== undefined
261 ? ` → ${JSON.stringify(part.output)}`
262 : ` · ${part.state}`}
263 </div>
264 )
265 }
266 if (part.type === 'tool-result') {
267 const body =
268 typeof part.content === 'string'
269 ? part.content
270 : JSON.stringify(part.content)
271 return (
272 <div
273 key={index}
274 className="mt-1 rounded-md bg-emerald-500/10 px-2 py-1 font-mono text-[11px] text-emerald-300"
275 >
276 {part.error ?? body}
277 </div>
278 )
279 }
280 return null
281 })}
282 </div>
283 ))}
284 </div>
285 )
287​
288function ReviewCard({
289 interrupt,
290 disabled,
291 record,
292}: {
293 interrupt: GenericInterrupt<typeof reviewPlan>
294 disabled: boolean
295 record: (message: string) => void
296}) {
297 const [note, setNote] = useState('Looks good')
298 const payload = interrupt.payload
299 const cardRef = useRef<HTMLElement>(null)
300​
301 useEffect(() => {
302 cardRef.current?.scrollIntoView({ block: 'nearest', behavior: 'smooth' })
303 }, [])
304​
305 return (
306 <article
307 ref={cardRef}
308 className="space-y-3 rounded-2xl border border-cyan-500/30 bg-gray-800 p-4"
309 >
310 <div>
311 <p className="text-xs uppercase tracking-wider text-cyan-400">
312 {payload?.boundary ?? interrupt.reason}
313 </p>
314 <h3 className="text-lg font-semibold leading-tight">
315 {payload?.title ?? 'Review plan'}
316 </h3>
317 <p className="text-sm text-gray-400">
318 {interrupt.message ?? 'Review this step, then continue.'}
319 </p>
320 </div>
321 <label className="block space-y-1">
322 <span className="text-xs uppercase tracking-wider text-gray-500">
323 Note (required)
324 </span>
325 <input
326 className="w-full rounded-md border border-gray-700 bg-gray-900 px-2 py-1 text-sm text-white placeholder-gray-500 focus:border-cyan-500/50 focus:outline-none"
327 placeholder="Looks good"
328 value={note}
329 onChange={(event) => setNote(event.target.value)}
330 />
331 </label>
332 <div className="flex flex-wrap gap-2">
333 <button
334 type="button"
335 onClick={() => {
336 record(`approved · ${note}`)
337 interrupt.resolveInterrupt({ approved: true, note })
338 }}
339 disabled={disabled}
340 className="inline-flex items-center gap-1 rounded-md bg-green-600 px-3 py-1 text-sm text-white transition-colors hover:bg-green-700 disabled:opacity-50"
341 >
342 <Check size={14} /> Approve
343 </button>
344 <button
345 type="button"
346 onClick={() => {
347 record(`rejected · ${note}`)
348 interrupt.resolveInterrupt({ approved: false, note })
349 }}
350 disabled={disabled}
351 className="inline-flex items-center gap-1 rounded-md bg-red-600 px-3 py-1 text-sm text-white transition-colors hover:bg-red-700 disabled:opacity-50"
352 >
353 Reject
354 </button>
355 <button
356 type="button"
357 onClick={() => {
358 record('cancelled')
359 interrupt.cancel()
360 }}
361 disabled={disabled}
362 className="inline-flex items-center gap-1 rounded-md px-3 py-1 text-sm text-gray-400 transition-colors hover:text-gray-200 disabled:opacity-50"
363 >
364 <Trash2 size={14} /> Cancel
365 </button>
366 </div>
367 {interrupt.errors.map((error) => (
368 <p
369 key={`${error.code}:${error.path?.join('.') ?? ''}`}
370 className="text-xs text-red-400"
371 >
372 {error.message}
373 </p>
374 ))}
375 </article>
376 )
378​
379function AudienceCard({
380 interrupt,
381 disabled,
382 record,
383}: {
384 interrupt: GenericInterrupt<typeof chooseAudience>
385 disabled: boolean
386 record: (message: string) => void
387}) {
388 const payload = interrupt.payload
389 const options = payload?.options ?? AUDIENCE_OPTIONS
390 const cardRef = useRef<HTMLElement>(null)
391​
392 useEffect(() => {
393 cardRef.current?.scrollIntoView({ block: 'nearest', behavior: 'smooth' })
394 }, [])
395​
396 return (
397 <article
398 ref={cardRef}
399 className="space-y-3 rounded-2xl border border-amber-500/30 bg-gray-800 p-4"
400 >
401 <div>
402 <p className="text-xs uppercase tracking-wider text-amber-400">
403 choose-audience
404 </p>
405 <h3 className="text-lg font-semibold leading-tight">
406 {payload?.question ?? 'Pick an audience'}
407 </h3>
408 <p className="text-sm text-gray-400">
409 {interrupt.message ?? 'This card uses a different response type.'}
410 </p>
411 </div>
412 <div className="flex flex-wrap gap-2">
413 {options.map((audience) => (
414 <button
415 key={audience}
416 type="button"
417 onClick={() => {
418 record(`audience · ${audience}`)
419 interrupt.resolveInterrupt({ audience })
420 }}
421 disabled={disabled}
422 className="inline-flex items-center rounded-md bg-amber-600 px-3 py-1 text-sm text-white transition-colors hover:bg-amber-700 disabled:opacity-50"
423 >
424 {audience}
425 </button>
426 ))}
427 <button
428 type="button"
429 onClick={() => {
430 record('audience cancelled')
431 interrupt.cancel()
432 }}
433 disabled={disabled}
434 className="inline-flex items-center gap-1 rounded-md px-3 py-1 text-sm text-gray-400 transition-colors hover:text-gray-200 disabled:opacity-50"
435 >
436 <Trash2 size={14} /> Cancel
437 </button>
438 </div>
439 {interrupt.errors.map((error) => (
440 <p
441 key={`${error.code}:${error.path?.join('.') ?? ''}`}
442 className="text-xs text-red-400"
443 >
444 {error.message}
445 </p>
446 ))}
447 </article>
448 )