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

multiple.md

255 lines8.4 KB

1---
2title: Multiple Interrupts
3id: interrupts-multiple
4order: 3
5description: "Render a queue of pending decisions and resolve them item by item or all at once as one validated batch."
6keywords:
7 - tanstack ai
8 - ag-ui interrupts
9 - resolveInterrupts
10 - batch approval
11 - cancelInterrupts
12---
13​
14One run can pause on several decisions at once. A tool approval and a generic
15middleware request can land in the same batch. You want to show the whole queue
16and send the answers back together, not one round trip each.
17​
18## Two ways to resolve
19​
20You have already seen the first one on the [Tool Approval](./tool-approval) page:
21call a method on the item itself.
22​
23```ts ignore
24// Per item: resolve each one where you render it.
25interrupt.resolveInterrupt(true)
26```
27​
28When several client-owned items are pending, it is often easier to answer them
29all from one place. The `useChat` hook gives you root helpers for those items:
30​
31```ts ignore
32// All at once: one callback decides every pending item.
33resolveInterrupts((interrupt) => {
34 if (interrupt.kind === 'tool-approval') {
35 interrupt.resolveInterrupt(true)
36 return
37 }
38 interrupt.cancel()
39})
40```
41​
42Both stage local drafts. Nothing goes to the server until every pending item has
43an answer. Then the client submits the whole set at once. The server validates
44the whole set before it accepts any item.
45​
46When persistence is enabled, `InterruptStore.commitBatch()` can commit the
47validated batch in one database transaction. Without `commitBatch()`, the
48compatibility fallback writes items in sequence. That fallback is not atomic.
49​
50For a mixed batch, switch on `kind`. Registered generic items use their
51definition id to narrow their payload and response. Tool approvals keep their
52own controls. A generic item with a valid raw binding has untyped controls and
53joins the resume batch. An `unbound` item has a missing, malformed, or
54unsupported binding. It remains visible, has no controls, and does not block
55the resumable items.
56​
57## Render the queue
58​
59Map over `interrupts` and switch on `kind`. Each item carries its own
60`canResolve` and `errors`:
61​
62```tsx
63// app/decision-queue.tsx
64import { fetchServerSentEvents, useChat } from '@tanstack/ai-react'
65import { transferTool } from '../tools/transfer'
66​
67export function DecisionQueue() {
68 const { interrupts, resolveInterrupts, cancelInterrupts, resuming } = useChat({
69 threadId: 'account-42',
70 connection: fetchServerSentEvents('/api/chat'),
71 tools: [transferTool] as const,
72 })
73​
74 if (interrupts.length === 0) return null
75​
76 return (
77 <section>
78 <p>{interrupts.length} decision(s) needed</p>
79​
80 {interrupts.map((interrupt) => {
81 if (
82 interrupt.kind === 'tool-approval' &&
83 interrupt.toolName === 'transfer'
84 ) {
85 return (
86 <article key={interrupt.id}>
87 <p>
88 {interrupt.originalArgs.amount} to{' '}
89 {interrupt.originalArgs.recipient}
90 </p>
91 <button
92 disabled={!interrupt.canResolve || resuming}
93 onClick={() => interrupt.resolveInterrupt(true)}
94 >
95 Approve
96 </button>
97 <button
98 disabled={!interrupt.canResolve || resuming}
99 onClick={() => interrupt.resolveInterrupt(false)}
100 >
101 Reject
102 </button>
103 </article>
104 )
105 }
106 return <article key={interrupt.id}>Unsupported: {interrupt.kind}</article>
107 })}
108​
109 <button onClick={() => resolveInterrupts(true)} disabled={resuming}>
110 Approve all
111 </button>
112 <button onClick={() => cancelInterrupts()} disabled={resuming}>
113 Cancel all
114 </button>
115 </section>
116 )
118```
119​
120## Resolve every item from one callback
121​
122`resolveInterrupts(callback)` runs your callback once per resumable item in a
123single synchronous transaction. This includes valid raw external generic
124bindings. It must resolve or cancel every such item. If it throws or leaves one
125unanswered, nothing submits:
126​
127```ts ignore
128resolveInterrupts((interrupt) => {
129 if (interrupt.kind === 'tool-approval') {
130 interrupt.resolveInterrupt(true, { payload: { note: 'Batch review' } })
131 return
132 }
133 interrupt.cancel()
134})
135```
136​
137Two shortcuts cover the common cases:
138​
139- `resolveInterrupts(true)` / `resolveInterrupts(false)` approves or rejects the
140 whole queue. It works only when every item is a tool approval that needs no
141 payload or edits. Generic items, mixed queues, or required payloads are
142 rejected.
143- `cancelInterrupts()` cancels every resumable item with no payload, including
144 client-tool execution steps that are hidden from `interrupts`.
145​
146Use the `onInterruptStateChange` source to apply different policies to restored
147(`hydrate`) and current-session (`live`) batches. Cancellation still applies to
148every resumable item in the batch.
149​
150## When an answer is wrong
151​
152A bad answer does not tear down the queue. The item keeps your last valid draft,
153shows what went wrong, and lets you fix it and resubmit. Errors come in two
154places, and you render both.
155​
156Each item carries its own `errors`: a bad payload, invalid edited args, or an
157expired item. The root `interruptErrors` carries failures for the whole batch:
158transport problems, server rejections, and errors for the internal client-tool
159steps that never show up as their own item.
160​
161This component renders both, gates its buttons correctly, and offers the two
162recovery paths:
163​
164```tsx
165// app/robust-queue.tsx
166import { fetchServerSentEvents, useChat } from '@tanstack/ai-react'
167import { toolDefinition } from '@tanstack/ai'
168import { z } from 'zod'
169​
170const transferTool = toolDefinition({
171 name: 'transfer',
172 description: 'Move money between accounts',
173 needsApproval: true,
174 inputSchema: z.object({
175 recipient: z.string(),
176 amount: z.number(),
177 }),
178 outputSchema: z.object({ receiptId: z.string() }),
179}).client()
180​
181export function RobustQueue() {
182 const { interrupts, interruptErrors, retryInterrupts, resuming } = useChat({
183 threadId: 'account-42',
184 connection: fetchServerSentEvents('/api/chat'),
185 tools: [transferTool] as const,
186 })
187​
188 // Retry only helps a transport failure. Expired or stale batches cannot
189 // be retried, so do not offer it for those.
190 const canRetry = interruptErrors.some((error) => error.code === 'transport')
191​
192 return (
193 <section>
194 {interrupts.map((interrupt) => {
195 if (
196 interrupt.kind !== 'tool-approval' ||
197 interrupt.toolName !== 'transfer'
198 ) {
199 return null
200 }
201​
202 // canResolve reflects the schema and binding, not the live phase, so
203 // also gate on the item's status and the run being busy.
204 const busy = interrupt.status === 'submitting' || resuming
205​
206 return (
207 <article key={interrupt.id}>
208 <p>
209 {interrupt.originalArgs.amount} to{' '}
210 {interrupt.originalArgs.recipient}
211 </p>
212 <button
213 disabled={!interrupt.canResolve || busy}
214 onClick={() => interrupt.resolveInterrupt(true)}
215 >
216 Approve
217 </button>
218 <button disabled={busy} onClick={() => interrupt.clearResolution()}>
219 Start over
220 </button>
221​
222 {/* Item errors: bad payload, bad edited args, expired. */}
223 {interrupt.errors.map((error) => (
224 <p key={`${error.code}:${error.path?.join('.') ?? ''}`}>
225 {error.message}
226 </p>
227 ))}
228 </article>
229 )
230 })}
231​
232 {/* Batch errors: transport, server, and hidden client-tool steps. */}
233 {interruptErrors.map((error) => (
234 <p key={error.code}>{error.message}</p>
235 ))}
236 {canRetry ? (
237 <button onClick={() => retryInterrupts()} disabled={resuming}>
238 Retry
239 </button>
240 ) : null}
241 </section>
242 )
244```
245​
246The two recovery paths, side by side:
247​
248- `interrupt.clearResolution()` drops one item's draft so the user can answer it
249 again from scratch. Fixing a form and calling `resolveInterrupt` again works
250 too, the draft is replaced, not stacked.
251- `retryInterrupts()` retries a staged batch after a transport failure. With
252 sequential durable storage, a failed request may have committed earlier
253 entries already. Reload the current pending records, then retry only the
254 remaining batch. It does nothing for expired or stale batches, start a fresh
255 run to get a new set of interrupts for those.