Open History to see the last commit
1---
2title: Overview
3id: interrupts-overview
4order: 1
5description: "Pause an agent run until a person or your app makes a decision, then continue the run from the same point."
6keywords:
7 - tanstack ai
8 - ag-ui interrupts
9 - human in the loop
10 - tool approval
11 - resolveInterrupt
12---
13
14An interrupt pauses a run until a person decides. The run then continues from the same point.
15
16## Quick setup
17
18This setup gates one tool behind a human approval. If you already have a chat
19route, it takes about 5 minutes.
20
21### 1. Mark the tool
22
23Add `needsApproval: true`. Put the tool in a file that the server and the
24browser both import, so both sides get the same types:
25
26```ts
27// tools/transfer.ts
28import { toolDefinition } from '@tanstack/ai'
29import { z } from 'zod'
30
31export const transferTool = toolDefinition({
32 name: 'transfer',
33 description: 'Transfer funds to a recipient',
34 needsApproval: true,
35 inputSchema: z.object({
36 amount: z.number().positive(),
37 recipient: z.string().min(1),
38 }),
39 outputSchema: z.object({ receiptId: z.string() }),
40})
41```
42
43### 2. Serve it
44
45Add the server implementation. Forward `parentRunId` and `resume` into
46`chat()`, so the continuation can find the paused call:
47
48```ts
49// app/api/chat/route.ts
50import {
51 chat,
52 chatParamsFromRequest,
53 toServerSentEventsResponse,
54} from '@tanstack/ai'
55import { openaiText } from '@tanstack/ai-openai'
56import { transferTool } from '../../../tools/transfer'
57
58const transfer = transferTool.server(
59 async (input: { amount: number; recipient: string }) => ({
60 receiptId: `${input.recipient}-${input.amount}-${crypto.randomUUID()}`,
61 }),
62)
63
64export async function POST(request: Request) {
65 const params = await chatParamsFromRequest(request)
66 const stream = chat({
67 adapter: openaiText('gpt-6.1-sol'),
68 messages: params.messages,
69 threadId: params.threadId,
70 runId: params.runId,
71 parentRunId: params.parentRunId,
72 ...(params.resume ? { resume: params.resume } : {}),
73 tools: [transfer],
74 })
75 return toServerSentEventsResponse(stream)
76}
77```
78
79### 3. Render the approval
80
81Pass the same tool to `useChat`. Render each item in `interrupts`, and call
82`interrupt.resolveInterrupt(...)` on it:
83
84```tsx
85// app/transfer-chat.tsx
86import { useState } from 'react'
87import { fetchServerSentEvents, useChat } from '@tanstack/ai-react'
88import { transferTool } from '../tools/transfer'
89
90export function TransferChat() {
91 const { messages, sendMessage, interrupts, resuming } = useChat({
92 threadId: 'account-42',
93 connection: fetchServerSentEvents('/api/chat'),
94 tools: [transferTool] as const,
95 })
96 const [input, setInput] = useState('')
97
98 return (
99 <div>
100 {messages.map((message) => (
101 <div key={message.id}>
102 <strong>{message.role}: </strong>
103 {message.parts.map((part, i) =>
104 part.type === 'text' ? <span key={i}>{part.content}</span> : null,
105 )}
106 </div>
107 ))}
108
109 {interrupts.map((interrupt) => {
110 if (
111 interrupt.kind !== 'tool-approval' ||
112 interrupt.toolName !== 'transfer'
113 ) {
114 return null
115 }
116 return (
117 <div key={interrupt.id}>
118 <p>
119 Send {interrupt.originalArgs.amount} to{' '}
120 {interrupt.originalArgs.recipient}?
121 </p>
122 <button
123 disabled={!interrupt.canResolve || resuming}
124 onClick={() => interrupt.resolveInterrupt(true)}
125 >
126 Approve
127 </button>
128 <button
129 disabled={!interrupt.canResolve || resuming}
130 onClick={() => interrupt.resolveInterrupt(false)}
131 >
132 Reject
133 </button>
134 </div>
135 )
136 })}
137
138 <form
139 onSubmit={(event) => {
140 event.preventDefault()
141 void sendMessage(input)
142 setInput('')
143 }}
144 >
145 <input value={input} onChange={(event) => setInput(event.target.value)} />
146 <button type="submit">Send</button>
147 </form>
148 </div>
149 )
150}
151```
152
153### 4. Try it
154
155Ask the model to send 20 to Ada. The chat stops on the `transfer` call and
156shows Approve and Reject. Click Approve. The tool runs, and the model gives its
157answer.
158
159## How it works
160
1611. The model calls a tool that has `needsApproval: true`. The server ends the
162 run with an `interrupt` outcome, with no final answer.
1632. `useChat` puts the pending decision in `interrupts`.
1643. You resolve each item: approve, reject, submit a value, or cancel.
1654. The client starts a new run, the continuation. It carries your answers, and
166 the agent continues from the pause.
167
168```mermaid
169sequenceDiagram
170 participant User
171 participant Client
172 participant Server
173
174 Client->>Server: send message, run starts
175 Server-->>Client: interrupt outcome, run ends without a final answer
176 Client->>User: pending decisions in `interrupts`
177 User->>Client: approve, reject, or submit a value
178 Client->>Server: continuation request with the answers, a new run
179 Server-->>Client: the agent continues from the pause, final answer
180```
181
182One turn that the user sees is two runs: the interrupted run and the
183continuation. See [Threads and runs](../chat/stream-events#threads-and-runs).
184
185The server needs no database. The browser sends the full message history back
186on the continuation request. Then a stateless server can rebuild the paused
187step and continue.
188
189## What can pause a run
190
191| `kind` | You get a pause when | Guide |
192| --- | --- | --- |
193| `tool-approval` | The model calls a tool that has `needsApproval` | [Tool Approval](./tool-approval) |
194| `generic` | Middleware asks the client for typed data at a lifecycle boundary | [Generic Interrupts](./generic) |
195
196An MCP server can also ask for input during a tool call. The run then ends with
197an interrupt. See [MCP client input](../tools/mcp-input).
198
199A tool with a `.client()` implementation runs in the browser and reports its
200own result. You make no decision, so it does not show in `interrupts`. See
201[Client Tools](../tools/client-tools).
202
203A tool pauses only when you mark it `needsApproval: true`. Then it waits for a
204yes or no first, on the server or in the browser:
205
206| Tool | What you handle |
207| --- | --- |
208| Server tool (`.server()`) | Nothing. With `needsApproval`, you approve first, then it runs on the server. |
209| Client tool (`.client()`) | Nothing. It runs in the browser. With `needsApproval`, you approve first, then it runs in the browser. |
210
211Both kinds use the same `tool-approval` interrupt, so your approval UI does not
212change.
213
214## Where to go next
215
216| You want to | Page |
217| --- | --- |
218| Add a note or a reason to an approval, or edit the arguments | [Tool Approval](./tool-approval) |
219| Resolve several pending decisions at once | [Multiple Interrupts](./multiple) |
220| Ask the user something that is not a tool call | [Generic Interrupts](./generic) |
221| Pick `beforeModel`, `afterModel`, `beforeTools`, or `afterTools` | [Lifecycle Boundaries](./boundaries) |
222| Use a generic answer in prompts, or stop the run | [Apply Answers](./apply-answers) |
223| Move a 0.x approval UI to 1.0 | [Migration](./migration) |
224
225## Advanced
226
227### Replayed events
228
229When the client replays saved events, it follows `parentRunId` links. Then it
230does not show a resolved pause again.
231
232- A continuation that ends without an interrupt clears the pending decisions of
233 its ancestor. This is true also when the parent link arrives later.
234- Intermediate `tool_calls` events do not mark the run or its ancestors as
235 answered.
236
237### Restored client tools
238
239Persistence can restore a pending client-tool execution. The client keeps it
240pending and does not run the browser code again. For recovery policies, see
241[Client persistence](../persistence/client-persistence#handle-restored-client-tools).
242
243### First-party generic interrupts
244
245A generic interrupt that TanStack AI owns starts with `defineInterrupt()`:
246
247- Register the definition with both `chat({ interrupts })` and
248 `useChat({ interrupts })`.
249- Middleware emits it from `onInterruptBoundary`.
250- The client gets a typed item that it can resolve or cancel.
251
252See [Generic Interrupts](./generic).
253
254### Interrupts from other systems
255
256An interrupt is a standard AG-UI object. Other producers can put one on the same stream. Examples are a workflow engine
257that pauses for a durable approval, or another agent framework on the same
258connection.
259
260The client sorts each generic interrupt into one of three cases:
261
262- **Registered first-party generic.** `kind: 'generic'`, a literal
263 `definitionId`, a typed `payload`, and a typed `resolveInterrupt`.
264- **External generic with a valid binding.** Also `kind: 'generic'`. Its
265 response is `unknown`, but it has `resolveInterrupt`, `cancel`, and
266 `clearResolution`. It joins the root batch controls.
267- **No valid binding.** `kind: 'unbound'`. The binding is missing, malformed, or
268 of an unsupported version. The item is visible, but it has no controls.
269
270The binding is in the interrupt metadata under
271`INTERRUPT_BINDING_METADATA_KEY`. It records the interrupted run and the
272generation. The client uses it to send the answer to the matching paused step.
273
274Show unbound items as status only. Do not show a response form for them:
275
276```tsx
277import { fetchServerSentEvents, useChat } from '@tanstack/ai-react'
278import { toolDefinition } from '@tanstack/ai'
279import { z } from 'zod'
280
281const transferTool = toolDefinition({
282 name: 'transfer',
283 description: 'Move money between accounts',
284 needsApproval: true,
285 inputSchema: z.object({ recipient: z.string(), amount: z.number() }),
286 outputSchema: z.object({ receiptId: z.string() }),
287}).client()
288
289export function Pauses() {
290 const { interrupts } = useChat({
291 threadId: 'thread-1',
292 connection: fetchServerSentEvents('/api/chat'),
293 tools: [transferTool] as const,
294 })
295
296 return (
297 <>
298 {interrupts.map((interrupt) => {
299 if (interrupt.kind === 'unbound') {
300 return (
301 <p key={interrupt.id}>
302 External pause: {interrupt.message ?? interrupt.reason}
303 </p>
304 )
305 }
306 if (interrupt.kind === 'generic') {
307 return (
308 <article key={interrupt.id}>
309 <p>{interrupt.message ?? interrupt.reason}</p>
310 <button
311 onClick={() =>
312 interrupt.resolveInterrupt({ speed: 'express' })
313 }
314 >
315 Choose express
316 </button>
317 <button onClick={() => interrupt.cancel()}>Cancel</button>
318 <button onClick={() => interrupt.clearResolution()}>
319 Clear choice
320 </button>
321 </article>
322 )
323 }
324 return (
325 <button
326 key={interrupt.id}
327 onClick={() => interrupt.resolveInterrupt(true)}
328 >
329 Approve {interrupt.toolName}
330 </button>
331 )
332 })}
333 </>
334 )
335}
336```
337
338The library does not make up a binding for an unbound item. With a made-up binding, the answer goes to a run that has nothing pending.
339Then the submit fails after the user fills in the form. `unbound` tells you that the pause
340belongs to a different system. Unbound items never block the items that are
341yours.
342
343For an external producer that wants the chat client to resume its pause, attach
344a valid binding with `withInterruptBinding`. Do not write the metadata key
345yourself. Use the exact interrupted run id and generation that own the pause:
346
347```ts
348import {
349 INTERRUPT_BINDING_VERSION,
350 canonicalInterruptJson,
351 digestInterruptJson,
352 withInterruptBinding,
353} from '@tanstack/ai'
354
355const responseSchema = {
356 type: 'object',
357 properties: { speed: { type: 'string' } },
358 required: ['speed'],
359}
360
361const descriptor = withInterruptBinding(
362 {
363 id: 'shipping-1',
364 reason: 'confirmation',
365 message: 'Which shipping speed?',
366 responseSchema,
367 },
368 {
369 v: INTERRUPT_BINDING_VERSION,
370 kind: 'generic',
371 interruptId: 'shipping-1',
372 interruptedRunId: 'run-42',
373 generation: 0,
374 // The server compares the schema it sends with the schema it validates
375 // against, so the hash comes from the schema itself.
376 responseSchemaHash: digestInterruptJson(
377 canonicalInterruptJson(responseSchema),
378 ),
379 },
380)
381```
382
383The client treats this item as an untyped generic interrupt. Like the `generic`
384branch above, it can stage a value, cancel, or clear the draft. It can also
385join `resolveInterrupts(...)` with tool approvals and first-party generic
386interrupts.
387
388`v` is the version of the binding format. The client rejects unknown versions
389and bad fields. Those interrupts become `unbound`, so you never get a form that
390cannot resume the owner.