Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

✅ test(database): cover more model/repository gaps (client-db 95.4%→95.7%) (#15612)

Arvin Xude1a5c88e4c1
diff --git a/packages/database/src/models/__tests__/asyncTask.test.ts b/packages/database/src/models/__tests__/asyncTask.test.ts
index 0a6bc7e50b7..ece9d93282a 100644
--- a/packages/database/src/models/__tests__/asyncTask.test.ts
+++ b/packages/database/src/models/__tests__/asyncTask.test.ts
@@ -502,6 +502,67 @@ describe('initUserMemoryExtractionMetadata', () => {
expect(result.source).toBe('chat_topic');
});
+
+ it('should preserve a full control block including upstash workflowRunIds', () => {
+ const cancelRequestedAt = new Date().toISOString();
+ const result = initUserMemoryExtractionMetadata({
+ control: {
+ cancelReason: 'user_requested',
+ cancelRequestedAt,
+ cancelledBy: 'user-1',
+ upstash: {
+ workflowRunIds: ['run-1', 'run-2'],
+ },
+ },
+ progress: {
+ completedTopics: 1,
+ totalTopics: 4,
+ },
+ source: 'chat_topic',
+ } as any);
+
+ expect(result.control).toEqual({
+ cancelReason: 'user_requested',
+ cancelRequestedAt,
+ cancelledBy: 'user-1',
+ upstash: {
+ workflowRunIds: ['run-1', 'run-2'],
+ },
+ });
+ expect(result.progress).toEqual({ completedTopics: 1, totalTopics: 4 });
+ });
+
+ it('should default upstash workflowRunIds to an empty array when missing', () => {
+ const result = initUserMemoryExtractionMetadata({
+ control: {
+ cancelRequestedAt: new Date().toISOString(),
+ upstash: {},
+ },
+ progress: {
+ completedTopics: 0,
+ totalTopics: null,
+ },
+ source: 'chat_topic',
+ } as any);
+
+ expect(result.control?.upstash).toEqual({ workflowRunIds: [] });
+ });
+
+ it('should leave upstash undefined when control has no upstash field', () => {
+ const result = initUserMemoryExtractionMetadata({
+ control: {
+ cancelRequestedAt: new Date().toISOString(),
+ },
+ progress: {
+ completedTopics: 0,
+ totalTopics: null,
+ },
+ source: 'chat_topic',
+ } as any);
+
+ expect(result.control).toBeDefined();
+ expect(result.control?.upstash).toBeUndefined();
+ });
});
describe('AsyncTaskModel.findByInferenceId', () => {
diff --git a/packages/database/src/models/__tests__/document.test.ts b/packages/database/src/models/__tests__/document.test.ts
index 8c184cd985d..8b958d75831 100644
--- a/packages/database/src/models/__tests__/document.test.ts
+++ b/packages/database/src/models/__tests__/document.test.ts
@@ -1,8 +1,16 @@
// @vitest-environment node
+import { eq } from 'drizzle-orm';
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
import { getTestDB } from '../../core/getTestDB';
-import { documentHistories, documents, files, users } from '../../schemas';
+import {
+ DOCUMENT_FOLDER_TYPE,
+ documentHistories,
+ documents,
+ files,
+ users,
+ workspaces,
+} from '../../schemas';
import type { LobeChatDatabase } from '../../type';
import { DocumentModel } from '../document';
import { FileModel } from '../file';
@@ -22,10 +30,11 @@ beforeEach(async () => {
});
afterEach(async () => {
- await serverDB.delete(users);
await serverDB.delete(files);
await serverDB.delete(documentHistories);
await serverDB.delete(documents);
+ await serverDB.delete(workspaces);
+ await serverDB.delete(users);
});
// Helper to create a minimal valid document
@@ -608,4 +617,246 @@ describe('DocumentModel', () => {
expect(found?.content).toBe('PDF content');
});
});
+
+ describe('countFileUsageInSubtree', () => {
+ it('should return 0 when the root document does not exist', async () => {
+ const total = await documentModel.countFileUsageInSubtree('non-existent-root');
+ expect(total).toBe(0);
+ });
+
+ it('should sum sizes of files anchored to the document and its descendants', async () => {
+ const root = await documentModel.findOrCreateFolder('root-folder');
+ const child = await documentModel.findOrCreateFolder('child-folder', root.id);
+ const grandchild = await documentModel.findOrCreateFolder('grandchild-folder', child.id);
+
+ // Files anchored to documents in the subtree (parentId points at a document)
+ await fileModel.create({
+ fileType: 'text/plain',
+ name: 'root-file.txt',
+ parentId: root.id,
+ size: 100,
+ url: 'https://example.com/root-file.txt',
+ });
+ await fileModel.create({
+ fileType: 'text/plain',
+ name: 'child-file.txt',
+ parentId: child.id,
+ size: 250,
+ url: 'https://example.com/child-file.txt',
+ });
+ await fileModel.create({
+ fileType: 'text/plain',
+ name: 'grandchild-file.txt',
+ parentId: grandchild.id,
+ size: 50,
+ url: 'https://example.com/grandchild-file.txt',
+ });
+
+ const total = await documentModel.countFileUsageInSubtree(root.id);
+ expect(total).toBe(400);
+ });
+
+ it('should return 0 when the subtree has no anchored files', async () => {
+ const root = await documentModel.findOrCreateFolder('empty-folder');
+ const total = await documentModel.countFileUsageInSubtree(root.id);
+ expect(total).toBe(0);
+ });
+
+ it('should not count files owned by another user', async () => {
+ const root = await documentModel.findOrCreateFolder('scoped-folder');
+ // A file anchored to the doc but owned by user2 must be ignored.
+ await fileModel2.create({
+ fileType: 'text/plain',
+ name: 'other-user-file.txt',
+ parentId: root.id,
+ size: 999,
+ url: 'https://example.com/other-user-file.txt',
+ });
+
+ const total = await documentModel.countFileUsageInSubtree(root.id);
+ expect(total).toBe(0);
+ });
+ });
+
+ describe('transferTo', () => {
+ it('should throw when the document does not exist', async () => {
+ await expect(documentModel.transferTo('non-existent-doc', null, userId2)).rejects.toThrow(
+ 'Document not found',
+ );
+ });
+
+ it('should transfer a document subtree to another user (personal scope)', async () => {
+ const root = await documentModel.findOrCreateFolder('transfer-root');
+ const child = await documentModel.findOrCreateFolder('transfer-child', root.id);
+ const { id: anchoredFileId } = await fileModel.create({
+ fileType: 'text/plain',
+ name: 'anchored.txt',
+ parentId: child.id,
+ size: 100,
+ url: 'https://example.com/anchored.txt',
+ });
+
+ const { documentIds } = await documentModel.transferTo(root.id, null, userId2);
+
+ expect(documentIds).toHaveLength(2);
+ expect(documentIds).toContain(root.id);
+ expect(documentIds).toContain(child.id);
+
+ // Original owner no longer sees the docs
+ expect(await documentModel.findById(root.id)).toBeUndefined();
+ // New owner sees them
+ const movedRoot = await documentModel2.findById(root.id);
+ expect(movedRoot).toBeDefined();
+ expect(movedRoot?.userId).toBe(userId2);
+
+ // The anchored file was re-homed to the new owner
+ const movedFile = await fileModel2.findById(anchoredFileId);
+ expect(movedFile).toBeDefined();
+ expect(movedFile?.userId).toBe(userId2);
+ });
+
+ it('should resolve slug conflicts in the target scope when transferring', async () => {
+ // Source doc with a known slug
+ const source = await documentModel.create({
+ content: 'source',
+ fileType: 'article',
+ filename: 'source',
+ slug: 'shared-slug',
+ source: 'https://example.com/source',
+ sourceType: 'web',
+ title: 'source',
+ totalCharCount: 6,
+ totalLineCount: 1,
+ });
+
+ // Target user already has a doc with the same slug
+ await documentModel2.create({
+ content: 'existing',
+ fileType: 'article',
+ filename: 'existing',
+ slug: 'shared-slug',
+ source: 'https://example.com/existing',
+ sourceType: 'web',
+ title: 'existing',
+ totalCharCount: 8,
+ totalLineCount: 1,
+ });
+
+ await documentModel.transferTo(source.id, null, userId2);
+
+ const moved = await documentModel2.findById(source.id);
+ expect(moved).toBeDefined();
+ expect(moved?.userId).toBe(userId2);
+ // Slug must have been bumped to avoid the unique conflict
+ expect(moved?.slug).not.toBe('shared-slug');
+ expect(moved?.slug).toBe('shared-slug-1');
+ });
+ });
+
+ describe('copyToWorkspace', () => {
+ const workspaceId = 'document-test-workspace-id';
+
+ beforeEach(async () => {
+ await serverDB.insert(workspaces).values({
+ id: workspaceId,
+ name: 'Test Workspace',
+ primaryOwnerId: userId,
+ slug: 'doc-test-ws',
+ });
+ });
+
+ it('should throw when the document does not exist', async () => {
+ await expect(
+ documentModel.copyToWorkspace('non-existent-doc', workspaceId, userId),
+ ).rejects.toThrow('Document not found');
+ });
+
+ it('should deep-clone a document subtree preserving topology', async () => {
+ const root = await documentModel.create({
+ content: 'root content',
+ fileType: DOCUMENT_FOLDER_TYPE,
+ filename: 'copy-root',
+ source: '',
+ sourceType: 'api',
+ title: 'copy-root',
+ totalCharCount: 12,
+ totalLineCount: 1,
+ });
+ const child = await documentModel.create({
+ content: 'child content',
+ fileType: 'article',
+ filename: 'copy-child',
+ parentId: root.id,
+ source: '',
+ sourceType: 'api',
+ title: 'copy-child',
+ totalCharCount: 13,
+ totalLineCount: 1,
+ });
+
+ const { rootId: newRootId } = await documentModel.copyToWorkspace(
+ root.id,
+ workspaceId,
+ userId,
+ );
+
+ expect(newRootId).toBeDefined();
+ expect(newRootId).not.toBe(root.id);
+
+ // Cloned root exists in the workspace scope
+ const wsModel = new DocumentModel(serverDB, userId, workspaceId);
+ const clonedRoot = await wsModel.findById(newRootId);
+ expect(clonedRoot).toBeDefined();
+ expect(clonedRoot?.workspaceId).toBe(workspaceId);
+ expect(clonedRoot?.content).toBe('root content');
+ expect(clonedRoot?.metadata).toMatchObject({ duplicatedFrom: root.id });
+
+ // Cloned child points at the cloned root, not the original
+ const wsDocs = await serverDB.query.documents.findMany({
+ where: eq(documents.workspaceId, workspaceId),
+ });
+ const clonedChild = wsDocs.find((d) => d.filename === 'copy-child');
+ expect(clonedChild).toBeDefined();
+ expect(clonedChild?.parentId).toBe(newRootId);
+ expect(clonedChild?.metadata).toMatchObject({ duplicatedFrom: child.id });
+
+ // Original docs untouched
+ expect(await documentModel.findById(root.id)).toBeDefined();
+ });
+
+ it('should resolve slug conflicts in the target workspace when copying', async () => {
+ // Pre-existing doc in the target workspace holding the slug
+ const wsModel = new DocumentModel(serverDB, userId, workspaceId);
+ await wsModel.create({
+ content: 'existing',
+ fileType: 'article',
+ filename: 'existing',
+ slug: 'copy-slug',
+ source: '',
+ sourceType: 'api',
+ title: 'existing',
+ totalCharCount: 8,
+ totalLineCount: 1,
+ });
+
+ const source = await documentModel.create({
+ content: 'source',
+ fileType: 'article',
+ filename: 'source',
+ slug: 'copy-slug',
+ source: '',
+ sourceType: 'api',
+ title: 'source',
+ totalCharCount: 6,
+ totalLineCount: 1,
+ });
+
+ const { rootId } = await documentModel.copyToWorkspace(source.id, workspaceId, userId);
+
+ const cloned = await wsModel.findById(rootId);
+ expect(cloned).toBeDefined();
+ expect(cloned?.slug).not.toBe('copy-slug');
+ expect(cloned?.slug).toBe('copy-slug-1');
+ });
+ });
});
diff --git a/packages/database/src/models/__tests__/systemBotProvider.test.ts b/packages/database/src/models/__tests__/systemBotProvider.test.ts
index c23f0939288..0ecb707957d 100644
--- a/packages/database/src/models/__tests__/systemBotProvider.test.ts
+++ b/packages/database/src/models/__tests__/systemBotProvider.test.ts
@@ -114,6 +114,34 @@ describe('SystemBotProviderModel', () => {
});
});
+ describe('findByPlatform', () => {
+ it('returns the row regardless of enabled flag', async () => {
+ await SystemBotProviderModel.upsertByPlatform(
+ serverDB,
+ {
+ credentials: { botToken: 'disabled-token' },
+ enabled: false,
+ platform: 'discord',
+ },
+ mockGateKeeper,
+ );
+
+ const found = await SystemBotProviderModel.findByPlatform(
+ serverDB,
+ 'discord',
+ mockGateKeeper,
+ );
+ expect(found?.platform).toBe('discord');
+ expect(found?.enabled).toBe(false);
+ expect(found?.credentials).toEqual({ botToken: 'disabled-token' });
+ });
+
+ it('returns null when no row for that platform', async () => {
+ const found = await SystemBotProviderModel.findByPlatform(serverDB, 'slack');
+ expect(found).toBeNull();
+ });
+ });
+
describe('update', () => {
it('re-encrypts credentials when provided and leaves them untouched otherwise', async () => {
const created = await SystemBotProviderModel.upsertByPlatform(
@@ -149,6 +177,32 @@ describe('SystemBotProviderModel', () => {
);
expect(afterRotate?.credentials).toEqual({ botToken: 'rotated' });
});
+
+ it('updates applicationId, settings and connectionMode when provided', async () => {
+ const created = await SystemBotProviderModel.upsertByPlatform(serverDB, {
+ credentials: { botToken: 'initial' },
+ platform: 'discord',
+ });
+
+ const updated = await SystemBotProviderModel.update(serverDB, created.id, {
+ applicationId: 'app-99',
+ connectionMode: 'gateway',
+ settings: { foo: 'bar' },
+ });
+
+ expect(updated?.applicationId).toBe('app-99');
+ expect(updated?.connectionMode).toBe('gateway');
+ expect(updated?.settings).toEqual({ foo: 'bar' });
+ });
+
+ it('returns undefined when updating a non-existent id', async () => {
+ const updated = await SystemBotProviderModel.update(
+ serverDB,
+ '00000000-0000-0000-0000-000000000000',
+ { enabled: false },
+ );
+ expect(updated).toBeUndefined();
+ });
});
describe('setEnabled', () => {
@@ -196,5 +250,17 @@ describe('SystemBotProviderModel', () => {
const found = await SystemBotProviderModel.findById(serverDB, created.id, broken);
expect(found?.credentials).toEqual({});
});
+
+ it('returns credentials = {} when the stored ciphertext is empty', async () => {
+ const [row] = await serverDB
+ .insert(systemBotProviders)
+ .values({ credentials: '', platform: 'discord' })
+ .returning();
+
+ const found = await SystemBotProviderModel.findById(serverDB, row.id, mockGateKeeper);
+ expect(found?.credentials).toEqual({});
+ // gateKeeper.decrypt must be skipped entirely for an empty ciphertext
+ expect(mockGateKeeper.decrypt).not.toHaveBeenCalled();
+ });
});
});
diff --git a/packages/database/src/models/__tests__/verifyCheckResult.test.ts b/packages/database/src/models/__tests__/verifyCheckResult.test.ts
index 0cf936eee23..8db856b4725 100644
--- a/packages/database/src/models/__tests__/verifyCheckResult.test.ts
+++ b/packages/database/src/models/__tests__/verifyCheckResult.test.ts
@@ -3,7 +3,7 @@ import type { VerifyCheckItem } from '@lobechat/types';
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
import { getTestDB } from '../../core/getTestDB';
-import { agentOperations, users, verifyCheckResults } from '../../schemas';
+import { agentOperations, llmGenerationTracing, users, verifyCheckResults } from '../../schemas';
import type { LobeChatDatabase } from '../../type';
import { AgentOperationModel } from '../agentOperation';
import { VerifyCheckResultModel } from '../verifyCheckResult';
@@ -32,6 +32,7 @@ beforeEach(async () => {
afterEach(async () => {
await serverDB.delete(verifyCheckResults);
+ await serverDB.delete(llmGenerationTracing);
await serverDB.delete(agentOperations);
await serverDB.delete(users);
});
@@ -49,6 +50,88 @@ describe('VerifyCheckResultModel', () => {
expect(rows[0].status).toBe('pending');
});
+ it('createMany returns an empty array without inserting when given no rows', async () => {
+ const model = new VerifyCheckResultModel(serverDB, userId);
+ const result = await model.createMany([]);
+ expect(result).toEqual([]);
+ expect(await model.listByOperation(operationId)).toHaveLength(0);
+ });
+
+ it('findById returns the matching row scoped to the user and undefined otherwise', async () => {
+ const model = new VerifyCheckResultModel(serverDB, userId);
+ const created = await model.create({
+ checkItemId: 'a',
+ checkItemIndex: 0,
+ operationId,
+ verifierType: 'llm',
+ });
+
+ const found = await model.findById(created.id);
+ expect(found?.id).toBe(created.id);
+ expect(found?.checkItemId).toBe('a');
+
+ // a different user must not see the row
+ const otherModel = new VerifyCheckResultModel(serverDB, 'someone-else');
+ expect(await otherModel.findById(created.id)).toBeUndefined();
+
+ // a valid-but-absent uuid resolves to undefined
+ expect(await model.findById('00000000-0000-0000-0000-000000000000')).toBeUndefined();
+ });
+
+ it('update mutates a row by its id', async () => {
+ const model = new VerifyCheckResultModel(serverDB, userId);
+ const created = await model.create({
+ checkItemId: 'a',
+ checkItemIndex: 0,
+ operationId,
+ verifierType: 'llm',
+ });
+
+ await model.update(created.id, { status: 'failed', verdict: 'failed' });
+
+ const row = await model.findById(created.id);
+ expect(row).toMatchObject({ status: 'failed', verdict: 'failed' });
+ });
+
+ it('backfillTracingId fills NULL tracing ids for the named items only and is idempotent', async () => {
+ const model = new VerifyCheckResultModel(serverDB, userId);
+ const [tracing] = await serverDB
+ .insert(llmGenerationTracing)
+ .values({
+ promptHash: 'hash',
+ promptVersion: 'v1',
+ scenario: 'verify',
+ success: true,
+ userId,
+ })
+ .returning();
+
+ await model.createMany([
+ { checkItemId: 'a', checkItemIndex: 0, operationId, verifierType: 'llm' },
+ { checkItemId: 'b', checkItemIndex: 1, operationId, verifierType: 'llm' },
+ ]);
+
+ // empty checkItemIds short-circuits (returns undefined, writes nothing)
+ expect(await model.backfillTracingId(operationId, [], tracing.id)).toBeUndefined();
+ expect(
+ (await model.listByOperation(operationId)).every((r) => r.verifierTracingId === null),
+ ).toBe(true);
+
+ await model.backfillTracingId(operationId, ['a'], tracing.id);
+
+ const after = await model.listByOperation(operationId);
+ const a = after.find((r) => r.checkItemId === 'a');
+ const b = after.find((r) => r.checkItemId === 'b');
+ expect(a?.verifierTracingId).toBe(tracing.id);
+ // 'b' was not in the list → untouched
+ expect(b?.verifierTracingId).toBeNull();
+
+ // idempotent: re-running only fills NULLs, so 'a' keeps its existing id
+ await model.backfillTracingId(operationId, ['a'], tracing.id);
+ const reloaded = await model.findById(a!.id);
+ expect(reloaded?.verifierTracingId).toBe(tracing.id);
+ });
+
it('updates a result by its stable (operationId, checkItemId) key', async () => {
const model = new VerifyCheckResultModel(serverDB, userId);
await model.create({ checkItemId: 'a', checkItemIndex: 0, operationId, verifierType: 'llm' });
diff --git a/packages/database/src/models/agentEval/__tests__/run.test.ts b/packages/database/src/models/agentEval/__tests__/run.test.ts
index 7038aad88d5..76a30157d75 100644
--- a/packages/database/src/models/agentEval/__tests__/run.test.ts
+++ b/packages/database/src/models/agentEval/__tests__/run.test.ts
@@ -195,6 +195,40 @@ describe('AgentEvalRunModel', () => {
expect(results[0].status).toBe('pending');
});
+ it('should filter by benchmarkId', async () => {
+ // The query beforeEach created dataset2 under the same benchmark, so
+ // all 3 user runs belong to datasets of `benchmarkId`.
+ const results = await runModel.query({ benchmarkId });
+
+ expect(results).toHaveLength(3);
+ expect(results.map((r) => r.name)).toContain('Run 1');
+ expect(results.map((r) => r.name)).toContain('Run 2');
+ expect(results.map((r) => r.name)).toContain('Run 3');
+ });
+
+ it('should return empty when benchmarkId has no datasets', async () => {
+ const [otherBenchmark] = await serverDB
+ .insert(agentEvalBenchmarks)
+ .values({
+ identifier: 'other-benchmark',
+ name: 'Other Benchmark',
+ rubrics: [],
+ isSystem: false,
+ })
+ .returning();
+
+ const results = await runModel.query({ benchmarkId: otherBenchmark.id });
+
+ expect(results).toHaveLength(0);
+ });
+
+ it('should filter by benchmarkId and status', async () => {
+ const results = await runModel.query({ benchmarkId, status: 'pending' });
+
+ expect(results).toHaveLength(1);
+ expect(results[0].name).toBe('Run 2');
+ });
+
it('should filter by datasetId and status', async () => {
const results = await runModel.query({
datasetId,
diff --git a/packages/database/src/models/agentEval/__tests__/runTopic.test.ts b/packages/database/src/models/agentEval/__tests__/runTopic.test.ts
index 89517b784b6..27b70bfcb0e 100644
--- a/packages/database/src/models/agentEval/__tests__/runTopic.test.ts
+++ b/packages/database/src/models/agentEval/__tests__/runTopic.test.ts
@@ -606,6 +606,118 @@ describe('AgentEvalRunTopicModel', () => {
});
});
+ describe('batchMarkAborted', () => {
+ it('should mark pending and running topics as error/Aborted', async () => {
+ const [topic3] = await serverDB
+ .insert(topics)
+ .values({ userId, title: 'Topic 3', trigger: 'eval', mode: 'test' })
+ .returning();
+
+ await serverDB.insert(agentEvalRunTopics).values([
+ { userId, runId, topicId: topicId1, testCaseId: testCaseId1, status: 'pending' },
+ { userId, runId, topicId: topicId2, testCaseId: testCaseId2, status: 'running' },
+ { userId, runId, topicId: topic3.id, testCaseId: testCaseId1, status: 'passed' },
+ ]);
+
+ const rows = await runTopicModel.batchMarkAborted(runId);
+
+ expect(rows).toHaveLength(2); // pending + running, not passed
+
+ const all = await serverDB.query.agentEvalRunTopics.findMany({
+ where: eq(agentEvalRunTopics.runId, runId),
+ });
+ const statusMap = Object.fromEntries(all.map((r) => [r.topicId, r.status]));
+ expect(statusMap[topicId1]).toBe('error');
+ expect(statusMap[topicId2]).toBe('error');
+ expect(statusMap[topic3.id]).toBe('passed'); // unchanged
+
+ const aborted = all.find((r) => r.topicId === topicId1);
+ expect(aborted?.evalResult).toMatchObject({ error: 'Aborted' });
+ });
+
+ it('should return empty array when no pending/running topics exist', async () => {
+ await serverDB.insert(agentEvalRunTopics).values([
+ { userId, runId, topicId: topicId1, testCaseId: testCaseId1, status: 'passed' },
+ { userId, runId, topicId: topicId2, testCaseId: testCaseId2, status: 'failed' },
+ ]);
+
+ const rows = await runTopicModel.batchMarkAborted(runId);
+
+ expect(rows).toHaveLength(0);
+ });
+
+ it('should not affect topics from other runs', async () => {
+ const [otherRun] = await serverDB
+ .insert(agentEvalRuns)
+ .values({ datasetId, userId, status: 'running' })
+ .returning();
+ const [otherTopic] = await serverDB
+ .insert(topics)
+ .values({ userId, title: 'Other', trigger: 'eval' })
+ .returning();
+
+ await serverDB.insert(agentEvalRunTopics).values([
+ { userId, runId, topicId: topicId1, testCaseId: testCaseId1, status: 'pending' },
+ {
+ userId,
+ runId: otherRun.id,
+ topicId: otherTopic.id,
+ testCaseId: testCaseId1,
+ status: 'pending',
+ },
+ ]);
+
+ const rows = await runTopicModel.batchMarkAborted(runId);
+
+ expect(rows).toHaveLength(1);
+
+ const [otherRow] = await serverDB.query.agentEvalRunTopics.findMany({
+ where: eq(agentEvalRunTopics.topicId, otherTopic.id),
+ });
+ expect(otherRow.status).toBe('pending'); // unchanged
+ });
+ });
+
+ describe('deleteByRunAndTestCase', () => {
+ beforeEach(async () => {
+ await serverDB.insert(agentEvalRunTopics).values([
+ { userId, runId, topicId: topicId1, testCaseId: testCaseId1 },
+ { userId, runId, topicId: topicId2, testCaseId: testCaseId2 },
+ ]);
+ });
+
+ it('should delete the matching run-testcase row and return it', async () => {
+ const deleted = await runTopicModel.deleteByRunAndTestCase(runId, testCaseId1);
+
+ expect(deleted).toHaveLength(1);
+ expect(deleted[0].testCaseId).toBe(testCaseId1);
+ expect(deleted[0].topicId).toBe(topicId1);
+
+ const remaining = await serverDB.query.agentEvalRunTopics.findMany({
+ where: eq(agentEvalRunTopics.runId, runId),
+ });
+ expect(remaining).toHaveLength(1);
+ expect(remaining[0].testCaseId).toBe(testCaseId2);
+ });
+
+ it('should return empty array when combination not found', async () => {
+ const [otherRun] = await serverDB
+ .insert(agentEvalRuns)
+ .values({ datasetId, userId, status: 'idle' })
+ .returning();
+
+ const deleted = await runTopicModel.deleteByRunAndTestCase(otherRun.id, testCaseId1);
+
+ expect(deleted).toHaveLength(0);
+
+ // original rows untouched
+ const remaining = await serverDB.query.agentEvalRunTopics.findMany({
+ where: eq(agentEvalRunTopics.runId, runId),
+ });
+ expect(remaining).toHaveLength(2);
+ });
+ });
+
describe('deleteErrorRunTopics', () => {
it('should delete only error and timeout RunTopics', async () => {
await serverDB.insert(agentEvalRunTopics).values([
diff --git a/packages/database/src/repositories/dataImporter/__tests__/index.test.ts b/packages/database/src/repositories/dataImporter/__tests__/index.test.ts
index 3f61cad6825..91607c3b1d3 100644
--- a/packages/database/src/repositories/dataImporter/__tests__/index.test.ts
+++ b/packages/database/src/repositories/dataImporter/__tests__/index.test.ts
@@ -651,4 +651,101 @@ describe('DataImporter', () => {
expect(models[0].id).toBe('model-a');
});
});
+
+ describe('aiProviders (preserveId dedup on same id)', () => {
+ it('should skip re-import of the same provider id via the preserveId/id match path', async () => {
+ // aiProviders has NO clientId column and preserveId=true. On re-import the existing
+ // record is discovered through the preserveId id lookup, and the dedup filter then
+ // matches on `preserveId && !isCompositeKey && record.id === item.id` (the right arm
+ // of the || at line 447, since the clientId left arm is always falsy here).
+ const data: ImportPgDataStructure = {
+ data: {
+ aiProviders: [
+ {
+ id: 'prov-keep',
+ name: 'Keep Provider',
+ source: 'custom',
+ createdAt: '2025-01-01T00:00:00Z',
+ updatedAt: '2025-01-01T00:00:00Z',
+ },
+ ],
+ },
+ mode: 'pglite',
+ schemaHash: 'test',
+ } as any;
+
+ const firstResult = await importer.importPgData(data);
+ expect(firstResult.success).toBe(true);
+ expect(firstResult.results.aiProviders).toMatchObject({ added: 1, errors: 0 });
+
+ // Re-import the exact same id with a fresh importer -> existing record found by id,
+ // recordsToInsert becomes empty -> early return with skips=1.
+ const importer2 = new DataImporterRepos(clientDB, userId);
+ const secondResult = await importer2.importPgData(data);
+ expect(secondResult.success).toBe(true);
+ expect(secondResult.results.aiProviders).toMatchObject({ added: 0, skips: 1 });
+
+ const providers = await clientDB.query.aiProviders.findMany({
+ where: eq(Schema.aiProviders.userId, userId),
+ });
+ expect(providers).toHaveLength(1);
+ expect(providers[0].id).toBe('prov-keep');
+ });
+ });
+
+ describe('agents slug field processor (null slug) + empty unique-constraint skip', () => {
+ it('should null out an empty slug and skip the slug unique check', async () => {
+ // agents config: fieldProcessor for `slug` returns null when the value is falsy
+ // (branch 87 false-arm). With slug=null, the unique-constraint loop hits the
+ // `if (!record.newRecord[field]) continue;` guard (branch 608) and skips the check.
+ const data: ImportPgDataStructure = {
+ data: {
+ agents: [
+ {
+ id: 'agt_nullslug',
+ slug: '',
+ model: 'gpt-4',
+ provider: 'openai',
+ systemRole: '',
+ createdAt: '2025-01-01T00:00:00Z',
+ updatedAt: '2025-01-01T00:00:00Z',
+ },
+ ],
+ agentsToSessions: [],
+ sessions: [],
+ },
+ mode: 'pglite',
+ schemaHash: 'test',
+ } as any;
+
+ const result = await importer.importPgData(data);
+ expect(result.success).toBe(true);
+ expect(result.results.agents).toMatchObject({ added: 1, errors: 0 });
+
+ const agents = await clientDB.query.agents.findMany({
+ where: eq(Schema.agents.userId, userId),
+ });
+ expect(agents).toHaveLength(1);
+ expect(agents[0].slug).toBeNull();
+ });
+ });
+
+ describe('extractErrorDetails fallback (no detail, non-23505)', () => {
+ afterEach(() => {
+ vi.restoreAllMocks();
+ });
+
+ it('should return "Unknown error details" when error has no code and no detail', async () => {
+ const bareError: any = new Error('bare failure with no detail');
+ // no .code, no .detail -> skips the 23505 block and falls to the `|| 'Unknown'` arm.
+
+ vi.spyOn(clientDB, 'transaction').mockRejectedValueOnce(bareError);
+
+ const result = await importer.importPgData(agentsData as ImportPgDataStructure);
+
+ expect(result.success).toBe(false);
+ expect((result as ImportErrorResult).error?.details).toBe('Unknown error details');
+ expect((result as ImportErrorResult).error?.message).toBe('bare failure with no detail');
+ });
+ });
});