Open History to see the last commit
1---
2title: Multiple Interrupts
3id: interrupts-multiple
4order: 3
5description: "Show a queue of pending decisions and resolve them one by one 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 interrupts at once. Render the queue, then send every answer in one request.
15
16`useChat` collects the answers as local drafts. It sends them together when
17every item has an answer, and the server validates the full batch.
18
19## Quick setup
20
21This page uses the `transfer` tool from [Tool Approval](./tool-approval).
22
23### 1. Render the queue
24
25Map over `interrupts` and switch on `kind`. Give each item its own buttons, and
26add root buttons for the full queue:
27
28```tsx
29// app/decision-queue.tsx
30import { fetchServerSentEvents, useChat } from '@tanstack/ai-react'
31import { transferTool } from '../tools/transfer'
32
33export function DecisionQueue() {
34 const { interrupts, resolveInterrupts, cancelInterrupts, resuming } = useChat({
35 threadId: 'account-42',
36 connection: fetchServerSentEvents('/api/chat'),
37 tools: [transferTool] as const,
38 })
39
40 if (interrupts.length === 0) return null
41
42 return (
43 <section>
44 <p>{interrupts.length} decision(s) needed</p>
45
46 {interrupts.map((interrupt) => {
47 if (
48 interrupt.kind === 'tool-approval' &&
49 interrupt.toolName === 'transfer'
50 ) {
51 return (
52 <article key={interrupt.id}>
53 <p>
54 {interrupt.originalArgs.amount} to{' '}
55 {interrupt.originalArgs.recipient}
56 </p>
57 <button
58 disabled={!interrupt.canResolve || resuming}
59 onClick={() => interrupt.resolveInterrupt(true)}
60 >
61 Approve
62 </button>
63 <button
64 disabled={!interrupt.canResolve || resuming}
65 onClick={() => interrupt.resolveInterrupt(false)}
66 >
67 Reject
68 </button>
69 </article>
70 )
71 }
72 return <article key={interrupt.id}>Unsupported: {interrupt.kind}</article>
73 })}
74
75 <button onClick={() => resolveInterrupts(true)} disabled={resuming}>
76 Approve all
77 </button>
78 <button onClick={() => cancelInterrupts()} disabled={resuming}>
79 Cancel all
80 </button>
81 </section>
82 )
83}
84```
85
86### 2. Try it
87
88Ask the model for two transfers in one message. The queue shows two items.
89Approve one, then the other. The client sends both answers in one request, and
90the run continues.
91
92## How it works
93
94You can resolve items in two ways:
95
96- **Per item.** Call `interrupt.resolveInterrupt(...)` or `interrupt.cancel()`
97 where you render the item.
98- **From the root.** Call `resolveInterrupts(...)` or `cancelInterrupts()` once
99 for the full queue.
100
101Both ways stage local drafts. The client sends nothing until every pending item
102has an answer. Then it submits the full set at once. The server validates the
103full set before it accepts any item.
104
105In a mixed batch, `kind` tells you what each item is:
106
107- `tool-approval`: a tool call. It has its own approval controls.
108- `generic` with a `definitionId`: a registered generic interrupt. The
109 definition id narrows its payload and response types.
110- `generic` without a `definitionId`: an external interrupt with a valid
111 binding. Its controls are untyped, and it joins the batch.
112- `unbound`: the binding is missing, malformed, or of an unsupported version.
113 The item is visible, has no controls, and does not block the other items.
114
115## Resolve every item from one callback
116
117`resolveInterrupts(callback)` runs your callback once for each item that can
118resume, in one synchronous transaction. This includes external generic items
119with a valid binding. The callback must resolve or cancel every item. If it
120throws or skips an item, nothing is sent:
121
122```ts ignore
123resolveInterrupts((interrupt) => {
124 if (interrupt.kind === 'tool-approval') {
125 interrupt.resolveInterrupt(true, { payload: { note: 'Batch review' } })
126 return
127 }
128 interrupt.cancel()
129})
130```
131
132Two shortcuts cover the common cases:
133
134- `resolveInterrupts(true)` or `resolveInterrupts(false)` approves or rejects
135 the full queue. It works only when every item is a tool approval that needs
136 no payload and no edits. It rejects generic items, mixed queues, and required
137 payloads.
138- `cancelInterrupts()` cancels every item that can resume, with no payload.
139 This includes the client-tool steps that `interrupts` does not show.
140
141## When an answer is wrong
142
143A bad answer does not clear the queue. The item keeps your last valid draft and
144shows the error. The user fixes it and submits again.
145
146Errors come in two places. Show both:
147
148- `interrupt.errors`, on each item: a bad payload, bad edited arguments, or an
149 expired item.
150- `interruptErrors`, on the root: errors for the full batch. These are transport
151 errors, server rejections, and errors for internal client-tool steps that
152 have no item of their own.
153
154This component shows both kinds of error, disables its buttons at the right
155times, and offers the two ways to recover:
156
157```tsx
158// app/error-queue.tsx
159import { fetchServerSentEvents, useChat } from '@tanstack/ai-react'
160import { toolDefinition } from '@tanstack/ai'
161import { z } from 'zod'
162
163const transferTool = toolDefinition({
164 name: 'transfer',
165 description: 'Move money between accounts',
166 needsApproval: true,
167 inputSchema: z.object({
168 recipient: z.string(),
169 amount: z.number(),
170 }),
171 outputSchema: z.object({ receiptId: z.string() }),
172}).client()
173
174export function ErrorQueue() {
175 const { interrupts, interruptErrors, retryInterrupts, resuming } = useChat({
176 threadId: 'account-42',
177 connection: fetchServerSentEvents('/api/chat'),
178 tools: [transferTool] as const,
179 })
180
181 // Retry helps only after a transport failure. Expired or stale batches
182 // cannot be retried, so do not offer it for those.
183 const canRetry = interruptErrors.some((error) => error.code === 'transport')
184
185 return (
186 <section>
187 {interrupts.map((interrupt) => {
188 if (
189 interrupt.kind !== 'tool-approval' ||
190 interrupt.toolName !== 'transfer'
191 ) {
192 return null
193 }
194
195 // canResolve reflects the schema and binding, not the live phase.
196 // Also check the item status and whether the run is busy.
197 const busy = interrupt.status === 'submitting' || resuming
198
199 return (
200 <article key={interrupt.id}>
201 <p>
202 {interrupt.originalArgs.amount} to{' '}
203 {interrupt.originalArgs.recipient}
204 </p>
205 <button
206 disabled={!interrupt.canResolve || busy}
207 onClick={() => interrupt.resolveInterrupt(true)}
208 >
209 Approve
210 </button>
211 <button disabled={busy} onClick={() => interrupt.clearResolution()}>
212 Start over
213 </button>
214
215 {/* Item errors: bad payload, bad edited args, expired. */}
216 {interrupt.errors.map((error) => (
217 <p key={`${error.code}:${error.path?.join('.') ?? ''}`}>
218 {error.message}
219 </p>
220 ))}
221 </article>
222 )
223 })}
224
225 {/* Batch errors: transport, server, and hidden client-tool steps. */}
226 {interruptErrors.map((error) => (
227 <p key={error.code}>{error.message}</p>
228 ))}
229 {canRetry ? (
230 <button onClick={() => retryInterrupts()} disabled={resuming}>
231 Retry
232 </button>
233 ) : null}
234 </section>
235 )
236}
237```
238
239The two ways to recover:
240
241- `interrupt.clearResolution()` drops the draft of one item, so the user can
242 answer it again. You can also call `resolveInterrupt` again after the user
243 fixes a form. The new draft replaces the old one.
244- `retryInterrupts()` sends a staged batch again after a transport failure. It
245 does nothing for expired or stale batches. For those, start a new run to get
246 a new set of interrupts.
247
248## Advanced
249
250### Persistence and batch commits
251
252With persistence, `InterruptStore.commitBatch()` can commit the validated batch
253in one database transaction. If the store has no `commitBatch()`, a fallback
254writes the items one after the other. That fallback is not atomic.
255
256With that sequential storage, a failed request can already have committed some
257items. Before you call `retryInterrupts()`, reload the current pending records.
258Then retry only the rest of the batch.
259
260### Restored and live batches
261
262`onInterruptStateChange` gets a `source` with each update:
263
264- `hydrate`: the batch came back from a restored snapshot.
265- `live`: the batch came from the stream or from the client in this session.
266
267Use it to apply a different policy to restored batches. Cancellation still
268applies to every item in the batch that can resume.