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): raise coverage back to 100% (#22719)

Arvin Xu7bcd72c8db42
diff --git a/packages/database/src/models/__tests__/connector.coverage.test.ts b/packages/database/src/models/__tests__/connector.coverage.test.ts
index 710c8008a6d..21664d6a313 100644
--- a/packages/database/src/models/__tests__/connector.coverage.test.ts
+++ b/packages/database/src/models/__tests__/connector.coverage.test.ts
@@ -1,9 +1,9 @@
// @vitest-environment node
import { eq } from 'drizzle-orm';
-import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { getTestDB } from '../../core/getTestDB';
-import { agents, userConnectors, users } from '../../schemas';
+import { agentEvalDatasets, agents, userConnectors, users } from '../../schemas';
import type { LobeChatDatabase } from '../../type';
import { ConnectorModel } from '../connector';
@@ -21,6 +21,7 @@ const composio = {
};
const cleanup = async () => {
+ await serverDB.delete(agentEvalDatasets).where(eq(agentEvalDatasets.userId, userId));
// agents and user_connectors cascade from the owning user.
await serverDB.delete(users).where(eq(users.id, userId));
};
@@ -138,4 +139,117 @@ describe('ConnectorModel coverage edges', () => {
});
});
});
+
+ describe('evaluation connections', () => {
+ const createDataset = async () => {
+ const [dataset] = await serverDB
+ .insert(agentEvalDatasets)
+ .values({ identifier: 'conncov-dataset', name: 'Eval Dataset', userId })
+ .returning();
+ return dataset.id;
+ };
+
+ it('requires a dataset id when building an evaluation model', () => {
+ expect(() => ConnectorModel.forEvaluation(serverDB, userId, '')).toThrow(
+ 'A Dataset is required for evaluation connections',
+ );
+ });
+
+ it('rejects the import marker on an ordinary connector create', async () => {
+ const model = new ConnectorModel(serverDB, userId);
+
+ await expect(
+ model.create({ ...base, metadata: { agentEval: { datasetId: 'x' } } } as any),
+ ).rejects.toThrow('Use the Dataset connection API for evaluation connections');
+ });
+
+ it('rejects a dataset outside the caller scope', async () => {
+ const model = ConnectorModel.forEvaluation(serverDB, userId, missingId);
+
+ await expect(model.create({ ...base } as any)).rejects.toThrow('Dataset not found');
+ });
+
+ it('stamps the imported marker with the owning dataset', async () => {
+ const datasetId = await createDataset();
+ const model = ConnectorModel.forEvaluation(serverDB, userId, datasetId);
+
+ const row = await model.create({ ...base, identifier: 'eval-mock' } as any);
+
+ expect(row.metadata).toEqual({ agentEval: { datasetId } });
+ });
+
+ it('requires secure storage for mock credentials', async () => {
+ const datasetId = await createDataset();
+ const model = ConnectorModel.forEvaluation(serverDB, userId, datasetId);
+
+ await expect(
+ model.create({
+ ...base,
+ credentials: JSON.stringify({ token: 't', type: 'bearer' }),
+ } as any),
+ ).rejects.toThrow('Secure connection storage is unavailable');
+ });
+
+ it('refuses to attach a mock connection to a normal agent', async () => {
+ const datasetId = await createDataset();
+ const gateKeeper = {
+ decrypt: vi.fn(),
+ encrypt: vi.fn(async (plaintext: string) => `enc:${plaintext}`),
+ };
+ const model = ConnectorModel.forEvaluation(
+ serverDB,
+ userId,
+ datasetId,
+ undefined,
+ gateKeeper,
+ );
+
+ await expect(model.create({ ...base, agentId } as any)).rejects.toThrow(
+ 'Evaluation connections cannot be assigned to a normal Agent',
+ );
+ });
+
+ it('reports a mock credential encryption failure as a stable error', async () => {
+ const datasetId = await createDataset();
+ const gateKeeper = {
+ decrypt: vi.fn(),
+ encrypt: vi.fn(async () => {
+ throw new Error('vault down');
+ }),
+ };
+ const model = ConnectorModel.forEvaluation(
+ serverDB,
+ userId,
+ datasetId,
+ undefined,
+ gateKeeper,
+ );
+ const row = await model.create({ ...base, identifier: 'eval-mock-update' } as any);
+
+ await expect(
+ model.update(row.id, {
+ credentials: JSON.stringify({ token: 't', type: 'bearer' }),
+ } as any),
+ ).rejects.toThrow('Could not securely store the mock connection');
+ });
+
+ it('rethrows a raw encryption failure for an ordinary connector', async () => {
+ const model = new ConnectorModel(serverDB, userId);
+ const row = await model.create({ ...base, identifier: 'plain-encrypt' } as any);
+ const gateKeeper = {
+ decrypt: vi.fn(),
+ encrypt: vi.fn(async () => {
+ throw new Error('vault down');
+ }),
+ };
+
+ await expect(
+ model.update(
+ row.id,
+ { credentials: JSON.stringify({ token: 't', type: 'bearer' }) } as any,
+ gateKeeper,
+ ),
+ ).rejects.toThrow('vault down');
+ });
+ });
});
diff --git a/packages/database/src/models/__tests__/connectorEval.test.ts b/packages/database/src/models/__tests__/connectorEval.test.ts
new file mode 100644
index 00000000000..60ef6c8b963
--- /dev/null
+++ b/packages/database/src/models/__tests__/connectorEval.test.ts
@@ -0,0 +1,374 @@
+// @vitest-environment node
+import { describe, expect, it, vi } from 'vitest';
+
+import {
+ EvalConnectorUpdateError,
+ normalizeEvalConnectorPatch,
+ withoutEvalConnectorMarker,
+} from '../connectorEval';
+
+const marker = { datasetId: '11111111-1111-4111-8111-111111111111' };
+
+/** A stored, imported mock connection: the marker plus optional header set. */
+const evalCurrent = (
+ overrides: Partial<{ credentials: null | string; customHeaders: Record<string, string> }> = {},
+) => ({
+ credentials: overrides.credentials ?? null,
+ metadata: {
+ agentEval: marker,
+ ...(overrides.customHeaders ? { customHeaders: overrides.customHeaders } : {}),
+ } as any,
+ mcpServerUrl: 'https://mock.example.com/mcp',
+});
+
+describe('withoutEvalConnectorMarker', () => {
+ it('passes empty metadata through untouched', () => {
+ expect(withoutEvalConnectorMarker(undefined)).toBeUndefined();
+ expect(withoutEvalConnectorMarker(null)).toBeNull();
+ });
+
+ it('drops the import marker from a submitted metadata object', () => {
+ expect(withoutEvalConnectorMarker({ agentEval: marker, customHeaders: {} } as any)).toEqual({
+ customHeaders: {},
+ });
+ });
+});
+
+describe('normalizeEvalConnectorPatch outside an imported connection', () => {
+ it('returns the patch as-is when no metadata is submitted', async () => {
+ const patch = { name: 'Renamed' };
+ await expect(
+ normalizeEvalConnectorPatch({ credentials: null, metadata: null, mcpServerUrl: null }, patch),
+ ).resolves.toEqual(patch);
+ });
+
+ it('strips a client-supplied marker from an ordinary connector patch', async () => {
+ const result = await normalizeEvalConnectorPatch(
+ { credentials: null, metadata: null, mcpServerUrl: null } as any,
+ { metadata: { agentEval: marker, customHeaders: { A: '1' } } as any },
+ );
+
+ expect(result.metadata).toEqual({ customHeaders: { A: '1' } });
+ });
+});
+
+describe('normalizeEvalConnectorPatch on an imported mock connection', () => {
+ it('rejects assigning the mock connection to a normal agent', async () => {
+ await expect(
+ normalizeEvalConnectorPatch(evalCurrent(), { agentId: 'agent-1' } as any),
+ ).rejects.toThrow(EvalConnectorUpdateError);
+ await expect(
+ normalizeEvalConnectorPatch(evalCurrent(), {
+ metadata: { mountedByAgentId: 'agent-1' },
+ } as any),
+ ).rejects.toThrow('cannot be assigned to a normal Agent');
+ });
+
+ it('rejects MCP addresses that carry embedded credentials', async () => {
+ for (const mcpServerUrl of [
+ 'ftp://mock.example.com/mcp',
+ 'https://user:[email protected]/mcp',
+ 'https://mock.example.com/mcp?token=1',
+ 'https://mock.example.com/mcp#fragment',
+ 'not-a-url',
+ ]) {
+ await expect(
+ normalizeEvalConnectorPatch(evalCurrent(), { mcpServerUrl } as any),
+ ).rejects.toThrow('Use an HTTP MCP address without embedded credentials, query or fragment');
+ }
+ });
+
+ it('accepts a plain https address swap when nothing is authenticated', async () => {
+ const result = await normalizeEvalConnectorPatch(evalCurrent(), {
+ mcpServerUrl: 'https://other.example.com/mcp',
+ } as any);
+
+ expect(result.status).toBe('disconnected');
+ expect(result.credentials).toBeUndefined();
+ });
+
+ it('refuses a URL swap that would drop stored authentication', async () => {
+ await expect(
+ normalizeEvalConnectorPatch(evalCurrent({ credentials: 'cipher' }), {
+ mcpServerUrl: 'https://other.example.com/mcp',
+ } as any),
+ ).rejects.toThrow('Clear or replace authentication when changing a mock connection address');
+ });
+
+ it('treats an explicit credential clear on a URL edit as authoritative', async () => {
+ const result = await normalizeEvalConnectorPatch(
+ evalCurrent({ credentials: 'cipher', customHeaders: { 'X-Token': '1' } }),
+ { credentials: null, mcpServerUrl: 'https://other.example.com/mcp' } as any,
+ );
+
+ expect(result).toMatchObject({
+ credentials: null,
+ status: 'disconnected',
+ tokenExpiresAt: null,
+ });
+ expect(result.metadata).toEqual({ agentEval: marker });
+ });
+
+ it('does not treat a credential-free patch as a URL swap when the address is unchanged', async () => {
+ const result = await normalizeEvalConnectorPatch(evalCurrent(), {
+ mcpServerUrl: 'https://mock.example.com/mcp',
+ } as any);
+
+ expect(result.status).toBeUndefined();
+ });
+
+ describe('header migration', () => {
+ it('migrates stored headers when the editor does not resend them', async () => {
+ const result = await normalizeEvalConnectorPatch(
+ evalCurrent({ customHeaders: { 'X-Stored': '1' } }),
+ { name: 'Renamed' } as any,
+ );
+
+ expect(JSON.parse(result.credentials as string)).toEqual({
+ headers: { 'X-Stored': '1' },
+ type: 'header',
+ });
+ // Headers never leak into stored metadata once they own the credential slot.
+ expect(result.metadata).toEqual({ agentEval: marker });
+ expect(result.status).toBe('disconnected');
+ expect(result.tokenExpiresAt).toBeNull();
+ });
+
+ it('does not migrate stored headers when the caller supplies credentials', async () => {
+ const result = await normalizeEvalConnectorPatch(
+ evalCurrent({ customHeaders: { 'X-Stored': '1' } }),
+ { credentials: JSON.stringify({ type: 'bearer', token: 't' }) } as any,
+ );
+
+ expect(JSON.parse(result.credentials as string)).toEqual({ type: 'bearer', token: 't' });
+ expect(result.metadata).toEqual({ agentEval: marker });
+ });
+
+ it('reads stored credentials when headers are resubmitted and storage is available', async () => {
+ const decrypt = vi.fn().mockResolvedValue({
+ plaintext: JSON.stringify({ headers: { Authorization: 'Bearer old' }, type: 'header' }),
+ });
+
+ const result = await normalizeEvalConnectorPatch(
+ evalCurrent({ credentials: 'cipher' }),
+ { metadata: { customHeaders: { 'X-New': '1' } } as any },
+ decrypt,
+ );
+
+ expect(decrypt).toHaveBeenCalledWith('cipher');
+ // Without an explicit credential the resubmitted header set replaces the stored one.
+ expect(JSON.parse(result.credentials as string)).toEqual({
+ headers: { 'X-New': '1' },
+ type: 'header',
+ });
+ });
+
+ it('clears stored headers when the editor sends an empty header set', async () => {
+ const result = await normalizeEvalConnectorPatch(evalCurrent(), {
+ metadata: { customHeaders: {} } as any,
+ });
+
+ expect(result.credentials).toBeNull();
+ expect(result.metadata).toEqual({ agentEval: marker });
+ });
+
+ it('falls back to an empty set when the header key is present but undefined', async () => {
+ const result = await normalizeEvalConnectorPatch(evalCurrent(), {
+ metadata: { customHeaders: undefined } as any,
+ });
+
+ expect(result.credentials).toBeNull();
+ });
+
+ it('merges resubmitted headers into a decrypted header credential', async () => {
+ const decrypt = vi.fn().mockResolvedValue({
+ plaintext: JSON.stringify({ headers: { 'X-Old': '1' }, type: 'header' }),
+ });
+
+ const result = await normalizeEvalConnectorPatch(
+ evalCurrent({ credentials: 'cipher' }),
+ {
+ credentials: JSON.stringify({ headers: { 'X-Sent': '1' }, type: 'header' }),
+ metadata: { customHeaders: { 'X-New': '2' } } as any,
+ },
+ decrypt,
+ );
+
+ expect(JSON.parse(result.credentials as string)).toEqual({
+ headers: { 'X-New': '2', 'X-Sent': '1' },
+ type: 'header',
+ });
+ });
+ });
+
+ describe('credential precedence', () => {
+ it('requires secure storage when stored credentials must be read for a header edit', async () => {
+ await expect(
+ normalizeEvalConnectorPatch(evalCurrent({ credentials: 'cipher' }), {
+ metadata: { customHeaders: { 'X-New': '1' } } as any,
+ }),
+ ).rejects.toThrow('Secure connection storage is unavailable');
+ });
+
+ it('hides decrypt failures behind a stable error', async () => {
+ await expect(
+ normalizeEvalConnectorPatch(
+ evalCurrent({ credentials: 'cipher' }),
+ { metadata: { customHeaders: { 'X-New': '1' } } as any },
+ vi.fn().mockRejectedValue(new Error('vault down')),
+ ),
+ ).rejects.toThrow('Could not securely read the mock connection');
+ });
+
+ it('keeps OAuth tokens untouched when no custom headers are submitted', async () => {
+ const result = await normalizeEvalConnectorPatch(evalCurrent(), {
+ credentials: JSON.stringify({ accessToken: 'a', type: 'oauth2' }),
+ } as any);
+
+ expect(JSON.parse(result.credentials as string)).toEqual({
+ accessToken: 'a',
+ type: 'oauth2',
+ });
+ // OAuth keeps its own expiry bookkeeping instead of being reset.
+ expect(result.tokenExpiresAt).toBeUndefined();
+ });
+
+ it('rejects custom headers alongside an OAuth login', async () => {
+ await expect(
+ normalizeEvalConnectorPatch(evalCurrent(), {
+ credentials: JSON.stringify({ accessToken: 'a', type: 'oauth2' }),
+ metadata: { customHeaders: { Authorization: 'Bearer x' } } as any,
+ } as any),
+ ).rejects.toThrow('Use OAuth authentication without custom headers for this mock connection');
+ });
+
+ it('folds a bearer token into the Authorization header', async () => {
+ const result = await normalizeEvalConnectorPatch(
+ evalCurrent(),
+ {
+ credentials: JSON.stringify({ token: 't', type: 'bearer' }),
+ metadata: { customHeaders: { 'authorization': 'Bearer stale', 'X-Extra': '1' } } as any,
+ },
+ undefined,
+ );
+
+ expect(JSON.parse(result.credentials as string)).toEqual({
+ headers: { 'X-Extra': '1', 'Authorization': 'Bearer t' },
+ type: 'header',
+ });
+ });
+
+ it('leaves a bearer credential alone when no headers accompany it', async () => {
+ const result = await normalizeEvalConnectorPatch(evalCurrent(), {
+ credentials: JSON.stringify({ token: 't', type: 'bearer' }),
+ } as any);
+
+ expect(JSON.parse(result.credentials as string)).toEqual({ token: 't', type: 'bearer' });
+ expect(result.status).toBe('disconnected');
+ });
+
+ it('promotes an api key to the Authorization header when headers are edited', async () => {
+ const result = await normalizeEvalConnectorPatch(evalCurrent(), {
+ credentials: JSON.stringify({ apiKey: 'k', type: 'apikey' }),
+ metadata: { customHeaders: { 'X-Extra': '1' } } as any,
+ } as any);
+
+ expect(JSON.parse(result.credentials as string)).toEqual({
+ headers: { 'X-Extra': '1', 'Authorization': 'Bearer k' },
+ type: 'header',
+ });
+ });
+
+ it('keeps an api key when no headers are submitted', async () => {
+ const result = await normalizeEvalConnectorPatch(evalCurrent(), {
+ credentials: JSON.stringify({ apiKey: 'k', type: 'apikey' }),
+ } as any);
+
+ expect(JSON.parse(result.credentials as string)).toEqual({ apiKey: 'k', type: 'apikey' });
+ });
+
+ it('clears the credential without touching the address', async () => {
+ const result = await normalizeEvalConnectorPatch(evalCurrent({ credentials: 'cipher' }), {
+ credentials: null,
+ } as any);
+
+ expect(result).toMatchObject({
+ credentials: null,
+ status: 'disconnected',
+ tokenExpiresAt: null,
+ });
+ });
+
+ it('keeps an OAuth login when the header form is submitted empty', async () => {
+ const result = await normalizeEvalConnectorPatch(evalCurrent(), {
+ credentials: JSON.stringify({ accessToken: 'a', type: 'oauth2' }),
+ metadata: { customHeaders: {} } as any,
+ } as any);
+
+ expect(JSON.parse(result.credentials as string)).toEqual({
+ accessToken: 'a',
+ type: 'oauth2',
+ });
+ expect(result.tokenExpiresAt).toBeUndefined();
+ });
+
+ it('keeps a bearer token when the header form is submitted empty', async () => {
+ const result = await normalizeEvalConnectorPatch(evalCurrent(), {
+ credentials: JSON.stringify({ token: 't', type: 'bearer' }),
+ metadata: { customHeaders: {} } as any,
+ } as any);
+
+ expect(JSON.parse(result.credentials as string)).toEqual({ token: 't', type: 'bearer' });
+ });
+
+ it.each([
+ ['invalid JSON', '{'],
+ ['an unknown type', JSON.stringify({ type: 'saml' })],
+ ['a header credential without headers', JSON.stringify({ type: 'header' })],
+ [
+ 'a header value with a line break',
+ JSON.stringify({ headers: { A: 'a\r\nb' }, type: 'header' }),
+ ],
+ [
+ 'a header name with a space',
+ JSON.stringify({ headers: { 'bad name': '1' }, type: 'header' }),
+ ],
+ ['a bearer token with a line break', JSON.stringify({ token: 'a\nb', type: 'bearer' })],
+ ['an api key with a line break', JSON.stringify({ apiKey: 'a\nb', type: 'apikey' })],
+ ['an oauth login without a token', JSON.stringify({ type: 'oauth2' })],
+ ])('rejects %s', async (_label, credentials) => {
+ await expect(
+ normalizeEvalConnectorPatch(evalCurrent(), { credentials } as any),
+ ).rejects.toThrow(EvalConnectorUpdateError);
+ });
+ });
+
+ describe('metadata merge', () => {
+ it('drops a submitted metadata object when only stored headers exist', async () => {
+ const result = await normalizeEvalConnectorPatch(
+ evalCurrent({ customHeaders: { 'X-Stored': '1' } }),
+ { metadata: null } as any,
+ );
+
+ expect(result.metadata).toEqual({ agentEval: marker });
+ });
+
+ it('falls back to an empty metadata object if the stored row vanishes mid-normalisation', async () => {
+ // Defensive `?? {}` only: the marker read and the header read both see the
+ // stored row, while the merge step sees a row that no longer exists.
+ let reads = 0;
+ const current = {
+ credentials: null,
+ get metadata() {
+ reads += 1;
+ return reads <= 2 ? { agentEval: marker, customHeaders: { 'X-Stored': '1' } } : null;
+ },
+ mcpServerUrl: 'https://mock.example.com/mcp',
+ };
+
+ const result = await normalizeEvalConnectorPatch(current as any, { name: 'Renamed' } as any);
+
+ expect(result.metadata).toEqual({ agentEval: marker });
+ });
+ });
+});
diff --git a/packages/database/src/models/__tests__/connectorTool.test.ts b/packages/database/src/models/__tests__/connectorTool.test.ts
index 28769063317..64bad29b3a3 100644
--- a/packages/database/src/models/__tests__/connectorTool.test.ts
+++ b/packages/database/src/models/__tests__/connectorTool.test.ts
@@ -510,4 +510,12 @@ describe('ConnectorToolModel', () => {
expect(await otherModel.findById(stored.id)).toBeUndefined();
});
});
+
+ describe('forEvaluation', () => {
+ it('requires a dataset id', () => {
+ expect(() => ConnectorToolModel.forEvaluation(serverDB, userId, '')).toThrow(
+ 'A Dataset is required for evaluation tools',
+ );
+ });
+ });
});
diff --git a/packages/database/src/models/__tests__/project.coverage.test.ts b/packages/database/src/models/__tests__/project.coverage.test.ts
index b38273c68b5..f5c4c6b29b6 100644
--- a/packages/database/src/models/__tests__/project.coverage.test.ts
+++ b/packages/database/src/models/__tests__/project.coverage.test.ts
@@ -9,6 +9,7 @@ import { agents, projects, users } from '../../schemas';
import type { LobeChatDatabase } from '../../type';
import { AgentModel } from '../agent';
import { ProjectModel } from '../project';
+import { ProjectIdentifierTakenError } from '../projectIdentifier';
import { TaskModel } from '../task';
import { createProxyTestDB } from './_proxyTestDB';
@@ -211,4 +212,47 @@ describe('ProjectModel coverage', () => {
await expect(model.isDedicatedCoordinator(legacy.id)).resolves.toBe(false);
});
});
+
+ describe('identifier conflict translation', () => {
+ /** Minimal insert chain: `create` is the only caller under test here. */
+ const failingDB = (error: unknown) =>
+ ({
+ insert: () => ({
+ values: () => ({
+ returning: async () => {
+ throw error;
+ },
+ }),
+ }),
+ }) as unknown as LobeChatDatabase;
+
+ it('treats a blank identifier as free without querying', async () => {
+ await expect(model.isIdentifierTaken(' ')).resolves.toBe(false);
+ });
+
+ it('rethrows an identifier error raised inside the insert path', async () => {
+ const taken = new ProjectIdentifierTakenError('LOBE');
+
+ await expect(
+ new ProjectModel(failingDB(taken), userId).create({ identifier: 'LOBE', name: 'Taken' }),
+ ).rejects.toBe(taken);
+ });
+
+ it('translates a wrapped unique-index violation into the field error', async () => {
+ const driverError = Object.assign(new Error('insert into "projects" failed'), {
+ cause: {
+ code: '23505',
+ constraint: 'projects_identifier_key',
+ message: 'duplicate key value violates unique constraint',
+ },
+ });
+
+ await expect(
+ new ProjectModel(failingDB(driverError), userId).create({
+ identifier: ' lobe ',
+ name: 'Duplicate',
+ }),
+ ).rejects.toBeInstanceOf(ProjectIdentifierTakenError);
+ });
+ });
});
diff --git a/packages/database/src/models/__tests__/project.identifier.test.ts b/packages/database/src/models/__tests__/project.identifier.test.ts
index f9368ae2de5..0c6fcfa23e4 100644
--- a/packages/database/src/models/__tests__/project.identifier.test.ts
+++ b/packages/database/src/models/__tests__/project.identifier.test.ts
@@ -6,7 +6,7 @@ import { ProjectRepository } from '../../repositories/project';
import { agents, environments, projectEnvironments, users, workspaces } from '../../schemas';
import type { LobeChatDatabase } from '../../type';
import { ProjectModel } from '../project';
-import { ProjectIdentifierTakenError } from '../projectIdentifier';
+import { isProjectIdentifierConflict, ProjectIdentifierTakenError } from '../projectIdentifier';
const serverDB: LobeChatDatabase = await getTestDB();
const userId = 'project-identifier-user';
@@ -111,3 +111,29 @@ describe('ProjectModel identifier allocation', () => {
);
});
});
+
+describe('isProjectIdentifierConflict', () => {
+ it('matches the identifier indexes by constraint name', () => {
+ expect(
+ isProjectIdentifierConflict({ constraint: 'projects_identifier_user_id_key', code: '23505' }),
+ ).toBe(true);
+ });
+
+ it('matches a bare unique violation that names the identifier constraint', () => {
+ expect(
+ isProjectIdentifierConflict({
+ code: '23505',
+ message: 'duplicate key value violates unique constraint "projects_identifier_pkey"',
+ }),
+ ).toBe(true);
+ });
+
+ it('ignores unrelated unique violations and non-string messages', () => {
+ expect(isProjectIdentifierConflict({ code: '23505', message: 42 })).toBe(false);
+ expect(isProjectIdentifierConflict({ code: '23505', constraint: 'projects_slug_key' })).toBe(
+ false,
+ );
+ expect(isProjectIdentifierConflict({ cause: new Error('plain') })).toBe(false);
+ expect(isProjectIdentifierConflict(null)).toBe(false);
+ });
+});
diff --git a/packages/database/src/models/__tests__/thread.coverage.test.ts b/packages/database/src/models/__tests__/thread.coverage.test.ts
index 08b9885334c..53690556375 100644
--- a/packages/database/src/models/__tests__/thread.coverage.test.ts
+++ b/packages/database/src/models/__tests__/thread.coverage.test.ts
@@ -112,6 +112,18 @@ describe('ThreadModel coverage', () => {
expect(await threadModel.settleRun('thread-settle-cancelled', 'op-1', value)).toBe(false);
expect((await findThread('thread-settle-cancelled'))?.status).toBe(ThreadStatus.Cancel);
});
+
+ it('refuses to settle when the caller carries no claim timestamp', async () => {
+ await insertThread('thread-settle-unstamped', ThreadStatus.Processing, 'op-1');
+
+ const unsettled = {
+ metadata: { completedAt: '2026-10-01T00:01:00.000Z', operationId: 'op-1' },
+ status: ThreadStatus.Completed,
+ } as unknown as typeof value;
+
+ expect(await threadModel.settleRun('thread-settle-unstamped', 'op-1', unsettled)).toBe(false);
+ expect((await findThread('thread-settle-unstamped'))?.status).toBe(ThreadStatus.Processing);
+ });
});
describe('claimForRun', () => {
diff --git a/packages/database/src/models/__tests__/userSkill.coverage.test.ts b/packages/database/src/models/__tests__/userSkill.coverage.test.ts
index 0d89551a8b1..cb68630b3af 100644
--- a/packages/database/src/models/__tests__/userSkill.coverage.test.ts
+++ b/packages/database/src/models/__tests__/userSkill.coverage.test.ts
@@ -5,6 +5,7 @@ import { afterEach, beforeEach, describe, expect, it } from 'vitest';
import { getTestDB } from '../../core/getTestDB';
import {
documents,
+ files,
SKILL_BUNDLE_FILE_TYPE,
SKILL_SCRIPT_FILE_TYPE,
SKILL_VERSION_FILE_TYPE,
@@ -210,6 +211,56 @@ describe('UserSkillModel coverage', () => {
expect(await model.findById(bundle.id)).toMatchObject({ version: 2 });
expect((await model.listVersions(bundle.id)).map((v) => v.version)).toEqual([2]);
});
+
+ it('names the published package after an unnamed bundle', async () => {
+ const bundle = await insertRow({
+ fileType: SKILL_BUNDLE_FILE_TYPE,
+ filename: null,
+ metadata: { userSkill: { version: 1 } },
+ });
+
+ expect(
+ await model.revise(bundle.id, {
+ archive: archiveFor('unnamed'),
+ baseVersion: 1,
+ content: 'v2 body',
+ }),
+ ).toBe(2);
+
+ const [published] = await serverDB.select().from(files).where(eq(files.parentId, bundle.id));
+ expect(published.name).toBe('@2.zip');
+ });
+
+ it('reads an archive published before file hashes were stored', async () => {
+ const bundle = await insertRow({ fileType: SKILL_BUNDLE_FILE_TYPE, filename: 'hashless' });
+ await model.revise(bundle.id, {
+ archive: archiveFor('hashless-v2'),
+ baseVersion: 1,
+ content: 'v2 body',
+ });
+ // Older rows predate the hash column being filled in by the publisher.
+ await serverDB.update(files).set({ fileHash: null }).where(eq(files.parentId, bundle.id));
+
+ const skill = await model.findById(bundle.id);
+
+ expect(skill?.archive).toMatchObject({ fileHash: '' });
+ });
+
+ it('tolerates an archive row that lost its metadata', async () => {
+ const scoped = new UserSkillModel(serverDB, userId);
+ const createdAt = new Date('2026-10-01T00:00:00.000Z');
+ // `archiveRows` only selects rows whose metadata carries `skillVersion`, so a
+ // metadata-less row is a defensive case the query cannot surface on its own.
+ (scoped as any).archiveRows = async () => [
+ { createdAt, fileHash: 'h', id: 'archive-1', metadata: null, size: 1, url: 'skills/a.zip' },
+ ];
+
+ const [version] = await scoped.listVersions('skill-1');
+
+ expect(version).toMatchObject({ archive: { fileHash: 'h', fileId: 'archive-1' } });
+ expect(version.note).toBeUndefined();
+ expect(Number.isNaN(version.version)).toBe(true);
+ });
});
describe('listVersions', () => {
diff --git a/packages/database/src/models/__tests__/verifyRun.coverage.test.ts b/packages/database/src/models/__tests__/verifyRun.coverage.test.ts
index 9015ad899f8..4069c56b3e5 100644
--- a/packages/database/src/models/__tests__/verifyRun.coverage.test.ts
+++ b/packages/database/src/models/__tests__/verifyRun.coverage.test.ts
@@ -143,4 +143,31 @@ describe('VerifyRunModel coverage', () => {
expect(gone).toBeUndefined();
});
});
+
+ describe('recordVerifierRedrive', () => {
+ it('stamps the re-drive without clobbering other metadata', async () => {
+ const run = await insertRun({ metadata: { keep: 'me' }, status: 'verifying' });
+ const at = new Date('2026-10-01T00:00:00.000Z');
+
+ await new VerifyRunModel(serverDB, userId).recordVerifierRedrive(run.id, at);
+
+ const [stored] = await serverDB.select().from(verifyRuns).where(eq(verifyRuns.id, run.id));
+ expect(stored.metadata).toEqual({
+ keep: 'me',
+ verifierRedrivenAt: '2026-10-01T00:00:00.000Z',
+ });
+ });
+
+ it('leaves another owner run untouched', async () => {
+ const run = await insertRun({ status: 'verifying' });
+
+ await new VerifyRunModel(serverDB, otherUserId).recordVerifierRedrive(
+ run.id,
+ new Date('2026-10-01T00:00:00.000Z'),
+ );
+
+ const [stored] = await serverDB.select().from(verifyRuns).where(eq(verifyRuns.id, run.id));
+ expect(stored.metadata ?? {}).not.toHaveProperty('verifierRedrivenAt');
+ });
+ });
});
diff --git a/packages/database/src/models/agentEval/__tests__/datasetFreeze.test.ts b/packages/database/src/models/agentEval/__tests__/datasetFreeze.test.ts
index 353cdff3be5..7939aa88a51 100644
--- a/packages/database/src/models/agentEval/__tests__/datasetFreeze.test.ts
+++ b/packages/database/src/models/agentEval/__tests__/datasetFreeze.test.ts
@@ -189,4 +189,29 @@ describe('server-derived Lobe Bench dataset freezing', () => {
expect(await datasets.update(system.id, { name: 'Changed' })).toBeUndefined();
expect((await datasets.findById(system.id))?.metadata).toEqual({ kind: 'lobe-bench' });
});
+
+ it('compares a cleared metadata object against the stored one before refusing', async () => {
+ const dataset = await datasets.create({
+ benchmarkId: lobeBenchId,
+ identifier: 'clear-metadata',
+ name: 'Clear metadata',
+ });
+
+ await expect(
+ datasets.update(dataset.id, { metadata: null } as unknown as Record<string, unknown>),
+ ).rejects.toBeInstanceOf(AgentEvalDatasetWriteError);
+ });
+
+ it('accepts a cleared metadata patch when the stored metadata is already empty', async () => {
+ const [legacy] = await db
+ .insert(agentEvalDatasets)
+ .values({ benchmarkId: lobeBenchId, identifier: 'no-metadata', name: 'No metadata', userId })
+ .returning();
+
+ const updated = await datasets.update(legacy.id, {
+ metadata: null,
+ } as unknown as Record<string, unknown>);
+
+ expect(updated?.metadata).toMatchObject({ custom: true, kind: 'lobe-bench' });
+ });
});
diff --git a/packages/database/src/models/agentEval/__tests__/environment.test.ts b/packages/database/src/models/agentEval/__tests__/environment.test.ts
index 709a47be703..759473c9d0c 100644
--- a/packages/database/src/models/agentEval/__tests__/environment.test.ts
+++ b/packages/database/src/models/agentEval/__tests__/environment.test.ts
@@ -62,4 +62,60 @@ describe('AgentEvalEnvironmentModel', () => {
.where(eq(agentEvalEnvironments.id, system.id));
expect(still.name).toBe('System');
});
+
+ it('updates a name without touching the stored configuration', async () => {
+ const created = await environmentModel.create({
+ config: { envPrompt: 'keep me' },
+ name: 'Before',
+ });
+
+ const updated = await environmentModel.update(created.id, { name: 'After' });
+
+ expect(updated?.name).toBe('After');
+ expect(updated?.config).toEqual({ envPrompt: 'keep me' });
+ });
+
+ it('keeps server-owned connections when the client resubmits the persona form', async () => {
+ const created = await environmentModel.create({
+ config: {
+ agent: { systemRole: 'Persona' },
+ connections: { github: { url: 'https://mock.example.com/github' } },
+ },
+ name: 'Shared',
+ });
+
+ const updated = await environmentModel.update(created.id, {
+ config: { agent: { systemRole: 'Updated persona' } },
+ });
+
+ expect(updated?.config).toEqual({
+ agent: { systemRole: 'Updated persona' },
+ connections: { github: { url: 'https://mock.example.com/github' } },
+ });
+ });
+
+ describe('findByIds', () => {
+ it('returns nothing for an empty list', async () => {
+ expect(await environmentModel.findByIds([])).toEqual([]);
+ });
+
+ it('resolves each environment once and skips unknown ids', async () => {
+ const [first, second] = await serverDB
+ .insert(agentEvalEnvironments)
+ .values([
+ { config: {}, identifier: 'env-a', name: 'A', userId },
+ { config: {}, identifier: 'env-b', name: 'B', userId },
+ ])
+ .returning();
+
+ const rows = await environmentModel.findByIds([
+ first.id,
+ second.id,
+ first.id,
+ '00000000-0000-4000-8000-000000000000',
+ ]);
+
+ expect(rows.map((row) => row.id).sort()).toEqual([first.id, second.id].sort());
+ });
+ });
});
diff --git a/packages/database/src/models/agentEval/__tests__/run.test.ts b/packages/database/src/models/agentEval/__tests__/run.test.ts
index 96806caa858..3b1b8894096 100644
--- a/packages/database/src/models/agentEval/__tests__/run.test.ts
+++ b/packages/database/src/models/agentEval/__tests__/run.test.ts
@@ -658,4 +658,67 @@ describe('AgentEvalRunModel', () => {
expect(count).toBe(0);
});
});
+
+ describe('startedAt guards', () => {
+ const startedAt = new Date('2026-10-01T00:00:00.000Z');
+
+ it('applies update only to the run whose start timestamp still matches', async () => {
+ const run = await runModel.create({ datasetId, startedAt, status: 'running' });
+
+ expect(await runModel.update(run.id, { name: 'Guarded' }, { startedAt })).toMatchObject({
+ name: 'Guarded',
+ });
+ // A caller that read an older start timestamp must not overwrite the new attempt.
+ expect(
+ await runModel.update(run.id, { name: 'Stale' }, { startedAt: new Date(0) }),
+ ).toBeUndefined();
+ expect((await runModel.findById(run.id))?.name).toBe('Guarded');
+ });
+
+ it('treats a null start timestamp as its own attempt', async () => {
+ const run = await runModel.create({ datasetId, status: 'running' });
+
+ expect(
+ await runModel.update(run.id, { name: 'Unstarted' }, { startedAt: null }),
+ ).toMatchObject({ name: 'Unstarted' });
+ expect(await runModel.update(run.id, { name: 'Wrong' }, { startedAt })).toBeUndefined();
+ });
+
+ it('writes progress only for the matching attempt of a live run', async () => {
+ const run = await runModel.create({ datasetId, startedAt, status: 'running' });
+
+ expect(
+ await runModel.updateProgress(run.id, { passedCases: 3 }, { startedAt }),
+ ).toMatchObject({ metrics: expect.objectContaining({ passedCases: 3 }) });
+ expect(
+ await runModel.updateProgress(run.id, { passedCases: 9 }, { startedAt: null }),
+ ).toBeUndefined();
+
+ const unstarted = await runModel.create({ datasetId, status: 'running' });
+ expect(
+ await runModel.updateProgress(unstarted.id, { passedCases: 1 }, { startedAt: null }),
+ ).toMatchObject({ metrics: expect.objectContaining({ passedCases: 1 }) });
+ });
+
+ it('finalizes only the matching attempt', async () => {
+ const run = await runModel.create({ datasetId, startedAt, status: 'running' });
+
+ expect(
+ await runModel.finalize(
+ run.id,
+ { metrics: { passedCases: 1 }, status: 'completed' },
+ { startedAt: startedAt.toISOString() },
+ ),
+ ).toMatchObject({ status: 'completed' });
+ expect(
+ await runModel.finalize(run.id, { status: 'failed' }, { startedAt: new Date(0) }),
+ ).toBeUndefined();
+ expect((await runModel.findById(run.id))?.status).toBe('completed');
+
+ const unstarted = await runModel.create({ datasetId, status: 'running' });
+ expect(
+ await runModel.finalize(unstarted.id, { status: 'completed' }, { startedAt: null }),
+ ).toMatchObject({ status: 'completed' });
+ });
+ });
});
diff --git a/packages/database/src/models/agentEval/__tests__/runTopic.test.ts b/packages/database/src/models/agentEval/__tests__/runTopic.test.ts
index 1f635e00d87..89699179beb 100644
--- a/packages/database/src/models/agentEval/__tests__/runTopic.test.ts
+++ b/packages/database/src/models/agentEval/__tests__/runTopic.test.ts
@@ -529,6 +529,62 @@ describe('AgentEvalRunTopicModel', () => {
error: 'Execution error: insufficient_user_quota',
});
});
+
+ it('guards the write by the execution that owns the row', async () => {
+ await serverDB
+ .update(agentEvalRunTopics)
+ .set({ evalResult: { executionId: 'exec-1' } })
+ .where(eq(agentEvalRunTopics.topicId, topicId1));
+
+ expect(
+ await runTopicModel.updateByRunAndTopic(
+ runId,
+ topicId1,
+ { score: 0.5 },
+ { executionId: 'exec-2' },
+ ),
+ ).toBeUndefined();
+ expect(
+ await runTopicModel.updateByRunAndTopic(
+ runId,
+ topicId1,
+ { score: 0.5 },
+ { executionId: 'exec-1' },
+ ),
+ ).toMatchObject({ score: 0.5 });
+ });
+
+ it('treats an explicit undefined execution id as "no execution yet"', async () => {
+ expect(
+ await runTopicModel.updateByRunAndTopic(
+ runId,
+ topicId1,
+ { score: 0.1 },
+ { executionId: undefined },
+ ),
+ ).toMatchObject({ score: 0.1 });
+ });
+
+ it('requires the expected status when a status guard is supplied', async () => {
+ await runTopicModel.updateByRunAndTopic(runId, topicId1, { status: 'running' });
+
+ expect(
+ await runTopicModel.updateByRunAndTopic(
+ runId,
+ topicId1,
+ { score: 0.2 },
+ { status: 'passed' },
+ ),
+ ).toBeUndefined();
+ expect(
+ await runTopicModel.updateByRunAndTopic(
+ runId,
+ topicId1,
+ { score: 0.2 },
+ { status: 'running' },
+ ),
+ ).toMatchObject({ score: 0.2 });
+ });
});
describe('batchMarkTimeout', () => {