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% (#20962)

Arvin Xuc8f8ad2a2ffe
diff --git a/packages/database/src/models/__tests__/agentAccount.test.ts b/packages/database/src/models/__tests__/agentAccount.test.ts
index 162c23accf5..73fb6d52c38 100644
--- a/packages/database/src/models/__tests__/agentAccount.test.ts
+++ b/packages/database/src/models/__tests__/agentAccount.test.ts
@@ -293,3 +293,64 @@ describe('AgentAccountModel schema invariants', () => {
).rejects.toThrow();
});
});
+
+describe('AgentAccountModel query filters', () => {
+ it('narrows by kind and provider within the caller scope', async () => {
+ const model = new AgentAccountModel(serverDB, userId, mockGateKeeper);
+
+ await model.create({
+ ...mailAccount('[email protected]'),
+ credential: { webhookSecret: 'whsec_filter' },
+ });
+ await model.create({
+ ...mailAccount('+15550000000'),
+ capabilities: { receive: true, send: true },
+ kind: 'phone',
+ provider: 'agent-sms',
+ });
+
+ expect((await model.query({ kind: 'mail' })).map((a) => a.identifier)).toEqual([
+ ]);
+ expect((await model.query({ provider: 'agent-sms' })).map((a) => a.kind)).toEqual(['phone']);
+ expect(await model.query({ kind: 'wallet' })).toHaveLength(0);
+ });
+});
+
+describe('AgentAccountModel credential read discipline', () => {
+ it('refuses to decrypt a stored credential without a gatekeeper, with an actionable message', async () => {
+ const writing = new AgentAccountModel(serverDB, userId, mockGateKeeper);
+ const created = await writing.create({
+ ...mailAccount('[email protected]'),
+ credential: { webhookSecret: 'whsec_read' },
+ });
+
+ const reading = new AgentAccountModel(serverDB, userId);
+ await expect(reading.getCredential(created.id)).rejects.toThrow(
+ /needs a gatekeeper to read credentials/,
+ );
+ });
+});
+
+describe('AgentAccountModel.findForInboundVerification', () => {
+ it('returns undefined when no live account matches the routing key', async () => {
+ expect(
+ await AgentAccountModel.findForInboundVerification(serverDB, 'agent-mail', '[email protected]'),
+ ).toBeUndefined();
+ });
+
+ it('reports a null credential for an account that never stored one', async () => {
+ const model = new AgentAccountModel(serverDB, userId);
+ const created = await model.create(mailAccount('[email protected]'));
+
+ const inbound = await AgentAccountModel.findForInboundVerification(
+ serverDB,
+ 'agent-mail',
+ mockGateKeeper,
+ );
+
+ expect(inbound?.view.id).toBe(created.id);
+ expect(inbound?.credential).toBeNull();
+ });
+});
diff --git a/packages/database/src/models/__tests__/agentLabel.test.ts b/packages/database/src/models/__tests__/agentLabel.test.ts
index 9941a02bda9..01cefadba03 100644
--- a/packages/database/src/models/__tests__/agentLabel.test.ts
+++ b/packages/database/src/models/__tests__/agentLabel.test.ts
@@ -240,4 +240,44 @@ describe('AgentLabelModel', () => {
expect(next).toEqual([]);
});
});
+
+ describe('toggleAgentLabel', () => {
+ it('should remove a single label when toggled off, leaving the rest intact', async () => {
+ await createAgent('agt-toggle-off');
+ const a = await personalModel.create({ name: 'Toggle A' });
+ const b = await personalModel.create({ name: 'Toggle B' });
+
+ await personalModel.toggleAgentLabel('agt-toggle-off', a.id, true);
+ await personalModel.toggleAgentLabel('agt-toggle-off', b.id, true);
+
+ const remaining = await personalModel.toggleAgentLabel('agt-toggle-off', a.id, false);
+
+ expect(remaining).toEqual([b.id]);
+ expect(await personalModel.getAgentLabelIds('agt-toggle-off')).toEqual([b.id]);
+ });
+
+ it('should be a no-op when toggling off a label that is not assigned', async () => {
+ await createAgent('agt-toggle-off-missing');
+ const label = await personalModel.create({ name: 'Never Assigned' });
+
+ const ids = await personalModel.toggleAgentLabel('agt-toggle-off-missing', label.id, false);
+
+ expect(ids).toEqual([]);
+ });
+
+ it('should reject applying a label that does not exist in the scope', async () => {
+ await createAgent('agt-toggle-unknown');
+
+ await expect(
+ personalModel.toggleAgentLabel(
+ 'agt-toggle-unknown',
+ '00000000-0000-0000-0000-000000000000',
+ true,
+ ),
+ ).rejects.toThrow(/not found in current scope/);
+
+ // the failed toggle writes nothing
+ expect(await personalModel.getAgentLabelIds('agt-toggle-unknown')).toEqual([]);
+ });
+ });
});
diff --git a/packages/database/src/models/__tests__/asyncTask.test.ts b/packages/database/src/models/__tests__/asyncTask.test.ts
index f9905ece9b4..75e05b79ce0 100644
--- a/packages/database/src/models/__tests__/asyncTask.test.ts
+++ b/packages/database/src/models/__tests__/asyncTask.test.ts
@@ -132,6 +132,16 @@ describe('AsyncTaskModel', () => {
expect(chunkTasks).toHaveLength(2);
expect(chunkTasks.every((t) => t.type === AsyncTaskType.Chunking)).toBe(true);
});
+
+ it('should return an empty list without scanning for timeout when given no ids', async () => {
+ await serverDB
+ .insert(asyncTasks)
+ .values({ status: AsyncTaskStatus.Processing, type: AsyncTaskType.Chunking, userId });
+
+ const chunkTasks = await asyncTaskModel.findByIds([], AsyncTaskType.Chunking);
+
+ expect(chunkTasks).toEqual([]);
+ });
});
describe('incrementUserMemoryExtractionProgress', () => {
@@ -644,6 +654,14 @@ describe('AsyncTaskModel', () => {
expect(requested).toBe(false);
});
+
+ it('should return false when the task id resolves to nothing', async () => {
+ const requested = await asyncTaskModel.isHourlyMemoryExtractionCancellationRequested(
+ '00000000-0000-0000-0000-000000000000',
+ );
+
+ expect(requested).toBe(false);
+ });
});
});
@@ -873,6 +891,32 @@ describe('initHourlyUserMemoryExtractionMetadata', () => {
scheduledChildRuns: 3,
});
});
+
+ it('should leave upstash undefined when control carries none', () => {
+ const result = initHourlyUserMemoryExtractionMetadata({
+ control: { cancelRequestedAt: '2026-07-06T01:00:00.000Z' },
+ startedAt: '2026-07-06T00:00:00.000Z',
+ });
+
+ expect(result.control).toEqual({
+ cancelReason: undefined,
+ cancelRequestedAt: '2026-07-06T01:00:00.000Z',
+ cancelledBy: undefined,
+ upstash: undefined,
+ });
+ });
+
+ it('should default workflowRunIds to an empty list when upstash omits it', () => {
+ const result = initHourlyUserMemoryExtractionMetadata({
+ control: { upstash: { entryWorkflowRunId: 'entry-only' } },
+ startedAt: '2026-07-06T00:00:00.000Z',
+ });
+
+ expect(result.control?.upstash).toEqual({
+ entryWorkflowRunId: 'entry-only',
+ workflowRunIds: [],
+ });
+ });
});
describe('AsyncTaskModel.findByInferenceId', () => {
diff --git a/packages/database/src/models/__tests__/connectorTool.test.ts b/packages/database/src/models/__tests__/connectorTool.test.ts
index e2d753deab3..a75a93a61b9 100644
--- a/packages/database/src/models/__tests__/connectorTool.test.ts
+++ b/packages/database/src/models/__tests__/connectorTool.test.ts
@@ -395,4 +395,30 @@ describe('ConnectorToolModel', () => {
expect(personalRows.map((r) => r.toolName)).toEqual(['personal']);
});
});
+
+ describe('findById', () => {
+ it('resolves a tool by id inside the owner scope', async () => {
+ const model = new ConnectorToolModel(serverDB, userId);
+ await model.upsertMany(connectorId, [
+ tool({ description: 'Create an issue', toolName: 'create_issue' }),
+ ]);
+
+ const [stored] = await model.queryByConnector(connectorId);
+ const found = await model.findById(stored.id);
+
+ expect(found?.id).toBe(stored.id);
+ expect(found?.toolName).toBe('create_issue');
+ });
+
+ it('returns undefined for an unknown id and for another user tool', async () => {
+ const model = new ConnectorToolModel(serverDB, userId);
+ await model.upsertMany(connectorId, [tool({ toolName: 'secret' })]);
+ const [stored] = await model.queryByConnector(connectorId);
+
+ expect(await model.findById('00000000-0000-0000-0000-000000000000')).toBeUndefined();
+
+ const otherModel = new ConnectorToolModel(serverDB, otherUserId);
+ expect(await otherModel.findById(stored.id)).toBeUndefined();
+ });
+ });
});
diff --git a/packages/database/src/models/__tests__/fileUpload.test.ts b/packages/database/src/models/__tests__/fileUpload.test.ts
index 7be5372801f..fd53e9d6354 100644
--- a/packages/database/src/models/__tests__/fileUpload.test.ts
+++ b/packages/database/src/models/__tests__/fileUpload.test.ts
@@ -170,4 +170,39 @@ describe('FileUploadModel', () => {
expect(await model.findActiveByPathname(live!.pathname)).toBeDefined();
expect((await model.findLatestByPathname(recentCleaning!.pathname))?.status).toBe('cleaning');
});
+
+ it('reports zero live bytes for a workspace with no live uploads', async () => {
+ const emptyWorkspaceId = 'file-upload-test-empty-workspace';
+ await serverDB.insert(workspaces).values({
+ id: emptyWorkspaceId,
+ name: 'Empty workspace',
+ primaryOwnerId: userId,
+ slug: emptyWorkspaceId,
+ });
+
+ // `sum()` over an empty set yields NULL, not 0 — the counter must coerce it.
+ expect(await FileUploadModel.countLiveUsageForWorkspace(serverDB, emptyWorkspaceId)).toBe(0);
+ });
+
+ it('returns empty results when nothing is eligible to claim or purge', async () => {
+ const model = new FileUploadModel(serverDB, userId);
+ await model.create({ expiresAt, pathname: 'files/not-yet-expired', size: 1 });
+
+ // Nothing has expired as of the cutoff…
+ expect(
+ await FileUploadModel.claimExpiredBatch(serverDB, {
+ batchSize: 10,
+ cleanupLeaseBefore: new Date('2000-01-01T00:00:00Z'),
+ expiresBefore: new Date('2000-01-01T00:00:00Z'),
+ }),
+ ).toEqual([]);
+
+ // …and no terminal row predates it either.
+ expect(
+ await FileUploadModel.deleteTerminalBatch(serverDB, {
+ batchSize: 10,
+ updatedBefore: new Date('2000-01-01T00:00:00Z'),
+ }),
+ ).toBe(0);
+ });
});
diff --git a/packages/database/src/models/__tests__/resourcePermission.test.ts b/packages/database/src/models/__tests__/resourcePermission.test.ts
index 916e02f6da8..369a68e281c 100644
--- a/packages/database/src/models/__tests__/resourcePermission.test.ts
+++ b/packages/database/src/models/__tests__/resourcePermission.test.ts
@@ -274,4 +274,28 @@ describe('ResourcePermissionModel collaborators', () => {
expect(await model.getAccessLevel('knowledgeBase', kbId)).toBeNull();
expect(await model.listCollaborators('knowledgeBase', kbId)).toEqual([]);
});
+
+ it('upsert and remove are no-ops on an empty member list', async () => {
+ // An empty batch must not emit an `in ()` / `values ()` statement — Drizzle
+ // throws on those — and must not disturb the rows already stored.
+ await model.upsertCollaborators({
+ accessLevel: 'edit',
+ createdBy: ownerId,
+ resourceId: kbId,
+ resourceType: 'knowledgeBase',
+ userIds: [memberA],
+ });
+
+ await model.upsertCollaborators({
+ accessLevel: 'edit',
+ createdBy: ownerId,
+ resourceId: kbId,
+ resourceType: 'knowledgeBase',
+ userIds: [],
+ });
+ await model.removeCollaborators('knowledgeBase', kbId, []);
+
+ const rows = await model.listCollaborators('knowledgeBase', kbId);
+ expect(rows.map((r) => r.userId)).toEqual([memberA]);
+ });
});