Open History to see the last commit
1---
2title: Approval Flow Processing Architecture
3id: approval-flow-processing
4description: "How a TanStack AI tool approval pauses a run, how the client resumes it, and what the server checks before the tool runs."
5keywords:
6 - tanstack ai
7 - approval flow
8 - interrupts
9 - state machine
10 - persistence
11---
12
13This page lists each step from the model tool call to the tool result, after a person approves the call.
14
15An approval is an interrupt. The run stops before the tool executes and ends with an `interrupt` outcome. The client sends the decision in a new run. The server checks that decision and then runs the tool.
16
17For the public guide, see [Interrupts](../interrupts/overview). This page shows the internals.
18
19## Set up an approval
20
211. Mark the tool with `needsApproval: true`:
22
23```ts
24// tools.ts
25import { toolDefinition } from '@tanstack/ai'
26import { z } from 'zod'
27
28const projects = new Map([['demo', { name: 'Demo project' }]])
29
30export const deleteProjectDefinition = toolDefinition({
31 name: 'delete_project',
32 description: 'Delete a project permanently',
33 inputSchema: z.object({ projectId: z.string() }),
34 outputSchema: z.object({ deleted: z.boolean() }),
35 needsApproval: true,
36})
37
38export const deleteProject = deleteProjectDefinition.server(async ({ projectId }) => {
39 return { deleted: projects.delete(projectId) }
40})
41```
42
432. Pass `parentRunId` and `resume` from the request to `chat()`:
44
45```ts
46// app/api/chat/route.ts
47import {
48 chat,
49 chatParamsFromRequest,
50 toServerSentEventsResponse,
51} from '@tanstack/ai'
52import { openaiText } from '@tanstack/ai-openai'
53import { deleteProject } from './tools'
54
55export async function POST(request: Request) {
56 const params = await chatParamsFromRequest(request)
57 const stream = chat({
58 adapter: openaiText('gpt-6.1-sol'),
59 messages: params.messages,
60 threadId: params.threadId,
61 runId: params.runId,
62 parentRunId: params.parentRunId,
63 ...(params.resume ? { resume: params.resume } : {}),
64 tools: [deleteProject],
65 })
66
67 return toServerSentEventsResponse(stream)
68}
69```
70
713. Render the pending interrupts from `useChat`:
72
73```tsx group=approval-ui
74import type { ItemInterruptError } from '@tanstack/ai'
75import { fetchServerSentEvents, useChat } from '@tanstack/ai-react'
76import { deleteProjectDefinition } from './tools'
77
78export function ApprovalQueue() {
79 const chat = useChat({
80 threadId: 'project-thread',
81 connection: fetchServerSentEvents('/api/chat'),
82 tools: [deleteProjectDefinition] as const,
83 })
84
85 return (
86 <section>
87 {chat.interrupts.map((interrupt) => (
88 <article key={interrupt.id}>
89 <p>Approval required: {interrupt.reason}</p>
90 {interrupt.kind === 'tool-approval' ? (
91 <button onClick={() => interrupt.resolveInterrupt(true)}>
92 Approve
93 </button>
94 ) : null}
95 <button onClick={() => interrupt.cancel()}>Cancel</button>
96 {interrupt.errors.map((error: ItemInterruptError) => (
97 <p key={`${error.code}:${error.path?.join('.') ?? ''}`}>
98 {error.message}
99 </p>
100 ))}
101 </article>
102 ))}
103 </section>
104 )
105}
106```
107
108Ask the model to delete the `demo` project. The Approve button shows. Click it, and the tool runs.
109
110This route needs no server storage. The browser sends the full message history back with the decision, and the engine rebuilds the paused call from it.
111
112## How it works
113
114One approval goes through these steps:
115
1161. The model emits a tool call. On the client, the tool-call part reaches `approval-requested`.
1172. The run ends with `RUN_FINISHED`, and `outcome.type` is `'interrupt'`.
1183. `useChat` shows a bound item in `interrupts`. While an interrupt waits, `useChat` rejects normal input, so no second branch starts.
1194. The UI calls `resolveInterrupt(...)` or `cancel()`. One item submits at once. A batch waits for a valid draft for each item.
1205. The next request has a fresh `runId`, the interrupted `parentRunId`, and the exact AG-UI `resume` array.
1216. The server checks the full set. Then the engine continues the tool call.
122
123Each layer has one job:
124
125| Layer | Job |
126| --- | --- |
127| Tool definition | Declares `needsApproval: true` for a sensitive operation. |
128| Chat engine | Stops before the tool executes and emits the interrupt outcome. |
129| Chat client | Binds descriptors to typed methods, stages drafts, and submits one exact resume batch. |
130| Application UI | Explains the operation and calls `resolveInterrupt`, `cancel`, or the root batch controls. |
131| Delivery adapter | Optional. Replays SSE events by opaque offsets that the adapter owns. |
132
133## Advanced
134
135### The interrupt terminal event
136
137A run that needs user input ends with one canonical event:
138
139```ts
140const interruptTerminal = {
141 type: 'RUN_FINISHED',
142 runId: 'run-1',
143 threadId: 'thread-1',
144 timestamp: Date.now(),
145 outcome: {
146 type: 'interrupt',
147 interrupts: [
148 {
149 id: 'approval-1',
150 reason: 'tool_call',
151 toolCallId: 'call-1',
152 responseSchema: {
153 oneOf: [
154 { type: 'object', properties: { approved: { const: true } } },
155 { type: 'object', properties: { approved: { const: false } } },
156 ],
157 },
158 },
159 ],
160 },
161}
162```
163
164This event stream is the only native approval event stream. It works without persistence.
165
166- **With server state persistence**, the server stores the complete descriptor and binding batch before it exposes the terminal event.
167- **With SSE delivery durability**, the adapter gives each delivered event an opaque resume offset. This is a separate layer.
168
169If your code uses custom approval events, see [Migrate to AG-UI interrupts](../interrupts/migration).
170
171### Descriptor to continuation pipeline
172
173The rule is **descriptor, then validate all, then continuation, then history**:
174
1751. The engine builds public descriptors and bindings. The output includes `MESSAGES_SNAPSHOT`, an optional `STATE_SNAPSHOT`, and the interrupt `RUN_FINISHED` terminal.
1762. The client binds a descriptor only when it matches the tool registry of the client. The match covers reason, tool identity, call ID, schema hashes, interrupted run, and generation. An untrusted descriptor becomes `generic`. It does not get a typed tool resolver.
1773. Item methods check and stage local drafts. The submit boundary holds each pending interrupt ID exactly once.
1784. The client submits a fresh run with the full current message history, the interrupted `parentRunId`, and the complete resume batch.
1795. The server checks **all** payloads, edited inputs, outputs, hashes, and correlation before it executes anything. It rebuilds the expected batch from the history that the client sent and from its current tool definitions.
1806. Resumed tool calls emit results only. They do not replay synthetic tool-call start or argument events. The successful history belongs to the continuation run.
181
182The server rebuilds the batch from history that the client sends. So ephemeral mode does not give replay, exactly-once, restart, or cross-instance guarantees. The server checks the message history, but it is still input from the client.
183
184### Resolve a batch
185
186When several interrupts wait, stage every resolution in one synchronous root callback:
187
188```tsx group=approval-ui
189function ResolveAll({ approved }: { approved: boolean }) {
190 const chat = useChat({
191 threadId: 'project-thread',
192 connection: fetchServerSentEvents('/api/chat'),
193 tools: [deleteProjectDefinition] as const,
194 })
195
196 return (
197 <button
198 onClick={() =>
199 void chat.resolveInterrupts((interrupt) => {
200 if (interrupt.kind === 'tool-approval') {
201 if (approved) {
202 interrupt.resolveInterrupt(true)
203 } else {
204 interrupt.resolveInterrupt(false)
205 }
206 return
207 }
208 interrupt.cancel()
209 })
210 }
211 >
212 Resolve all
213 </button>
214 )
215}
216```
217
218### State durability and delivery durability
219
220These are two different layers:
221
222- **State.** Interrupts run ephemerally. The engine rebuilds the paused call from the message history that the browser sends on the continuation request. Durable recovery is an optional layer, and approvals do not need it.
223- **Delivery.** Delivery durability makes the live byte stream replayable after a dropped connection. You configure it on `toServerSentEventsResponse`. It gives one opaque SSE id per chunk. It is not available for NDJSON. See [Resumable Streams](../resumable-streams/overview).