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): 100% coverage for models root (acceptance … agentShare) (#21807)

Arvin Xu472028b881d0
diff --git a/packages/database/src/models/__tests__/acceptance.coverage.test.ts b/packages/database/src/models/__tests__/acceptance.coverage.test.ts
new file mode 100644
index 00000000000..76e82d0b075
--- /dev/null
+++ b/packages/database/src/models/__tests__/acceptance.coverage.test.ts
@@ -0,0 +1,76 @@
+// @vitest-environment node
+import { inArray } from 'drizzle-orm';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+
+import { getTestDB } from '../../core/getTestDB';
+import { topics, users } from '../../schemas';
+import type { LobeChatDatabase } from '../../type';
+import { AcceptanceModel } from '../acceptance';
+import { ProjectModel } from '../project';
+
+const serverDB: LobeChatDatabase = await getTestDB();
+
+const userId = 'acceptance-cov-user';
+const topicIds = ['acceptance-cov-topic-1', 'acceptance-cov-topic-2'];
+
+beforeEach(async () => {
+ await serverDB.insert(users).values({ id: userId });
+ await serverDB.insert(topics).values(topicIds.map((id) => ({ id, userId })));
+});
+
+afterEach(async () => {
+ // Acceptances, projects and topics all cascade with their owner.
+ await serverDB.delete(users).where(inArray(users.id, [userId]));
+});
+
+describe('AcceptanceModel coverage', () => {
+ it('keeps the recorded project while a later ensure fills a missing requirement', async () => {
+ const project = await new ProjectModel(serverDB, userId).create({
+ identifier: 'ACOV',
+ name: 'Coverage project',
+ });
+ const model = new AcceptanceModel(serverDB, userId);
+ const created = await model.ensureForSubject('topic', topicIds[0], { projectId: project.id });
+ expect(created.requirement).toBeNull();
+
+ const other = await new ProjectModel(serverDB, userId).create({
+ identifier: 'ACOT',
+ name: 'Other project',
+ });
+ const ensured = await model.ensureForSubject('topic', topicIds[0], {
+ projectId: other.id,
+ requirement: 'Ship the fix',
+ });
+
+ expect(ensured).toMatchObject({ projectId: project.id, requirement: 'Ship the fix' });
+ expect(await model.findById(created.id)).toMatchObject({
+ projectId: project.id,
+ requirement: 'Ship the fix',
+ });
+ });
+
+ it('lists without a row cap when asked for an unbounded query', async () => {
+ const model = new AcceptanceModel(serverDB, userId);
+ await model.ensureForSubject('topic', topicIds[0]);
+ await model.ensureForSubject('topic', topicIds[1]);
+
+ const rows = await model.query({ limit: 1, unbounded: true });
+
+ expect(rows.map((row) => row.subjectId).sort()).toEqual([...topicIds].sort());
+ });
+
+ it('stamps completedAt when the policy status turns terminal', async () => {
+ const model = new AcceptanceModel(serverDB, userId);
+ const acceptance = await model.ensureForSubject('topic', topicIds[0]);
+ expect(acceptance.completedAt).toBeNull();
+
+ await model.updatePolicyStatus(acceptance.id, 'accepted');
+
+ const settled = await model.findById(acceptance.id);
+ expect(settled?.status).toBe('accepted');
+ expect(settled?.completedAt).toBeInstanceOf(Date);
+
+ await model.updatePolicyStatus(acceptance.id, 'pending');
+ expect((await model.findById(acceptance.id))?.completedAt).toBeNull();
+ });
+});
diff --git a/packages/database/src/models/__tests__/acceptanceComment.coverage.test.ts b/packages/database/src/models/__tests__/acceptanceComment.coverage.test.ts
new file mode 100644
index 00000000000..e3e84e8ec91
--- /dev/null
+++ b/packages/database/src/models/__tests__/acceptanceComment.coverage.test.ts
@@ -0,0 +1,119 @@
+// @vitest-environment node
+import { randomUUID } from 'node:crypto';
+
+import { eq, inArray } from 'drizzle-orm';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { getTestDB } from '../../core/getTestDB';
+import { acceptanceComments, acceptances, users } from '../../schemas';
+import type { LobeChatDatabase } from '../../type';
+import { AcceptanceCommentModel } from '../acceptanceComment';
+import { createProxyTestDB } from './_proxyTestDB';
+
+const serverDB: LobeChatDatabase = await getTestDB();
+
+const owner = 'acceptance-comment-cov-owner';
+const reviewer = 'acceptance-comment-cov-reviewer';
+const model = new AcceptanceCommentModel(serverDB);
+
+let acceptanceId: string;
+
+/**
+ * Run the next `transaction` body on a driver-boundary proxy whose result rows can be rewritten,
+ * to reach shapes the real database never hands back (an aggregate with no row, a row that
+ * vanished between two reads). Queries still execute against the real test database.
+ */
+const runNextTransactionThrough = (rewrite: (query: string) => boolean) => {
+ const proxyDB = createProxyTestDB(serverDB, (query, result) =>
+ rewrite(query) ? [] : result.rows,
+ );
+ vi.spyOn(serverDB, 'transaction').mockImplementationOnce(async (body) =>
+ body(proxyDB as unknown as Parameters<typeof body>[0]),
+ );
+};
+
+const isCount = (query: string) => query.includes('count(*)');
+
+const comment = (authorUserId: string, clientId: string, parentCommentId?: string) =>
+ model.create({ acceptanceId, authorUserId, clientId, content: clientId, parentCommentId });
+
+const rowById = async (id: string) =>
+ serverDB.query.acceptanceComments.findFirst({ where: eq(acceptanceComments.id, id) });
+
+beforeEach(async () => {
+ await serverDB.insert(users).values([{ id: owner }, { id: reviewer }]);
+ const [acceptance] = await serverDB
+ .insert(acceptances)
+ .values({ subjectId: randomUUID(), subjectType: 'standalone', userId: owner })
+ .returning();
+ acceptanceId = acceptance.id;
+});
+
+afterEach(async () => {
+ vi.restoreAllMocks();
+ // Acceptances and their comments cascade with the owner.
+ await serverDB.delete(users).where(inArray(users.id, [owner, reviewer]));
+});
+
+describe('AcceptanceCommentModel coverage', () => {
+ describe('create', () => {
+ it('lets the comment through when the rate-limit count yields no row', async () => {
+ runNextTransactionThrough(isCount);
+
+ const { comment: created, isDuplicate } = await model.create({
+ acceptanceId,
+ authorUserId: reviewer,
+ clientId: 'rate-limit-no-row',
+ content: 'hello',
+ rateLimit: { max: 0, since: new Date(Date.now() - 60_000) },
+ });
+
+ expect(isDuplicate).toBe(false);
+ expect(await rowById(created.id)).toMatchObject({ content: 'hello' });
+ });
+ });
+
+ describe('delete', () => {
+ it('lets a moderator remove someone else’s comment', async () => {
+ const { comment: remark } = await comment(reviewer, 'moderated');
+
+ expect(await model.delete(remark.id, { moderator: true })).toBe('hard');
+ expect(await rowById(remark.id)).toBeUndefined();
+ });
+
+ it('keeps a tombstoned root while another reply still holds it up', async () => {
+ const { comment: root } = await comment(owner, 'root');
+ const { comment: first } = await comment(reviewer, 'reply-1', root.id);
+ const { comment: second } = await comment(reviewer, 'reply-2', root.id);
+ expect(await model.delete(root.id, { authorUserId: owner })).toBe('soft');
+
+ expect(await model.delete(first.id, { authorUserId: reviewer })).toBe('hard');
+
+ expect(await rowById(first.id)).toBeUndefined();
+ expect(await rowById(root.id)).toMatchObject({ content: '' });
+ expect((await rowById(root.id))?.deletedAt).toBeInstanceOf(Date);
+ expect(await rowById(second.id)).toMatchObject({ content: 'reply-2' });
+ });
+
+ it('reports nothing removed when the thread root vanishes before it is locked', async () => {
+ const { comment: root } = await comment(owner, 'vanishing-root');
+ runNextTransactionThrough((query) => query.includes('for update'));
+
+ expect(await model.delete(root.id, { authorUserId: owner })).toBe(false);
+ expect(await rowById(root.id)).toMatchObject({ content: 'vanishing-root' });
+ });
+
+ it('treats reply and sibling counts that yield no row as zero', async () => {
+ const { comment: root } = await comment(owner, 'lone-root');
+ const { comment: reply } = await comment(reviewer, 'lone-reply', root.id);
+ // A reply props the root up, so this first delete only tombstones it.
+ expect(await model.delete(root.id, { authorUserId: owner })).toBe('soft');
+ runNextTransactionThrough(isCount);
+
+ expect(await model.delete(reply.id, { authorUserId: reviewer })).toBe('hard');
+
+ expect(await rowById(reply.id)).toBeUndefined();
+ expect(await rowById(root.id)).toBeUndefined();
+ });
+ });
+});
diff --git a/packages/database/src/models/__tests__/acceptanceFlow.coverage.test.ts b/packages/database/src/models/__tests__/acceptanceFlow.coverage.test.ts
new file mode 100644
index 00000000000..639a3d88143
--- /dev/null
+++ b/packages/database/src/models/__tests__/acceptanceFlow.coverage.test.ts
@@ -0,0 +1,525 @@
+// @vitest-environment node
+import { randomUUID } from 'node:crypto';
+
+import type { AcceptanceFlowDefinition, VerifyCheckDefinition } from '@lobechat/types';
+import { eq } from 'drizzle-orm';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { getTestDB } from '../../core/getTestDB';
+import { acceptances, users, verifyCheckResults, verifyCriteria, verifyRuns } from '../../schemas';
+import {
+ acceptanceFlowNodes as nodes,
+ acceptanceFlows as flows,
+} from '../../schemas/acceptanceFlow';
+import type { LobeChatDatabase } from '../../type';
+import { AcceptanceFlowModel } from '../acceptanceFlow';
+import { createProxyTestDB } from './_proxyTestDB';
+
+const db = await getTestDB();
+const owner = 'afcov-owner';
+const model = new AcceptanceFlowModel(db, owner);
+let acceptanceId: string;
+
+beforeEach(async () => {
+ await db.insert(users).values({ id: owner }).onConflictDoNothing();
+ const [acceptance] = await db
+ .insert(acceptances)
+ .values({ userId: owner, subjectType: 'standalone', subjectId: randomUUID() })
+ .returning();
+ acceptanceId = acceptance.id;
+});
+
+afterEach(async () => {
+ vi.restoreAllMocks();
+ await db.delete(users).where(eq(users.id, owner));
+});
+
+const checkNode = (id: string, title: string, definition: VerifyCheckDefinition = {}) => ({
+ id,
+ check: { id: randomUUID(), title, definition },
+});
+
+/** Entry → second, both fresh check assets. */
+const twoStep = (title: string, definition?: VerifyCheckDefinition): AcceptanceFlowDefinition => {
+ const first = randomUUID();
+ const second = randomUUID();
+ return {
+ title,
+ entryNodeId: first,
+ nodes: [
+ checkNode(first, 'First', definition ?? { expected: 'First ok' }),
+ checkNode(second, 'Second', definition ?? { expected: 'Second ok' }),
+ ],
+ edges: [
+ {
+ id: randomUUID(),
+ sourceNodeId: first,
+ targetNodeId: second,
+ trigger: 'Go',
+ required: true,
+ },
+ ],
+ };
+};
+
+const roundById = async (id: string) => {
+ const [run] = await db.select().from(verifyRuns).where(eq(verifyRuns.id, id));
+ return run;
+};
+
+const seedRound = async (values: Partial<typeof verifyRuns.$inferInsert>) => {
+ const [run] = await db
+ .insert(verifyRuns)
+ .values({ acceptanceId, userId: owner, ...values })
+ .returning();
+ return run;
+};
+
+describe('AcceptanceFlowModel coverage · draft refresh', () => {
+ it('skips an open draft that carries no flow snapshots', async () => {
+ const draft = await seedRound({ roundIndex: 1, status: 'planned' });
+
+ const published = await model.publish(acceptanceId, twoStep('Fresh'));
+
+ expect(published.flowId).toBeTruthy();
+ const after = await roundById(draft.id);
+ expect(after.flowSnapshots).toBeNull();
+ expect(after.plan).toBeNull();
+ });
+
+ it('rebuilds a draft whose plan is missing, next to an older round without a plan', async () => {
+ const older = await seedRound({ roundIndex: 1, status: 'delivered' });
+ const definition = twoStep('Original');
+ const { flowId, hash } = await model.publish(acceptanceId, definition);
+ const draft = await model.start(acceptanceId, flowId);
+ expect(draft.id).not.toBe(older.id);
+ expect((await roundById(draft.id)).roundIndex).toBe(2);
+ // The prior round has no plan, so nothing is superseded.
+ expect((await roundById(draft.id)).plan!.every((item) => !item.supersedes)).toBe(true);
+
+ await db.update(verifyRuns).set({ plan: null }).where(eq(verifyRuns.id, draft.id));
+ await model.publish(acceptanceId, { ...definition, title: 'Renamed' }, flowId, hash);
+
+ const refreshed = await roundById(draft.id);
+ expect(refreshed.flowSnapshots?.[0].title).toBe('Renamed');
+ expect(refreshed.plan).toHaveLength(2);
+ expect(refreshed.plan!.map((item) => item.index)).toEqual([0, 1]);
+ expect(refreshed.plan!.every((item) => item.sourceFlowNode?.flowId === flowId)).toBe(true);
+ expect(refreshed.plan!.every((item) => !item.supersedes)).toBe(true);
+ expect((await roundById(older.id)).plan).toBeNull();
+ });
+});
+
+describe('AcceptanceFlowModel coverage · delete and replay with missing plans', () => {
+ it('unplans a draft whose plan column is empty', async () => {
+ const { flowId } = await model.publish(acceptanceId, twoStep('Abandoned'));
+ const draft = await model.start(acceptanceId, flowId);
+ await db.update(verifyRuns).set({ plan: null }).where(eq(verifyRuns.id, draft.id));
+
+ const removed = await model.delete(acceptanceId, flowId);
+
+ expect(removed).toEqual({ flowId, title: 'Abandoned', unplannedRounds: [draft.id] });
+ const round = await roundById(draft.id);
+ expect(round.plan).toEqual([]);
+ expect(round.flowSnapshots).toEqual([]);
+ expect(await db.select().from(flows).where(eq(flows.id, flowId))).toHaveLength(0);
+ });
+
+ it('replays a source round that froze a snapshot but no plan', async () => {
+ const { flowId } = await model.publish(acceptanceId, twoStep('Replayed'));
+ const source = await model.start(acceptanceId, flowId);
+ const snapshot = (await roundById(source.id)).flowSnapshots;
+ await db.update(verifyRuns).set({ plan: null }).where(eq(verifyRuns.id, source.id));
+
+ const replay = await model.start(acceptanceId, flowId, undefined, source.id);
+
+ expect(replay.id).not.toBe(source.id);
+ const round = await roundById(replay.id);
+ expect(round.plan).toEqual([]);
+ expect(round.flowSnapshots).toEqual(snapshot);
+ expect(round.metadata).toMatchObject({ replayOfRunId: source.id });
+ });
+});
+
+describe('AcceptanceFlowModel coverage · graph expansion', () => {
+ it('adds edge conditions to preconditions for checks and subflow occurrences', async () => {
+ const childEntry = randomUUID();
+ const child = await model.publish(acceptanceId, {
+ title: 'Child',
+ entryNodeId: childEntry,
+ nodes: [checkNode(childEntry, 'Child check', { expected: 'ok' })],
+ edges: [],
+ });
+ const entry = randomUUID();
+ const sub = randomUUID();
+ const tail = randomUUID();
+ const toSub = randomUUID();
+ const toTail = randomUUID();
+ const parent = await model.publish(acceptanceId, {
+ title: 'Parent',
+ entryNodeId: entry,
+ nodes: [
+ checkNode(entry, 'Entry', { expected: 'Start' }),
+ { id: sub, subFlowId: child.flowId },
+ checkNode(tail, 'Tail', { expected: 'Done', preconditions: ['Signed in'] }),
+ ],
+ edges: [
+ {
+ id: toSub,
+ sourceNodeId: entry,
+ targetNodeId: sub,
+ trigger: 'Open child',
+ condition: 'When online',
+ required: true,
+ },
+ {
+ id: toTail,
+ sourceNodeId: sub,
+ targetNodeId: tail,
+ trigger: 'Finish',
+ condition: 'If child passed',
+ required: true,
+ },
+ ],
+ });
+
+ const run = await model.start(acceptanceId, parent.flowId);
+ const plan = (await roundById(run.id)).plan!;
+
+ expect(plan.map((item) => item.title)).toEqual(['Entry', 'Child check', 'Tail']);
+ expect(plan[0].definition?.preconditions).toEqual([]);
+ expect(plan[1].definition?.preconditions).toEqual(['Open child', 'When online']);
+ // The child entry has no incoming edge of its own inside the child graph.
+ expect(plan[1].sourceFlowNode).toEqual({
+ flowId: parent.flowId,
+ nodeId: `${sub}/${toSub}/${childEntry}`,
+ incomingEdgeId: undefined,
+ });
+ expect(plan[2].definition?.preconditions).toEqual(['Signed in', 'Finish', 'If child passed']);
+ });
+
+ it('builds a legacy definition from verifier config when an asset has none', async () => {
+ const [legacy, bare, nullConfig] = await db
+ .insert(verifyCriteria)
+ .values([
+ {
+ userId: owner,
+ title: 'Legacy',
+ verifierType: 'agent',
+ verifierConfig: { expected: 'Legacy expected', method: 'Click legacy' },
+ },
+ { userId: owner, title: 'Bare', verifierType: 'agent', verifierConfig: {} },
+ { userId: owner, title: 'Null config', verifierType: 'agent', verifierConfig: null },
+ ])
+ .returning();
+ const ids = [randomUUID(), randomUUID(), randomUUID()];
+ const { flowId } = await model.publish(acceptanceId, {
+ title: 'Legacy flow',
+ entryNodeId: ids[0],
+ nodes: [
+ { id: ids[0], criterionId: legacy.id },
+ { id: ids[1], criterionId: bare.id },
+ { id: ids[2], criterionId: nullConfig.id },
+ ],
+ edges: [
+ {
+ id: randomUUID(),
+ sourceNodeId: ids[0],
+ targetNodeId: ids[1],
+ trigger: 'A',
+ required: true,
+ },
+ {
+ id: randomUUID(),
+ sourceNodeId: ids[1],
+ targetNodeId: ids[2],
+ trigger: 'B',
+ required: true,
+ },
+ ],
+ });
+
+ const run = await model.start(acceptanceId, flowId);
+ const plan = (await roundById(run.id)).plan!;
+
+ expect(plan.map((item) => item.title)).toEqual(['Legacy', 'Bare', 'Null config']);
+ expect(plan[0].definition?.expected).toBe('Legacy expected');
+ expect(plan[0].definition?.steps).toEqual([
+ { id: 'legacy-method', instruction: 'Click legacy' },
+ ]);
+ expect(plan[1].definition?.expected).toBeUndefined();
+ expect(plan[1].definition?.steps).toBeUndefined();
+ expect(plan[2].definition?.expected).toBeUndefined();
+ expect(plan[2].definition?.steps).toBeUndefined();
+ expect(plan[2].verifierConfig).toEqual({});
+ });
+
+ it('refuses a graph whose subflow expansion exceeds 1000 nodes', async () => {
+ const [asset] = await db
+ .insert(verifyCriteria)
+ .values({
+ userId: owner,
+ title: 'Step',
+ verifierType: 'agent',
+ definition: { expected: 'x' },
+ })
+ .returning();
+ const childIds = Array.from({ length: 20 }, () => randomUUID());
+ const child = await model.publish(acceptanceId, {
+ title: 'Wide child',
+ entryNodeId: childIds[0],
+ nodes: childIds.map((id) => ({ id, criterionId: asset.id })),
+ edges: childIds.slice(1).map((id, i) => ({
+ id: randomUUID(),
+ sourceNodeId: childIds[i],
+ targetNodeId: id,
+ trigger: `Step ${i}`,
+ required: true,
+ })),
+ });
+ const entry = randomUUID();
+ const sub = randomUUID();
+
+ await expect(
+ model.publish(acceptanceId, {
+ title: 'Exploding parent',
+ entryNodeId: entry,
+ nodes: [
+ { id: entry, criterionId: asset.id },
+ { id: sub, subFlowId: child.flowId },
+ ],
+ // 50 parallel edges → 50 occurrences × (group + 20 child nodes) > 1000.
+ edges: Array.from({ length: 50 }, (_, i) => ({
+ id: randomUUID(),
+ sourceNodeId: entry,
+ targetNodeId: sub,
+ trigger: `Path ${i}`,
+ required: true,
+ })),
+ }),
+ ).rejects.toThrow('Expanded flow exceeds 1000 nodes');
+
+ const remaining = await db.select().from(flows).where(eq(flows.acceptanceId, acceptanceId));
+ expect(remaining.map((flow) => flow.id)).toEqual([child.flowId]);
+ });
+
+ it('reports a check node whose asset disappeared inside the same transaction', async () => {
+ const definition = twoStep('Vanishing');
+ const { flowId } = await model.publish(acceptanceId, definition);
+ const assetId = definition.nodes[1].check!.id;
+
+ // The node FK is deferred to commit, so a transaction can briefly see a node without its asset.
+ await expect(
+ db.transaction(async (tx) => {
+ await tx.delete(verifyCriteria).where(eq(verifyCriteria.id, assetId));
+ await new AcceptanceFlowModel(tx as unknown as LobeChatDatabase, owner).list(acceptanceId);
+ }),
+ ).rejects.toThrow('Check asset not found');
+
+ expect(
+ await db.select().from(verifyCriteria).where(eq(verifyCriteria.id, assetId)),
+ ).toHaveLength(1);
+ expect((await model.list(acceptanceId)).map((flow) => flow.id)).toEqual([flowId]);
+ });
+
+ it('reports a subflow node whose flow disappeared inside the same transaction', async () => {
+ const child = await model.publish(acceptanceId, twoStep('Child'));
+ const occurrence = randomUUID();
+ const parent = await model.publish(acceptanceId, {
+ title: 'Parent',
+ entryNodeId: occurrence,
+ nodes: [{ id: occurrence, subFlowId: child.flowId }],
+ edges: [],
+ });
+
+ // The subflow FK is deferred to commit, so a transaction can briefly see a dangling occurrence.
+ await expect(
+ db.transaction(async (tx) => {
+ await tx.delete(flows).where(eq(flows.id, child.flowId));
+ await new AcceptanceFlowModel(tx as unknown as LobeChatDatabase, owner).list(acceptanceId);
+ }),
+ ).rejects.toThrow('Flow not found');
+
+ expect((await model.list(acceptanceId)).map((flow) => flow.id).sort()).toEqual(
+ [child.flowId, parent.flowId].sort(),
+ );
+ });
+
+ it('re-prefixes nested group parents when a subflow itself contains a subflow', async () => {
+ const leafEntry = randomUUID();
+ const leaf = await model.publish(acceptanceId, {
+ title: 'Leaf',
+ entryNodeId: leafEntry,
+ nodes: [checkNode(leafEntry, 'Leaf check', { expected: 'Leaf ok' })],
+ edges: [],
+ });
+ const middleEntry = randomUUID();
+ const middle = await model.publish(acceptanceId, {
+ title: 'Middle',
+ entryNodeId: middleEntry,
+ nodes: [{ id: middleEntry, subFlowId: leaf.flowId }],
+ edges: [],
+ });
+ const top = randomUUID();
+ const root = await model.publish(acceptanceId, {
+ title: 'Root',
+ entryNodeId: top,
+ nodes: [{ id: top, subFlowId: middle.flowId }],
+ edges: [],
+ });
+
+ const run = await model.start(acceptanceId, root.flowId);
+ const snapshot = (await roundById(run.id)).flowSnapshots![0];
+
+ const prefix = `${top}/entry/`;
+ expect(snapshot.nodes.map((node) => [node.id, node.parentNodeId])).toEqual([
+ [top, undefined],
+ [`${prefix}${middleEntry}`, top],
+ [`${prefix}${middleEntry}/entry/${leafEntry}`, `${prefix}${middleEntry}`],
+ ]);
+ });
+
+ it('reports an edge whose target node is missing from the node read', async () => {
+ const definition = twoStep('Torn read');
+ const { flowId } = await model.publish(acceptanceId, definition);
+ const missing = definition.nodes[1].id;
+ // A concurrent republish between the node and edge reads can leave an edge without its node.
+ const torn = createProxyTestDB(db, (query, result) =>
+ query.includes('from "acceptance_flow_nodes" left join')
+ ? result.rows.filter((row) => row[0] !== missing)
+ : result.rows,
+ );
+
+ await expect(new AcceptanceFlowModel(torn, owner).list(acceptanceId)).rejects.toThrow(
+ 'Unknown edge endpoint',
+ );
+ expect(await db.select().from(nodes).where(eq(nodes.flowId, flowId))).toHaveLength(2);
+ });
+});
+
+describe('AcceptanceFlowModel coverage · record and complete', () => {
+ it('stores a blocked verdict as skipped/uncertain and a failure as failed', async () => {
+ const { flowId } = await model.publish(
+ acceptanceId,
+ twoStep('No expectation', { steps: [{ id: 'open', instruction: 'Open' }] }),
+ );
+ const run = await model.start(acceptanceId, flowId);
+ const plan = (await roundById(run.id)).plan!;
+
+ const blocked = await model.record(acceptanceId, {
+ verifyRunId: run.id,
+ checkItemId: plan[0].id,
+ verdict: 'blocked',
+ observation: 'Environment down',
+ });
+ const failed = await model.record(acceptanceId, {
+ verifyRunId: run.id,
+ checkItemId: plan[1].id,
+ verdict: 'failed',
+ observation: 'Broken',
+ });
+
+ expect(blocked).toMatchObject({ status: 'skipped', verdict: 'uncertain' });
+ expect(blocked.toulmin).toEqual({ evidence: 'Environment down', reasoning: '' });
+ expect(failed).toMatchObject({ status: 'failed', verdict: 'failed' });
+ // Re-recording the same blocked observation is idempotent.
+ expect(
+ (
+ await model.record(acceptanceId, {
+ verifyRunId: run.id,
+ checkItemId: plan[0].id,
+ verdict: 'blocked',
+ observation: 'Environment down',
+ })
+ ).id,
+ ).toBe(blocked.id);
+ });
+
+ it('completes an untouched round with only optional checks and stamps its confirmation', async () => {
+ const nodeId = randomUUID();
+ const { flowId } = await model.publish(acceptanceId, {
+ title: 'Optional only',
+ entryNodeId: nodeId,
+ nodes: [
+ { ...checkNode(nodeId, 'Optional', { expected: 'Maybe' }), overrides: { required: false } },
+ ],
+ edges: [],
+ });
+ const run = await model.start(acceptanceId, flowId);
+ expect((await roundById(run.id)).planConfirmedAt).toBeNull();
+
+ const completed = await model.complete(acceptanceId, run.id);
+
+ expect(completed.status).toBe('delivered');
+ expect(completed.planConfirmedAt).toBeInstanceOf(Date);
+ });
+});
+
+describe('AcceptanceFlowModel coverage · list projection', () => {
+ it('renders rounds without snapshots, without plans and results without detail', async () => {
+ const { flowId } = await model.publish(acceptanceId, twoStep('Projected'));
+ const empty = await seedRound({ roundIndex: 1, status: 'delivered' });
+ const run = await model.start(acceptanceId, flowId);
+ const plan = (await roundById(run.id)).plan!;
+ await db
+ .update(verifyRuns)
+ .set({ plan: null, status: 'delivered' })
+ .where(eq(verifyRuns.id, run.id));
+ const [bareResult] = await db
+ .insert(verifyCheckResults)
+ .values({
+ verifyRunId: run.id,
+ userId: owner,
+ checkItemId: plan[0].id,
+ verifierType: 'agent',
+ })
+ .returning();
+
+ const [flow] = await model.list(acceptanceId);
+
+ expect(flow.id).toBe(flowId);
+ // The empty round contributes no history; the plan-less round still renders its snapshot.
+ expect(flow.versions.map((v) => v.runs[0]?.id)).toEqual([undefined, run.id]);
+ const history = flow.versions[1];
+ expect(history.nodes.map((n) => n.title)).toEqual(['', '']);
+ expect(history.nodes.map((n) => n.expected)).toEqual(['', '']);
+ expect(history.nodes.map((n) => n.requiredCheckItemIds)).toEqual([[], []]);
+ // Without plan items, the result cannot be attributed to this flow.
+ expect(history.runs[0].attempts).toEqual([]);
+ expect(flow.versions.some((v) => v.runs[0]?.id === empty.id)).toBe(false);
+ expect(bareResult.toulmin).toBeNull();
+ });
+
+ it('defaults an attempt without evidence text or verdict', async () => {
+ const { flowId } = await model.publish(acceptanceId, twoStep('Bare attempts'));
+ const run = await model.start(acceptanceId, flowId);
+ const plan = (await roundById(run.id)).plan!;
+ const [bareResult] = await db
+ .insert(verifyCheckResults)
+ .values({
+ verifyRunId: run.id,
+ userId: owner,
+ checkItemId: plan[0].id,
+ verifierType: 'agent',
+ })
+ .returning();
+
+ const [flow] = await model.list(acceptanceId);
+ const attempt = flow.versions
+ .flatMap((v) => v.runs)
+ .flatMap((r) => r.attempts)
+ .find((a) => a.id === bareResult.id)!;
+
+ expect(attempt).toMatchObject({
+ observation: '',
+ verdict: 'uncertain',
+ review: null,
+ reviewComment: null,
+ reviewDetail: null,
+ evidence: [],
+ });
+ expect(
+ await db.select().from(verifyCheckResults).where(eq(verifyCheckResults.verifyRunId, run.id)),
+ ).toHaveLength(1);
+ });
+});
diff --git a/packages/database/src/models/__tests__/agentBotProvider.coverage.test.ts b/packages/database/src/models/__tests__/agentBotProvider.coverage.test.ts
new file mode 100644
index 00000000000..494d9df8da9
--- /dev/null
+++ b/packages/database/src/models/__tests__/agentBotProvider.coverage.test.ts
@@ -0,0 +1,139 @@
+// @vitest-environment node
+import { inArray } from 'drizzle-orm';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+
+import { getTestDB } from '../../core/getTestDB';
+import { agentBotProviders, agents, users } from '../../schemas';
+import type { LobeChatDatabase } from '../../type';
+import { AgentBotProviderModel } from '../agentBotProvider';
+
+const serverDB: LobeChatDatabase = await getTestDB();
+
+const userId = 'bot-provider-cov-user';
+const agentId = 'bot-provider-cov-agent';
+const platform = 'bot-provider-cov-platform';
+
+/** A gateKeeper whose ciphertext is just the plaintext, so stored rows stay readable. */
+const passthroughGateKeeper = {
+ decrypt: async (ciphertext: string) => ({ plaintext: ciphertext }),
+ encrypt: async (plaintext: string) => plaintext,
+};
+
+/** Seed a provider row with raw credentials, bypassing the model's encryption. */
+const seed = async (applicationId: string, credentials: string | null, enabled = true) => {
+ const [row] = await serverDB
+ .insert(agentBotProviders)
+ .values({ agentId, applicationId, credentials, enabled, platform, userId })
+ .returning();
+ return row;
+};
+
+beforeEach(async () => {
+ await serverDB.insert(users).values({ id: userId });
+ await serverDB.insert(agents).values({ id: agentId, userId });
+});
+
+afterEach(async () => {
+ // Providers cascade with their agent and owner.
+ await serverDB.delete(users).where(inArray(users.id, [userId]));
+});
+
+describe('AgentBotProviderModel coverage', () => {
+ describe('findByIds', () => {
+ it('skips the query when no id is UUID-shaped', async () => {
+ expect(await AgentBotProviderModel.findByIds(serverDB, [])).toEqual([]);
+ expect(await AgentBotProviderModel.findByIds(serverDB, ['system-bot:discord'])).toEqual([]);
+ });
+
+ it('returns the rows matching the UUID-shaped ids and ignores the rest', async () => {
+ const row = await seed('cov-by-ids', '{}', false);
+
+ const found = await AgentBotProviderModel.findByIds(serverDB, [
+ row.id,
+ 'system-bot:discord',
+ '00000000-0000-4000-8000-000000000000',
+ ]);
+
+ expect(found).toEqual([
+ {
+ applicationId: 'cov-by-ids',
+ enabled: false,
+ id: row.id,
+ platform,
+ settings: row.settings,
+ },
+ ]);
+ });
+ });
+
+ describe('findEnabledByPlatformAndAppId', () => {
+ it('returns empty credentials for a row without any', async () => {
+ await seed('cov-no-creds', null);
+
+ const found = await AgentBotProviderModel.findEnabledByPlatformAndAppId(
+ serverDB,
+ platform,
+ 'cov-no-creds',
+ );
+
+ expect(found).toMatchObject({ applicationId: 'cov-no-creds', credentials: {} });
+ });
+
+ it('returns empty credentials when they fail to parse', async () => {
+ await seed('cov-bad-creds', 'not-json');
+
+ const found = await AgentBotProviderModel.findEnabledByPlatformAndAppId(
+ serverDB,
+ platform,
+ 'cov-bad-creds',
+ passthroughGateKeeper,
+ );
+
+ expect(found).toMatchObject({ applicationId: 'cov-bad-creds', credentials: {} });
+ });
+ });
+
+ describe('static findByAgentId', () => {
+ it('decodes plain JSON, and falls back to empty credentials for missing or broken ones', async () => {
+ await seed('cov-agent-plain', JSON.stringify({ botToken: 'plain' }));
+ await seed('cov-agent-none', null);
+ await seed('cov-agent-broken', '{broken');
+
+ const rows = await AgentBotProviderModel.findByAgentId(serverDB, agentId);
+
+ const byApp = Object.fromEntries(rows.map((r) => [r.applicationId, r.credentials]));
+ expect(byApp).toEqual({
+ 'cov-agent-broken': {},
+ 'cov-agent-none': {},
+ 'cov-agent-plain': { botToken: 'plain' },
+ });
+ });
+ });
+
+ describe('findEnabledByPlatform', () => {
+ it('keeps missing and undecryptable rows only when asked to', async () => {
+ await seed('cov-platform-ok', JSON.stringify({ botToken: 'ok' }));
+ await seed('cov-platform-none', null);
+ await seed('cov-platform-broken', '{broken');
+
+ const strict = await AgentBotProviderModel.findEnabledByPlatform(
+ serverDB,
+ platform,
+ passthroughGateKeeper,
+ );
+ expect(strict.map((r) => r.applicationId)).toEqual(['cov-platform-ok']);
+
+ const lenient = await AgentBotProviderModel.findEnabledByPlatform(
+ serverDB,
+ platform,
+ passthroughGateKeeper,
+ { includeUndecryptable: true },
+ );
+ expect(Object.fromEntries(lenient.map((r) => [r.applicationId, r.credentials]))).toEqual({
+ 'cov-platform-broken': {},
+ 'cov-platform-none': {},
+ 'cov-platform-ok': { botToken: 'ok' },
+ });
+ });
+ });
+});
diff --git a/packages/database/src/models/__tests__/agentCopyJob.coverage.test.ts b/packages/database/src/models/__tests__/agentCopyJob.coverage.test.ts
new file mode 100644
index 00000000000..ad3c99d535d
--- /dev/null
+++ b/packages/database/src/models/__tests__/agentCopyJob.coverage.test.ts
@@ -0,0 +1,360 @@
+// @vitest-environment node
+import { eq, inArray } from 'drizzle-orm';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+
+import { getTestDB } from '../../core/getTestDB';
+import {
+ agentHistoryJobs,
+ agentHistoryJobTopics,
+ agents,
+ chatGroups,
+ messages,
+ threads,
+ topics,
+ users,
+} from '../../schemas';
+import type { LobeChatDatabase } from '../../type';
+import { INSERT_BATCH_SIZE } from '../../utils/batchInsert';
+import { AgentCopyJobModel } from '../agentCopyJob';
+
+const serverDB: LobeChatDatabase = await getTestDB();
+
+const userId = 'acj-cov-user';
+const scope = { userId, workspaceId: null };
+
+beforeEach(async () => {
+ await serverDB.insert(users).values({ id: userId });
+});
+
+afterEach(async () => {
+ // Jobs carry no FK onto users; remove them explicitly before the user cascade.
+ await serverDB.delete(agentHistoryJobs).where(eq(agentHistoryJobs.sourceUserId, userId));
+ await serverDB.delete(users).where(inArray(users.id, [userId]));
+});
+
+const threadsOf = (topicId: string) =>
+ serverDB.query.threads.findMany({ where: eq(threads.topicId, topicId) });
+
+const jobOf = (jobId: string) =>
+ serverDB.query.agentHistoryJobs.findFirst({ where: eq(agentHistoryJobs.id, jobId) });
+
+/**
+ * Source topic `<prefix>-src` whose threads exercise every remap edge: a root thread, a child of
+ * it, a child of a thread in ANOTHER topic (its parent is not copied), and a thread anchored on a
+ * message from another topic (its anchor is not copied). `<prefix>-elsewhere` holds those two
+ * out-of-topic references.
+ */
+const seedRemapEdges = async (
+ prefix: string,
+ owner: { agentId?: string; groupId?: string },
+ threadAgentIds: { child: null | string; root: null | string },
+) => {
+ await serverDB.insert(topics).values([
+ { ...owner, id: `${prefix}-src`, userId },
+ { ...owner, id: `${prefix}-elsewhere`, userId },
+ ]);
+ await serverDB.insert(messages).values([
+ { content: 'in', id: `${prefix}-m-in`, role: 'user', topicId: `${prefix}-src`, userId },
+ { content: 'out', id: `${prefix}-m-out`, role: 'user', topicId: `${prefix}-elsewhere`, userId },
+ ]);
+ const base = { groupId: owner.groupId, type: 'continuation' as const, userId };
+ await serverDB.insert(threads).values([
+ { ...base, agentId: owner.agentId, id: `${prefix}-th-far`, topicId: `${prefix}-elsewhere` },
+ {
+ ...base,
+ agentId: threadAgentIds.root,
+ id: `${prefix}-th-root`,
+ sourceMessageId: `${prefix}-m-in`,
+ title: 'root',
+ topicId: `${prefix}-src`,
+ },
+ ]);
+ await serverDB.insert(threads).values([
+ {
+ ...base,
+ agentId: threadAgentIds.child,
+ id: `${prefix}-th-child`,
+ parentThreadId: `${prefix}-th-root`,
+ title: 'child',
+ topicId: `${prefix}-src`,
+ },
+ {
+ ...base,
+ agentId: threadAgentIds.child,
+ id: `${prefix}-th-orphan`,
+ parentThreadId: `${prefix}-th-far`,
+ sourceMessageId: `${prefix}-m-out`,
+ title: 'orphan',
+ topicId: `${prefix}-src`,
+ },
+ ]);
+};
+
+/** Index copied threads by title and check every out-of-topic reference collapsed to null. */
+const expectRemappedThreads = async (newTopicId: string) => {
+ const list = await threadsOf(newTopicId);
+ const copied: Record<string, (typeof list)[number]> = Object.fromEntries(
+ list.map((t) => [t.title, t]),
+ );
+ expect(Object.keys(copied).sort()).toEqual(['child', 'orphan', 'root']);
+ const [copiedMessage] = await serverDB.query.messages.findMany({
+ where: eq(messages.topicId, newTopicId),
+ });
+
+ expect(copied.root.parentThreadId).toBeNull();
+ expect(copied.root.sourceMessageId).toBe(copiedMessage.id);
+ expect(copied.child.parentThreadId).toBe(copied.root.id);
+ expect(copied.child.sourceMessageId).toBeNull();
+ expect(copied.orphan.parentThreadId).toBeNull();
+ expect(copied.orphan.sourceMessageId).toBeNull();
+ return copied;
+};
+
+/**
+ * One more thread than an insert batch holds, ordered so the earliest-created thread is the
+ * child of the latest one: the child lands in batch 0, its parent in batch 1, and the copy has
+ * to defer that link to an UPDATE after both batches are in.
+ */
+const seedCrossBatchThreads = async (
+ topicId: string,
+ owner: { agentId?: string; groupId?: string },
+) => {
+ const base = { ...owner, topicId, type: 'continuation' as const, userId };
+ const start = Date.UTC(2026, 0, 1);
+ await serverDB.insert(threads).values({
+ ...base,
+ createdAt: new Date(start + INSERT_BATCH_SIZE * 1000),
+ id: `${topicId}-parent`,
+ title: 'parent',
+ });
+ await serverDB.insert(threads).values([
+ {
+ ...base,
+ createdAt: new Date(start),
+ id: `${topicId}-child`,
+ parentThreadId: `${topicId}-parent`,
+ title: 'child',
+ },
+ ...Array.from({ length: INSERT_BATCH_SIZE - 1 }, (_, i) => ({
+ ...base,
+ createdAt: new Date(start + (i + 1) * 1000),
+ id: `${topicId}-filler-${i}`,
+ })),
+ ]);
+};
+
+/** The copied child still points at the copied parent once the deferred fixup ran. */
+const expectDeferredParentLink = async (newTopicId: string) => {
+ const copied = await threadsOf(newTopicId);
+ expect(copied).toHaveLength(INSERT_BATCH_SIZE + 1);
+ const parent = copied.find((t) => t.title === 'parent')!;
+ const child = copied.find((t) => t.title === 'child')!;
+ expect(child.parentThreadId).toBe(parent.id);
+ expect(parent.parentThreadId).toBeNull();
+};
+
+describe('AgentCopyJobModel coverage', () => {
+ it('reports no pending group copy for an empty group list without querying', async () => {
+ expect(await AgentCopyJobModel.hasPendingCopyJobForSourceGroups(serverDB, [])).toBe(false);
+ });
+
+ it('remaps thread parents and anchors that stay inside an agent topic, nulling the rest', async () => {
+ const [source, target] = await serverDB
+ .insert(agents)
+ .values([
+ { title: 'source', userId },
+ { title: 'target', userId },
+ ])
+ .returning();
+ await seedRemapEdges(
+ 'acj-cov-a',
+ { agentId: source.id },
+ { child: source.id, root: source.id },
+ );
+ await serverDB.insert(topics).values({ agentId: target.id, id: 'acj-cov-a-new', userId });
+ const jobId = await AgentCopyJobModel.createJob(serverDB, {
+ agents: [{ newAgentId: target.id, sourceAgentId: source.id }],
+ source: scope,
+ target: scope,
+ topics: [
+ {
+ activityAt: new Date(),
+ newAgentId: target.id,
+ newTopicId: 'acj-cov-a-new',
+ sourceAgentId: source.id,
+ sourceTopicId: 'acj-cov-a-src',
+ },
+ ],
+ });
+
+ await AgentCopyJobModel.drain(serverDB, jobId);
+
+ const copied = await expectRemappedThreads('acj-cov-a-new');
+ expect(copied.child.agentId).toBe(target.id);
+ expect(await jobOf(jobId)).toMatchObject({ completedTopics: 1, status: 'completed' });
+ });
+
+ it('copies a group topic for a job recorded without member agents', async () => {
+ const [member] = await serverDB.insert(agents).values({ title: 'member', userId }).returning();
+ await serverDB.insert(chatGroups).values([
+ { id: 'acj-cov-g-src-group', userId },
+ { id: 'acj-cov-g-new-group', userId },
+ ]);
+ await seedRemapEdges(
+ 'acj-cov-g',
+ { groupId: 'acj-cov-g-src-group' },
+ {
+ child: member.id,
+ root: null,
+ },
+ );
+ await serverDB
+ .insert(topics)
+ .values({ groupId: 'acj-cov-g-new-group', id: 'acj-cov-g-new', userId });
+ const group = { newGroupId: 'acj-cov-g-new-group', sourceGroupId: 'acj-cov-g-src-group' };
+ const jobId = await AgentCopyJobModel.createJob(serverDB, {
+ agents: [],
+ group,
+ source: scope,
+ target: scope,
+ topics: [
+ { activityAt: new Date(), newTopicId: 'acj-cov-g-new', sourceTopicId: 'acj-cov-g-src' },
+ ],
+ });
+ // The agent map is the job-level payload; a row that carries only the group still drains.
+ await serverDB
+ .update(agentHistoryJobs)
+ .set({ payload: { group } })
+ .where(eq(agentHistoryJobs.id, jobId));
+ expect(
+ await serverDB.query.agentHistoryJobAgents.findMany({
+ where: (t, { eq: equals }) => equals(t.jobId, jobId),
+ }),
+ ).toEqual([]);
+
+ await AgentCopyJobModel.drain(serverDB, jobId);
+
+ const copied = await expectRemappedThreads('acj-cov-g-new');
+ // Members outside the (empty) agent map, and agent-less threads, both land on no agent.
+ expect(Object.values(copied).map((t) => [t.agentId, t.groupId])).toEqual(
+ Array.from({ length: 3 }, () => [null, 'acj-cov-g-new-group']),
+ );
+ expect(await jobOf(jobId)).toMatchObject({ completedTopics: 1, status: 'completed' });
+ });
+
+ it('drops a queue row without a payload and still counts it', async () => {
+ const [target] = await serverDB.insert(agents).values({ title: 'target', userId }).returning();
+ await serverDB.insert(topics).values({ agentId: target.id, id: 'acj-cov-p-new', userId });
+ const jobId = await AgentCopyJobModel.createJob(serverDB, {
+ agents: [{ newAgentId: target.id, sourceAgentId: 'acj-cov-p-gone' }],
+ source: scope,
+ target: scope,
+ topics: [{ activityAt: new Date(), newTopicId: 'acj-cov-p-new', sourceTopicId: 'unused' }],
+ });
+ await serverDB
+ .update(agentHistoryJobTopics)
+ .set({ payload: null })
+ .where(eq(agentHistoryJobTopics.jobId, jobId));
+
+ expect(await AgentCopyJobModel.processNextTopic(serverDB, jobId)).toEqual({
+ done: false,
+ topicId: 'acj-cov-p-new',
+ });
+
+ expect(await jobOf(jobId)).toMatchObject({ completedTopics: 1, status: 'pending' });
+ // Without coordinates nothing is copied or cleaned up: the shell stays as it was.
+ expect(
+ await serverDB.query.topics.findFirst({ where: eq(topics.id, 'acj-cov-p-new') }),
+ ).toBeDefined();
+ });
+
+ it('drops a personal target shell whose source topic was deleted', async () => {
+ const [source, target] = await serverDB
+ .insert(agents)
+ .values([
+ { title: 'source', userId },
+ { title: 'target', userId },
+ ])
+ .returning();
+ await serverDB.insert(topics).values({ agentId: target.id, id: 'acj-cov-d-new', userId });
+ const jobId = await AgentCopyJobModel.createJob(serverDB, {
+ agents: [{ newAgentId: target.id, sourceAgentId: source.id }],
+ source: scope,
+ target: scope,
+ topics: [
+ {
+ activityAt: new Date(),
+ newAgentId: target.id,
+ newTopicId: 'acj-cov-d-new',
+ sourceAgentId: source.id,
+ sourceTopicId: 'acj-cov-d-deleted',
+ },
+ ],
+ });
+
+ await AgentCopyJobModel.drain(serverDB, jobId);
+
+ expect(
+ await serverDB.query.topics.findFirst({ where: eq(topics.id, 'acj-cov-d-new') }),
+ ).toBeUndefined();
+ expect(await jobOf(jobId)).toMatchObject({ completedTopics: 1, status: 'completed' });
+ });
+
+ it('defers an agent thread parent link that lands in a later insert batch', async () => {
+ const [source, target] = await serverDB
+ .insert(agents)
+ .values([
+ { title: 'source', userId },
+ { title: 'target', userId },
+ ])
+ .returning();
+ await serverDB.insert(topics).values([
+ { agentId: source.id, id: 'acj-cov-wa-src', userId },
+ { agentId: target.id, id: 'acj-cov-wa-new', userId },
+ ]);
+ await seedCrossBatchThreads('acj-cov-wa-src', { agentId: source.id });
+ const jobId = await AgentCopyJobModel.createJob(serverDB, {
+ agents: [{ newAgentId: target.id, sourceAgentId: source.id }],
+ source: scope,
+ target: scope,
+ topics: [
+ {
+ activityAt: new Date(),
+ newAgentId: target.id,
+ newTopicId: 'acj-cov-wa-new',
+ sourceAgentId: source.id,
+ sourceTopicId: 'acj-cov-wa-src',
+ },
+ ],
+ });
+
+ await AgentCopyJobModel.drain(serverDB, jobId);
+
+ await expectDeferredParentLink('acj-cov-wa-new');
+ });
+
+ it('defers a group thread parent link that lands in a later insert batch', async () => {
+ await serverDB.insert(chatGroups).values([
+ { id: 'acj-cov-wg-src-group', userId },
+ { id: 'acj-cov-wg-new-group', userId },
+ ]);
+ await serverDB.insert(topics).values([
+ { groupId: 'acj-cov-wg-src-group', id: 'acj-cov-wg-src', userId },
+ { groupId: 'acj-cov-wg-new-group', id: 'acj-cov-wg-new', userId },
+ ]);
+ await seedCrossBatchThreads('acj-cov-wg-src', { groupId: 'acj-cov-wg-src-group' });
+ const jobId = await AgentCopyJobModel.createJob(serverDB, {
+ agents: [],
+ group: { newGroupId: 'acj-cov-wg-new-group', sourceGroupId: 'acj-cov-wg-src-group' },
+ source: scope,
+ target: scope,
+ topics: [
+ { activityAt: new Date(), newTopicId: 'acj-cov-wg-new', sourceTopicId: 'acj-cov-wg-src' },
+ ],
+ });
+
+ await AgentCopyJobModel.drain(serverDB, jobId);
+
+ await expectDeferredParentLink('acj-cov-wg-new');
+ });
+});
diff --git a/packages/database/src/models/__tests__/agentCronJob.coverage.test.ts b/packages/database/src/models/__tests__/agentCronJob.coverage.test.ts
new file mode 100644
index 00000000000..30b4caf40e4
--- /dev/null
+++ b/packages/database/src/models/__tests__/agentCronJob.coverage.test.ts
@@ -0,0 +1,50 @@
+// @vitest-environment node
+import { inArray } from 'drizzle-orm';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+
+import { getTestDB } from '../../core/getTestDB';
+import { agents, users } from '../../schemas';
+import type { LobeChatDatabase } from '../../type';
+import { AgentCronJobModel } from '../agentCronJob';
+import { createProxyTestDB } from './_proxyTestDB';
+
+const serverDB: LobeChatDatabase = await getTestDB();
+
+const userId = 'agent-cron-cov-user';
+const agentId = 'agent-cron-cov-agent';
+
+beforeEach(async () => {
+ await serverDB.insert(users).values({ id: userId });
+ await serverDB.insert(agents).values({ id: agentId, userId });
+});
+
+afterEach(async () => {
+ // Cron jobs cascade with their agent and owner.
+ await serverDB.delete(users).where(inArray(users.id, [userId]));
+});
+
+describe('AgentCronJobModel coverage', () => {
+ /**
+ * `sum()` is bigint, which the drivers hand back in different shapes; the proxy delivers the
+ * pending-executions cell as a number, the shape the unlimited-job sentinel compares against.
+ */
+ it('reports no pending executions for a lone unlimited job', async () => {
+ await new AgentCronJobModel(serverDB, userId).create({
+ agentId,
+ content: 'unlimited',
+ cronPattern: '0 * * * *',
+ });
+ const numericSums = createProxyTestDB(serverDB, (_query, result) =>
+ result.rows.map((row) => row.map((cell) => (cell === null ? null : Number(cell)))),
+ );
+
+ const stats = await new AgentCronJobModel(numericSums, userId).getExecutionStats();
+
+ expect(stats).toEqual({
+ activeJobs: 1,
+ completedExecutions: 0,
+ pendingExecutions: 0,
+ totalJobs: 1,
+ });
+ });
+});
diff --git a/packages/database/src/models/__tests__/agentHistoryJob.test.ts b/packages/database/src/models/__tests__/agentHistoryJob.test.ts
new file mode 100644
index 00000000000..a1745895773
--- /dev/null
+++ b/packages/database/src/models/__tests__/agentHistoryJob.test.ts
@@ -0,0 +1,68 @@
+// @vitest-environment node
+import { eq, inArray } from 'drizzle-orm';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+
+import { getTestDB } from '../../core/getTestDB';
+import { agentHistoryJobs, agentHistoryJobTopics, topics, users } from '../../schemas';
+import type { LobeChatDatabase } from '../../type';
+import { drainAgentHistoryJob, processNextAgentHistoryJobTopic } from '../agentHistoryJob';
+import { AgentTransferJobModel } from '../agentTransferJob';
+
+const serverDB: LobeChatDatabase = await getTestDB();
+
+const userId = 'ahj-dispatch-user';
+const topicId = 'ahj-dispatch-topic';
+
+const createTransferJob = () =>
+ AgentTransferJobModel.createJob(serverDB, {
+ agentIds: [],
+ sessionIds: [],
+ source: { userId, workspaceId: null },
+ target: { userId, workspaceId: null },
+ topics: [{ activityAt: new Date(), id: topicId }],
+ });
+
+beforeEach(async () => {
+ await serverDB.insert(users).values({ id: userId });
+ await serverDB.insert(topics).values({ id: topicId, title: 'queued', userId });
+});
+
+afterEach(async () => {
+ // Jobs carry no FK onto users; remove them explicitly before the user cascade.
+ await serverDB.delete(agentHistoryJobs).where(eq(agentHistoryJobs.sourceUserId, userId));
+ await serverDB.delete(users).where(inArray(users.id, [userId]));
+});
+
+describe('agentHistoryJob dispatcher', () => {
+ it('reports an unknown job as done without touching anything', async () => {
+ expect(await processNextAgentHistoryJobTopic(serverDB, 'ahj-missing-job')).toEqual({
+ done: true,
+ });
+ });
+
+ it('routes a transfer job to the transfer drain', async () => {
+ const jobId = await createTransferJob();
+
+ expect(await processNextAgentHistoryJobTopic(serverDB, jobId)).toEqual({
+ done: false,
+ topicId,
+ });
+ expect(
+ await serverDB.query.agentHistoryJobTopics.findMany({
+ where: eq(agentHistoryJobTopics.jobId, jobId),
+ }),
+ ).toHaveLength(0);
+ });
+
+ it('drains a job of any type to completion', async () => {
+ const jobId = await createTransferJob();
+
+ await drainAgentHistoryJob(serverDB, jobId);
+
+ const job = await serverDB.query.agentHistoryJobs.findFirst({
+ where: eq(agentHistoryJobs.id, jobId),
+ });
+ expect(job).toMatchObject({ completedTopics: 1, status: 'completed', type: 'transfer' });
+ expect(job?.completedAt).toBeInstanceOf(Date);
+ });
+});
diff --git a/packages/database/src/models/__tests__/agentOperation.coverage.test.ts b/packages/database/src/models/__tests__/agentOperation.coverage.test.ts
new file mode 100644
index 00000000000..c6125e6efc0
--- /dev/null
+++ b/packages/database/src/models/__tests__/agentOperation.coverage.test.ts
@@ -0,0 +1,95 @@
+// @vitest-environment node
+import { eq, inArray, sql } from 'drizzle-orm';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+
+import { getTestDB } from '../../core/getTestDB';
+import { agentOperations, tasks, users } from '../../schemas';
+import type { LobeChatDatabase } from '../../type';
+import { AgentOperationModel } from '../agentOperation';
+import { createProxyTestDB } from './_proxyTestDB';
+
+const serverDB: LobeChatDatabase = await getTestDB();
+
+const userId = 'agent-operation-cov-user';
+const model = new AgentOperationModel(serverDB, userId);
+
+/** Write a numeric `NaN` cost: Postgres numeric accepts it, and `sum()` over it stays NaN. */
+const setNaNCost = (operationId: string) =>
+ serverDB
+ .update(agentOperations)
+ .set({ totalCost: sql`'NaN'::numeric` })
+ .where(eq(agentOperations.id, operationId));
+
+beforeEach(async () => {
+ await serverDB.insert(users).values({ id: userId });
+});
+
+afterEach(async () => {
+ // `agent_operations.user_id` and `tasks.created_by_user_id` are cleaned explicitly.
+ await serverDB.delete(agentOperations).where(eq(agentOperations.userId, userId));
+ await serverDB.delete(tasks).where(eq(tasks.createdByUserId, userId));
+ await serverDB.delete(users).where(inArray(users.id, [userId]));
+});
+
+describe('AgentOperationModel coverage', () => {
+ it('treats a claimed redrive without a numeric attempt as not claimed', async () => {
+ const operationId = 'op-cov-redrive-shape';
+ await model.recordStart({ operationId });
+ await serverDB
+ .update(agentOperations)
+ .set({ updatedAt: new Date('2026-01-01T00:00:00.000Z') })
+ .where(eq(agentOperations.id, operationId));
+ // The UPDATE still runs for real; only the RETURNING metadata comes back without an attempt.
+ const proxied = new AgentOperationModel(
+ createProxyTestDB(serverDB, (query, result) =>
+ query.startsWith('update') ? result.rows.map(() => [{ staleRedrive: {} }]) : result.rows,
+ ),
+ userId,
+ );
+
+ expect(await proxied.claimStaleRedrive(operationId, new Date(Date.now() - 60_000), 3)).toBe(
+ null,
+ );
+ const [row] = await serverDB
+ .select({ metadata: agentOperations.metadata })
+ .from(agentOperations)
+ .where(eq(agentOperations.id, operationId));
+ expect(row.metadata).toMatchObject({ staleRedrive: { attempts: 1 } });
+ });
+
+ it('rolls a NaN child cost up as zero', async () => {
+ await model.recordStart({ operationId: 'op-cov-parent' });
+ await model.recordStart({ operationId: 'op-cov-child', parentOperationId: 'op-cov-parent' });
+ await model.recordCompletion('op-cov-child', {
+ completionReason: 'done',
+ status: 'done',
+ totalCost: 1,
+ });
+ await setNaNCost('op-cov-child');
+
+ expect(await model.sumChildUsage('op-cov-parent')).toMatchObject({ totalCost: 0 });
+ });
+
+ it('sums a NaN task cost as zero', async () => {
+ await serverDB.insert(tasks).values({
+ createdByUserId: userId,
+ id: 'task-cov-nan',
+ identifier: 'T-COV-NAN',
+ instruction: 'x',
+ seq: 1,
+ });
+ await model.recordStart({ operationId: 'op-cov-task', taskId: 'task-cov-nan' });
+ await setNaNCost('op-cov-task');
+
+ expect(await model.sumCostByTask('task-cov-nan')).toBe(0);
+ });
+
+ it('reports a zero max duration when the aggregate yields no row', async () => {
+ const proxied = new AgentOperationModel(
+ createProxyTestDB(serverDB, () => []),
+ userId,
+ );
+
+ expect(await proxied.getMaxDurationSeconds()).toBe(0);
+ });
+});
diff --git a/packages/database/src/models/__tests__/agentQuota.coverage.test.ts b/packages/database/src/models/__tests__/agentQuota.coverage.test.ts
new file mode 100644
index 00000000000..0a45920d445
--- /dev/null
+++ b/packages/database/src/models/__tests__/agentQuota.coverage.test.ts
@@ -0,0 +1,22 @@
+// @vitest-environment node
+import { randomUUID } from 'node:crypto';
+
+import { describe, expect, it } from 'vitest';
+
+import { getTestDB } from '../../core/getTestDB';
+import type { LobeChatDatabase } from '../../type';
+import { AgentQuotaUsageLedgerModel } from '../agentQuota';
+import { createProxyTestDB } from './_proxyTestDB';
+
+const serverDB: LobeChatDatabase = await getTestDB();
+
+describe('AgentQuotaUsageLedgerModel coverage', () => {
+ it('reports zero spend when the cost aggregate yields no row', async () => {
+ const ledger = new AgentQuotaUsageLedgerModel(
+ createProxyTestDB(serverDB, () => []),
+ 'agent-quota-cov-user',
+ );
+
+ expect(await ledger.sumCostUsd(randomUUID(), new Date(0), new Date())).toBe(0);
+ });
+});
diff --git a/packages/database/src/models/__tests__/agentShare.coverage.test.ts b/packages/database/src/models/__tests__/agentShare.coverage.test.ts
new file mode 100644
index 00000000000..bd7056c7ce9
--- /dev/null
+++ b/packages/database/src/models/__tests__/agentShare.coverage.test.ts
@@ -0,0 +1,193 @@
+// @vitest-environment node
+import { eq, inArray } from 'drizzle-orm';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { getTestDB } from '../../core/getTestDB';
+import { agents, agentShares, users, workspaces } from '../../schemas';
+import type { LobeChatDatabase } from '../../type';
+import { AgentShareModel } from '../agentShare';
+
+const serverDB: LobeChatDatabase = await getTestDB();
+
+const userId = 'ascov-user';
+const workspaceId = 'ascov-workspace';
+const agentId = 'ascov-agent';
+const unsharedAgentId = 'ascov-unshared-agent';
+const workspaceAgentId = 'ascov-workspace-agent';
+const nullListsAgentId = 'ascov-null-lists-agent';
+
+const cleanup = async () => {
+ // agents / workspaces / agent_shares all cascade from the owning user.
+ await serverDB.delete(users).where(inArray(users.id, [userId]));
+};
+
+describe('AgentShareModel coverage edges', () => {
+ beforeEach(async () => {
+ await cleanup();
+ await serverDB.insert(users).values({ id: userId });
+ await serverDB.insert(workspaces).values({
+ id: workspaceId,
+ name: 'ascov workspace',
+ primaryOwnerId: userId,
+ slug: 'ascov-workspace',
+ });
+ await serverDB.insert(agents).values([
+ { id: agentId, slug: 'ascov-agent-slug', title: 'ascov agent', userId },
+ { id: unsharedAgentId, slug: 'ascov-unshared-slug', userId },
+ { id: workspaceAgentId, slug: 'ascov-workspace-slug', userId, workspaceId },
+ {
+ id: nullListsAgentId,
+ openingQuestions: null,
+ slug: 'ascov-null-lists-slug',
+ tags: null,
+ title: 'ascov null lists',
+ userId,
+ },
+ ]);
+ });
+
+ afterEach(async () => {
+ vi.restoreAllMocks();
+ await cleanup();
+ });
+
+ describe('create', () => {
+ it('refuses when the conflicting share disappears before it can be re-read', async () => {
+ const model = new AgentShareModel(serverDB, userId);
+ const original = await model.create(agentId, 'link');
+
+ // Simulates a concurrent hard delete that commits between the conflicting
+ // INSERT ... ON CONFLICT DO NOTHING and the follow-up SELECT: the
+ // re-read of the existing share comes back empty.
+ const authorizeMutation = vi.fn(async (tx: LobeChatDatabase) => {
+ vi.spyOn(tx, 'select').mockImplementationOnce(
+ () =>
+ ({
+ from: () => ({ where: () => ({ limit: async () => [] }) }),
+ }) as unknown as ReturnType<LobeChatDatabase['select']>,
+ );
+ });
+ const racingModel = new AgentShareModel(serverDB, userId, undefined, { authorizeMutation });
+
+ await expect(racingModel.create(agentId, 'link')).rejects.toMatchObject({
+ code: 'FORBIDDEN',
+ message: 'Agent sharing is not available in this scope',
+ });
+ expect(authorizeMutation).toHaveBeenCalledWith(expect.anything(), agentId);
+
+ // The pre-existing share itself was not touched by the refused call.
+ const rows = await serverDB
+ .select()
+ .from(agentShares)
+ .where(eq(agentShares.agentId, agentId));
+ expect(rows).toHaveLength(1);
+ expect(rows[0]).toMatchObject({ id: original.id, visibility: 'link' });
+ });
+ });
+
+ describe('forceDisableWorkspaceShare', () => {
+ it('returns null without touching the share when the workspace agent is in the recycle bin', async () => {
+ const share = await new AgentShareModel(serverDB, userId, workspaceId).create(
+ workspaceAgentId,
+ 'link',
+ );
+ await serverDB
+ .update(agents)
+ .set({ deletedAt: new Date(), isDeleted: true })
+ .where(eq(agents.id, workspaceAgentId));
+ const authorizeMutation = vi.fn();
+
+ await expect(
+ AgentShareModel.forceDisableWorkspaceShare(serverDB, workspaceId, share.id, {
+ authorizeMutation,
+ }),
+ ).resolves.toBeNull();
+ expect(authorizeMutation).not.toHaveBeenCalled();
+
+ const [row] = await serverDB.select().from(agentShares).where(eq(agentShares.id, share.id));
+ expect(row.visibility).toBe('link');
+ });
+
+ it('returns null when the share is deleted after the agent lock is taken', async () => {
+ const share = await new AgentShareModel(serverDB, userId, workspaceId).create(
+ workspaceAgentId,
+ 'link',
+ );
+ const authorizeMutation = vi.fn(async (tx: LobeChatDatabase) => {
+ await tx.delete(agentShares).where(eq(agentShares.id, share.id));
+ });
+
+ await expect(
+ AgentShareModel.forceDisableWorkspaceShare(serverDB, workspaceId, share.id, {
+ authorizeMutation,
+ }),
+ ).resolves.toBeNull();
+ expect(authorizeMutation).toHaveBeenCalledWith(expect.anything(), workspaceAgentId);
+
+ const rows = await serverDB.select().from(agentShares).where(eq(agentShares.id, share.id));
+ expect(rows).toHaveLength(0);
+ });
+ });
+
+ describe('updateConfig', () => {
+ it('keeps the stored config when the patch carries no defined field', async () => {
+ const model = new AgentShareModel(serverDB, userId);
+ await model.create(agentId);
+ await model.updateConfig(agentId, { maxTurnsPerTopic: 7, showModelInfo: true });
+
+ const updated = await model.updateConfig(agentId, {
+ maxTurnsPerTopic: undefined,
+ showModelInfo: undefined,
+ });
+
+ expect(updated?.shareConfig).toMatchObject({
+ maxTurnsPerTopic: 7,
+ showModelInfo: true,
+ slug: 'ascov-agent-slug',
+ });
+
+ const empty = await model.updateConfig(agentId, {});
+ expect(empty?.shareConfig).toMatchObject({ maxTurnsPerTopic: 7, showModelInfo: true });
+ });
+ });
+
+ describe('updateSlug', () => {
+ it('returns null when clearing the slug of an owned agent that has no share', async () => {
+ const model = new AgentShareModel(serverDB, userId);
+
+ await expect(model.updateSlug(unsharedAgentId, null)).resolves.toBeNull();
+ const rows = await serverDB
+ .select()
+ .from(agentShares)
+ .where(eq(agentShares.agentId, unsharedAgentId));
+ expect(rows).toHaveLength(0);
+ });
+
+ it('returns null when setting a slug on an owned agent that has no share', async () => {
+ const model = new AgentShareModel(serverDB, userId);
+
+ await expect(model.updateSlug(unsharedAgentId, 'ascov-fresh-slug')).resolves.toBeNull();
+ const rows = await serverDB
+ .select()
+ .from(agentShares)
+ .where(eq(agentShares.agentId, unsharedAgentId));
+ expect(rows).toHaveLength(0);
+ expect(await AgentShareModel.findBySlugOrId(serverDB, 'ascov-fresh-slug')).toBeNull();
+ });
+ });
+
+ describe('findByShareId', () => {
+ it('falls back to empty lists when the agent stores null tags and opening questions', async () => {
+ const share = await new AgentShareModel(serverDB, userId).create(nullListsAgentId, 'link');
+
+ const found = await AgentShareModel.findByShareId(serverDB, share.id);
+
+ expect(found).toMatchObject({
+ agentId: nullListsAgentId,
+ agentOpeningQuestions: [],
+ agentTags: [],
+ shareId: share.id,
+ });
+ });
+ });
+});
diff --git a/packages/database/src/models/acceptanceFlow.ts b/packages/database/src/models/acceptanceFlow.ts
index 488ce8fb735..24e338e172d 100644
--- a/packages/database/src/models/acceptanceFlow.ts
+++ b/packages/database/src/models/acceptanceFlow.ts
@@ -478,7 +478,9 @@ export class AcceptanceFlowModel {
definition: {
...item.definition,
preconditions: [
+ /* v8 ignore start -- unreachable: child plan items come from graph(), which always builds definition.preconditions as an array, and materialize() keeps item.definition as-is, so `?? []` never applies */
...(item.definition?.preconditions ?? []),
+ /* v8 ignore stop */
...(branch
? [branch.trigger, ...(branch.condition ? [branch.condition] : [])]
: []),
diff --git a/packages/database/src/models/agentShare.ts b/packages/database/src/models/agentShare.ts
index 530c941303f..a9e7b0e8593 100644
--- a/packages/database/src/models/agentShare.ts
+++ b/packages/database/src/models/agentShare.ts
@@ -234,6 +234,7 @@ export class AgentShareModel {
.where(eq(agentShares.id, share.id))
.returning();
+ /* v8 ignore next -- unreachable: `share` was inserted by this same open transaction (uncommitted, invisible to and undeletable by any other session), so the UPDATE by its id always returns the row */
return updated ?? share;
};