🤯 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.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
✅ test(database): 100% coverage for agentEval, agentSignal, chatGroup, linear and scm models (#21781)
Arvin Xu6b4010363821
diff --git a/packages/database/src/models/__tests__/_proxyTestDB.ts b/packages/database/src/models/__tests__/_proxyTestDB.tsnew file mode 100644index 00000000000..7d034eecc24--- /dev/null+++ b/packages/database/src/models/__tests__/_proxyTestDB.ts@@ -0,0 +1,42 @@+import { drizzle as drizzleProxy } from 'drizzle-orm/pg-proxy';+import { Pool } from 'pg';++import * as schema from '../../schemas';+import type { LobeChatDatabase } from '../../type';++/** One raw result in array row mode, as both node-postgres and PGlite return it. */+export interface ArrayQueryResult {+ fields: { name: string }[];+ rows: unknown[][];+}++type RowRewriter = (query: string, result: ArrayQueryResult) => unknown[][];++/**+ * Runs a query on the test database's own driver in array row mode. `getTestDB()` hands back+ * node-postgres (server suite, `TEST_SERVER_DB=1`) or PGlite (client suite), and the two take+ * row mode differently: a query-config object versus a third options argument.+ */+const queryArrayRows = (db: LobeChatDatabase, text: string, values: unknown[]) => {+ const client = (db as unknown as { $client: unknown }).$client;++ return client instanceof Pool+ ? (client.query({ rowMode: 'array', text, values }) as Promise<ArrayQueryResult>)+ : (client as { query: (...args: unknown[]) => Promise<ArrayQueryResult> }).query(text, values, {+ rowMode: 'array',+ });+};++/**+ * A database seam at the driver boundary: every query still runs against the real test+ * database, but the rows come back through the driver's default type parsers (so timestamps+ * arrive as `Date`) and can optionally be rewritten before drizzle maps them.+ */+export const createProxyTestDB = (db: LobeChatDatabase, rewrite?: RowRewriter) =>+ drizzleProxy(+ async (query, params) => {+ const result = await queryArrayRows(db, query, params);+ return { rows: rewrite ? rewrite(query, result) : result.rows };+ },+ { schema },+ ) as unknown as LobeChatDatabase;diff --git a/packages/database/src/models/__tests__/chatGroup.coverage.test.ts b/packages/database/src/models/__tests__/chatGroup.coverage.test.tsnew file mode 100644index 00000000000..32f4f3ab432--- /dev/null+++ b/packages/database/src/models/__tests__/chatGroup.coverage.test.ts@@ -0,0 +1,89 @@+// @vitest-environment node+import { inArray } from 'drizzle-orm';+import { drizzle as drizzleProxy } from 'drizzle-orm/pg-proxy';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import type { LobeChatDatabase } from '@/database/type';++import { getTestDB } from '../../core/getTestDB';+import * as schema from '../../schemas';+import { agents as agentsTable, chatGroups, chatGroupsAgents, users } from '../../schemas';+import { ChatGroupModel } from '../chatGroup';++const userId = 'chat-group-coverage-user';+const otherUserId = 'chat-group-coverage-other';++const serverDB: LobeChatDatabase = await getTestDB();++const chatGroupModel = new ChatGroupModel(serverDB, userId);++beforeEach(async () => {+ await serverDB.insert(users).values([{ id: userId }, { id: otherUserId }]);+});++afterEach(async () => {+ vi.restoreAllMocks();+ // Groups, agents and memberships cascade with their owner.+ await serverDB.delete(users).where(inArray(users.id, [userId, otherUserId]));+});++describe('ChatGroupModel coverage', () => {+ it('skips a member row whose agent did not load', async () => {+ await serverDB.insert(chatGroups).values({ id: 'cg-cov-orphan', title: 'Orphan', userId });+ await serverDB.insert(agentsTable).values({ id: 'cg-cov-kept', title: 'Kept', userId });+ await serverDB+ .insert(chatGroupsAgents)+ .values({ agentId: 'cg-cov-kept', chatGroupId: 'cg-cov-orphan', userId });++ // A junction row can outlive its agent between reads; the relation then loads as null.+ const findMany = serverDB.query.chatGroupsAgents.findMany;+ vi.spyOn(serverDB.query.chatGroupsAgents, 'findMany').mockImplementationOnce(+ (config) =>+ findMany+ .call(serverDB.query.chatGroupsAgents, config)+ .then((rows) => [+ ...rows,+ { ...rows[0], agent: null, agentId: 'cg-cov-gone' },+ ]) as unknown as ReturnType<typeof findMany>,+ );++ const [group] = await chatGroupModel.queryWithMemberDetails();++ expect(group.id).toBe('cg-cov-orphan');+ expect(group.agents.map((agent: { id: string }) => agent.id)).toEqual(['cg-cov-kept']);+ });++ it('treats a legacy member without an order as order 0', async () => {+ await serverDB.insert(chatGroups).values({ id: 'cg-cov-null-order', title: 'Legacy', userId });+ await serverDB.insert(agentsTable).values([+ { id: 'cg-cov-legacy', title: 'Legacy', userId },+ { id: 'cg-cov-new', title: 'New', userId },+ ]);+ await serverDB.insert(chatGroupsAgents).values({+ agentId: 'cg-cov-legacy',+ chatGroupId: 'cg-cov-null-order',+ order: null,+ userId,+ });++ const result = await chatGroupModel.addAgentsToGroup('cg-cov-null-order', ['cg-cov-new']);++ expect(result.added.map((a) => a.order)).toEqual([1]);+ });++ it('short-circuits an empty group list in findOwnedMemberAgentIds without querying', async () => {+ const select = vi.spyOn(serverDB, 'select');++ expect(await chatGroupModel.findOwnedMemberAgentIds([])).toEqual([]);+ expect(select).not.toHaveBeenCalled();+ });++ it('counts 0 blocking groups when the aggregate comes back without a row', async () => {+ const proxyDB = drizzleProxy(async () => ({ rows: [] }), {+ schema,+ }) as unknown as LobeChatDatabase;+ const model = new ChatGroupModel(proxyDB, otherUserId, 'chat-group-coverage-ws');++ expect(await model.countGroupsBlockingAgentDemotion('any-agent', userId)).toBe(0);+ });+});diff --git a/packages/database/src/models/agentEval/__tests__/dataset.coverage.test.ts b/packages/database/src/models/agentEval/__tests__/dataset.coverage.test.tsnew file mode 100644index 00000000000..ccb0bdbf64f--- /dev/null+++ b/packages/database/src/models/agentEval/__tests__/dataset.coverage.test.ts@@ -0,0 +1,41 @@+import { inArray } from 'drizzle-orm';+import { afterEach, beforeEach, describe, expect, it } from 'vitest';++import { getTestDB } from '../../../core/getTestDB';+import { agentEvalBenchmarks, agentEvalDatasets, users } from '../../../schemas';+import { AgentEvalDatasetModel } from '../dataset';++const serverDB = await getTestDB();++const userId = 'dataset-coverage-user';+const datasetModel = new AgentEvalDatasetModel(serverDB, userId);++beforeEach(async () => {+ await serverDB.insert(users).values({ id: userId });+});++afterEach(async () => {+ // Benchmarks and datasets below are user-owned, so they cascade with the user.+ await serverDB.delete(users).where(inArray(users.id, [userId]));+});++describe('AgentEvalDatasetModel coverage', () => {+ it('filters the list by benchmarkId', async () => {+ const [first, second] = await serverDB+ .insert(agentEvalBenchmarks)+ .values([+ { identifier: 'dataset-cov-a', isSystem: false, name: 'A', rubrics: [], userId },+ { identifier: 'dataset-cov-b', isSystem: false, name: 'B', rubrics: [], userId },+ ])+ .returning();+ await serverDB.insert(agentEvalDatasets).values([+ { benchmarkId: first.id, identifier: 'dataset-cov-in-a', name: 'In A', userId },+ { benchmarkId: second.id, identifier: 'dataset-cov-in-b', name: 'In B', userId },+ ]);++ const filtered = await datasetModel.queryList({ benchmarkId: second.id });++ expect(filtered.map((d) => d.identifier)).toEqual(['dataset-cov-in-b']);+ expect(await datasetModel.count({ benchmarkId: second.id })).toBe(1);+ });+});diff --git a/packages/database/src/models/agentEval/__tests__/experiment.coverage.test.ts b/packages/database/src/models/agentEval/__tests__/experiment.coverage.test.tsnew file mode 100644index 00000000000..6df5fdfdf11--- /dev/null+++ b/packages/database/src/models/agentEval/__tests__/experiment.coverage.test.ts@@ -0,0 +1,119 @@+import { inArray } from 'drizzle-orm';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { getTestDB } from '../../../core/getTestDB';+import { agentEvalDatasets, agentEvalExperiments, agentEvalRuns, users } from '../../../schemas';+import { createProxyTestDB } from '../../__tests__/_proxyTestDB';+import { AgentEvalExperimentModel } from '../experiment';++const serverDB = await getTestDB();++const userId = 'experiment-coverage-user';+const otherOwnerId = 'experiment-coverage-other-owner';+const model = new AgentEvalExperimentModel(serverDB, userId);++beforeEach(async () => {+ await serverDB.insert(users).values([{ id: userId }, { id: otherOwnerId }]);+});++afterEach(async () => {+ vi.restoreAllMocks();+ // Experiments, datasets and runs here are all user-owned and cascade with the user.+ await serverDB.delete(users).where(inArray(users.id, [userId, otherOwnerId]));+});++describe('AgentEvalExperimentModel coverage', () => {+ describe('create race', () => {+ /**+ * The concurrent create commits first and ours fails on the primary key. The stand-in throws+ * the driver's error shape (`code` on the error itself) — see the PR "Findings" for why the+ * drizzle-wrapped shape never reaches this branch today.+ */+ it('returns the winner of a create race that surfaces as a unique violation', async () => {+ const id = 'experiment-cov-race-winner';+ vi.spyOn(serverDB, 'transaction').mockImplementationOnce(async () => {+ await serverDB.insert(agentEvalExperiments).values({ id, name: 'winner', userId });+ throw Object.assign(new Error('duplicate key value'), { code: '23505' });+ });++ const created = await model.create({ benchmarkIds: [], id, name: 'loser' });++ expect(created.id).toBe(id);+ expect(created.name).toBe('winner');+ });++ it('rethrows a unique violation whose winner is not visible to the caller', async () => {+ const id = 'experiment-cov-race-hidden';+ const violation = Object.assign(new Error('duplicate key value'), { code: '23505' });+ vi.spyOn(serverDB, 'transaction').mockImplementationOnce(async () => {+ await serverDB+ .insert(agentEvalExperiments)+ .values({ id, name: 'hidden', userId: otherOwnerId });+ throw violation;+ });++ await expect(model.create({ benchmarkIds: [], id, name: 'mine' })).rejects.toBe(violation);+ });+ });++ it('findById skips the dataset lookup for an experiment without benchmarks', async () => {+ const experiment = await model.create({ benchmarkIds: [], name: 'Bare detail' });++ const detail = await model.findById(experiment.id);++ expect(detail?.benchmarks).toEqual([]);+ expect(detail?.datasets).toEqual([]);+ expect(detail?.runs).toEqual([]);+ });++ it('lists a recent run from a dataset outside any benchmark without a benchmark id', async () => {+ const experiment = await model.create({ benchmarkIds: [], name: 'Captured cases' });+ const [dataset] = await serverDB+ .insert(agentEvalDatasets)+ .values({ identifier: 'experiment-cov-captured', name: 'Captured', userId })+ .returning();+ await serverDB+ .insert(agentEvalRuns)+ .values({ datasetId: dataset.id, experimentId: experiment.id, userId });++ const [item] = await model.query();++ expect(item.recentRuns).toEqual([+ expect.objectContaining({ benchmarkId: undefined, datasetName: 'Captured' }),+ ]);+ });++ it('drops a ranked run that comes back without an experiment id', async () => {+ const experiment = await model.create({ benchmarkIds: [], name: 'Detached mid-read' });+ const [dataset] = await serverDB+ .insert(agentEvalDatasets)+ .values({ identifier: 'experiment-cov-detached', name: 'Detached', userId })+ .returning();+ const [kept, detached] = await serverDB+ .insert(agentEvalRuns)+ .values([+ { datasetId: dataset.id, experimentId: experiment.id, name: 'kept', userId },+ { datasetId: dataset.id, experimentId: experiment.id, name: 'detached', userId },+ ])+ .returning();++ // The ranked-runs read sees one run whose experiment link was cleared concurrently+ // (runs detach with `experiment_id = NULL` when an experiment is deleted).+ const proxyDB = createProxyTestDB(serverDB, (query, { fields, rows }) => {+ if (!query.includes('"ranked_runs"')) return rows;++ const idIndex = fields.findIndex((field) => field.name === 'id');+ const experimentIndex = fields.findIndex((field) => field.name === 'experiment_id');+ return rows.map((row) =>+ row[idIndex] === detached.id+ ? row.map((value, index) => (index === experimentIndex ? null : value))+ : row,+ );+ });++ const [item] = await new AgentEvalExperimentModel(proxyDB, userId).query();++ expect(item.id).toBe(experiment.id);+ expect(item.recentRuns?.map((run) => run.id)).toEqual([kept.id]);+ });+});diff --git a/packages/database/src/models/agentSignal/__tests__/nightlyReview.coverage.test.ts b/packages/database/src/models/agentSignal/__tests__/nightlyReview.coverage.test.tsnew file mode 100644index 00000000000..79f85cbdf8d--- /dev/null+++ b/packages/database/src/models/agentSignal/__tests__/nightlyReview.coverage.test.ts@@ -0,0 +1,59 @@+// @vitest-environment node+import { inArray } from 'drizzle-orm';+import { afterEach, describe, expect, it } from 'vitest';++import { getTestDB } from '../../../core/getTestDB';+import { agents, messages, topics, users } from '../../../schemas';+import type { LobeChatDatabase } from '../../../type';+import { createProxyTestDB } from '../../__tests__/_proxyTestDB';+import { AgentSignalNightlyReviewModel } from '../nightlyReview';++const serverDB: LobeChatDatabase = await getTestDB();++const userId = 'nightly-review-coverage-user';+const agentId = 'nightly-review-coverage-agent';+const topicId = 'nightly-review-coverage-topic';++afterEach(async () => {+ // Agents, topics and messages cascade with their owner.+ await serverDB.delete(users).where(inArray(users.id, [userId]));+});++describe('AgentSignalNightlyReviewModel coverage', () => {+ /**+ * node-postgres in this repo hands `MIN`/`MAX` of a timestamptz back as a string, but a driver+ * keeping pg's default parsers returns a `Date`; both must come out as the same instant.+ */+ it('keeps activity timestamps a driver already parsed into Date objects', async () => {+ await serverDB+ .insert(users)+ .values({ id: userId, preference: { lab: { enableSelfLearning: true } } });+ await serverDB.insert(agents).values({ id: agentId, title: 'Custom', userId });+ await serverDB.insert(topics).values({ agentId, id: topicId, title: 'Custom', userId });+ await serverDB.insert(messages).values({+ agentId,+ content: 'activity',+ createdAt: new Date('2026-05-03T14:00:00.000Z'),+ id: 'nightly-review-coverage-message',+ role: 'user',+ topicId,+ userId,+ });++ // Raw driver rows go through its default type parsers, so timestamps arrive as Date.+ const dateParsingDB = createProxyTestDB(serverDB);++ const result = await new AgentSignalNightlyReviewModel(dateParsingDB).listActiveAgentTargets(+ userId,+ {+ agentId,+ windowEnd: new Date('2026-05-03T23:59:59.999Z'),+ windowStart: new Date('2026-05-03T00:00:00.000Z'),+ },+ );++ expect(result).toHaveLength(1);+ expect(result[0].firstActivityAt).toEqual(new Date('2026-05-03T14:00:00.000Z'));+ expect(result[0].lastActivityAt).toEqual(new Date('2026-05-03T14:00:00.000Z'));+ });+});diff --git a/packages/database/src/models/agentSignal/__tests__/reviewContext.coverage.test.ts b/packages/database/src/models/agentSignal/__tests__/reviewContext.coverage.test.tsnew file mode 100644index 00000000000..c82cff30da8--- /dev/null+++ b/packages/database/src/models/agentSignal/__tests__/reviewContext.coverage.test.ts@@ -0,0 +1,62 @@+// @vitest-environment node+import { inArray } from 'drizzle-orm';+import { afterEach, describe, expect, it } from 'vitest';++import { getTestDB } from '../../../core/getTestDB';+import { agents, messagePlugins, messages, topics, users } from '../../../schemas';+import type { LobeChatDatabase } from '../../../type';+import { createProxyTestDB } from '../../__tests__/_proxyTestDB';+import { AgentSignalReviewContextModel } from '../reviewContext';++const serverDB: LobeChatDatabase = await getTestDB();++const userId = 'review-context-coverage-user';+const agentId = 'review-context-coverage-agent';+const topicId = 'review-context-coverage-topic';+const messageId = 'review-context-coverage-tool';++afterEach(async () => {+ // Agents, topics, messages and plugins cascade with their owner.+ await serverDB.delete(users).where(inArray(users.id, [userId]));+});++describe('AgentSignalReviewContextModel coverage', () => {+ /**+ * node-postgres in this repo hands `MIN`/`MAX` of a timestamptz back as a string, but a driver+ * keeping pg's default parsers returns a `Date`; both must come out as the same instant.+ */+ it('keeps usage timestamps a driver already parsed into Date objects', async () => {+ await serverDB.insert(users).values({ id: userId });+ await serverDB.insert(agents).values({ id: agentId, title: 'Review Context Agent', userId });+ await serverDB.insert(topics).values({ agentId, id: topicId, title: 'Date topic', userId });+ await serverDB.insert(messages).values({+ agentId,+ content: 'created document',+ createdAt: new Date('2026-05-03T12:00:00.000Z'),+ id: messageId,+ role: 'assistant',+ topicId,+ userId,+ });+ await serverDB.insert(messagePlugins).values({+ apiName: 'createDocument',+ id: messageId,+ identifier: 'lobe-agent-documents',+ toolCallId: 'review-context-coverage-call',+ userId,+ });++ // Raw driver rows go through its default type parsers, so timestamps arrive as Date.+ const dateParsingDB = createProxyTestDB(serverDB);++ const result = await new AgentSignalReviewContextModel(dateParsingDB, userId).listToolActivity({+ agentId,+ windowEnd: new Date('2026-05-03T23:59:59.999Z'),+ windowStart: new Date('2026-05-03T00:00:00.000Z'),+ });++ expect(result).toHaveLength(1);+ expect(result[0].firstUsedAt).toEqual(new Date('2026-05-03T12:00:00.000Z'));+ expect(result[0].lastUsedAt).toEqual(new Date('2026-05-03T12:00:00.000Z'));+ });+});diff --git a/packages/database/src/models/linear/__tests__/connection.coverage.test.ts b/packages/database/src/models/linear/__tests__/connection.coverage.test.tsnew file mode 100644index 00000000000..38343771575--- /dev/null+++ b/packages/database/src/models/linear/__tests__/connection.coverage.test.ts@@ -0,0 +1,78 @@+// @vitest-environment node+import { inArray } from 'drizzle-orm';+import { afterEach, beforeEach, describe, expect, it } from 'vitest';++import { getTestDB } from '../../../core/getTestDB';+import { linearConnections, users } from '../../../schemas';+import type { LobeChatDatabase } from '../../../type';+import { LinearConnectionModel } from '../connection';++const db: LobeChatDatabase = await getTestDB();++const userId = 'linear-conn-coverage-user';++const organization = {+ actorExternalId: 'linear-cov-actor',+ actorName: 'Ada',+ organizationId: 'linear-cov-org',+ organizationName: 'Acme',+ organizationUrlKey: 'acme-cov',+};++/** Reversible stand-in for KeyVaultsGateKeeper. */+const gateKeeper = {+ decrypt: async (ciphertext: string) => ({ plaintext: ciphertext.replace(/^enc:/, '') }),+ encrypt: async (plaintext: string) => `enc:${plaintext}`,+};++beforeEach(async () => {+ await db.insert(users).values({ id: userId });+});++afterEach(async () => {+ // Connections cascade with their owner.+ await db.delete(users).where(inArray(users.id, [userId]));+});++describe('LinearConnectionModel coverage', () => {+ it('returns null for an unknown connection id', async () => {+ const missingId = '00000000-0000-4000-8000-000000000000';++ expect(await LinearConnectionModel.findById(db, missingId)).toBeNull();+ expect(await LinearConnectionModel.findDecryptedById(db, missingId)).toBeNull();+ });++ it('reads a token stored without a gate keeper as plain JSON', async () => {+ const row = await LinearConnectionModel.upsert(db, {+ ...organization,+ credentials: { accessToken: 'plain' },+ userId,+ });++ expect(row.credentials).toBe('{"accessToken":"plain"}');+ const decrypted = await LinearConnectionModel.findDecryptedById(db, row.id);+ expect(decrypted?.credentials).toEqual({ accessToken: 'plain' });+ });++ it('decrypts a revoked connection to null credentials', async () => {+ const row = await LinearConnectionModel.upsert(+ db,+ { ...organization, credentials: { accessToken: 'a' }, userId },+ gateKeeper,+ );+ await LinearConnectionModel.revoke(db, row.id);++ const decrypted = await LinearConnectionModel.findDecryptedById(db, row.id, gateKeeper);+ expect(decrypted).toMatchObject({ credentials: null, id: row.id });+ });++ it('treats a token that does not parse as JSON as missing', async () => {+ const [row] = await db+ .insert(linearConnections)+ .values({ ...organization, credentials: 'not-json', userId })+ .returning();++ const decrypted = await LinearConnectionModel.findDecryptedById(db, row.id);+ expect(decrypted).toMatchObject({ credentials: null, id: row.id });+ });+});diff --git a/packages/database/src/models/scm/__tests__/changeRequest.coverage.test.ts b/packages/database/src/models/scm/__tests__/changeRequest.coverage.test.tsnew file mode 100644index 00000000000..c3372f67402--- /dev/null+++ b/packages/database/src/models/scm/__tests__/changeRequest.coverage.test.ts@@ -0,0 +1,126 @@+// @vitest-environment node+import { eq, inArray } from 'drizzle-orm';+import { afterEach, beforeEach, describe, expect, it } from 'vitest';++import { getTestDB } from '../../../core/getTestDB';+import { acceptances, users } from '../../../schemas';+import { ScmChangeRequestModel } from '../changeRequest';++const serverDB = await getTestDB();+const userId = 'scm-change-request-coverage-user';++const sha1 = 'a'.repeat(40);++const snapshot = {+ headSha: sha1,+ number: 7,+ provider: 'github' as const,+ repoFullName: 'lobehub-cov/change-request',+ state: 'open' as const,+ url: 'https://github.com/lobehub-cov/change-request/pull/7',+ userId,+};++beforeEach(async () => {+ await serverDB.insert(users).values({ id: userId });+});++afterEach(async () => {+ // Change requests and acceptances cascade with their owner.+ await serverDB.delete(users).where(inArray(users.id, [userId]));+});++describe('ScmChangeRequestModel coverage', () => {+ it('finds a row by a pasted repository name whatever its casing', async () => {+ const row = await ScmChangeRequestModel.upsert(serverDB, {+ ...snapshot,+ repoFullName: 'LobeHub-Cov/Change-Request',+ });++ const found = await ScmChangeRequestModel.findByIdentityIgnoringCase(+ serverDB,+ 'github',+ 'lobehub-cov/CHANGE-REQUEST',+ 7,+ );+ expect(found?.id).toBe(row.id);+ expect(found?.repoFullName).toBe('LobeHub-Cov/Change-Request');++ expect(+ await ScmChangeRequestModel.findByIdentityIgnoringCase(+ serverDB,+ 'github',+ 'lobehub-cov/change-request',+ 8,+ ),+ ).toBeNull();+ });++ it('lets only one acceptance hold the row, and detaches only its own claim', async () => {+ const [first, second] = await serverDB+ .insert(acceptances)+ .values([+ { subjectId: 'scm-cov-first', subjectType: 'standalone', userId },+ { subjectId: 'scm-cov-second', subjectType: 'standalone', userId },+ ])+ .returning();+ const row = await ScmChangeRequestModel.upsert(serverDB, snapshot);++ expect(+ (await ScmChangeRequestModel.claimAcceptance(serverDB, row.id, first.id))?.acceptanceId,+ ).toBe(first.id);+ // Re-claiming is idempotent for the holder; a rival claim is refused.+ expect(+ (await ScmChangeRequestModel.claimAcceptance(serverDB, row.id, first.id))?.acceptanceId,+ ).toBe(first.id);+ expect(await ScmChangeRequestModel.claimAcceptance(serverDB, row.id, second.id)).toBeNull();++ // A rival cannot detach the holder's claim.+ await ScmChangeRequestModel.detachAcceptance(serverDB, row.id, second.id);+ expect((await ScmChangeRequestModel.findById(serverDB, row.id))?.acceptanceId).toBe(first.id);++ await ScmChangeRequestModel.detachAcceptance(serverDB, row.id, first.id);+ expect((await ScmChangeRequestModel.findById(serverDB, row.id))?.acceptanceId).toBeNull();++ // Once released, the rival may claim it.+ expect(+ (await ScmChangeRequestModel.claimAcceptance(serverDB, row.id, second.id))?.acceptanceId,+ ).toBe(second.id);+ });++ it('keeps a hand-linked acceptance the row already carries without re-checking the link', async () => {+ const [linked] = await serverDB+ .insert(acceptances)+ .values({+ metadata: {+ pullRequests: [+ {+ linkedAt: '2026-10-28T00:00:00.000Z',+ number: snapshot.number,+ provider: snapshot.provider,+ repoFullName: snapshot.repoFullName,+ url: snapshot.url,+ },+ ],+ },+ subjectId: 'scm-cov-linked',+ subjectType: 'standalone',+ userId,+ })+ .returning();+ const links = { acceptanceId: linked.id, acceptanceSource: 'hand-link' as const };+ const first = await ScmChangeRequestModel.upsert(serverDB, { ...snapshot, links });+ expect(first.acceptanceId).toBe(linked.id);++ // The hand link is gone by now, but the row already holds this acceptance:+ // re-asserting it is not a new binding, so nothing is re-checked or cleared.+ await serverDB.update(acceptances).set({ metadata: {} }).where(eq(acceptances.id, linked.id));+ const again = await ScmChangeRequestModel.upsert(serverDB, {+ ...snapshot,+ eventKind: 'review_commented',+ links,+ });++ expect(again.acceptanceId).toBe(linked.id);+ });+});diff --git a/packages/database/src/models/scm/changeRequest.ts b/packages/database/src/models/scm/changeRequest.tsindex 78ba626bc70..430d2f87df7 100644--- a/packages/database/src/models/scm/changeRequest.ts+++ b/packages/database/src/models/scm/changeRequest.ts@@ -9,7 +9,7 @@ import type {ScmReviewDecision,ScmUpsertChangeRequestParams,} from '@lobechat/types';-import { and, desc, eq, inArray, isNull, lt, or, type SQL,sql } from 'drizzle-orm';+import { and, desc, eq, inArray, isNull, lt, or, type SQL, sql } from 'drizzle-orm';import type { ScmChangeRequestItem } from '../../schemas';import { acceptances, scmChangeRequests, scmInstallations } from '../../schemas';@@ -488,6 +488,7 @@ export class ScmChangeRequestModel {const adopted = held && held.sha === params.headSha ? held.checks : null;return {checks: adopted,+ /* v8 ignore next -- unreachable: `ciValues` is only built when `headChanged`, which already requires a truthy `params.headSha` */ciHeadSha: params.headSha ?? null,ciStatus: adopted ? rollupCiStatus(adopted) : null,};