diff --git a/.changeset/five-candles-care.md b/.changeset/five-candles-care.md new file mode 100644 index 000000000..fdffb04f4 --- /dev/null +++ b/.changeset/five-candles-care.md @@ -0,0 +1,14 @@ +--- +"@voltagent/core": patch +--- + +fix(core): persist reasoning and tool parts across step checkpoint flushes (#1130) + +When `conversationPersistence.mode = "step"` was used with tool calls, some checkpoint flows could +persist incomplete assistant messages and lose non-text parts in stored conversation history. + +This update preserves complete assistant message parts during checkpoint merges and persistence +flushes, including reasoning, tool-call, tool-result, and text parts. + +Regression coverage is expanded with end-to-end agent persistence tests against both LibSQL and +PostgreSQL backends to reduce the chance of similar regressions. diff --git a/.github/workflows/prerelease.yml b/.github/workflows/prerelease.yml index 41c33ea5d..bcf022d9d 100644 --- a/.github/workflows/prerelease.yml +++ b/.github/workflows/prerelease.yml @@ -52,9 +52,28 @@ jobs: - name: Test Package run: lerna run test --scope "${{ steps.scope.outputs.scope }}" + e2e-tests: + runs-on: ubuntu-latest + name: E2E Tests + steps: + - uses: actions/checkout@v4 + - uses: pnpm/action-setup@v4 + - uses: actions/setup-node@v4 + with: + node-version: 20 + cache: "pnpm" + - name: Install Dependencies + run: pnpm install + env: + NODE_OPTIONS: "--max-old-space-size=8192" + - name: Build E2E Dependencies + run: pnpm lerna run build --scope @voltagent/e2e --include-dependencies + - name: Run E2E Tests + run: pnpm --filter @voltagent/e2e test + prerelease: name: Prerelease - needs: test-packages + needs: [test-packages, e2e-tests] runs-on: ubuntu-latest permissions: contents: write diff --git a/.github/workflows/pull-request.yml b/.github/workflows/pull-request.yml index 0a1d08a8f..25d7eb857 100644 --- a/.github/workflows/pull-request.yml +++ b/.github/workflows/pull-request.yml @@ -172,3 +172,56 @@ jobs: npm run test:integration:ci env: DATABASE_URL: postgresql://test:test@localhost:5432/voltagent_test + + e2e-tests: + runs-on: ubuntu-latest + name: E2E Tests + concurrency: + group: ${{ github.ref }}-e2e-tests + cancel-in-progress: true + steps: + - uses: actions/checkout@v4 + with: + fetch-depth: 0 + + - name: Check for E2E-related changes + id: check_e2e + run: | + BASE_SHA="${{ github.event.pull_request.base.sha }}" + + if ! git cat-file -e "$BASE_SHA^{commit}" 2>/dev/null; then + git fetch origin "${{ github.event.pull_request.base.ref }}" --depth=1 + BASE_SHA="origin/${{ github.event.pull_request.base.ref }}" + fi + + if git diff --name-only "$BASE_SHA"...HEAD | grep -E '^(\.github/workflows/pull-request\.yml|packages/e2e/|packages/core/|packages/libsql/|packages/postgres/|packages/internal/|packages/logger/|package\.json|pnpm-lock\.yaml)'; then + echo "e2e_changed=true" >> $GITHUB_OUTPUT + else + echo "e2e_changed=false" >> $GITHUB_OUTPUT + fi + + - name: Skip if no E2E-related changes + if: steps.check_e2e.outputs.e2e_changed == 'false' + run: echo "No E2E-related changes detected, skipping E2E tests" + + - uses: pnpm/action-setup@v4 + if: steps.check_e2e.outputs.e2e_changed == 'true' + - uses: actions/setup-node@v4 + if: steps.check_e2e.outputs.e2e_changed == 'true' + with: + node-version: 20 + cache: "pnpm" + + - name: Install Dependencies + if: steps.check_e2e.outputs.e2e_changed == 'true' + run: pnpm install + env: + NODE_OPTIONS: "--max-old-space-size=8192" + + - name: Build E2E Dependencies + if: steps.check_e2e.outputs.e2e_changed == 'true' + run: pnpm lerna run build --scope @voltagent/e2e --include-dependencies + + - name: Run E2E Tests + if: steps.check_e2e.outputs.e2e_changed == 'true' + run: pnpm --filter @voltagent/e2e test diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 31e63b4b1..edd3b8da4 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -48,8 +48,27 @@ jobs: - name: Test Package run: lerna run test --scope "${{ steps.scope.outputs.scope }}" + e2e-tests: + runs-on: ubuntu-latest + name: E2E Tests + steps: + - uses: actions/checkout@v4 + - uses: pnpm/action-setup@v4 + - uses: actions/setup-node@v4 + with: + node-version: 20 + cache: "pnpm" + - name: Install Dependencies + run: pnpm install + env: + NODE_OPTIONS: "--max-old-space-size=8192" + - name: Build E2E Dependencies + run: pnpm lerna run build --scope @voltagent/e2e --include-dependencies + - name: Run E2E Tests + run: pnpm --filter @voltagent/e2e test + publish: - needs: test-packages + needs: [test-packages, e2e-tests] permissions: contents: write id-token: write diff --git a/packages/core/src/agent/conversation-buffer.spec.ts b/packages/core/src/agent/conversation-buffer.spec.ts index 5615028f4..39d380545 100644 --- a/packages/core/src/agent/conversation-buffer.spec.ts +++ b/packages/core/src/agent/conversation-buffer.spec.ts @@ -104,6 +104,78 @@ describe("ConversationBuffer", () => { expect(reasoningParts[1]?.providerMetadata).toEqual({ openai: { itemId: "rs_TWO" } }); }); + it("merges subsequent response checkpoints with same assistant id after an intermediate flush", () => { + const buffer = new ConversationBuffer(); + + buffer.addModelMessages( + [ + { + id: "response-1", + role: "assistant", + content: [ + { + type: "tool-call", + toolCallId: "call-1", + toolName: "getWeather", + input: { location: "Berlin" }, + }, + ], + }, + { + role: "tool", + content: [ + { + type: "tool-result", + toolCallId: "call-1", + toolName: "getWeather", + output: { condition: "sunny" }, + }, + ], + }, + ], + "response", + ); + + const firstFlush = buffer.drainPendingMessages(); + expect(firstFlush).toHaveLength(1); + expect(firstFlush[0]?.id).toBe("response-1"); + + buffer.addModelMessages( + [ + { + id: "response-1", + role: "assistant", + content: [ + { + type: "text", + text: "Berlin hava durumu güneşli.", + }, + ], + }, + ], + "response", + ); + + const secondFlush = buffer.drainPendingMessages(); + expect(secondFlush).toHaveLength(1); + expect(secondFlush[0]?.id).toBe("response-1"); + expect(secondFlush[0]?.parts).toEqual([ + { + type: "tool-getWeather", + toolCallId: "call-1", + state: "output-available", + input: { location: "Berlin" }, + output: { condition: "sunny" }, + providerExecuted: false, + }, + { type: "step-start" }, + { type: "text", text: "Berlin hava durumu güneşli." }, + ]); + + const all = buffer.getAllMessages(); + expect(all).toHaveLength(1); + }); + it("preserves preloaded memory messages without marking them pending", () => { const existing: UIMessage[] = [ { diff --git a/packages/core/src/agent/conversation-buffer.ts b/packages/core/src/agent/conversation-buffer.ts index f50d512f8..04ba65238 100644 --- a/packages/core/src/agent/conversation-buffer.ts +++ b/packages/core/src/agent/conversation-buffer.ts @@ -304,6 +304,19 @@ export class ConversationBuffer { } if (source === "response") { + const hasSameAssistantId = + typeof message.id === "string" && + message.id.length > 0 && + typeof lastMessage.id === "string" && + lastMessage.id.length > 0 && + message.id === lastMessage.id; + + if (hasSameAssistantId) { + this.mergeAssistantMessage(message); + this.activeAssistantMessageId = lastMessage.id; + return; + } + const isActiveTarget = this.activeAssistantMessageId !== undefined && this.activeAssistantMessageId === lastMessage.id; diff --git a/packages/core/src/agent/memory-persistence.integration.spec.ts b/packages/core/src/agent/memory-persistence.integration.spec.ts index 0c6422ba4..618e14600 100644 --- a/packages/core/src/agent/memory-persistence.integration.spec.ts +++ b/packages/core/src/agent/memory-persistence.integration.spec.ts @@ -210,4 +210,105 @@ describe("Conversation persistence integration", () => { output: { results: ["Result A", "Result B"] }, }); }); + + it("keeps tool call/result parts when final text arrives after an intermediate checkpoint flush", async () => { + const logger = createLogger(); + const memoryManager = { + saveMessage: vi.fn().mockResolvedValue(undefined), + }; + + const buffer = new ConversationBuffer(undefined, logger as any); + const queue = new MemoryPersistQueue(memoryManager as any, { + debounceMs: 0, + logger: logger as any, + }); + const oc = createOperationContext(logger); + + buffer.addModelMessages( + [ + { + id: "assistant-checkpoint", + role: "assistant", + content: [ + { + type: "reasoning", + text: "First I should read the calendar for that date.", + }, + { + type: "tool-call", + toolCallId: "call-1", + toolName: "checkCalendar", + input: { date: "2023-11-15" }, + }, + ], + }, + { + role: "tool", + content: [ + { + type: "tool-result", + toolCallId: "call-1", + toolName: "checkCalendar", + output: { + events: [{ title: "Team meeting" }], + }, + }, + ], + }, + ], + "response", + ); + + await queue.flush(buffer, oc); + + buffer.addModelMessages( + [ + { + id: "assistant-checkpoint", + role: "assistant", + content: [ + { + type: "text", + text: "You have one event: Team meeting.", + }, + ], + }, + ], + "response", + ); + + await queue.flush(buffer, oc); + + expect(memoryManager.saveMessage).toHaveBeenCalledTimes(2); + + const persistedAssistantMessages = memoryManager.saveMessage.mock.calls.map( + (call) => call[1] as UIMessage, + ); + const firstMessage = persistedAssistantMessages[0]; + const finalMessage = persistedAssistantMessages[1]; + + expect(firstMessage?.id).toBe("assistant-checkpoint"); + expect(finalMessage?.id).toBe("assistant-checkpoint"); + expect(finalMessage?.parts.map((part) => part.type)).toEqual([ + "reasoning", + "tool-checkCalendar", + "step-start", + "text", + ]); + expect(finalMessage?.parts[0]).toMatchObject({ + type: "reasoning", + text: "First I should read the calendar for that date.", + }); + expect(finalMessage?.parts[1]).toMatchObject({ + toolCallId: "call-1", + state: "output-available", + output: { + events: [{ title: "Team meeting" }], + }, + }); + expect(finalMessage?.parts[3]).toMatchObject({ + type: "text", + text: "You have one event: Team meeting.", + }); + }); }); diff --git a/packages/core/src/memory/manager/memory-manager.spec.ts b/packages/core/src/memory/manager/memory-manager.spec.ts index 3750e83d5..e9e5a8a31 100644 --- a/packages/core/src/memory/manager/memory-manager.spec.ts +++ b/packages/core/src/memory/manager/memory-manager.spec.ts @@ -1,3 +1,4 @@ +import type { UIMessage } from "ai"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import type { OperationContext } from "../../agent/types"; import { getGlobalLogger } from "../../logger"; @@ -6,6 +7,15 @@ import { InMemoryStorageAdapter } from "../../memory/adapters/storage/in-memory" import { createTestUIMessage } from "../../memory/test-utils"; import { MemoryManager } from "./memory-manager"; +type EnsureConversationExistsSpyTarget = { + ensureConversationExists: ( + context: OperationContext, + userId: string, + conversationId: string, + input?: OperationContext["input"] | UIMessage, + ) => Promise; +}; + // Helper function to create mock OperationContext function createMockOperationContext(): OperationContext { const mockSpan = { @@ -217,4 +227,75 @@ describe("MemoryManager", () => { await expect(manager.shutdown()).resolves.not.toThrow(); }); }); + + describe("saveConversationSteps", () => { + it("should create conversation automatically before persisting steps", async () => { + const context = createMockOperationContext(); + context.input = "first turn"; + + await manager.saveConversationSteps( + context, + [ + { + id: "step-1", + conversationId: "conv-steps-auto", + userId: "user-steps-auto", + agentId: "agent-1", + agentName: "Agent 1", + operationId: "op-1", + stepIndex: 0, + type: "text", + role: "assistant", + content: "hello", + createdAt: new Date().toISOString(), + }, + ], + "user-steps-auto", + "conv-steps-auto", + ); + + const conversation = await memory.getConversation("conv-steps-auto"); + expect(conversation).not.toBeNull(); + + const steps = await memory.getConversationSteps("user-steps-auto", "conv-steps-auto"); + expect(steps).toHaveLength(1); + expect(steps[0]?.id).toBe("step-1"); + }); + + it("should skip step persistence when ensuring conversation fails", async () => { + const context = createMockOperationContext(); + context.input = "first turn"; + + const managerWithEnsureConversationExists = + manager as unknown as EnsureConversationExistsSpyTarget; + const ensureConversationExistsSpy = vi + .spyOn(managerWithEnsureConversationExists, "ensureConversationExists") + .mockResolvedValue(false); + const saveConversationStepsSpy = vi.spyOn(memory, "saveConversationSteps"); + + await manager.saveConversationSteps( + context, + [ + { + id: "step-2", + conversationId: "conv-steps-fail", + userId: "user-steps-fail", + agentId: "agent-1", + agentName: "Agent 1", + operationId: "op-2", + stepIndex: 0, + type: "text", + role: "assistant", + content: "hello", + createdAt: new Date().toISOString(), + }, + ], + "user-steps-fail", + "conv-steps-fail", + ); + + expect(ensureConversationExistsSpy).toHaveBeenCalledTimes(1); + expect(saveConversationStepsSpy).not.toHaveBeenCalled(); + }); + }); }); diff --git a/packages/core/src/memory/manager/memory-manager.ts b/packages/core/src/memory/manager/memory-manager.ts index 287fb0248..54f1bb9c9 100644 --- a/packages/core/src/memory/manager/memory-manager.ts +++ b/packages/core/src/memory/manager/memory-manager.ts @@ -242,6 +242,17 @@ export class MemoryManager { try { await trace.withSpan(span, async () => { + const ensuredConversation = await this.ensureConversationExists( + context, + userId, + conversationId, + context.input, + ); + if (!ensuredConversation) { + throw new Error( + `Failed to ensure conversation exists before step persistence for conversation ${conversationId}`, + ); + } await this.conversationMemory?.saveConversationSteps?.(steps); }); trace.endChildSpan(span, "completed", { @@ -522,7 +533,17 @@ export class MemoryManager { operation: async () => { try { // First ensure conversation exists - await this.ensureConversationExists(context, userId, conversationId, input); + const ensuredConversation = await this.ensureConversationExists( + context, + userId, + conversationId, + input, + ); + if (!ensuredConversation) { + throw new Error( + `Failed to ensure conversation exists before input persistence for conversation ${conversationId}`, + ); + } // Then save current input await this.saveCurrentInput(context, input, userId, conversationId); @@ -583,13 +604,36 @@ export class MemoryManager { * Ensure conversation exists (background task) * PRESERVED FROM ORIGINAL */ + private isConversationAlreadyExistsError(error: unknown): boolean { + if (!error || typeof error !== "object") { + return false; + } + + const record = error as Record; + const code = typeof record.code === "string" ? record.code : ""; + const duplicateCodes = new Set([ + "CONVERSATION_ALREADY_EXISTS", + "23505", // PostgreSQL unique violation + "SQLITE_CONSTRAINT_PRIMARYKEY", + "SQLITE_CONSTRAINT_UNIQUE", + "SQLITE_CONSTRAINT", + ]); + + if (duplicateCodes.has(code)) { + return true; + } + + const message = typeof record.message === "string" ? record.message.toLowerCase() : ""; + return message.includes("already exists") || message.includes("duplicate"); + } + private async ensureConversationExists( context: OperationContext, userId: string, conversationId: string, input?: OperationContext["input"] | UIMessage, - ): Promise { - if (!this.conversationMemory) return; + ): Promise { + if (!this.conversationMemory) return false; try { const existingConversation = await this.conversationMemory.getConversation(conversationId); @@ -607,9 +651,9 @@ export class MemoryManager { context.logger.debug("[Memory] Created new conversation", { title, }); - } catch (createError: any) { + } catch (createError: unknown) { // If conversation already exists (race condition), that's fine - our goal is achieved - if (createError.code === "CONVERSATION_ALREADY_EXISTS") { + if (this.isConversationAlreadyExistsError(createError)) { context.logger.debug("[Memory] Conversation already exists (race condition handled)", { conversationId, }); @@ -625,10 +669,12 @@ export class MemoryManager { await this.conversationMemory.updateConversation(conversationId, {}); context.logger.trace("[Memory] Updated conversation"); } + return true; } catch (error) { context.logger.error("[Memory] Failed to ensure conversation exists", { error, }); + return false; } } diff --git a/packages/e2e/package.json b/packages/e2e/package.json new file mode 100644 index 000000000..beca75c79 --- /dev/null +++ b/packages/e2e/package.json @@ -0,0 +1,23 @@ +{ + "name": "@voltagent/e2e", + "dependencies": { + "@libsql/client": "^0.15.0", + "@voltagent/core": "^2.6.3", + "@voltagent/internal": "^1.0.3", + "@voltagent/libsql": "^2.1.2", + "@voltagent/postgres": "^2.1.2", + "ai": "^6.0.0", + "pg": "^8.16.0", + "zod": "^3.25.76" + }, + "devDependencies": { + "vitest": "^3.2.4" + }, + "private": true, + "scripts": { + "build": "echo \"No build step for @voltagent/e2e\"", + "lint": "biome check .", + "test": "sh -c 'docker compose -f ../postgres/docker-compose.test.yaml up -d && vitest run --config vitest.config.mts; status=$?; docker compose -f ../postgres/docker-compose.test.yaml down -v; exit $status'" + }, + "type": "module" +} diff --git a/packages/e2e/src/message-persistence.libsql.e2e.spec.ts b/packages/e2e/src/message-persistence.libsql.e2e.spec.ts new file mode 100644 index 000000000..514975449 --- /dev/null +++ b/packages/e2e/src/message-persistence.libsql.e2e.spec.ts @@ -0,0 +1,75 @@ +import { randomUUID } from "node:crypto"; +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import { createClient } from "@libsql/client"; +import { Memory } from "@voltagent/core"; +import { LibSQLMemoryAdapter } from "@voltagent/libsql"; +import type { UIMessage } from "ai"; +import { afterEach, describe, expect, it } from "vitest"; +import { assertAssistantParts, runFiveTurns } from "./message-persistence.shared"; + +describe.sequential("message persistence e2e (libsql)", () => { + let libsqlTempDir: string | undefined; + + afterEach(() => { + if (libsqlTempDir) { + fs.rmSync(libsqlTempDir, { recursive: true, force: true }); + libsqlTempDir = undefined; + } + }); + + it("persists reasoning + tool + text via agent calls on libsql", async () => { + libsqlTempDir = fs.mkdtempSync(path.join(os.tmpdir(), "voltagent-e2e-libsql-")); + const dbPath = path.join(libsqlTempDir, "memory.db"); + const dbUrl = `file:${dbPath}`; + const tablePrefix = `voltagent_e2e_libsql_${randomUUID().replace(/-/g, "").slice(0, 8)}`; + const userId = `user-${randomUUID()}`; + const conversationId = `conversation-${randomUUID()}`; + + const memory = new Memory({ + storage: new LibSQLMemoryAdapter({ + url: dbUrl, + tablePrefix, + }), + }); + + await runFiveTurns(memory, userId, conversationId); + + const client = createClient({ url: dbUrl }); + try { + const conversationRows = await client.execute({ + sql: `SELECT id, user_id, resource_id FROM ${tablePrefix}_conversations WHERE id = ?`, + args: [conversationId], + }); + expect(conversationRows.rows).toHaveLength(1); + expect(conversationRows.rows[0]?.id).toBe(conversationId); + expect(conversationRows.rows[0]?.user_id).toBe(userId); + expect(conversationRows.rows[0]?.resource_id).toBe("persistence-e2e-agent"); + + const messageRows = await client.execute({ + sql: `SELECT role, parts FROM ${tablePrefix}_messages WHERE conversation_id = ? AND user_id = ? ORDER BY created_at ASC`, + args: [conversationId, userId], + }); + const assistantRows = messageRows.rows.filter((row) => row.role === "assistant"); + expect(assistantRows).toHaveLength(5); + + for (const [index, row] of assistantRows.entries()) { + const rawParts = row.parts; + if (typeof rawParts !== "string") { + throw new Error("Expected libsql parts to be JSON string."); + } + const parts = JSON.parse(rawParts) as UIMessage["parts"]; + assertAssistantParts({ id: "libsql-row", role: "assistant", parts }, index + 1); + } + + const stepCountRows = await client.execute({ + sql: `SELECT COUNT(*) AS count FROM ${tablePrefix}_steps WHERE conversation_id = ? AND user_id = ?`, + args: [conversationId, userId], + }); + expect(Number(stepCountRows.rows[0]?.count ?? 0)).toBeGreaterThan(0); + } finally { + client.close(); + } + }); +}); diff --git a/packages/e2e/src/message-persistence.postgres.e2e.spec.ts b/packages/e2e/src/message-persistence.postgres.e2e.spec.ts new file mode 100644 index 000000000..36ad3043e --- /dev/null +++ b/packages/e2e/src/message-persistence.postgres.e2e.spec.ts @@ -0,0 +1,85 @@ +import { randomUUID } from "node:crypto"; +import { Memory } from "@voltagent/core"; +import { PostgreSQLMemoryAdapter } from "@voltagent/postgres"; +import type { UIMessage } from "ai"; +import { Pool } from "pg"; +import { describe, expect, it } from "vitest"; +import { assertAssistantParts, runFiveTurns } from "./message-persistence.shared"; + +describe.sequential("message persistence e2e (postgres)", () => { + it("persists reasoning + tool + text via agent calls on postgres", async () => { + const tablePrefix = `voltagent_e2e_pg_${randomUUID().replace(/-/g, "").slice(0, 8)}`; + const userId = `user-${randomUUID()}`; + const conversationId = `conversation-${randomUUID()}`; + const postgresConfig = { + host: process.env.VOLTAGENT_E2E_POSTGRES_HOST ?? "127.0.0.1", + port: Number(process.env.VOLTAGENT_E2E_POSTGRES_PORT ?? "5433"), + database: process.env.VOLTAGENT_E2E_POSTGRES_DB ?? "voltagent_test", + user: process.env.VOLTAGENT_E2E_POSTGRES_USER ?? "test", + password: process.env.VOLTAGENT_E2E_POSTGRES_PASSWORD ?? "test", + } as const; + + const probePool = new Pool({ + ...postgresConfig, + connectionTimeoutMillis: 2000, + max: 1, + }); + + try { + await probePool.query("SELECT 1"); + } catch (error) { + throw new Error( + `Postgres E2E requires a reachable database. Checked ${postgresConfig.host}:${postgresConfig.port}/${postgresConfig.database}.`, + { cause: error as Error }, + ); + } finally { + await probePool.end(); + } + + const memory = new Memory({ + storage: new PostgreSQLMemoryAdapter({ + connection: postgresConfig, + tablePrefix, + }), + }); + + await runFiveTurns(memory, userId, conversationId); + + const pool = new Pool(postgresConfig); + + try { + const conversationRows = await pool.query( + `SELECT id, user_id, resource_id FROM ${tablePrefix}_conversations WHERE id = $1`, + [conversationId], + ); + expect(conversationRows.rows).toHaveLength(1); + expect(conversationRows.rows[0]?.id).toBe(conversationId); + expect(conversationRows.rows[0]?.user_id).toBe(userId); + expect(conversationRows.rows[0]?.resource_id).toBe("persistence-e2e-agent"); + + const messageRows = await pool.query( + `SELECT role, parts FROM ${tablePrefix}_messages WHERE conversation_id = $1 AND user_id = $2 ORDER BY created_at ASC`, + [conversationId, userId], + ); + const assistantRows = messageRows.rows.filter((row) => row.role === "assistant"); + expect(assistantRows).toHaveLength(5); + + for (const [index, row] of assistantRows.entries()) { + const rawParts = row.parts; + const parts = + typeof rawParts === "string" + ? (JSON.parse(rawParts) as UIMessage["parts"]) + : (rawParts as UIMessage["parts"]); + assertAssistantParts({ id: "postgres-row", role: "assistant", parts }, index + 1); + } + + const stepCountRows = await pool.query( + `SELECT COUNT(*)::int AS count FROM ${tablePrefix}_steps WHERE conversation_id = $1 AND user_id = $2`, + [conversationId, userId], + ); + expect(Number(stepCountRows.rows[0]?.count ?? 0)).toBeGreaterThan(0); + } finally { + await pool.end(); + } + }); +}); diff --git a/packages/e2e/src/message-persistence.shared.ts b/packages/e2e/src/message-persistence.shared.ts new file mode 100644 index 000000000..83792fe38 --- /dev/null +++ b/packages/e2e/src/message-persistence.shared.ts @@ -0,0 +1,262 @@ +import { Agent, type Memory, type Tool, createTool } from "@voltagent/core"; +import { safeStringify } from "@voltagent/internal"; +import type { UIMessage } from "ai"; +import { MockLanguageModelV3 } from "ai/test"; +import { expect, vi } from "vitest"; +import { z } from "zod"; + +const turns = [ + { prompt: "Turn 1: fetch weather", topic: "weather", summary: "Turn 1 summary: weather saved." }, + { + prompt: "Turn 2: add to calendar", + topic: "calendar", + summary: "Turn 2 summary: calendar saved.", + }, + { prompt: "Turn 3: add to task list", topic: "tasks", summary: "Turn 3 summary: task saved." }, + { + prompt: "Turn 4: summarize previous outputs", + topic: "summary", + summary: "Turn 4 summary: recap saved.", + }, + { + prompt: "Turn 5: summarize all conversation", + topic: "final", + summary: "Turn 5 summary: final recap saved.", + }, +] as const; + +const usage = { + inputTokens: { + total: 120, + noCache: 120, + cacheRead: 0, + cacheWrite: 0, + }, + outputTokens: { + total: 60, + text: 30, + reasoning: 30, + }, +}; + +const parseUnknownJson = (value: unknown): unknown => { + if (typeof value !== "string") { + return value; + } + + const trimmed = value.trim(); + if (!trimmed) { + return value; + } + + try { + return JSON.parse(trimmed); + } catch { + return value; + } +}; + +const unwrapJsonEnvelope = (value: unknown): unknown => { + const parsed = parseUnknownJson(value); + if ( + parsed && + typeof parsed === "object" && + (parsed as Record).type === "json" && + "value" in (parsed as Record) + ) { + return (parsed as Record).value; + } + return parsed; +}; + +const getTurnExpectation = (turnNumber: number) => { + const turn = turns[turnNumber - 1]; + if (!turn) { + throw new Error(`Unexpected turn number for assertions: ${turnNumber}`); + } + return turn; +}; + +export const assertAssistantParts = (message: UIMessage, turnNumber: number) => { + const turn = getTurnExpectation(turnNumber); + const partTypes = message.parts.map((part) => part.type); + + expect(partTypes).toContain("reasoning"); + expect(partTypes).toContain("tool-lookup"); + expect(partTypes).toContain("text"); + + const reasoningParts = message.parts.filter((part) => part.type === "reasoning") as Array<{ + type: "reasoning"; + text?: string; + }>; + expect(reasoningParts.length).toBeGreaterThan(0); + expect( + reasoningParts.some( + (part) => typeof part.text === "string" && part.text.includes(`Turn ${turnNumber}:`), + ), + ).toBe(true); + + const toolLookupParts = message.parts.filter((part) => part.type === "tool-lookup") as Array<{ + type: "tool-lookup"; + toolCallId?: string; + state?: string; + input?: unknown; + output?: unknown; + }>; + expect(toolLookupParts).toHaveLength(1); + + const toolPart = toolLookupParts[0]; + expect(toolPart.toolCallId).toBe(`lookup-call-${turnNumber}`); + expect(toolPart.state).toBe("output-available"); + + const parsedInput = unwrapJsonEnvelope(toolPart.input); + expect(parsedInput).toMatchObject({ + topic: turn.topic, + turn: turnNumber, + }); + + const parsedOutput = unwrapJsonEnvelope(toolPart.output); + expect(parsedOutput).toMatchObject({ + ok: true, + topic: turn.topic, + turn: turnNumber, + }); + + const textParts = message.parts.filter((part) => part.type === "text") as Array<{ + type: "text"; + text?: string; + }>; + expect(textParts.length).toBeGreaterThan(0); + expect(textParts.some((part) => part.text === turn.summary)).toBe(true); +}; + +const createAgent = (memory: Memory, model: MockLanguageModelV3, tool: Tool) => + new Agent({ + name: "persistence-e2e-agent", + instructions: "Use tools and answer briefly.", + model: model, + tools: [tool], + memory, + conversationPersistence: { + mode: "step", + debounceMs: 0, + flushOnToolResult: true, + }, + }); + +export const runFiveTurns = async (memory: Memory, userId: string, conversationId: string) => { + let generateCallCount = 0; + let contextReplayChecks = 0; + + const toolExecute = vi.fn(async ({ topic, turn }: { topic: string; turn: number }) => ({ + ok: true, + topic, + turn, + })); + + const tool = createTool({ + name: "lookup", + description: "Lookup turn payload", + parameters: z.object({ + topic: z.string(), + turn: z.number(), + }), + execute: toolExecute, + }); + + const model = new MockLanguageModelV3({ + modelId: "mock-persistence-model", + doGenerate: async (callOptions) => { + generateCallCount += 1; + const turnNumber = Math.ceil(generateCallCount / 2); + const isToolStep = generateCallCount % 2 === 1; + const turn = turns[turnNumber - 1]; + + if (!turn) { + throw new Error(`Unexpected turn number: ${turnNumber}`); + } + + const promptSnapshot = safeStringify(callOptions.prompt); + if (isToolStep && turnNumber > 1) { + for (let previous = 1; previous < turnNumber; previous += 1) { + const marker = `Turn ${previous} summary:`; + if (!promptSnapshot.includes(marker)) { + throw new Error(`Missing persisted marker "${marker}" in turn ${turnNumber}`); + } + } + contextReplayChecks += 1; + } + + if (isToolStep) { + return { + finishReason: { + unified: "tool-calls", + raw: undefined, + }, + content: [ + { + type: "reasoning", + text: `Turn ${turnNumber}: calling lookup.`, + }, + { + type: "tool-call", + toolCallId: `lookup-call-${turnNumber}`, + toolName: "lookup", + input: safeStringify({ + topic: turn.topic, + turn: turnNumber, + }), + }, + ], + usage, + warnings: [], + }; + } + + return { + finishReason: { + unified: "stop", + raw: undefined, + }, + content: [ + { + type: "reasoning", + text: `Turn ${turnNumber}: composing response.`, + }, + { + type: "text", + text: turn.summary, + }, + ], + usage, + warnings: [], + }; + }, + }); + + let agent = createAgent(memory, model, tool); + + for (const [index, turn] of turns.entries()) { + if (index === turns.length - 1) { + // Recreate agent to prove context is replayed from persistence. + agent = createAgent(memory, model, tool); + } + + const result = await agent.generateText(turn.prompt, { + userId, + conversationId, + }); + expect(result.text).toBe(turn.summary); + } + + expect(toolExecute).toHaveBeenCalledTimes(5); + expect(generateCallCount).toBe(10); + expect(contextReplayChecks).toBe(4); + + const allMessages = await memory.getMessages(userId, conversationId); + const assistantMessages = allMessages.filter((message) => message.role === "assistant"); + expect(assistantMessages).toHaveLength(5); + assistantMessages.forEach((message, index) => { + assertAssistantParts(message, index + 1); + }); +}; diff --git a/packages/e2e/vitest.config.mts b/packages/e2e/vitest.config.mts new file mode 100644 index 000000000..fd5765f8c --- /dev/null +++ b/packages/e2e/vitest.config.mts @@ -0,0 +1,14 @@ +import { defineConfig } from "vitest/config"; + +export default defineConfig({ + test: { + globals: true, + environment: "node", + include: ["src/**/*.spec.ts"], + testTimeout: 120000, + hookTimeout: 120000, + sequence: { + concurrent: false, + }, + }, +}); diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index db7f31fcf..0b83f2426 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -4014,6 +4014,37 @@ importers: specifier: ^4.1.11 version: 4.1.11 + packages/e2e: + dependencies: + '@libsql/client': + specifier: ^0.15.0 + version: 0.15.10 + '@voltagent/core': + specifier: ^2.6.3 + version: link:../core + '@voltagent/internal': + specifier: ^1.0.3 + version: link:../internal + '@voltagent/libsql': + specifier: ^2.1.2 + version: link:../libsql + '@voltagent/postgres': + specifier: ^2.1.2 + version: link:../postgres + ai: + specifier: ^6.0.0 + version: 6.0.3(zod@3.25.76) + pg: + specifier: ^8.16.0 + version: 8.16.3 + zod: + specifier: ^3.25.76 + version: 3.25.76 + devDependencies: + vitest: + specifier: ^3.2.4 + version: 3.2.4(@types/node@24.2.1)(@vitest/ui@1.6.1)(jsdom@22.1.0)(msw@2.11.6) + packages/evals: dependencies: '@voltagent/internal': @@ -17276,13 +17307,8 @@ packages: resolution: {integrity: sha512-vENRlFU4YbrwVqNDZ7fLvy+JR1CRkyr01jhSiDpE1u6py3OMzQfztQU2jxykW3ALNxO4kSlqIDeYyD0Y9RcQeQ==} dev: true - /@rolldown/pluginutils@1.0.0-beta.58: - resolution: {integrity: sha512-qWhDs6yFGR5xDfdrwiSa3CWGIHxD597uGE/A9xGqytBjANvh4rLCTTkq7szhMV4+Ygh+PMS90KVJ8xWG/TkX4w==} - dev: false - /@rolldown/pluginutils@1.0.0-rc.6: resolution: {integrity: sha512-Y0+JT8Mi1mmW08K6HieG315XNRu4L0rkfCpA364HtytjgiqYnMYRdFPcxRl+BQQqNXzecL2S9nii+RUpO93XIA==} - dev: true /@rollup/plugin-alias@5.1.1(rollup@4.50.2): resolution: {integrity: sha512-PR9zDb+rOzkRb2VD+EuKB7UC41vU5DIwZ5qqCpk0KJudcWAyi8rvYOhS7+L5aZCspw1stTViLgN5v6FF1p5cgQ==} @@ -20979,7 +21005,7 @@ packages: '@babel/core': 7.28.5 '@babel/plugin-syntax-typescript': 7.27.1(@babel/core@7.28.5) '@babel/plugin-transform-typescript': 7.28.0(@babel/core@7.28.5) - '@rolldown/pluginutils': 1.0.0-beta.58 + '@rolldown/pluginutils': 1.0.0-rc.6 '@vue/babel-plugin-jsx': 1.5.0(@babel/core@7.28.5) vite: 7.2.7(@types/node@24.2.1)(jiti@2.6.1) vue: 3.5.22(typescript@5.9.3)