A person clicked approve once, and the refund went out twice. This guide shows the two ways that happens in the Vercel AI SDK and gives you a fix you can paste in, so one approval means one side effect. Everything below was run on ai 7.0.154 and 7.0.142 (Node 20.19.2), Oct 26, 2026.
How approval works (in one paragraph)
In AI SDK 7 you set toolApproval on generateText or streamText. When the model calls a tool that needs a human, the SDK doesn't run it. It returns a tool-approval-request. Later you send the history back with a tool message holding a tool-approval-response, and the SDK runs the tool and carries on (AI SDK docs: tool approval). The older needsApproval option on tool() still works but is deprecated.
Why it runs twice
- The same approval appears twice in one request. A replayed client event or a buggy merge can put two copies of the same
tool-approval-responseinto the last tool message. In ai 7.0.148 and earlier, the SDK ran the tool once per copy. ai 7.0.149 changed this: "process only the first approval response per tool call" (changelog, PR #23791). - The same approval arrives in two requests. A double click, a retried POST, a second tab or a queue that delivers twice. Each request is a new
generateTextcall with the same history, and the SDK has no memory of the first one. Every version we tested runs the tool twice here, including 7.0.154. This one is yours to fix.
If you use useChat, there was also a client-side case: calling addToolApprovalResponse() twice while an async sendAutomaticallyWhen check was pending sent two continuation requests (issue #22279, fixed in PR #22285). Even with that fix, a retried network request still lands as case 2.
Reproduce it, then fix it
Only the model is fake (MockLanguageModelV4 from ai/test). generateText, the tool loop and the approval logic are real SDK code. charges stands in for your payment provider, and the Map stands in for a database table with a UNIQUE key.
// twice.mjs (npm i ai@7.0.154 zod@4.6.7, "type": "module")
import { generateText, tool, stepCountIs } from 'ai';
import { MockLanguageModelV4 } from 'ai/test';
import { z } from 'zod';
const usage = { inputTokens: { total: 1, noCache: 1, cacheRead: 0, cacheWrite: 0 }, outputTokens: { total: 1, text: 1, reasoning: 0 } };
const finish = (u) => ({ unified: u, raw: u });
const model = () => new MockLanguageModelV4({
doGenerate: async ({ prompt }) => {
const done = prompt.some((m) => m.role === 'tool' && m.content.some((p) => p.type === 'tool-result'));
if (done) return { content: [{ type: 'text', text: 'Refund done.' }], finishReason: finish('stop'), usage, warnings: [] };
return { content: [{ type: 'tool-call', toolCallId: 'call_refund', toolName: 'refund',
input: JSON.stringify({ orderId: '42', amount: 79 }) }], finishReason: finish('tool-calls'), usage, warnings: [] };
},
});
let charges = []; // stands in for your payment provider
const processed = new Map(); // stands in for a table with a UNIQUE key column
const makeTools = (safe) => ({
refund: tool({
description: 'Refund an order',
inputSchema: z.object({ orderId: z.string(), amount: z.number() }),
execute: async ({ orderId, amount }, { toolCallId }) => {
if (safe) {
const key = `chat-1:${toolCallId}`;
if (processed.has(key)) return processed.get(key); // repeat: return the stored result
const result = { refunded: amount };
charges.push(amount);
processed.set(key, result);
return result;
}
charges.push(amount);
return { refunded: amount };
},
}),
});
const toolApproval = { refund: () => ({ type: 'user-approval', reason: 'refunds need a human' }) };
async function pause(tools) {
const messages = [{ role: 'user', content: 'refund order 42' }];
const r = await generateText({ model: model(), tools, toolApproval, messages, stopWhen: stepCountIs(5) });
const req = r.content.find((p) => p.type === 'tool-approval-request');
return { history: [...messages, ...r.response.messages], approvalId: req.approvalId };
}
const approve = (id) => ({ type: 'tool-approval-response', approvalId: id, approved: true });
const resume = (tools, history, parts) =>
generateText({ model: model(), tools, toolApproval, stopWhen: stepCountIs(5),
messages: [...history, { role: 'tool', content: parts }] });
// A: the same approval appears twice in ONE request (e.g. a replayed client event)
charges = []; { const tools = makeTools(false); const p = await pause(tools);
await resume(tools, p.history, [approve(p.approvalId), approve(p.approvalId)]);
console.log('A duplicate response in one request :', charges); }
// B: the same approval is sent in TWO requests (double click, retried POST)
charges = []; { const tools = makeTools(false); const p = await pause(tools);
await Promise.all([resume(tools, p.history, [approve(p.approvalId)]), resume(tools, p.history, [approve(p.approvalId)])]);
console.log('B same approval, two requests :', charges); }
// C: B again, with an idempotent tool keyed on toolCallId
charges = []; { const tools = makeTools(true); const p = await pause(tools);
await Promise.all([resume(tools, p.history, [approve(p.approvalId)]), resume(tools, p.history, [approve(p.approvalId)])]);
console.log('C two requests, idempotent tool :', charges); }
Output on ai 7.0.154:
A duplicate response in one request : [ 79 ]
B same approval, two requests : [ 79, 79 ]
C two requests, idempotent tool : [ 79 ]
On ai 7.0.142 the first line is [ 79, 79 ]. We checked each release: 7.0.148 still charges twice, 7.0.149 charges once. Case B charges twice on every version, and the idempotent tool in case C charges once.
The fix in 3 steps
- Upgrade to ai 7.0.149 or newer. That covers duplicate responses inside one request.
- Make the tool idempotent.
executegets the tool call id as its second argument ({ toolCallId }). That id is saved in the chat history, so every resume of the same call sees the same one. Build a key from your own chat id plustoolCallId. Prefix it with the chat id, because the id comes from the model provider and you shouldn't count on it being unique across chats. Then either send it as your payment provider's idempotency key, or insert it into a table with a UNIQUE constraint before acting and return the stored result if it's already there. TheMapabove only works inside one process; use a real database in production. - Use each approval only once. Before you resume, mark the approval as used in one atomic step, for example
UPDATE approvals SET status='used' WHERE id=$1 AND status='pending', and resume only if one row changed. This stops most duplicates early. The idempotency key catches the rest, such as a retry after a crash.
What we did not test
No real model provider, payment API or database. We tested generateText, not streamText, ToolLoopAgent or WorkflowAgent, and we didn't run the useChat client case ourselves; that part comes from issue #22279. The two requests in case B ran concurrently in one Node process.
Get the template
- Free: Vercel AI SDK tool approval with generateText, the pause, approve, deny and resume flow this guide builds on.
- Done for you: the $79 Agent Approval-Flow Fix. Send a minimal repro. You pay $79 only when our patch passes it.
Check your own agent in 2 minutes
Want to see a repeated side effect happen, then stop? Run the free 2-minute crash test. It kills an agent right after an approved charge and shows how many times the charge runs. Today it covers LangGraph and the OpenAI Agents SDK, not the Vercel AI SDK, but the fix is the same idea: one key per tool call.