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

Arvin Xufe479d681ff2
diff --git a/packages/database/src/models/__tests__/acceptanceReview.replies.test.ts b/packages/database/src/models/__tests__/acceptanceReview.replies.test.ts
new file mode 100644
index 00000000000..a080ca51f15
--- /dev/null
+++ b/packages/database/src/models/__tests__/acceptanceReview.replies.test.ts
@@ -0,0 +1,321 @@
+// @vitest-environment node
+import { randomUUID } from 'node:crypto';
+
+import { and, eq } from 'drizzle-orm';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+
+import { getTestDB } from '../../core/getTestDB';
+import { ProjectRepository } from '../../repositories/project';
+import {
+ acceptanceComments,
+ acceptanceReviewMarks,
+ acceptances,
+ users,
+ workspaces,
+} from '../../schemas';
+import type { LobeChatDatabase } from '../../type';
+import { AcceptanceReviewModel } from '../acceptanceReview';
+import { ProjectSiteModel } from '../projectReview';
+
+const serverDB: LobeChatDatabase = await getTestDB();
+
+const owner = 'acceptance-replies-owner';
+const reviewer = 'acceptance-replies-reviewer';
+const workspaceId = 'acceptance-replies-workspace';
+
+const model = new AcceptanceReviewModel(serverDB);
+
+let siteId: string;
+let projectId: string;
+let acceptanceId: string;
+
+const markInput = (clientId: string, content = 'Cards are too tight') => ({
+ clientId,
+ content,
+ kind: 'region' as const,
+ rectDocument: { height: 160, width: 384, x: 448, y: 1294 },
+ rectViewport: { height: 160, width: 384, x: 448, y: 494 },
+ routeKey: '/notebook',
+ scroll: { x: 0, y: 800 },
+ url: 'https://preview.example.com/notebook',
+ viewport: { dpr: 2, height: 800, width: 1280 },
+});
+
+const draftOf = (userId: string) => model.createDraft({ projectId, siteId, userId });
+
+const submittedReviewOf = async (userId: string) => {
+ const review = await draftOf(userId);
+ await model.addMark(review.id, markInput('a'));
+ await model.markSubmitted(review.id);
+ return review;
+};
+
+const markIdsOf = async (reviewId: string) => {
+ const rows = await serverDB
+ .select({ id: acceptanceReviewMarks.id })
+ .from(acceptanceReviewMarks)
+ .where(eq(acceptanceReviewMarks.reviewId, reviewId));
+ return rows.map((row) => row.id);
+};
+
+beforeEach(async () => {
+ await serverDB.delete(users);
+ await serverDB.insert(users).values([{ id: owner }, { id: reviewer }]);
+ await serverDB
+ .insert(workspaces)
+ .values({ id: workspaceId, name: 'WS', primaryOwnerId: owner, slug: 'acceptance-replies' });
+
+ const project = await new ProjectRepository(serverDB, owner).create({
+ identifier: 'FNT',
+ name: 'Fieldnotes',
+ });
+ projectId = project.id;
+ const site = await new ProjectSiteModel(serverDB).create({
+ name: 'Preview',
+ origins: ['https://preview.example.com'],
+ projectId,
+ });
+ siteId = site.id;
+
+ const [acceptance] = await serverDB
+ .insert(acceptances)
+ .values({ subjectId: randomUUID(), subjectType: 'standalone', userId: owner })
+ .returning();
+ acceptanceId = acceptance.id;
+});
+
+afterEach(async () => {
+ await serverDB.delete(users);
+ await serverDB.delete(workspaces);
+});
+
+describe('AcceptanceReviewModel.createDraft without a project', () => {
+ it('stores a draft that belongs to no project', async () => {
+ const draft = await model.createDraft({ siteId, userId: reviewer });
+
+ expect(draft.projectId).toBeNull();
+ });
+});
+
+describe('AcceptanceReviewModel.revertToDraft', () => {
+ it('reopens a submitted review so the reviewer can keep marking', async () => {
+ const review = await submittedReviewOf(reviewer);
+
+ const reverted = await model.revertToDraft(review.id);
+
+ expect(reverted).toMatchObject({ id: review.id, status: 'draft', submittedAt: null });
+ // Reopening frees the draft slot, so marking resumes on the same review.
+ expect((await model.addMark(review.id, markInput('b')))?.seq).toBe(2);
+ });
+
+ it('leaves a review that was never submitted alone', async () => {
+ const review = await draftOf(reviewer);
+
+ expect(await model.revertToDraft(review.id)).toBeUndefined();
+ expect((await model.findById(review.id))?.status).toBe('draft');
+ });
+});
+
+describe('AcceptanceReviewModel.discard on a submitted review', () => {
+ it('refuses to discard and keeps the marks a reviewer already sent', async () => {
+ const review = await submittedReviewOf(reviewer);
+ const marks = await markIdsOf(review.id);
+
+ expect(await model.discard(review.id)).toBeUndefined();
+ expect((await model.findById(review.id))?.status).toBe('submitted');
+ expect(await markIdsOf(review.id)).toEqual(marks);
+ });
+});
+
+describe('AcceptanceReviewModel.findMark', () => {
+ it('finds a mark of the review it belongs to and nothing across reviews', async () => {
+ const review = await draftOf(reviewer);
+ const other = await draftOf(owner);
+ const mark = await model.addMark(review.id, markInput('a'));
+
+ expect((await model.findMark(review.id, mark!.id))?.clientId).toBe('a');
+ expect(await model.findMark(other.id, mark!.id)).toBeUndefined();
+ });
+});
+
+describe('AcceptanceReviewModel.countMarks', () => {
+ it('counts without querying when there is nothing to count', async () => {
+ expect((await model.countMarks([])).size).toBe(0);
+ });
+
+ it('counts the marks of every review in one round trip', async () => {
+ const busy = await draftOf(reviewer);
+ const quiet = await draftOf(owner);
+ await model.addMark(busy.id, markInput('a'));
+ await model.addMark(busy.id, markInput('b'));
+
+ const counts = await model.countMarks([busy.id, quiet.id]);
+
+ expect(counts.get(busy.id)).toBe(2);
+ expect(counts.get(quiet.id)).toBeUndefined();
+ });
+});
+
+describe('AcceptanceReviewModel replies', () => {
+ it('returns the stored reply and keeps a retried clientId to one row', async () => {
+ const review = await draftOf(reviewer);
+ const mark = await model.addMark(review.id, markInput('a'));
+
+ const reply = await model.addReply(acceptanceId, mark!.id, {
+ authorUserId: reviewer,
+ clientId: 'reply-1',
+ content: 'Agreed',
+ });
+ const retried = await model.addReply(acceptanceId, mark!.id, {
+ authorUserId: reviewer,
+ clientId: 'reply-1',
+ content: 'Agreed',
+ });
+
+ expect(retried?.id).toBe(reply!.id);
+ expect(await model.listReplies(mark!.id)).toHaveLength(1);
+ });
+
+ it('copies the workspace of a reply and leaves a personal one unscoped', async () => {
+ const review = await draftOf(reviewer);
+ const mark = await model.addMark(review.id, markInput('a'));
+
+ const personal = await model.addReply(acceptanceId, mark!.id, {
+ authorUserId: reviewer,
+ clientId: 'personal',
+ content: 'Personal',
+ });
+ const inWorkspace = await model.addReply(acceptanceId, mark!.id, {
+ authorUserId: reviewer,
+ clientId: 'in-workspace',
+ content: 'Workspace',
+ workspaceId,
+ });
+
+ expect(personal?.workspaceId).toBeNull();
+ expect(inWorkspace?.workspaceId).toBe(workspaceId);
+ });
+
+ it('counts only live replies, per mark', async () => {
+ const review = await draftOf(reviewer);
+ const first = await model.addMark(review.id, markInput('a'));
+ const second = await model.addMark(review.id, markInput('b'));
+
+ await model.addReply(acceptanceId, first!.id, {
+ authorUserId: reviewer,
+ clientId: 'one',
+ content: 'One',
+ });
+ const gone = await model.addReply(acceptanceId, first!.id, {
+ authorUserId: reviewer,
+ clientId: 'two',
+ content: 'Two',
+ });
+ await serverDB
+ .update(acceptanceComments)
+ .set({ deletedAt: new Date() })
+ .where(eq(acceptanceComments.id, gone!.id));
+
+ expect((await model.countReplies([])).size).toBe(0);
+ const counts = await model.countReplies([first!.id, second!.id]);
+ expect(counts.get(first!.id)).toBe(1);
+ expect(counts.get(second!.id)).toBeUndefined();
+ });
+
+ it('lists the live replies of a mark oldest first and hides deleted ones', async () => {
+ const review = await draftOf(reviewer);
+ const mark = await model.addMark(review.id, markInput('a'));
+
+ const earlier = await model.addReply(acceptanceId, mark!.id, {
+ authorUserId: reviewer,
+ clientId: 'earlier',
+ content: 'Earlier',
+ });
+ const later = await model.addReply(acceptanceId, mark!.id, {
+ authorUserId: reviewer,
+ clientId: 'later',
+ content: 'Later',
+ });
+ await serverDB
+ .update(acceptanceComments)
+ .set({ createdAt: new Date('2026-01-01T00:00:00Z') })
+ .where(eq(acceptanceComments.id, earlier!.id));
+ await serverDB
+ .update(acceptanceComments)
+ .set({ createdAt: new Date('2026-01-02T00:00:00Z') })
+ .where(eq(acceptanceComments.id, later!.id));
+
+ expect((await model.listReplies(mark!.id)).map((row) => row.content)).toEqual([
+ 'Earlier',
+ 'Later',
+ ]);
+
+ await serverDB
+ .update(acceptanceComments)
+ .set({ deletedAt: new Date() })
+ .where(eq(acceptanceComments.id, earlier!.id));
+
+ expect((await model.listReplies(mark!.id)).map((row) => row.content)).toEqual(['Later']);
+ });
+
+ it('collects every reply id of an acceptance, and no global comment', async () => {
+ const review = await draftOf(reviewer);
+ const mark = await model.addMark(review.id, markInput('a'));
+ const reply = await model.addReply(acceptanceId, mark!.id, {
+ authorUserId: reviewer,
+ clientId: 'reply',
+ content: 'Reply',
+ });
+ const [global] = await serverDB
+ .insert(acceptanceComments)
+ .values({ acceptanceId, authorUserId: owner, clientId: 'global', content: 'Global' })
+ .returning();
+
+ const ids = await model.listReplyIds(acceptanceId);
+
+ expect(ids.has(reply!.id)).toBe(true);
+ expect(ids.has(global.id)).toBe(false);
+ });
+});
+
+describe('AcceptanceReviewModel.addMark failures', () => {
+ it('surfaces a write failure instead of reporting a saved mark', async () => {
+ const review = await draftOf(reviewer);
+
+ await expect(
+ model.addMark(review.id, { ...markInput('broken'), content: null as unknown as string }),
+ ).rejects.toThrow();
+ expect(await markIdsOf(review.id)).toEqual([]);
+ // The transaction rolled back, so the numbering the caller sees is unchanged.
+ expect((await model.findById(review.id))?.lastMarkSeq).toBe(0);
+ });
+});
+
+describe('AcceptanceReviewModel reply linkage', () => {
+ it('keeps replies of one acceptance apart from another', async () => {
+ const review = await draftOf(reviewer);
+ const mark = await model.addMark(review.id, markInput('a'));
+ await model.addReply(acceptanceId, mark!.id, {
+ authorUserId: reviewer,
+ clientId: 'only',
+ content: 'Only',
+ });
+ const [other] = await serverDB
+ .insert(acceptances)
+ .values({ subjectId: randomUUID(), subjectType: 'standalone', userId: owner })
+ .returning();
+
+ expect(await model.listReplyIds(other.id)).toEqual(new Set());
+ expect(
+ await serverDB
+ .select({ id: acceptanceComments.id })
+ .from(acceptanceComments)
+ .where(
+ and(
+ eq(acceptanceComments.acceptanceId, acceptanceId),
+ eq(acceptanceComments.reviewMarkId, mark!.id),
+ ),
+ ),
+ ).toHaveLength(1);
+ });
+});
diff --git a/packages/database/src/models/__tests__/connector.coverage.test.ts b/packages/database/src/models/__tests__/connector.coverage.test.ts
index 1304075e804..02918513527 100644
--- a/packages/database/src/models/__tests__/connector.coverage.test.ts
+++ b/packages/database/src/models/__tests__/connector.coverage.test.ts
@@ -6,6 +6,7 @@ import { getTestDB } from '../../core/getTestDB';
import { agentEvalDatasets, agents, userConnectors, users } from '../../schemas';
import type { LobeChatDatabase } from '../../type';
import { ConnectorModel } from '../connector';
+import { ConnectorLinkModel } from '../connectorLink';
const serverDB: LobeChatDatabase = await getTestDB();
@@ -285,3 +286,119 @@ describe('ConnectorModel coverage edges', () => {
});
});
});
+
+describe('ConnectorModel remaining edges', () => {
+ beforeEach(async () => {
+ await cleanup();
+ await serverDB.insert(users).values({ id: userId });
+ await serverDB.insert(agents).values({ id: agentId, userId });
+ });
+
+ afterEach(async () => {
+ await cleanup();
+ });
+
+ it('exposes the account model of the same scope', () => {
+ const model = new ConnectorModel(serverDB, userId);
+
+ expect(model.getLinkModel()).toBeInstanceOf(ConnectorLinkModel);
+ });
+
+ it('resolves inside an evaluation Dataset scope', async () => {
+ const [dataset] = await serverDB
+ .insert(agentEvalDatasets)
+ .values({ identifier: 'conncov-dataset', name: 'Dataset', userId })
+ .returning();
+ const evalModel = ConnectorModel.forEvaluation(serverDB, userId, dataset.id);
+ const row = await insertBaseRow({
+ identifier: 'gmail',
+ metadata: { agentEval: { datasetId: dataset.id } },
+ });
+
+ expect((await evalModel.queryByIdentifiers(['gmail'])).map((r) => r.id)).toEqual([row.id]);
+ expect((await evalModel.resolveByIdentifiers(['gmail'])).map((r) => r.id)).toEqual([row.id]);
+ expect((await evalModel.resolveAll()).map((r) => r.id)).toEqual([row.id]);
+ expect((await evalModel.queryAvailableForAgent(agentId)).map((r) => r.id)).toEqual([row.id]);
+ });
+
+ it('finds the row a write should update, and nothing for an unknown identifier', async () => {
+ const model = new ConnectorModel(serverDB, userId);
+ const row = await model.create({ ...base, identifier: 'gmail' });
+
+ expect(await model.findManageableByIdentifier('gmail')).toMatchObject({ id: row.id });
+ expect(await model.findManageableByIdentifier('not-there')).toBeNull();
+ });
+
+ it('finds an Agent-bound row a write should update', async () => {
+ const model = new ConnectorModel(serverDB, userId);
+ const [row] = await serverDB
+ .insert(userConnectors)
+ .values({ ...base, agentId, identifier: 'gmail', userId })
+ .returning();
+
+ expect(await model.findManageableByIdentifier('gmail', agentId)).toMatchObject({ id: row.id });
+ });
+
+ it('scopes Composio account holders to the caller outside a workspace', async () => {
+ const model = new ConnectorModel(serverDB, userId);
+ const row = await insertBaseRow({ identifier: 'gmail', metadata: { composio } });
+
+ expect((await model.queryComposioAccountHolders('ca-1')).map((r) => r.id)).toEqual([row.id]);
+ });
+
+ it('picks no legacy mirrors from an empty projection', async () => {
+ const model = new ConnectorModel(serverDB, userId);
+
+ expect(await model.pickLegacyComposioMirrors([])).toEqual([]);
+ });
+
+ it('ends OAuth accounts on a server change read without a vault', async () => {
+ const [row] = await serverDB
+ .insert(userConnectors)
+ .values({
+ ...base,
+ credentials: `enc:${JSON.stringify({ accessToken: 't', type: 'oauth2' })}`,
+ identifier: 'gmail',
+ mcpServerUrl: 'https://a.example',
+ userId,
+ })
+ .returning();
+ // No vault: the stored value is read as it is, and still recognised as OAuth.
+ const plain = new ConnectorModel(serverDB, userId);
+
+ expect(await plain.update(row.id, { mcpServerUrl: 'https://b.example' })).toBe(true);
+ const [after] = await serverDB
+ .select({ credentials: userConnectors.credentials })
+ .from(userConnectors)
+ .where(eq(userConnectors.id, row.id));
+ expect(after.credentials).not.toBeNull();
+ });
+
+ it('keeps credentials it cannot decrypt instead of assuming nothing is stored', async () => {
+ const [row] = await serverDB
+ .insert(userConnectors)
+ .values({
+ ...base,
+ credentials: 'enc:{"accessToken":"t","type":"oauth2"}',
+ identifier: 'gmail',
+ mcpServerUrl: 'https://a.example',
+ userId,
+ })
+ .returning();
+ const brokenVault = {
+ decrypt: async () => {
+ throw new Error('vault unavailable');
+ },
+ encrypt: async (value: string) => `enc:${value}`,
+ };
+ const guarded = new ConnectorModel(serverDB, userId, undefined, brokenVault as never);
+
+ expect(await guarded.update(row.id, { mcpServerUrl: 'https://c.example' })).toBe(true);
+ const [after] = await serverDB
+ .select({ credentials: userConnectors.credentials })
+ .from(userConnectors)
+ .where(eq(userConnectors.id, row.id));
+ // Unreadable counts as OAuth: the new server could not use it anyway.
+ expect(after.credentials).toBeNull();
+ });
+});
diff --git a/packages/database/src/models/__tests__/connectorAgentScope.test.ts b/packages/database/src/models/__tests__/connectorAgentScope.test.ts
index 55363b7d180..33c4a0372b2 100644
--- a/packages/database/src/models/__tests__/connectorAgentScope.test.ts
+++ b/packages/database/src/models/__tests__/connectorAgentScope.test.ts
@@ -9,6 +9,7 @@ import {
rehomeAgentConnectorsForScopeTransfer,
} from '../../utils/agentConnectors';
import { ConnectorModel } from '../connector';
+import { connectorAgentConfigScope } from '../connectorScope';
const serverDB: LobeChatDatabase = await getTestDB();
@@ -494,3 +495,47 @@ describe('ConnectorModel.queryAllAgentScoped', () => {
expect(rows.map((r) => r.id)).toEqual([wsOwned.id]);
});
});
+
+describe('connectorAgentConfigScope', () => {
+ it('keeps a personal Agent to the caller own rows outside a workspace', async () => {
+ const mine = await insertConnector({ agentId: agentA, identifier: 'gmail', name: 'Mine' });
+ await insertConnector({ identifier: 'slack', name: 'Theirs', userId: otherUserId });
+
+ const rows = await serverDB
+ .select({ id: userConnectors.id })
+ .from(userConnectors)
+ .where(connectorAgentConfigScope(serverDB, { userId }, agentA));
+
+ expect(rows.map((row) => row.id)).toEqual([mine.id]);
+ });
+
+ it('keeps another member private row out of a workspace Agent config', async () => {
+ const shared = await insertConnector({
+ agentId: agentA,
+ identifier: 'gmail',
+ name: 'Shared',
+ workspaceId,
+ });
+ const [privateRow] = await serverDB
+ .insert(userConnectors)
+ .values({
+ agentId: agentB,
+ identifier: 'slack',
+ name: 'Private',
+ sourceType: 'custom',
+ status: 'connected',
+ userId: otherUserId,
+ visibility: 'private',
+ workspaceId,
+ })
+ .returning();
+
+ const rows = await serverDB
+ .select({ id: userConnectors.id })
+ .from(userConnectors)
+ .where(connectorAgentConfigScope(serverDB, { userId, workspaceId }, agentA));
+
+ expect(rows.map((row) => row.id)).toEqual([shared.id]);
+ expect(rows.map((row) => row.id)).not.toContain(privateRow.id);
+ });
+});
diff --git a/packages/database/src/models/__tests__/connectorLink.test.ts b/packages/database/src/models/__tests__/connectorLink.test.ts
index 7166687c88d..9dac26c7e48 100644
--- a/packages/database/src/models/__tests__/connectorLink.test.ts
+++ b/packages/database/src/models/__tests__/connectorLink.test.ts
@@ -409,3 +409,112 @@ describe('ConnectorLinkModel', () => {
});
});
});
+
+describe('ConnectorLinkModel edge cases', () => {
+ it('keeps allocating past a name that is taken twice', () => {
+ expect(allocateLinkName(['x', 'x (2)'], 'x')).toBe('x (3)');
+ });
+
+ it('reads a live legacy token as a connected account', async () => {
+ const row = await create({ credentials: JSON.stringify(credentials) });
+
+ const [legacy] = await links.listByConnectorIds([row.id]);
+
+ expect(legacy).toMatchObject({ id: LEGACY_LINK_ID, status: 'connected' });
+ });
+
+ it('lists nothing when asked about no connector', async () => {
+ expect(await links.listByConnectorIds([])).toEqual([]);
+ });
+
+ it('returns accounts of several connectors in the order the connectors were asked about', async () => {
+ const first = await create();
+ await save(first.id, 'issuer/first');
+ const second = await create();
+ await save(second.id, 'issuer/second');
+
+ const accounts = await links.listByConnectorIds([second.id, first.id]);
+
+ expect(accounts.map((account) => account.userConnectorId)).toEqual([second.id, first.id]);
+ expect(accounts.map((account) => account.credentials.accessToken)).toEqual([
+ 'alice-token',
+ 'alice-token',
+ ]);
+ });
+
+ it('updates the status of one account and ignores a status it already has', async () => {
+ const row = await create();
+ const { linkId } = await save(row.id, 'issuer/alice');
+
+ await links.updateStatus(row.id, linkId, 'error');
+ expect((await links.findById(row.id, linkId))?.status).toBe('error');
+
+ await links.updateStatus(row.id, linkId, 'error');
+ expect((await links.findById(row.id, linkId))?.status).toBe('error');
+ });
+
+ it('leaves the other accounts untouched when one changes status', async () => {
+ const row = await create();
+ const { linkId } = await save(row.id, 'issuer/alice');
+ const other = await save(row.id, 'issuer/bob');
+
+ await links.updateStatus(row.id, linkId, 'error');
+
+ const accounts = await links.listByConnectorIds([row.id]);
+ expect(accounts.find((a) => a.id === linkId)?.status).toBe('error');
+ expect(accounts.find((a) => a.id === other.linkId)?.status).toBe('connected');
+ });
+
+ it('leaves the accounts alone when refreshing one that no longer exists', async () => {
+ const row = await create();
+ await save(row.id, 'issuer/alice');
+
+ await links.updateCredentials(row.id, 'lnk_missing', {
+ type: 'oauth2',
+ accessToken: 'nobody',
+ });
+
+ const accounts = await links.listByConnectorIds([row.id]);
+ expect(accounts.map((account) => account.credentials.accessToken)).toEqual(['alice-token']);
+ });
+
+ it('reads credentials written without a vault, and reads unreadable ones as none', async () => {
+ const plainLinks = new ConnectorLinkModel(db, 'alice');
+ const row = await create();
+ await save(row.id, 'issuer/alice');
+ // A vault-less instance cannot read vault ciphertext, and reads it as no account.
+ expect(await plainLinks.listByConnectorIds([row.id])).toEqual([]);
+
+ const [broken] = await db
+ .update(userConnectors)
+ .set({ credentials: 'not-json' })
+ .where(eq(userConnectors.id, row.id))
+ .returning({ id: userConnectors.id });
+ expect(await plainLinks.listByConnectorIds([broken.id])).toEqual([]);
+ // A change never overwrites credentials it could not read.
+ await expect(plainLinks.updateStatus(broken.id, LEGACY_LINK_ID, 'error')).rejects.toThrow();
+ });
+
+ it('stores accounts in the clear for an instance without a vault', async () => {
+ const plainLinks = new ConnectorLinkModel(db, 'alice');
+ const row = await create();
+
+ await plainLinks.applyAuthorization(row.id, {
+ authorizerId: 'alice',
+ credentials,
+ target: { kind: 'new' },
+ });
+
+ expect(JSON.parse((await storedPlaintext(row.id))!)).toMatchObject({ type: 'oauth2' });
+ });
+
+ it('leaves the authorizer name empty when the account has none', async () => {
+ await db.update(users).set({ fullName: null, username: null }).where(eq(users.id, 'alice'));
+ const row = await create();
+ await save(row.id, 'issuer/alice');
+
+ const [account] = await links.listByConnectorIds([row.id]);
+
+ expect(account.authorizedByName).toBeNull();
+ });
+});
diff --git a/packages/database/src/models/__tests__/contact.test.ts b/packages/database/src/models/__tests__/contact.test.ts
index 1876fe74459..ab33ae97d25 100644
--- a/packages/database/src/models/__tests__/contact.test.ts
+++ b/packages/database/src/models/__tests__/contact.test.ts
@@ -292,3 +292,89 @@ describe('search', () => {
expect(added).toMatchObject({ relation: 'contact' });
});
});
+
+describe('contact edge cases', () => {
+ it('treats a bare @ as no handle at all', () => {
+ expect(parseContactHandle('@')).toBeUndefined();
+ });
+
+ it('reports a person already in the address book as a contact', async () => {
+ const { requestId } = await aliceModel.sendRequest(bob);
+ await bobModel.acceptRequest(requestId);
+
+ expect(await aliceModel.relationTo(bob)).toBe('contact');
+ });
+
+ it('lists a request in both directions', async () => {
+ await aliceModel.sendRequest(bob);
+
+ const [outgoing] = await aliceModel.listRequests();
+ expect(outgoing).toMatchObject({ direction: 'outgoing', user: { id: bob } });
+
+ const [incoming] = await bobModel.listRequests();
+ expect(incoming).toMatchObject({ direction: 'incoming', user: { id: alice } });
+ });
+
+ it('declines a pending request without creating a contact', async () => {
+ const { requestId } = await aliceModel.sendRequest(bob);
+
+ await bobModel.declineRequest(requestId);
+
+ expect(await aliceModel.list()).toEqual([]);
+ expect(await aliceModel.relationTo(bob)).toBe('none');
+ const [row] = await serverDB
+ .select({ status: userContactRequests.status })
+ .from(userContactRequests)
+ .where(eq(userContactRequests.id, requestId));
+ expect(row.status).toBe('declined');
+ });
+
+ it('rejects a request to somebody who does not exist', async () => {
+ await expect(aliceModel.sendRequest('contact-test-missing')).rejects.toThrow('User not found');
+ });
+
+ it('rejects a request id that is not a uuid', async () => {
+ await expect(aliceModel.cancelRequest('not-a-uuid')).rejects.toThrow('Request not found');
+ await expect(bobModel.acceptRequest('not-a-uuid')).rejects.toThrow('Request not found');
+ await expect(bobModel.declineRequest('not-a-uuid')).rejects.toThrow('Request not found');
+ });
+
+ it('refuses to add an Agent when the handle names nothing', async () => {
+ await expect(aliceModel.addAgent('@')).rejects.toThrow('Agent not found');
+ expect(await aliceModel.search('@')).toEqual([]);
+ });
+
+ it('removes a shared Agent from the address book', async () => {
+ await aliceModel.addAgent('bob-helper');
+
+ await aliceModel.removeAgent(bobAgent);
+
+ expect(await aliceModel.list()).toEqual([]);
+ expect(await aliceModel.findAgentAccess(bobAgent)).toBeUndefined();
+ });
+
+ it('reports an Agent that has no title as having none', async () => {
+ await serverDB.insert(agents).values({ id: 'agt_contact_untitled', userId: bob });
+ await serverDB.insert(agentShares).values({
+ agentId: 'agt_contact_untitled',
+ shareConfig: { monthlySpendLimit: 1, slug: 'untitled-helper' },
+ visibility: 'link',
+ });
+
+ const [found] = await aliceModel.search('untitled-helper');
+
+ expect(found.type).toBe('agent');
+ expect(found.agent?.title).toBeNull();
+ });
+
+ it('marks your own Agent share as your own', async () => {
+ await serverDB
+ .update(agentShares)
+ .set({ shareConfig: { monthlySpendLimit: 1, slug: 'alice-helper' } })
+ .where(eq(agentShares.agentId, aliceAgent));
+
+ const [own] = await aliceModel.search('alice-helper');
+
+ expect(own).toMatchObject({ agent: { agentId: aliceAgent }, relation: 'self', type: 'agent' });
+ });
+});
diff --git a/packages/database/src/models/__tests__/generation.music.test.ts b/packages/database/src/models/__tests__/generation.music.test.ts
index 28673306ce4..dcefc8c9fe9 100644
--- a/packages/database/src/models/__tests__/generation.music.test.ts
+++ b/packages/database/src/models/__tests__/generation.music.test.ts
@@ -172,4 +172,25 @@ describe('GenerationModel with music assets', () => {
expect((result.asset as any).coverUrl).toBeUndefined();
expect(mockGetFullFileUrl).not.toHaveBeenCalled();
});
+
+ it('resolves a song that has no stored file yet by its asset url', async () => {
+ const result = await generationModel.transformGeneration({
+ asset: { ...musicAsset } as any,
+ asyncTaskId: null,
+ createdAt: new Date(),
+ fileId: null,
+ id: 'gen-3',
+ seed: null,
+ } as any);
+
+ // No `files` row yet: the access url is asked without a fileId, and the
+ // cover is still resolved from the asset key.
+ expect(mockGetFileAccessUrl).toHaveBeenCalledWith({
+ fileId: undefined,
+ url: 'generations/music/song_audio.mp3',
+ });
+ expect((result.asset as any).coverUrl).toBe(
+ 'https://s3.example.com/generations/music/song_cover.jpg',
+ );
+ });
});
diff --git a/packages/database/src/models/__tests__/goalMark.test.ts b/packages/database/src/models/__tests__/goalMark.test.ts
new file mode 100644
index 00000000000..ce145d7e3bd
--- /dev/null
+++ b/packages/database/src/models/__tests__/goalMark.test.ts
@@ -0,0 +1,155 @@
+// @vitest-environment node
+import { eq } from 'drizzle-orm';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+
+import { getTestDB } from '../../core/getTestDB';
+import { agents, goalNodes, goals, tasks, taskTopics, users } from '../../schemas';
+import type { LobeChatDatabase } from '../../type';
+import { GoalMarkModel } from '../goalMark';
+
+const serverDB: LobeChatDatabase = await getTestDB();
+
+const userId = 'goal-mark-user';
+const otherUserId = 'goal-mark-other-user';
+const agentId = 'goal-mark-agent';
+
+const model = new GoalMarkModel(serverDB, userId);
+const otherModel = new GoalMarkModel(serverDB, otherUserId);
+
+let seq = 0;
+
+const seedRun = async (options: {
+ assigneeAgentId?: string | null;
+ kind?: 'pattern' | 'task';
+ operationId: string;
+ owner?: string;
+ taskId: string;
+}) => {
+ const owner = options.owner ?? userId;
+ seq += 1;
+
+ const [goal] = await serverDB
+ .insert(goals)
+ .values({ title: `Goal ${options.taskId}`, userId: owner })
+ .returning();
+ const [task] = await serverDB
+ .insert(tasks)
+ .values({
+ assigneeAgentId: options.assigneeAgentId ?? null,
+ createdByUserId: owner,
+ id: options.taskId,
+ identifier: `GM-${seq}`,
+ instruction: 'Run the task',
+ seq,
+ })
+ .returning();
+ const [node] = await serverDB
+ .insert(goalNodes)
+ .values({
+ goalId: goal.id,
+ kind: options.kind ?? 'task',
+ taskId: task.id,
+ title: `Node ${options.taskId}`,
+ })
+ .returning();
+ await serverDB.insert(taskTopics).values({
+ operationId: options.operationId,
+ seq: 1,
+ taskId: task.id,
+ userId: owner,
+ });
+
+ return { goalId: goal.id, nodeId: node.id, taskId: task.id };
+};
+
+const confidenceOf = async (nodeId: string) => {
+ const [row] = await serverDB
+ .select({ confidence: goalNodes.confidence })
+ .from(goalNodes)
+ .where(eq(goalNodes.id, nodeId));
+ return row?.confidence;
+};
+
+beforeEach(async () => {
+ seq = 0;
+ await serverDB.delete(users);
+ await serverDB.insert(users).values([{ id: userId }, { id: otherUserId }]);
+ await serverDB.insert(agents).values({ id: agentId, userId });
+});
+
+afterEach(async () => {
+ await serverDB.delete(users);
+});
+
+describe('GoalMarkModel.findRunNode', () => {
+ it('resolves the Task node a run works for, with the agent it marks as', async () => {
+ const seeded = await seedRun({
+ assigneeAgentId: agentId,
+ operationId: 'op-owned',
+ taskId: 'goal-mark-task-1',
+ });
+
+ expect(await model.findRunNode('op-owned')).toEqual({
+ agentId,
+ goalId: seeded.goalId,
+ nodeId: seeded.nodeId,
+ taskId: seeded.taskId,
+ });
+ });
+
+ it('omits the agent when the Task has no assignee', async () => {
+ const seeded = await seedRun({ operationId: 'op-agentless', taskId: 'goal-mark-task-2' });
+
+ expect(await model.findRunNode('op-agentless')).toEqual({
+ agentId: undefined,
+ goalId: seeded.goalId,
+ nodeId: seeded.nodeId,
+ taskId: seeded.taskId,
+ });
+ });
+
+ it('returns undefined for a run nobody owns the Goal of', async () => {
+ await seedRun({ operationId: 'op-someone-else', taskId: 'goal-mark-task-3' });
+
+ expect(await otherModel.findRunNode('op-someone-else')).toBeUndefined();
+ });
+
+ it('returns undefined for a run whose Task is not bound to a Goal node', async () => {
+ await seedRun({ operationId: 'op-bound', taskId: 'goal-mark-task-4' });
+
+ expect(await model.findRunNode('op-unbound')).toBeUndefined();
+ });
+});
+
+describe('GoalMarkModel.setConfidence', () => {
+ it('stores the confidence on a mark node', async () => {
+ const seeded = await seedRun({
+ kind: 'pattern',
+ operationId: 'op-pattern',
+ taskId: 'goal-mark-task-5',
+ });
+
+ expect(await model.setConfidence(seeded.goalId, seeded.nodeId, 0.75)).toEqual({
+ id: seeded.nodeId,
+ });
+ expect(await confidenceOf(seeded.nodeId)).toBe('0.750');
+ });
+
+ it('leaves an ordinary task node alone', async () => {
+ const seeded = await seedRun({ operationId: 'op-task', taskId: 'goal-mark-task-6' });
+
+ expect(await model.setConfidence(seeded.goalId, seeded.nodeId, 0.5)).toBeUndefined();
+ expect(await confidenceOf(seeded.nodeId)).toBeNull();
+ });
+
+ it('returns undefined for a Goal the caller does not own', async () => {
+ const seeded = await seedRun({
+ kind: 'pattern',
+ operationId: 'op-foreign',
+ taskId: 'goal-mark-task-7',
+ });
+
+ expect(await otherModel.setConfidence(seeded.goalId, seeded.nodeId, 0.9)).toBeUndefined();
+ expect(await confidenceOf(seeded.nodeId)).toBeNull();
+ });
+});
diff --git a/packages/database/src/models/__tests__/inboundWebhook.test.ts b/packages/database/src/models/__tests__/inboundWebhook.test.ts
index 9e8bf0fe9f3..7319f49ce91 100644
--- a/packages/database/src/models/__tests__/inboundWebhook.test.ts
+++ b/packages/database/src/models/__tests__/inboundWebhook.test.ts
@@ -207,6 +207,7 @@ describe('InboundWebhookModel scope and lifecycle', () => {
expect(await model.query({ topicId: 'missing-topic' })).toEqual([]);
expect(await model.query({ agentId: 'missing-agent' })).toEqual([]);
expect(await model.query({ connectorId: missing })).toEqual([]);
+ expect(await model.query({ kind: 'generic' })).toEqual([]);
expect(await model.query({ includeHidden: true })).toHaveLength(4);
});
@@ -413,6 +414,33 @@ describe('InboundWebhookModel maintenance and quotas', () => {
).toMatchObject({ status: 'active', state: { remoteSubscriptionId: 'manual' } });
});
+ it('applies a status-guarded patch that carries no state at all', async () => {
+ const row = await model.create(input({ status: 'active' }));
+
+ expect(
+ await model.updateIfStatus(row.id, { lastError: 'timeout', status: 'error' }, ['active']),
+ ).toMatchObject({ lastError: 'timeout', status: 'error', state: {} });
+ });
+
+ it('pushes still-due rows past the sweep without touching ones rescheduled since', async () => {
+ const due = new Date(Date.now() - 1000);
+ const rescheduled = new Date(Date.now() + 60_000);
+ const dueRow = await model.create(input({ nextMaintenanceAt: due, status: 'active' }));
+ const laterRow = await model.create(
+ input({ nextMaintenanceAt: rescheduled, status: 'active' }),
+ );
+ const doneRow = await model.create(input({ nextMaintenanceAt: due, status: 'terminated' }));
+ const until = new Date(Date.now() + 3_600_000);
+
+ await InboundWebhookModel.deferMaintenance(db, [], until);
+ expect((await model.findById(dueRow.id))?.nextMaintenanceAt).toEqual(due);
+
+ await InboundWebhookModel.deferMaintenance(db, [dueRow.id, laterRow.id, doneRow.id], until);
+ expect((await model.findById(dueRow.id))?.nextMaintenanceAt).toEqual(until);
+ expect((await model.findById(laterRow.id))?.nextMaintenanceAt).toEqual(rescheduled);
+ expect((await model.findById(doneRow.id))?.nextMaintenanceAt).toEqual(due);
+ });
+
it('applies topic and user limits, including subscriptions being created or deleted', async () => {
await model.createWithLimits(input({ status: 'deleting' }), { topic: 1, user: 2 });
await expect(model.createWithLimits(input(), { topic: 1, user: 2 })).rejects.toBeInstanceOf(
diff --git a/packages/database/src/models/__tests__/messages/message.backgroundSubAgent.test.ts b/packages/database/src/models/__tests__/messages/message.backgroundSubAgent.test.ts
index a5174723750..d0c3115c99b 100644
--- a/packages/database/src/models/__tests__/messages/message.backgroundSubAgent.test.ts
+++ b/packages/database/src/models/__tests__/messages/message.backgroundSubAgent.test.ts
@@ -194,6 +194,10 @@ describe('MessageModel background sub-agent calls', () => {
expect(await readState('c')).toMatchObject({ deliveredAt: 'when-2' });
});
+ it('releases nothing when given no ids', async () => {
+ expect(await messageModel.releaseCancelSuppressedDelivery([])).toEqual([]);
+ });
+
it('leaves a delivery claim alone', async () => {
await seedCall({ id: 'd', state: { background: true, status: 'completed' } });
await messageModel.claimBackgroundSubAgentDelivery(['d'], 'when-1');
diff --git a/packages/database/src/models/__tests__/user.islandDismissals.test.ts b/packages/database/src/models/__tests__/user.islandDismissals.test.ts
index 8d5db9b1c21..d9c68913542 100644
--- a/packages/database/src/models/__tests__/user.islandDismissals.test.ts
+++ b/packages/database/src/models/__tests__/user.islandDismissals.test.ts
@@ -42,6 +42,20 @@ describe('UserModel island dismissals', () => {
expect(await readPreference()).toMatchObject({ topicGroupMode: 'byTime' });
});
+ it('writes nothing when every key is already dismissed', async () => {
+ await userModel.addIslandDismissals(['goal-decision:d1']);
+ const before = await readPreference();
+
+ expect(await userModel.addIslandDismissals(['goal-decision:d1'])).toEqual(['goal-decision:d1']);
+ expect(await readPreference()).toEqual(before);
+ });
+
+ it('returns an empty list for a user that no longer exists', async () => {
+ const gone = new UserModel(serverDB, 'user-island-dismissals-deleted');
+
+ expect(await gone.addIslandDismissals(['goal-decision:d1'])).toEqual([]);
+ });
+
it('keeps only the newest keys once the cap is reached', async () => {
const full = Array.from({ length: MAX_ISLAND_DISMISSALS }, (_, i) => `k${i}`);
await userModel.addIslandDismissals(full);