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

Arvin Xu95f1b6788460
diff --git a/packages/database/src/models/__tests__/acceptanceFlow.guards.test.ts b/packages/database/src/models/__tests__/acceptanceFlow.guards.test.ts
new file mode 100644
index 00000000000..bfe86c16760
--- /dev/null
+++ b/packages/database/src/models/__tests__/acceptanceFlow.guards.test.ts
@@ -0,0 +1,166 @@
+// @vitest-environment node
+import { randomUUID } from 'node:crypto';
+
+import type { AcceptanceFlowDefinition } from '@lobechat/types';
+import { eq } from 'drizzle-orm';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+
+import { getTestDB } from '../../core/getTestDB';
+import { acceptances, users, verifyCriteria, verifyRuns } from '../../schemas';
+import {
+ acceptanceFlowNodes as nodes,
+ acceptanceFlows as flows,
+} from '../../schemas/acceptanceFlow';
+import { AcceptanceFlowModel } from '../acceptanceFlow';
+
+const db = await getTestDB();
+const owner = 'flow-guard-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 () => {
+ await db.delete(users).where(eq(users.id, owner));
+});
+
+/** A single-check graph whose asset id is caller supplied, so reuse can be exercised. */
+function singleCheckFlow(
+ title: string,
+ checkId: string,
+ definition: { expected?: string; fixtures?: { data?: any; id: string; name: string }[] },
+ overrides?: { fixtureData?: Record<string, Record<string, unknown>> },
+): AcceptanceFlowDefinition {
+ const nodeId = randomUUID();
+ return {
+ title,
+ entryNodeId: nodeId,
+ nodes: [
+ {
+ id: nodeId,
+ check: { id: checkId, title, definition },
+ overrides,
+ },
+ ],
+ edges: [],
+ };
+}
+
+describe('publish rejects invalid graph content', () => {
+ it('refuses fixture overrides on a subflow node', async () => {
+ const child = await model.publish(acceptanceId, singleCheckFlow('Child', randomUUID(), {}));
+ const nodeId = randomUUID();
+
+ await expect(
+ model.publish(acceptanceId, {
+ title: 'Parent',
+ entryNodeId: nodeId,
+ nodes: [
+ { id: nodeId, subFlowId: child.flowId, overrides: { fixtureData: { f1: { a: 1 } } } },
+ ],
+ edges: [],
+ }),
+ ).rejects.toThrow('Fixture overrides belong to check nodes');
+
+ expect(await model.list(acceptanceId)).toHaveLength(1);
+ });
+
+ it('refuses a check whose asset id is already taken by another definition', async () => {
+ const checkId = randomUUID();
+ await model.publish(acceptanceId, singleCheckFlow('Ready', checkId, { expected: 'Ready' }));
+
+ await expect(
+ model.publish(acceptanceId, singleCheckFlow('Ready', checkId, { expected: 'Other' })),
+ ).rejects.toThrow('Check asset id already used');
+ });
+
+ it('refuses to reuse an archived check asset id', async () => {
+ const checkId = randomUUID();
+ await model.publish(acceptanceId, singleCheckFlow('Ready', checkId, { expected: 'Ready' }));
+ await db
+ .update(verifyCriteria)
+ .set({ archivedAt: new Date() })
+ .where(eq(verifyCriteria.id, checkId));
+
+ await expect(
+ model.publish(acceptanceId, singleCheckFlow('Ready', checkId, { expected: 'Ready' })),
+ ).rejects.toThrow('Check asset id already used');
+ });
+
+ it('rejects an unknown fixture override and applies a known one', async () => {
+ const checkId = randomUUID();
+ const definition = {
+ fixtures: [{ id: 'account', name: 'Account', data: { plan: 'free' } }],
+ steps: [{ id: 'open', instruction: 'Open billing' }],
+ };
+
+ await expect(
+ model.publish(
+ acceptanceId,
+ singleCheckFlow('Billing', checkId, definition, { fixtureData: { missing: { a: 1 } } }),
+ ),
+ ).rejects.toThrow('Unknown fixture override');
+
+ const { flowId } = await model.publish(
+ acceptanceId,
+ singleCheckFlow('Billing', checkId, definition, {
+ fixtureData: { account: { plan: 'team' } },
+ }),
+ );
+
+ const run = await model.start(acceptanceId, flowId);
+ const [round] = await db.select().from(verifyRuns).where(eq(verifyRuns.id, run.id));
+ expect(round.plan?.[0].definition?.fixtures?.[0].data).toEqual({ plan: 'team' });
+ });
+});
+
+describe('graph guards on inconsistent rows', () => {
+ it('reports a node that no edge reaches', async () => {
+ const checkId = randomUUID();
+ const { flowId } = await model.publish(
+ acceptanceId,
+ singleCheckFlow('Ready', checkId, { expected: 'Ready' }),
+ );
+ await db.insert(nodes).values({ flowId, criterionId: checkId, isEntry: false });
+
+ await expect(model.list(acceptanceId)).rejects.toThrow('Unreachable nodes');
+ });
+
+ it('stops expanding subflows past eight levels of nesting', async () => {
+ const [leafAsset] = await db
+ .insert(verifyCriteria)
+ .values({
+ userId: owner,
+ title: 'Leaf',
+ definition: { expected: 'Leaf' },
+ verifierType: 'agent',
+ })
+ .returning();
+
+ const flowIds: string[] = [];
+ for (let depth = 0; depth < 10; depth++) {
+ const [flow] = await db
+ .insert(flows)
+ .values({ acceptanceId, title: `Depth ${depth}` })
+ .returning();
+ flowIds.push(flow.id);
+ }
+ for (let depth = 0; depth < flowIds.length; depth++) {
+ const next = flowIds[depth + 1];
+ await db.insert(nodes).values({
+ flowId: flowIds[depth],
+ isEntry: true,
+ ...(next ? { subFlowId: next } : { criterionId: leafAsset.id }),
+ });
+ }
+
+ await expect(model.list(acceptanceId)).rejects.toThrow('Subflow nesting exceeds 8 levels');
+ });
+});
diff --git a/packages/database/src/models/__tests__/userMemoryModelUtils.test.ts b/packages/database/src/models/__tests__/userMemoryModelUtils.test.ts
new file mode 100644
index 00000000000..69e34a747e2
--- /dev/null
+++ b/packages/database/src/models/__tests__/userMemoryModelUtils.test.ts
@@ -0,0 +1,146 @@
+import { describe, expect, it } from 'vitest';
+
+import { verifyCriteria } from '../../schemas/verify';
+import {
+ buildContainsCondition,
+ buildTextSearchCondition,
+ coerceDate,
+ escapeLikePattern,
+ isPGliteDatabase,
+} from '../userMemory/model/utils';
+
+/** Collects the raw strings and bound values out of a drizzle SQL node. */
+const sqlText = (node: unknown) => {
+ const out: string[] = [];
+ const walk = (current: any) => {
+ if (!current || typeof current !== 'object') return;
+ const chunks = current.queryChunks;
+ if (!Array.isArray(chunks)) return;
+ for (const chunk of chunks) {
+ if (typeof chunk === 'string') out.push(chunk);
+ else if (typeof chunk?.value === 'string') out.push(chunk.value);
+ else if (Array.isArray(chunk?.value))
+ out.push(...chunk.value.filter((v: unknown) => typeof v === 'string'));
+ else walk(chunk);
+ }
+ };
+ walk(node);
+ return out.join(' ');
+};
+
+describe('coerceDate', () => {
+ it('returns null for empty and unsupported input', () => {
+ expect(coerceDate(null)).toBeNull();
+ expect(coerceDate(undefined)).toBeNull();
+ expect(coerceDate({})).toBeNull();
+ expect(coerceDate(true)).toBeNull();
+ });
+
+ it('keeps a valid Date and drops an invalid one', () => {
+ const date = new Date('2026-01-02T03:04:05.000Z');
+ expect(coerceDate(date)).toBe(date);
+ expect(coerceDate(new Date('not a date'))).toBeNull();
+ });
+
+ it('parses strings and numbers, rejecting unparsable ones', () => {
+ expect(coerceDate('2026-01-02T03:04:05.000Z')?.toISOString()).toBe('2026-01-02T03:04:05.000Z');
+ expect(coerceDate(0)?.toISOString()).toBe('1970-01-01T00:00:00.000Z');
+ expect(coerceDate('not a date')).toBeNull();
+ expect(coerceDate(Number.NaN)).toBeNull();
+ });
+});
+
+describe('escapeLikePattern', () => {
+ it('escapes backslashes, percent and underscore', () => {
+ expect(escapeLikePattern('50%_off\\now')).toBe('50\\%\\_off\\\\now');
+ });
+});
+
+describe('buildContainsCondition', () => {
+ it('skips blank queries', () => {
+ expect(buildContainsCondition(verifyCriteria.title)).toBeUndefined();
+ expect(buildContainsCondition(verifyCriteria.title, ' ')).toBeUndefined();
+ });
+
+ it('builds an escaped ILIKE condition for a real query', () => {
+ const condition = buildContainsCondition(verifyCriteria.title, ' 100%_done ');
+ expect(condition).toBeDefined();
+ expect(sqlText(condition)).toContain('%100\\%\\_done%');
+ });
+});
+
+describe('isPGliteDatabase', () => {
+ it('detects the pglite client by its waitReady/dataDir pair', () => {
+ expect(isPGliteDatabase({ $client: { dataDir: 'idb://x', waitReady: true } } as never)).toBe(
+ true,
+ );
+ expect(isPGliteDatabase({ $client: { dataDir: 'idb://x' } } as never)).toBe(false);
+ expect(isPGliteDatabase({ $client: { waitReady: true } } as never)).toBe(false);
+ expect(isPGliteDatabase({} as never)).toBe(false);
+ });
+});
+
+describe('buildTextSearchCondition', () => {
+ const groups = [
+ {
+ fallbackColumns: [verifyCriteria.title],
+ fields: ['title'],
+ keyColumn: verifyCriteria.id,
+ },
+ ];
+
+ it('returns undefined without a normalized query', () => {
+ expect(
+ buildTextSearchCondition({
+ bm25MatchQuery: 'plan',
+ groups,
+ normalizedQuery: '',
+ supportsBm25: true,
+ }),
+ ).toBeUndefined();
+ });
+
+ it('builds a bm25 boolean condition when the engine supports it', () => {
+ const condition = buildTextSearchCondition({
+ bm25MatchQuery: 'plan',
+ groups,
+ normalizedQuery: 'plan',
+ supportsBm25: true,
+ });
+ expect(condition).toBeDefined();
+ expect(sqlText(condition)).toContain('paradedb');
+ });
+
+ it('skips bm25 groups without searchable fields', () => {
+ expect(
+ buildTextSearchCondition({
+ bm25MatchQuery: 'plan',
+ groups: [{ ...groups[0], fields: [] }],
+ normalizedQuery: 'plan',
+ supportsBm25: true,
+ }),
+ ).toBeUndefined();
+ });
+
+ it('falls back to contains conditions without bm25 support', () => {
+ const condition = buildTextSearchCondition({
+ bm25MatchQuery: 'plan',
+ groups,
+ normalizedQuery: 'plan',
+ supportsBm25: false,
+ });
+ expect(condition).toBeDefined();
+ expect(sqlText(condition)).toContain('ILIKE');
+ });
+
+ it('returns undefined when no fallback column is searchable', () => {
+ expect(
+ buildTextSearchCondition({
+ bm25MatchQuery: 'plan',
+ groups: [{ ...groups[0], fallbackColumns: [] }],
+ normalizedQuery: 'plan',
+ supportsBm25: false,
+ }),
+ ).toBeUndefined();
+ });
+});
diff --git a/packages/database/src/models/work/__tests__/goalReport.test.ts b/packages/database/src/models/work/__tests__/goalReport.test.ts
new file mode 100644
index 00000000000..ff94249b6a9
--- /dev/null
+++ b/packages/database/src/models/work/__tests__/goalReport.test.ts
@@ -0,0 +1,142 @@
+// @vitest-environment node
+import type { GoalReportMetadata } from '@lobechat/types';
+import { eq, sql } from 'drizzle-orm';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+
+import { works, workVersions } from '../../../schemas';
+import { workspaces } from '../../../schemas/workspace';
+import { WorkModel } from '..';
+import type { WorkContext } from '../context';
+import type { RegisterGoalReportWorkParams } from '../goalReport';
+import { goalReportWorkAdapter } from '../goalReport';
+import type { WorkspaceSummaryQueryRow } from '../internal';
+import {
+ cleanupWorkTestData,
+ seedWorkTestData,
+ serverDB,
+ threadId,
+ topicId,
+ userId,
+} from './_fixtures';
+
+beforeEach(seedWorkTestData);
+afterEach(cleanupWorkTestData);
+
+const goalId = 'goal-report-goal';
+const workspaceId = 'goal-report-workspace';
+
+const metadata: GoalReportMetadata = {
+ chapters: [
+ {
+ detours: [],
+ findingIds: [],
+ narrative: 'Wrapped up the goal',
+ nodeIds: [],
+ title: 'Kickoff',
+ workVersionIds: [],
+ },
+ ],
+ graphCursor: 'goal-event-1',
+ headline: 'Shipped the wrap-up report',
+ nextSteps: [],
+};
+
+const reportParams = (
+ overrides: Partial<RegisterGoalReportWorkParams> = {},
+): RegisterGoalReportWorkParams => ({
+ content: '# Wrap-up\n\nAll done.',
+ goalId,
+ metadata,
+ threadId,
+ title: 'Wrap-up report',
+ toolCallId: 'op:goal-report',
+ toolIdentifier: 'lobe-goal',
+ toolName: 'submitGoalReport',
+ topicId,
+ ...overrides,
+});
+
+describe('WorkModel · goal report', () => {
+ it('writes one personal goal_report Work and hides the page id when there is none', async () => {
+ const model = new WorkModel(serverDB, userId);
+ const work = await model.registerGoalReport(reportParams());
+
+ const [row] = await serverDB.select().from(works).where(eq(works.id, work.id));
+ expect(row).toMatchObject({
+ description: 'Shipped the wrap-up report',
+ resourceId: goalId,
+ resourceType: 'goal_report',
+ title: 'Wrap-up report',
+ visibility: 'private',
+ });
+ const [version] = await serverDB
+ .select()
+ .from(workVersions)
+ .where(eq(workVersions.workId, work.id));
+ expect(version.content).toBe('# Wrap-up\n\nAll done.');
+ expect(version.metadata).toEqual({ goalReport: metadata });
+ });
+
+ it('appends a new version per submission and keeps the page document id', async () => {
+ const model = new WorkModel(serverDB, userId);
+ await model.registerGoalReport(reportParams());
+ await model.registerGoalReport(
+ reportParams({
+ content: '# Wrap-up v2',
+ metadata: { ...metadata, headline: 'Second pass' },
+ pageDocumentId: 'doc-goal-report',
+ title: 'Wrap-up report v2',
+ toolCallId: 'op:goal-report-2',
+ }),
+ );
+
+ const latest = await model.findLatestGoalReport(goalId);
+ expect(latest).toBeDefined();
+ expect(latest!.content).toBe('# Wrap-up v2');
+ expect(latest!.version).toBe(2);
+ expect(latest!.metadata).toEqual({
+ goalReport: { ...metadata, headline: 'Second pass' },
+ goalReportPageId: 'doc-goal-report',
+ });
+
+ const [row] = await serverDB.select().from(works).where(eq(works.id, latest!.workId));
+ expect(row).toMatchObject({ description: 'Second pass', title: 'Wrap-up report v2' });
+ });
+
+ it('publishes a workspace goal report to the whole workspace', async () => {
+ await serverDB.insert(workspaces).values({
+ id: workspaceId,
+ name: 'Report workspace',
+ primaryOwnerId: userId,
+ slug: 'report-ws',
+ });
+
+ const model = new WorkModel(serverDB, userId, workspaceId);
+ const work = await model.registerGoalReport(reportParams());
+
+ const [row] = await serverDB.select().from(works).where(eq(works.id, work.id));
+ expect(row.visibility).toBe('public');
+ expect(row.workspaceId).toBe(workspaceId);
+ });
+
+ it('returns undefined when the goal has no report version', async () => {
+ const model = new WorkModel(serverDB, userId);
+ expect(await model.findLatestGoalReport('goal-without-report')).toBeUndefined();
+ });
+
+ it('keeps the goal report out of the generic Work listings', async () => {
+ const ctx: WorkContext = { db: serverDB, userId };
+
+ expect(
+ await goalReportWorkAdapter.listConversationRows(ctx, {
+ rowLimit: 5,
+ threadFilter: sql`true`,
+ topicId,
+ }),
+ ).toEqual([]);
+ expect(await goalReportWorkAdapter.listVersionEvents(ctx, [], 5)).toEqual([]);
+ expect(() => goalReportWorkAdapter.mapCurrentRow({} as WorkspaceSummaryQueryRow, null)).toThrow(
+ 'goal_report Works are not listed',
+ );
+ });
+});