Open History to see the last commit
1---
2title: Generic Interrupts
3id: interrupts-generic
4order: 4
5description: "Ask for typed data from the client during a chat lifecycle boundary."
6keywords:
7 - tanstack ai
8 - generic interrupt
9 - defineInterrupt
10 - onInterruptBoundary
11 - onInterruptResolution
12 - INTERRUPT_BOUNDARY_PHASES
13---
14
15Use a generic interrupt when the server needs data from the client but no tool
16call caused the request. For example, ask the user to select a plan before the
17model runs.
18
19`defineInterrupt` defines the data that the client sees and the data it must
20return. Register the same definition with `chat()` and `useChat()`. This gives
21both sides the same types.
22
23## Define and emit an interrupt
24
25Put the definition in a module that both the route and the client can import.
26The schemas must export JSON Schema.
27
28```ts
29// app/interrupts.ts
30import { defineInterrupt } from '@tanstack/ai'
31import { z } from 'zod'
32
33export const reviewPlan = defineInterrupt({
34 id: 'review-plan',
35 payloadSchema: z.object({ title: z.string(), changes: z.array(z.string()) }),
36 responseSchema: z.object({ approved: z.boolean(), note: z.string().optional() }),
37})
38```
39
40`payloadSchema` describes display data that travels from the server to the
41client. `responseSchema` describes data that travels from the client back to
42the server. The display payload is optional. The response schema is required.
43
44Return requests from `onInterruptBoundary`. The hook can run at each value in
45`INTERRUPT_BOUNDARY_PHASES`:
46
47- `beforeModel`: before the adapter call
48- `afterModel`: after the model stream ends
49- `beforeTools`: before tool execution
50- `afterTools`: after tool results are in `messages`
51
52Requests from every middleware in the same boundary form one interrupt batch.
53
54Pick the phase with a `ctx.phase` guard. If `ctx.parentRunId` is set, skip
55the emit. If you do not, the same pause happens again.
56
57When to use each phase, and what `ctx` contains there, is in
58[Lifecycle Boundaries](./boundaries).
59
60```ts
61// app/chat-middleware.ts
62import type { ChatMiddleware } from '@tanstack/ai'
63import { reviewPlan } from './interrupts'
64
65export const requestReview: ChatMiddleware<unknown, typeof reviewPlan> = {
66 name: 'request-review',
67 onInterruptBoundary(ctx) {
68 if (ctx.phase !== 'beforeModel') return
69 if (ctx.parentRunId) return
70 if (ctx.iteration !== 0) return
71 return {
72 interrupts: [
73 reviewPlan.interrupt({
74 key: 'initial-plan',
75 reason: 'review-required',
76 message: 'Review the proposed plan.',
77 payload: { title: 'Release plan', changes: ['Add search', 'Add tests'] },
78 }),
79 ],
80 }
81 },
82}
83```
84
85`interrupt()` accepts only `key`, `reason`, `message`, `expiresAt`, and, when
86declared, `payload`. It returns an immutable request. Do not put secrets in the
87payload because the client receives it and persistence can store it.
88
89## Register it on the server
90
91Register all definitions on `chat({ interrupts })`. A duplicate definition id
92fails before the adapter starts.
93
94```ts
95// app/api/chat/route.ts
96import { chat, chatParamsFromRequest, toServerSentEventsResponse } from '@tanstack/ai'
97import { openaiText } from '@tanstack/ai-openai'
98import { requestReview } from '../../chat-middleware'
99import { reviewPlan } from '../../interrupts'
100
101export async function POST(request: Request) {
102 const params = await chatParamsFromRequest(request)
103 const stream = chat({
104 adapter: openaiText('gpt-5.5'),
105 messages: params.messages,
106 threadId: params.threadId,
107 runId: params.runId,
108 ...(params.parentRunId ? { parentRunId: params.parentRunId } : {}),
109 ...(params.resume ? { resume: params.resume } : {}),
110 interrupts: [reviewPlan],
111 middleware: [requestReview],
112 })
113 return toServerSentEventsResponse(stream)
114}
115```
116
117An interrupt ends the current AG-UI run with one `RUN_FINISHED` event whose
118outcome is `interrupt`. Resolving it starts a new run with `parentRunId` set to
119the interrupted run. The continuation carries the response to the registered
120middleware.
121
122## Resolve it in React
123
124Register the same definitions with `useChat`. A bound generic interrupt has its
125definition id, typed display payload, and typed `resolveInterrupt` method.
126
127Check `kind` and `definitionId`. Then pass the item to a card that takes
128`GenericInterrupt<typeof reviewPlan>`.
129
130```tsx
131// app/plan-review.tsx
132import { fetchServerSentEvents, useChat } from '@tanstack/ai-react'
133import type { GenericInterrupt } from '@tanstack/ai-react'
134import { reviewPlan } from './interrupts'
135
136function ReviewCard({
137 interrupt,
138}: {
139 interrupt: GenericInterrupt<typeof reviewPlan>
140}) {
141 return (
142 <article>
143 <h2>{interrupt.payload?.title}</h2>
144 <button onClick={() => interrupt.resolveInterrupt({ approved: true })}>
145 Approve
146 </button>
147 <button onClick={() => interrupt.cancel()}>Cancel</button>
148 </article>
149 )
150}
151
152export function PlanReview() {
153 const { interrupts } = useChat({
154 threadId: 'release-42',
155 connection: fetchServerSentEvents('/api/chat'),
156 interrupts: [reviewPlan],
157 })
158
159 return (
160 <>
161 {interrupts.map((interrupt) => {
162 if (interrupt.kind !== 'generic') return null
163 if (!('definitionId' in interrupt)) return null
164 if (interrupt.definitionId !== reviewPlan.id) return null
165 return <ReviewCard key={interrupt.id} interrupt={interrupt} />
166 })}
167 </>
168 )
169}
170```
171
172`resolveInterrupt` stages the answer. The client sends one continuation only
173after every bound interrupt in the batch is resolved or cancelled. Use
174`cancel()` when the user declines to provide data.
175
176## Read resumed values in middleware
177
178`onInterruptResolution` does not run in the `chat()` call that paused. It runs
179once at the start of the **next** `chat()` call, after the client answers.
180
181That second call is a new run. `useChat` sends `parentRunId` and `resume`.
182Each generic resume item carries the original request in `metadata`. The hook
183runs after init `onConfig` and before `onStart`. `ctx.phase` is still `'init'`.
184
185`for(definition)` keeps the response type for that definition. `all()` reads
186all registered definitions. `all(definitionA, definitionB)` narrows the
187result to those definitions.
188
189```ts
190import type { ChatMiddleware } from '@tanstack/ai'
191import { reviewPlan } from './interrupts'
192
193export const applyReview: ChatMiddleware<unknown, typeof reviewPlan> = {
194 name: 'apply-review',
195 onInterruptResolution(_ctx, resumedInterrupts) {
196 for (const result of resumedInterrupts.for(reviewPlan)) {
197 if (result.status === 'resolved' && !result.response.approved) {
198 return { toolResume: 'stop' }
199 }
200 }
201 },
202}
203```
204
205Middleware can return `toolResume: 'continue'`, `'cancel'`, or `'stop'`.
206When more than one middleware returns a value, `stop` wins over `cancel`, and
207`cancel` wins over `continue`.
208
209This hook cannot change prompts, tools, or messages. Store the answer on a
210capability, then return those fields from `onConfig` when
211`ctx.phase === 'beforeModel'`. The full order, plus a working example, is in
212[Apply Answers](./apply-answers).
213
214## Try the four lifecycle phases
215
216The React chat example has a playground for `beforeModel`, `afterModel`,
217`beforeTools`, and `afterTools`. Each pause shows two typed cards:
218`reviewPlan` and `chooseAudience`.
219
2201. Start `examples/ts-react-chat`.
2212. Open `/generic-interrupts`.
2223. Pick a phase, resolve both cards, and watch the selected policy.
223
224## External generic interrupts
225
226An external system can emit a standard AG-UI generic interrupt. TanStack AI
227shows it as `kind: 'unbound'` unless it has a valid TanStack binding. It stays
228visible, but it has no resolve or cancel method. This keeps another system from
229receiving a continuation that TanStack AI owns.
230
231See [Multiple Interrupts](./multiple) for mixed tool approvals and generic
232interrupts. See [Chat persistence](../persistence/chat-persistence) when an
233interrupt must survive a restart.
234
235| You want to | Page |
236| --- | --- |
237| Pick `beforeModel`, `afterModel`, `beforeTools`, or `afterTools` | [Lifecycle Boundaries](./boundaries) |
238| Apply the user answer to prompts, tools, or `toolResume` | [Apply Answers](./apply-answers) |
239| Mix generic interrupts with tool approvals | [Multiple Interrupts](./multiple) |