Skip to content
5 changes: 5 additions & 0 deletions .changeset/olive-wolves-approve.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@voltagent/core": patch
---

fix(core): persist client approval decisions onto buffered tool parts so restored conversations keep `approval-responded` state instead of re-validating stale parts and throwing `AI_TypeValidationError`
30 changes: 29 additions & 1 deletion packages/core/src/agent/agent.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5005,10 +5005,22 @@ export class Agent {
buffer: ConversationBuffer,
runtimeToolkits: Toolkit[] = [],
): Promise<UIMessage[]> {
const resolvedInput = await this.validateIncomingUIMessages(input, oc);
let resolvedInput = await this.validateIncomingUIMessages(input, oc);
const messages: UIMessage[] = [];
const resolvedMemory = this.resolveMemoryRuntimeOptions(options, oc);
const canIUseMemory = Boolean(resolvedMemory.userId);
if (
resolvedMemory.userId &&
resolvedMemory.conversationId &&
Array.isArray(resolvedInput) &&
(resolvedInput as any[])[0]?.parts
) {
resolvedInput = await this.memoryManager.hydrateApprovalMessages(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: Approval hydration propagates storage read failures before the existing memory fallback can run, so a transient memory outage aborts generation. Catch the hydration read error and continue with the original input.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At packages/core/src/agent/agent.ts, line 5018:

<comment>Approval hydration propagates storage read failures before the existing memory fallback can run, so a transient memory outage aborts generation. Catch the hydration read error and continue with the original input.</comment>

<file context>
@@ -5005,10 +5005,22 @@ export class Agent {
+      Array.isArray(resolvedInput) &&
+      (resolvedInput as any[])[0]?.parts
+    ) {
+      resolvedInput = await this.memoryManager.hydrateApprovalMessages(
+        resolvedInput as UIMessage[],
+        resolvedMemory.userId,
</file context>

resolvedInput as UIMessage[],
resolvedMemory.userId,
resolvedMemory.conversationId,
);
}
const shouldPersistMemory = resolvedMemory.readOnly !== true;
const speculativeInputGuardrail = this.getSpeculativeInputGuardrail(oc);
const shouldPersistInputImmediately =
Expand Down Expand Up @@ -5075,6 +5087,14 @@ export class Agent {
},
);
buffer.ingestUIMessages(memMessages, true);
// Apply approval decisions carried by the input so buffered
// approval-requested parts don't keep a stale `approval`.
if (Array.isArray(resolvedInput)) {
const approvalInput = (resolvedInput as any[])[0]?.parts
? (resolvedInput as UIMessage[])
: convertModelMessagesToUIMessages(resolvedInput as BaseMessage[]);
buffer.applyApprovalResponses(approvalInput);
}
return memMessages;
}
// Regular memory context
Expand Down Expand Up @@ -5103,6 +5123,14 @@ export class Agent {

buffer.ingestUIMessages(result.messages, true);

// Apply approval decisions carried by the input so buffered
// approval-requested parts don't keep a stale `approval`
// (otherwise a later `output-available` part fails AI SDK
// validation and breaks every subsequent turn).
if (Array.isArray(inputForMemory)) {
buffer.applyApprovalResponses(inputForMemory);
}

if (
shouldPersistMemory &&
speculativeInputGuardrail &&
Expand Down
171 changes: 171 additions & 0 deletions packages/core/src/agent/approval-persistence.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,171 @@
/**
* Regression tests for https://github.com/VoltAgent/voltagent/issues/1535
*
* After a `needsApproval` tool call is approved and runs, memory must store
* the tool part as `state: "output-available"` WITH `approval.approved`
* preserved. Previously the buffer was seeded only from stored memory (which
* still held the pre-approval part, `approval: { id }`), the approval
* response in the input never reached the buffer, and the flush overwrote
* the input message - so the stored part lost `approved: true` and every
* later `generateText` on the conversation threw AI_TypeValidationError.
*/
import { MockLanguageModelV3 } from "ai/test";
import { describe, expect, it } from "vitest";
import { z } from "zod";
import { Memory } from "../memory";
import { InMemoryStorageAdapter } from "../memory/adapters/storage/in-memory";
import { createTool } from "../tool";
import { Agent } from "./agent";

const usage = {
inputTokens: 10,
outputTokens: 5,
totalTokens: 15,
inputTokenDetails: {
noCacheTokens: 10,
cacheReadTokens: 0,
cacheWriteTokens: 0,
},
outputTokenDetails: {
textTokens: 5,
reasoningTokens: 0,
},
};

const makeAgent = (storage: InMemoryStorageAdapter) => {
const model = new MockLanguageModelV3({
modelId: "test-model",
doGenerate: async ({ prompt }) => {
await new Promise((r) => setTimeout(r, 1));
return prompt.some((m: any) => m.role === "tool")
? {
content: [{ type: "text" as const, text: "Refund done." }],
finishReason: { unified: "stop" as const, raw: "stop" },
usage,
warnings: [],
}
: {
content: [
{
type: "tool-call" as const,
toolCallId: "call_1",
toolName: "refund",
input: '{"amount":50}',
},
],
finishReason: { unified: "tool-calls" as const, raw: "tool_use" },
usage,
warnings: [],
};
},
});

return new Agent({
name: "a",
instructions: "x",
model: model as any,
memory: new Memory({ storage }),
tools: [
createTool({
name: "refund",
description: "refund",
parameters: z.object({ amount: z.number() }),
needsApproval: true,
execute: async () => ({ refunded: true }),
}),
],
});
};

const memory = { userId: "u", conversationId: "c" };

const storedToolParts = async (storage: InMemoryStorageAdapter) => {
const stored = await storage.getMessages("u", "c");
return stored.flatMap((m: any) => m.parts ?? []).filter((p: any) => p.type === "tool-refund");
};

describe("needsApproval persistence (issue #1535)", () => {
it("keeps approval.approved when an approved tool's result is persisted, and later turns work", async () => {
const storage = new InMemoryStorageAdapter();
const agent = makeAgent(storage);

// Turn 1: model calls the tool, agent asks for approval.
await agent.generateText("refund 50", { memory });

const stored1 = await storage.getMessages("u", "c");
const msg = structuredClone(stored1.at(-1)) as any;
const part = msg.parts.find((p: any) => p.type === "tool-refund");
expect(part.state).toBe("approval-requested");

// Client approves (shape produced by the AI SDK's addToolApprovalResponse).
part.state = "approval-responded";
part.approval = { id: part.approval.id, approved: true };

// Turn 2: tool runs.
await agent.generateText([msg], { memory });

const parts2 = await storedToolParts(storage);
expect(parts2).toHaveLength(1);
expect(parts2[0].state).toBe("output-available");
expect(parts2[0].output).toBeDefined();
expect(parts2[0].approval).toMatchObject({ approved: true });

// Turn 3: a plain follow-up must not fail AI SDK UI message validation.
const result = await agent.generateText("did it go through?", { memory });
expect(result.text).toBe("Refund done.");
}, 30000);

it("keeps approval.approved === false when the client denies the tool", async () => {
const storage = new InMemoryStorageAdapter();
const agent = makeAgent(storage);

await agent.generateText("refund 50", { memory });

const stored1 = await storage.getMessages("u", "c");
const msg = structuredClone(stored1.at(-1)) as any;
const part = msg.parts.find((p: any) => p.type === "tool-refund");

// Client denies.
part.state = "approval-responded";
part.approval = { id: part.approval.id, approved: false };

await agent.generateText([msg], { memory });

const parts2 = await storedToolParts(storage);
expect(parts2).toHaveLength(1);
// The client's denial decision is preserved, never rewritten to an approval.
expect(parts2[0].approval?.approved).toBe(false);
}, 30000);
});

it("keeps approval evidence when memory context is omitted", async () => {
const storage = new InMemoryStorageAdapter();
const agent = makeAgent(storage);
const memory = { userId: "u", conversationId: "c", options: { contextLimit: 0 } };
await agent.generateText("refund 50", { memory });
const stored = await storage.getMessages("u", "c");
const message = structuredClone(stored.at(-1)) as any;
const part = message.parts.find((p: any) => p.type === "tool-refund");
message.parts.unshift({ type: "text", text: "preserve this text" });
message.parts.push({
type: "tool-other",
toolCallId: "other",
state: "output-available",
input: {},
output: "done",
});
await storage.addMessage(structuredClone(message), "u", "c");
part.state = "approval-responded";
part.approval.approved = true;
// Client submits just the approved part; stored sibling parts must survive.
await agent.generateText([{ ...message, parts: [part] }], { memory });
const parts = await storedToolParts(storage);
expect(parts[0]).toMatchObject({ state: "output-available", approval: { approved: true } });
const saved = (await storage.getMessages("u", "c")).find((m) => m.id === message.id);
expect(saved?.parts).toEqual(
expect.arrayContaining([
expect.objectContaining({ type: "text", text: "preserve this text" }),
expect.objectContaining({ toolCallId: "other", output: "done" }),
]),
);
});
126 changes: 126 additions & 0 deletions packages/core/src/agent/conversation-buffer.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -285,3 +285,129 @@ describe("ConversationBuffer", () => {
expect(pending[0]?.id).toBe("user-1");
});
});

describe("approval response persistence", () => {
const stored = {
id: "approval-message",
role: "assistant",
parts: [
{
type: "tool-refund",
toolCallId: "call-refund",
state: "approval-requested",
input: { amount: 50 },
approval: { id: "approval-1" },
},
],
} as unknown as UIMessage;

it.each([true, false])(
"marks an explicit decision %s pending even without a result merge",
(approved) => {
const buffer = new ConversationBuffer([stored]);
const response = structuredClone(stored) as any;
response.parts[0].state = "approval-responded";
response.parts[0].approval.approved = approved;
buffer.applyApprovalResponses([response]);
expect(buffer.drainPendingMessages()).toMatchObject([
{ id: stored.id, parts: [{ state: "approval-responded", approval: { approved } }] },
]);
},
);

it("does not replace terminal approval evidence with a conflicting stale decision", () => {
const terminal = structuredClone(stored) as any;
Object.assign(terminal.parts[0], {
state: "output-available",
output: { ok: true },
approval: { id: "approval-1", approved: true },
});
const buffer = new ConversationBuffer([terminal]);
const stale = structuredClone(stored) as any;
stale.parts[0].approval.approved = false;
stale.parts[0].state = "approval-responded";
buffer.applyApprovalResponses([stale]);
expect((buffer.getAllMessages()[0] as any).parts[0].approval.approved).toBe(true);
expect(buffer.drainPendingMessages()).toEqual([]);
});
});

describe("approval responses with omitted memory context", () => {
it("seeds an explicit approval part so a tool-only result can merge", () => {
const buffer = new ConversationBuffer();
const response = {
id: "omitted",
role: "assistant",
parts: [
{
type: "tool-refund",
toolCallId: "call-1",
input: {},
state: "approval-responded",
approval: { id: "a", approved: true },
},
],
} as unknown as UIMessage;
buffer.applyApprovalResponses([response]);
buffer.addModelMessages([
{
role: "tool",
content: [
{
type: "tool-result",
toolCallId: "call-1",
toolName: "refund",
output: { type: "json", value: "ok" },
},
],
},
]);
expect(buffer.drainPendingMessages()).toMatchObject([
{ id: "omitted", parts: [{ state: "output-available", approval: { approved: true } }] },
]);
});
it("does not invent a decision when omitted input has no boolean approval", () => {
const buffer = new ConversationBuffer();
buffer.applyApprovalResponses([
{
id: "omitted",
role: "assistant",
parts: [
{
type: "tool-refund",
toolCallId: "c",
state: "approval-requested",
input: {},
approval: { id: "a" },
},
],
} as unknown as UIMessage,
]);
expect(buffer.getAllMessages()).toEqual([]);
});
});

it("repairs a terminal part missing its explicit decision without changing the terminal state", () => {
const message = {
id: "legacy",
role: "assistant",
parts: [
{
type: "tool-refund",
toolCallId: "c",
state: "output-available",
input: {},
output: "ok",
approval: { id: "a" },
},
],
} as unknown as UIMessage;
const buffer = new ConversationBuffer([message]);
const input = structuredClone(message) as any;
input.parts[0].state = "approval-responded";
input.parts[0].approval.approved = true;
buffer.applyApprovalResponses([input]);
expect(buffer.drainPendingMessages()).toMatchObject([
{ parts: [{ state: "output-available", approval: { approved: true } }] },
]);
});
Loading