Open History to see the last commit
1---
2title: Approval Flow Processing Architecture
3id: approval-flow-processing
4description: "Internal architecture of TanStack AI tool approvals, interrupts, persistence, and typed client resume handling."
5keywords:
6 - tanstack ai
7 - approval flow
8 - interrupts
9 - state machine
10 - persistence
11---
12
13Tool approval is an interrupt-and-resume protocol. A run that needs user input
14ends with one canonical event:
15
16```ts
17const interruptTerminal = {
18 type: 'RUN_FINISHED',
19 runId: 'run-1',
20 threadId: 'thread-1',
21 timestamp: Date.now(),
22 outcome: {
23 type: 'interrupt',
24 interrupts: [
25 {
26 id: 'approval-1',
27 reason: 'tool_call',
28 toolCallId: 'call-1',
29 responseSchema: {
30 oneOf: [
31 { type: 'object', properties: { approved: { const: true } } },
32 { type: 'object', properties: { approved: { const: false } } },
33 ],
34 },
35 },
36 ],
37 },
38}
39```
40
41The canonical event stream is the only native approval event stream. It works
42ephemerally without persistence. When server state persistence is configured,
43it stores the complete descriptor/binding batch before the terminal is exposed;
44SSE delivery durability separately assigns opaque resume offsets to delivered
45events. Native paths do not emit `approval-requested` or
46`tool-input-available` custom events.
47
48See [Interrupts](../interrupts/overview) for the public server/client guide and
49[Migrate to AG-UI interrupts](../interrupts/migration) for deprecated readers.
50
51## Responsibilities
52
53| Layer | Responsibility |
54| --- | --- |
55| Tool definition | Declares `needsApproval: true` for a sensitive operation. |
56| Chat engine | Stops before tool execution and emits the interrupt outcome. |
57| Chat client | Binds descriptors to typed methods, stages drafts, and submits one exact resume batch. |
58| Application UI | Explains the operation and uses `resolveInterrupt`, `cancel`, or root batch controls. |
59| Delivery adapter | Optionally replays SSE events by opaque adapter-owned offsets. |
60
61## Descriptor to continuation pipeline
62
63The invariant is **descriptor → validate all → continuation → history**:
64
651. The engine builds public descriptors and bindings. Output includes
66 `MESSAGES_SNAPSHOT`, optional `STATE_SNAPSHOT`, and the interrupt
67 `RUN_FINISHED` terminal.
682. The client binds only descriptors whose reason, tool identity, call ID,
69 schema hashes, interrupted run, and generation match its tool registry.
70 Anything untrusted degrades to `generic` rather than gaining a typed tool
71 resolver.
723. Item methods validate and stage local drafts. The submit boundary contains
73 every pending interrupt ID exactly once.
744. The client submits a fresh run with the full current message history, the
75 interrupted `parentRunId`, and the complete resume batch.
765. The server validates **all** payloads, edited inputs, outputs, hashes, and
77 correlation before executing anything, reconstructing the expected batch
78 from the client-provided history and its current tool definitions.
796. Resumed tool calls emit results only; they do not replay synthetic tool-call
80 start/argument events. Successful history belongs to the continuation run.
81
82Because the batch is rebuilt from client-provided history, ephemeral mode does
83not provide replay, exactly-once, restart, or cross-instance guarantees; the
84message history is validated but remains client-provided input.
85
86## Server setup
87
88Define the tool normally. The following route is the **ephemeral** flow (no
89persistence middleware): `chat` + `chatParamsFromRequest` resume the interrupt
90batch from client message history and tool definitions. Durable recovery is a
91separate optional layer and is not required for tool approvals.
92
93```ts
94// tools.ts
95import { toolDefinition } from '@tanstack/ai'
96import { z } from 'zod'
97
98export const deleteProjectDefinition = toolDefinition({
99 name: 'delete_project',
100 description: 'Delete a project permanently',
101 inputSchema: z.object({ projectId: z.string() }),
102 outputSchema: z.object({ deleted: z.boolean() }),
103 needsApproval: true,
104})
105
106export const deleteProject = deleteProjectDefinition.server(async ({ projectId }) => {
107 await deleteProjectFromDatabase(projectId)
108 return { deleted: true }
109})
110
111declare function deleteProjectFromDatabase(projectId: string): Promise<void>
112```
113
114```ts
115// app/api/chat/route.ts
116import {
117 chat,
118 chatParamsFromRequest,
119 toServerSentEventsResponse,
120} from '@tanstack/ai'
121import { openaiText } from '@tanstack/ai-openai'
122import { deleteProject } from './tools'
123
124export async function POST(request: Request) {
125 const params = await chatParamsFromRequest(request)
126 const stream = chat({
127 adapter: openaiText('gpt-5.5'),
128 messages: params.messages,
129 threadId: params.threadId,
130 runId: params.runId,
131 parentRunId: params.parentRunId,
132 ...(params.resume ? { resume: params.resume } : {}),
133 tools: [deleteProject],
134 })
135
136 return toServerSentEventsResponse(stream)
137}
138```
139
140No server storage is required to emit or resolve interrupts. The route above is
141the complete flow: the browser sends the full message history back on the
142continuation request, and the engine rebuilds the paused call from it.
143
144## Client state machine
145
146A single approval follows this sequence:
147
1481. The model emits a tool call.
1492. The client tool-call part reaches `approval-requested`.
1503. The run ends with `RUN_FINISHED.outcome.type === 'interrupt'`.
1514. `useChat` exposes a bound item in `interrupts`.
1525. The UI calls `resolveInterrupt(...)` or `cancel()`; a singleton
153 submits immediately, while a multi-item batch waits for every valid draft.
1546. The next request carries a fresh `runId`, the interrupted `parentRunId`, and
155 the exact AG-UI `resume` array.
1567. The server validates the full set before the engine continues the tool call.
157
158Normal input is rejected at step 4. This prevents a second branch from being
159created while the existing run still waits for a decision.
160
161## React approval UI
162
163Use the bound values returned by `useChat`. Rendering `interrupts` keeps IDs,
164tool types, drafts, and errors connected to the hook that owns the run.
165
166```tsx group=approval-ui
167import type { ItemInterruptError } from '@tanstack/ai'
168import { fetchServerSentEvents, useChat } from '@tanstack/ai-react'
169import { deleteProjectDefinition } from './tools'
170
171export function ApprovalQueue() {
172 const chat = useChat({
173 id: 'project-chat',
174 threadId: 'project-thread',
175 connection: fetchServerSentEvents('/api/chat'),
176 tools: [deleteProjectDefinition] as const,
177 })
178
179 return (
180 <section>
181 {chat.interrupts.map((interrupt) => (
182 <article key={interrupt.id}>
183 <p>Approval required: {interrupt.reason}</p>
184 {interrupt.kind === 'tool-approval' ? (
185 <button onClick={() => interrupt.resolveInterrupt(true)}>
186 Approve
187 </button>
188 ) : null}
189 <button onClick={() => interrupt.cancel()}>Cancel</button>
190 {interrupt.errors.map((error: ItemInterruptError) => (
191 <p key={`${error.code}:${error.path?.join('.') ?? ''}`}>
192 {error.message}
193 </p>
194 ))}
195 </article>
196 ))}
197 </section>
198 )
199}
200```
201
202For a batch, stage every resolution in one synchronous root callback:
203
204```tsx group=approval-ui
205function ResolveAll({ approved }: { approved: boolean }) {
206 const chat = useChat({
207 threadId: 'project-thread',
208 connection: fetchServerSentEvents('/api/chat'),
209 tools: [deleteProjectDefinition] as const,
210 })
211
212 return (
213 <button
214 onClick={() =>
215 void chat.resolveInterrupts((interrupt) => {
216 if (interrupt.kind === 'tool-approval') {
217 if (approved) {
218 interrupt.resolveInterrupt(true)
219 } else {
220 interrupt.resolveInterrupt(false)
221 }
222 return
223 }
224 interrupt.cancel()
225 })
226 }
227 >
228 Resolve all
229 </button>
230 )
231}
232```
233
234## State durability versus delivery durability
235
236Interrupts run ephemerally: the paused call is rebuilt from the message history
237the browser replays on the continuation request. That is separate from
238*delivery* durability, which makes the live byte stream replayable after a
239dropped connection. Delivery durability is configured on
240`toServerSentEventsResponse` and assigns one opaque SSE id per chunk (it is not
241available for NDJSON). See [Resumable Streams](../resumable-streams/overview).