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

Arvin Xu0de0f5216a3e
diff --git a/packages/database/src/models/__tests__/agentAccount.routingKey.coverage.test.ts b/packages/database/src/models/__tests__/agentAccount.routingKey.coverage.test.ts
new file mode 100644
index 00000000000..f5483d57305
--- /dev/null
+++ b/packages/database/src/models/__tests__/agentAccount.routingKey.coverage.test.ts
@@ -0,0 +1,68 @@
+// @vitest-environment node
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+
+import { getTestDB } from '../../core/getTestDB';
+import { agentAccounts, agents, users } from '../../schemas';
+import type { LobeChatDatabase } from '../../type';
+import { AgentAccountModel } from '../agentAccount';
+
+const serverDB: LobeChatDatabase = await getTestDB();
+const userId = 'agent-account-routing-user';
+const agentId = 'agent-account-routing-agent';
+
+const gateKeeper = {
+ decrypt: async (ciphertext: string) => ({ plaintext: ciphertext }),
+ encrypt: async (plaintext: string) => plaintext,
+};
+
+beforeEach(async () => {
+ await serverDB.insert(users).values({ id: userId });
+ await serverDB.insert(agents).values({ id: agentId, userId });
+});
+
+afterEach(async () => {
+ await serverDB.delete(agentAccounts);
+ await serverDB.delete(agents);
+ await serverDB.delete(users);
+});
+
+const createAccount = async (identifier: string) =>
+ new AgentAccountModel(serverDB, userId, gateKeeper).create({
+ agentId,
+ capabilities: { receive: true, send: true },
+ identifier,
+ kind: 'mail',
+ provider: 'agent-mail',
+ });
+
+describe('AgentAccountModel.isRoutingKeyHeld', () => {
+ it('reports a handle a live account still routes on', async () => {
+ await createAccount('[email protected]');
+
+ expect(await AgentAccountModel.isRoutingKeyHeld(serverDB, 'agent-mail', '[email protected]')).toBe(
+ true,
+ );
+ });
+
+ it('releases the handle once the account is revoked', async () => {
+ const model = new AgentAccountModel(serverDB, userId, gateKeeper);
+ const created = await createAccount('[email protected]');
+
+ await model.revoke(created.id);
+
+ expect(
+ await AgentAccountModel.isRoutingKeyHeld(serverDB, 'agent-mail', '[email protected]'),
+ ).toBe(false);
+ });
+
+ it('reports a handle nobody holds', async () => {
+ expect(await AgentAccountModel.isRoutingKeyHeld(serverDB, 'agent-mail', '[email protected]')).toBe(
+ false,
+ );
+ // Same handle, different provider: the key is the pair.
+ await createAccount('[email protected]');
+ expect(await AgentAccountModel.isRoutingKeyHeld(serverDB, 'other-mail', '[email protected]')).toBe(
+ false,
+ );
+ });
+});
diff --git a/packages/database/src/models/__tests__/canvasFile.coverage.test.ts b/packages/database/src/models/__tests__/canvasFile.coverage.test.ts
index 6e6ebf5ea6d..47338ee634c 100644
--- a/packages/database/src/models/__tests__/canvasFile.coverage.test.ts
+++ b/packages/database/src/models/__tests__/canvasFile.coverage.test.ts
@@ -1,5 +1,6 @@
// @vitest-environment node
-import { eq } from 'drizzle-orm';
+import { FileSource } from '@lobechat/types';
+import { eq, inArray } from 'drizzle-orm';
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
import { getTestDB } from '../../core/getTestDB';
@@ -10,6 +11,7 @@ import { CanvasFileModel } from '../canvasFile';
const serverDB: LobeChatDatabase = await getTestDB();
const userId = 'canvascov-user';
+const otherUserId = 'canvascov-user-2';
const hash = 'canvascov-hash-1';
const blob = {
contentType: 'image/png',
@@ -22,9 +24,9 @@ const blob = {
const cleanup = async () => {
// files cascade from the owning user; `global_files.creator` is NOT NULL with
// ON DELETE SET NULL, so its row has to go first.
- await serverDB.delete(files).where(eq(files.userId, userId));
- await serverDB.delete(globalFiles).where(eq(globalFiles.hashId, hash));
- await serverDB.delete(users).where(eq(users.id, userId));
+ await serverDB.delete(files).where(inArray(files.userId, [userId, otherUserId]));
+ await serverDB.delete(globalFiles).where(inArray(globalFiles.hashId, [hash]));
+ await serverDB.delete(users).where(inArray(users.id, [userId, otherUserId]));
};
describe('CanvasFileModel coverage edges', () => {
@@ -62,4 +64,37 @@ describe('CanvasFileModel coverage edges', () => {
expect(await model.deleteByCanvas('canvas-unknown')).toEqual([]);
expect(await serverDB.select().from(files).where(eq(files.userId, userId))).toHaveLength(1);
});
+
+ it('reports whether the caller still holds files of a canvas', async () => {
+ const model = new CanvasFileModel(serverDB, userId);
+ await model.insertFiles('canvas-1', [blob]);
+
+ expect(await model.hasCanvasFiles('canvas-1')).toBe(true);
+ expect(await model.hasCanvasFiles('canvas-2')).toBe(false);
+ });
+
+ it('does not treat another owner’s canvas files as the caller’s', async () => {
+ await serverDB.insert(users).values({ id: otherUserId });
+ await new CanvasFileModel(serverDB, otherUserId).insertFiles('canvas-shared', [blob]);
+
+ expect(await new CanvasFileModel(serverDB, userId).hasCanvasFiles('canvas-shared')).toBe(false);
+ expect(await new CanvasFileModel(serverDB, otherUserId).hasCanvasFiles('canvas-shared')).toBe(
+ true,
+ );
+ });
+
+ it('ignores files that carry a canvasId but were not stored as canvas files', async () => {
+ await serverDB.insert(files).values({
+ fileHash: hash,
+ fileType: 'image/png',
+ metadata: { canvasId: 'canvas-1' },
+ name: 'page-editor.png',
+ size: 1,
+ source: FileSource.PageEditor,
+ url: 'files/canvascov-page-editor.png',
+ userId,
+ });
+
+ expect(await new CanvasFileModel(serverDB, userId).hasCanvasFiles('canvas-1')).toBe(false);
+ });
});
diff --git a/packages/database/src/models/__tests__/canvasFile.stats.test.ts b/packages/database/src/models/__tests__/canvasFile.stats.test.ts
new file mode 100644
index 00000000000..7c514b3020b
--- /dev/null
+++ b/packages/database/src/models/__tests__/canvasFile.stats.test.ts
@@ -0,0 +1,42 @@
+// @vitest-environment node
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+import { getTestDB } from '../../core/getTestDB';
+import type { LobeChatDatabase } from '../../type';
+import { CanvasFileModel } from '../canvasFile';
+
+const serverDB: LobeChatDatabase = await getTestDB();
+
+const userId = 'canvas-file-stats-user';
+
+afterEach(() => {
+ vi.restoreAllMocks();
+});
+
+describe('CanvasFileModel.summarizeByCanvas', () => {
+ it('reports 0 bytes for a canvas whose rows carry no usable size', async () => {
+ // `files.size` is `notNull`, so `sum(size)` in Postgres returns a number for
+ // every group; a driver that hands back null must still be reported as 0
+ // bytes rather than surfacing null to the canvas list.
+ const orderBy = vi
+ .fn()
+ .mockResolvedValue([
+ { canvasId: 'canvas-without-size', fileCount: 1, totalSize: null, updatedAt: null },
+ ]);
+ vi.spyOn(serverDB, 'select').mockReturnValueOnce({
+ from: () => ({ where: () => ({ groupBy: () => ({ orderBy }) }) }),
+ } as unknown as ReturnType<LobeChatDatabase['select']>);
+
+ const rows = await new CanvasFileModel(serverDB, userId).summarizeByCanvas();
+
+ expect(rows).toEqual([
+ {
+ canvasId: 'canvas-without-size',
+ fileCount: 1,
+ totalSize: 0,
+ updatedAt: null,
+ },
+ ]);
+ expect(orderBy).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/packages/database/src/models/__tests__/favorite.test.ts b/packages/database/src/models/__tests__/favorite.test.ts
index f0beec0527c..c3027d98645 100644
--- a/packages/database/src/models/__tests__/favorite.test.ts
+++ b/packages/database/src/models/__tests__/favorite.test.ts
@@ -163,6 +163,15 @@ describe('FavoriteModel', () => {
expect((await workspaceModel.query()).map((item) => item.id)).toEqual([foreign.id]);
});
+ it('ignores a reorder while this sidebar holds no favorites', async () => {
+ const item = await personalModel.add(topic('tpc_keep'));
+
+ await expect(workspaceModel.reorder([item.id, 'tpc_missing'])).resolves.toBeUndefined();
+
+ expect(await workspaceModel.query()).toEqual([]);
+ expect((await personalModel.query()).map((row) => row.id)).toEqual([item.id]);
+ });
+
it('leaves the scope untouched when it has no favorites to reorder', async () => {
const foreign = await workspaceModel.add(topic('tpc_ws'));
diff --git a/packages/database/src/models/__tests__/goalGraph.findGoalsByTaskIds.test.ts b/packages/database/src/models/__tests__/goalGraph.findGoalsByTaskIds.test.ts
new file mode 100644
index 00000000000..6e68a894e90
--- /dev/null
+++ b/packages/database/src/models/__tests__/goalGraph.findGoalsByTaskIds.test.ts
@@ -0,0 +1,156 @@
+// @vitest-environment node
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+
+import { getTestDB } from '../../core/getTestDB';
+import { users } from '../../schemas';
+import type { LobeChatDatabase } from '../../type';
+import { GoalModel } from '../goal';
+import { GoalGraphModel } from '../goalGraph';
+import { TaskModel } from '../task';
+
+const serverDB: LobeChatDatabase = await getTestDB();
+const userId = 'goal-bulk-user';
+const otherUserId = 'goal-bulk-other';
+
+const goalModel = new GoalModel(serverDB, userId);
+const graphModel = new GoalGraphModel(serverDB, userId);
+const taskModel = new TaskModel(serverDB, userId);
+
+beforeEach(async () => {
+ await serverDB.delete(users);
+ await serverDB.insert(users).values([{ id: userId }, { id: otherUserId }]);
+});
+
+afterEach(async () => {
+ await serverDB.delete(users);
+});
+
+describe('GoalGraphModel.findGoalsByTaskIds', () => {
+ it('asks the database for nothing when it is handed no tasks', async () => {
+ expect(await graphModel.findGoalsByTaskIds([])).toEqual(new Map());
+ });
+
+ it('returns nothing for tasks that no longer exist', async () => {
+ // The ancestor walk yields no row, so the goal query is skipped entirely.
+ expect(await graphModel.findGoalsByTaskIds(['missing-task-id'])).toEqual(new Map());
+ });
+
+ it('maps every task to its nearest goal and leaves tasks without one absent', async () => {
+ const parent = await taskModel.create({ instruction: 'parent' });
+ const child = await taskModel.create({ instruction: 'child', parentTaskId: parent.id });
+ const loose = await taskModel.create({ instruction: 'no goal' });
+
+ // Carried by the parent: one level above the child.
+ const carried = await goalModel.create({
+ createdAt: new Date('2026-01-01T00:00:00Z'),
+ subjectId: parent.id,
+ subjectType: 'task',
+ title: 'Carried by parent',
+ });
+ // Bound to the child itself: depth 0, so it wins over the carried goal.
+ const bound = await goalModel.create({
+ createdAt: new Date('2026-02-01T00:00:00Z'),
+ subjectType: 'standalone',
+ title: 'Bound to child',
+ });
+ const node = await graphModel.createNode(bound.id, { kind: 'task', title: 'Bound' });
+ await graphModel.bindTask(bound.id, node!.id, child.id);
+
+ const goals = await graphModel.findGoalsByTaskIds([child.id, loose.id]);
+
+ expect(goals.get(child.id)).toEqual({
+ id: bound.id,
+ status: bound.status,
+ title: 'Bound to child',
+ });
+ expect(goals.has(loose.id)).toBe(false);
+ expect(goals.size).toBe(1);
+
+ // The parent is its own root: the carried goal sits at depth 0 for it.
+ const forParent = await graphModel.findGoalsByTaskIds([parent.id]);
+ expect(forParent.get(parent.id)).toEqual({
+ id: carried.id,
+ status: carried.status,
+ title: 'Carried by parent',
+ });
+ });
+
+ it('prefers the newest goal when two sit at the same distance', async () => {
+ const task = await taskModel.create({ instruction: 'shared' });
+
+ await goalModel.create({
+ createdAt: new Date('2026-01-01T00:00:00Z'),
+ subjectId: task.id,
+ subjectType: 'task',
+ title: 'Older goal',
+ });
+ const newer = await goalModel.create({
+ createdAt: new Date('2026-02-01T00:00:00Z'),
+ subjectType: 'standalone',
+ title: 'Newer goal',
+ });
+ const node = await graphModel.createNode(newer.id, { kind: 'task', title: 'Shared' });
+ await graphModel.bindTask(newer.id, node!.id, task.id);
+
+ expect((await graphModel.findGoalsByTaskIds([task.id])).get(task.id)?.id).toBe(newer.id);
+ });
+
+ it('replaces a farther goal with a nearer one found later', async () => {
+ const grandparent = await taskModel.create({ instruction: 'grandparent' });
+ const parent = await taskModel.create({ instruction: 'parent', parentTaskId: grandparent.id });
+ const leaf = await taskModel.create({ instruction: 'leaf', parentTaskId: parent.id });
+
+ // Carried two levels above the leaf.
+ await goalModel.create({
+ createdAt: new Date('2026-03-01T00:00:00Z'),
+ subjectId: grandparent.id,
+ subjectType: 'task',
+ title: 'Far but newer',
+ });
+ // Carried one level above the leaf: nearer, even though it is older.
+ const nearer = await goalModel.create({
+ createdAt: new Date('2026-01-01T00:00:00Z'),
+ subjectId: parent.id,
+ subjectType: 'task',
+ title: 'Near but older',
+ });
+
+ const goals = await graphModel.findGoalsByTaskIds([leaf.id]);
+
+ expect(goals.get(leaf.id)?.id).toBe(nearer.id);
+ });
+
+ it('ignores a goal carried by a task outside the walked chain', async () => {
+ const task = await taskModel.create({ instruction: 'bound' });
+ const elsewhere = await taskModel.create({ instruction: 'carrier outside the chain' });
+ // A node binding puts the row in scope; its carrier is not an ancestor of `task`.
+ const goal = await goalModel.create({
+ subjectId: elsewhere.id,
+ subjectType: 'task',
+ title: 'Carried elsewhere',
+ });
+ const node = await graphModel.createNode(goal.id, { kind: 'task', title: 'Bound' });
+ await graphModel.bindTask(goal.id, node!.id, task.id);
+
+ const goals = await graphModel.findGoalsByTaskIds([task.id]);
+
+ expect(goals.get(task.id)?.id).toBe(goal.id);
+ expect(goals.has(elsewhere.id)).toBe(false);
+ });
+
+ it("never reaches another user's goals", async () => {
+ const task = await taskModel.create({ instruction: 'mine' });
+ const otherTask = await new TaskModel(serverDB, otherUserId).create({ instruction: 'theirs' });
+ const otherGoal = await new GoalModel(serverDB, otherUserId).create({
+ subjectId: otherTask.id,
+ subjectType: 'task',
+ title: 'Their goal',
+ });
+
+ const goals = await graphModel.findGoalsByTaskIds([task.id, otherTask.id]);
+
+ expect(goals.has(task.id)).toBe(false);
+ expect(goals.has(otherTask.id)).toBe(false);
+ expect(goals.get(otherTask.id)).not.toMatchObject({ id: otherGoal.id });
+ });
+});
diff --git a/packages/database/src/models/__tests__/goalGraph.renameProblem.coverage.test.ts b/packages/database/src/models/__tests__/goalGraph.renameProblem.coverage.test.ts
new file mode 100644
index 00000000000..6444f53006a
--- /dev/null
+++ b/packages/database/src/models/__tests__/goalGraph.renameProblem.coverage.test.ts
@@ -0,0 +1,78 @@
+// @vitest-environment node
+import { and, eq } from 'drizzle-orm';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+
+import { getTestDB } from '../../core/getTestDB';
+import { goalEvents, users } from '../../schemas';
+import type { LobeChatDatabase } from '../../type';
+import { GoalModel } from '../goal';
+import { GoalGraphModel } from '../goalGraph';
+
+const serverDB: LobeChatDatabase = await getTestDB();
+const userId = 'goal-rename-problem-user';
+const otherUserId = 'goal-rename-problem-other';
+
+const goalModel = new GoalModel(serverDB, userId);
+const graphModel = new GoalGraphModel(serverDB, userId);
+
+beforeEach(async () => {
+ await serverDB.insert(users).values([{ id: userId }, { id: otherUserId }]);
+});
+
+afterEach(async () => {
+ await serverDB.delete(users).where(eq(users.id, userId));
+ await serverDB.delete(users).where(eq(users.id, otherUserId));
+});
+
+/** A standalone goal with its root question seeded from the goal title. */
+const createGoalWithProblem = async (title: string) => {
+ const goal = await goalModel.create({ subjectType: 'standalone', title });
+ const node = await graphModel.createNode(goal.id, { kind: 'problem', title });
+ if (!node) throw new Error('problem node was not created');
+ return { goal, node };
+};
+
+describe('GoalGraphModel.renameProblemNode', () => {
+ it('renames the root question and records an updated event', async () => {
+ const { goal, node } = await createGoalWithProblem('Ship the scheduler');
+
+ const renamed = await graphModel.renameProblemNode(
+ goal.id,
+ 'Ship the scheduler',
+ 'Ship the scheduler with retries',
+ );
+
+ expect(renamed).toMatchObject({ id: node.id, title: 'Ship the scheduler with retries' });
+
+ const events = await serverDB
+ .select()
+ .from(goalEvents)
+ .where(and(eq(goalEvents.goalId, goal.id), eq(goalEvents.eventType, 'updated')));
+ expect(events).toHaveLength(1);
+ expect(events[0]).toMatchObject({
+ entityId: node.id,
+ entityType: 'node',
+ reason: 'Goal renamed',
+ taskId: null,
+ });
+ });
+
+ it('leaves the graph alone when the question no longer carries the old title', async () => {
+ const { goal, node } = await createGoalWithProblem('Ship the scheduler');
+
+ expect(
+ await graphModel.renameProblemNode(goal.id, 'a title it never had', 'ignored'),
+ ).toBeUndefined();
+
+ const events = await serverDB
+ .select()
+ .from(goalEvents)
+ .where(and(eq(goalEvents.goalId, goal.id), eq(goalEvents.eventType, 'updated')));
+ expect(events).toHaveLength(0);
+ expect(node.title).toBe('Ship the scheduler');
+ });
+
+ it('returns undefined for a goal the user does not own', async () => {
+ expect(await graphModel.renameProblemNode('goal-missing', 'from', 'to')).toBeUndefined();
+ });
+});
diff --git a/packages/database/src/models/__tests__/project.coverage.test.ts b/packages/database/src/models/__tests__/project.coverage.test.ts
index 4ca7ffd432e..7a18a141c1c 100644
--- a/packages/database/src/models/__tests__/project.coverage.test.ts
+++ b/packages/database/src/models/__tests__/project.coverage.test.ts
@@ -155,4 +155,58 @@ describe('ProjectModel coverage', () => {
expect(rows?.map((row) => row.id)).toEqual([task.id]);
});
});
+
+ describe('deleteDedicatedCoordinator', () => {
+ /** A coordinator provisioned for one project: virtual and without a slug. */
+ const legacyCoordinator = async (id: string) => {
+ const [agent] = await serverDB
+ .insert(agents)
+ .values({ id, title: 'Legacy coordinator', userId, virtual: true })
+ .returning();
+ return agent;
+ };
+
+ it('takes the virtual coordinator with the project that provisioned it', async () => {
+ const legacy = await legacyCoordinator('t863-legacy-coordinator');
+ const project = await model.create({
+ coordinatorAgentId: legacy.id,
+ identifier: 'LEG01',
+ name: 'Legacy project',
+ });
+
+ await model.delete(project.id);
+
+ expect(await serverDB.select().from(agents).where(eq(agents.id, legacy.id))).toEqual([]);
+ });
+
+ it('keeps a coordinator the user picked, and its sessions with it', async () => {
+ const picked = await new AgentModel(serverDB, userId).create({ title: 'Reusable' });
+ const project = await model.create({
+ coordinatorAgentId: picked.id,
+ identifier: 'LEG02',
+ name: 'Picked project',
+ });
+
+ await model.delete(project.id);
+
+ expect(await serverDB.select().from(agents).where(eq(agents.id, picked.id))).toHaveLength(1);
+ });
+
+ it('does not count the project being handed over as still using the coordinator', async () => {
+ const legacy = await legacyCoordinator('t863-handover-coordinator');
+ const project = await model.create({
+ coordinatorAgentId: legacy.id,
+ identifier: 'LEG03',
+ name: 'Handover project',
+ });
+
+ // The caller asks on behalf of `project` itself, so its own lead and
+ // membership do not make the coordinator look shared.
+ await expect(
+ model.isDedicatedCoordinator(legacy.id, { exceptProjectId: project.id }),
+ ).resolves.toBe(true);
+ // Without the exception the project still holds it.
+ await expect(model.isDedicatedCoordinator(legacy.id)).resolves.toBe(false);
+ });
+ });
});
diff --git a/packages/database/src/models/__tests__/project.mainAgent.test.ts b/packages/database/src/models/__tests__/project.mainAgent.test.ts
index 9536acf1517..2f23c00f5f1 100644
--- a/packages/database/src/models/__tests__/project.mainAgent.test.ts
+++ b/packages/database/src/models/__tests__/project.mainAgent.test.ts
@@ -15,7 +15,8 @@ import { AgentModel } from '../agent';
import { AgentLabelModel } from '../agentLabel';
import type { CreateProjectInput } from '../project';
import { ProjectModel } from '../project';
-import { PROJECT_AGENT_LABEL } from '../projectMainAgent';
+import { createProjectMainAgent, PROJECT_AGENT_LABEL } from '../projectMainAgent';
+import { createProxyTestDB } from './_proxyTestDB';
const serverDB: LobeChatDatabase = await getTestDB();
const userId = 'project-main-agent-user';
@@ -148,4 +149,36 @@ describe('the main agent a project creates', () => {
),
).toEqual([{ accessLevel: 'edit', resourceId: shared.coordinatorAgentId }]);
});
+
+ it('adopts the Project label another project created mid-flight', async () => {
+ // The label exists, but this caller's first lookup runs before it is visible:
+ // the insert then loses the race and has to read the winner's row.
+ await new AgentLabelModel(serverDB, userId).create({ name: PROJECT_AGENT_LABEL });
+ let labelLookups = 0;
+ const proxy = createProxyTestDB(serverDB, (query, result) => {
+ if (query.includes('from "agent_labels"')) {
+ labelLookups += 1;
+ if (labelLookups === 1) return [];
+ }
+ return result.rows;
+ });
+
+ const agent = await createProjectMainAgent(proxy, { userId }, { name: 'Raced' });
+
+ const [label] = await labelsOf(agent.id);
+ expect(label).toMatchObject({ name: PROJECT_AGENT_LABEL });
+ expect(await serverDB.select().from(agentLabels)).toHaveLength(1);
+ });
+
+ it('fails loudly when the Project label can be neither found nor created', async () => {
+ const proxy = createProxyTestDB(serverDB, (query, result) => {
+ if (query.includes('from "agent_labels"')) return [];
+ if (query.startsWith('insert into "agent_labels"')) return [];
+ return result.rows;
+ });
+
+ await expect(createProjectMainAgent(proxy, { userId }, { name: 'Doomed' })).rejects.toThrow(
+ 'Failed to create the project agent label',
+ );
+ });
});
diff --git a/packages/database/src/models/__tests__/signalDecision.edges.test.ts b/packages/database/src/models/__tests__/signalDecision.edges.test.ts
new file mode 100644
index 00000000000..8c25d59bd53
--- /dev/null
+++ b/packages/database/src/models/__tests__/signalDecision.edges.test.ts
@@ -0,0 +1,177 @@
+// @vitest-environment node
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { getTestDB } from '../../core/getTestDB';
+import { agents, users } from '../../schemas';
+import type { LobeChatDatabase } from '../../type';
+import { SignalModel } from '../signal';
+import { SignalDecisionModel } from '../signalDecision';
+
+const serverDB: LobeChatDatabase = await getTestDB();
+
+const userId = 'signal-decision-edges-user';
+const agentId = 'signal-decision-edges-agent';
+const scopeKey = 'discord:app-edges';
+
+let seq = 0;
+
+/**
+ * Records one signal/decision pair for `scopeKey`. `metadata` is what the source
+ * addressed the message to (kept after a purge); `payload` is the content itself.
+ */
+const record = async ({
+ metadata = {},
+ payload = {},
+ outcome = 'wake',
+ reason = 'explicit-mention',
+}: {
+ metadata?: Record<string, unknown>;
+ outcome?: 'defer' | 'skip' | 'wake';
+ payload?: Record<string, unknown>;
+ reason?: string;
+} = {}) => {
+ seq += 1;
+ const signal = (await new SignalModel(serverDB, userId).record({
+ externalId: `edges-${seq}`,
+ metadata,
+ payload,
+ scopeKey,
+ source: 'bot:discord',
+ type: 'bot.message.merged',
+ }))!;
+
+ const decision = (await new SignalDecisionModel(serverDB, userId).record({
+ agentId,
+ finalReason: reason,
+ outcome,
+ pipelineVersion: 'bot-wake@3',
+ scopeKey,
+ signalId: signal.id,
+ }))!;
+
+ return { decision, signal };
+};
+
+beforeEach(async () => {
+ await serverDB.delete(users);
+ await serverDB.insert(users).values([{ id: userId }]);
+ await serverDB.insert(agents).values({ id: agentId, userId });
+});
+
+afterEach(async () => {
+ vi.restoreAllMocks();
+ await serverDB.delete(users);
+});
+
+describe('SignalDecisionModel scope read edges', () => {
+ it('reads a message that carried neither an address nor text', async () => {
+ const { decision } = await record();
+
+ const [item] = (await new SignalDecisionModel(serverDB, userId).listByScope({ scopeKey }))
+ .items;
+
+ expect(item).toMatchObject({
+ address: null,
+ // The payload held no `text` and the signal was never purged: nothing to preview.
+ text: null,
+ textPurged: false,
+ });
+ expect(item.id).toBe(decision.id);
+ });
+
+ it('counts no follow-up wakes when the scope declares no follow-up reasons', async () => {
+ await record({ reason: 'watch-keyword' });
+ await record({ outcome: 'skip', reason: 'not-addressed' });
+
+ const summary = await new SignalDecisionModel(serverDB, userId).summaryByScope({
+ followupReasons: [],
+ labelSources: [],
+ scopeKey,
+ since: new Date(0),
+ });
+
+ expect(summary).toEqual({
+ defer: 0,
+ // A wake whose reason is on no follow-up list is an ordinary wake.
+ followupWakes: 0,
+ labels: {},
+ skip: 1,
+ total: 2,
+ wake: 1,
+ });
+ });
+
+ it('degrades to zeros when the aggregate comes back without a row', async () => {
+ // `count(*)` always yields a row in Postgres, so a driver/result set that
+ // carries none is a defensive case the DB itself cannot produce. Counts must
+ // still read as 0 rather than undefined, and labels must not be queried.
+ const where = vi.fn().mockResolvedValue([]);
+ vi.spyOn(serverDB, 'select').mockReturnValueOnce({
+ from: () => ({ where }),
+ } as unknown as ReturnType<LobeChatDatabase['select']>);
+
+ const summary = await new SignalDecisionModel(serverDB, userId).summaryByScope({
+ followupReasons: ['watch-keyword'],
+ labelSources: ['user'],
+ scopeKey,
+ since: new Date(0),
+ });
+
+ expect(summary).toEqual({
+ defer: 0,
+ followupWakes: 0,
+ labels: {},
+ skip: 0,
+ total: 0,
+ wake: 0,
+ });
+ expect(where).toHaveBeenCalledTimes(1);
+ });
+
+ it('treats a decision row without stored verdicts as no verdicts', async () => {
+ // `verdicts` is `notNull().default([])`, so only a row read from an older
+ // snapshot (or a driver that hands back null) can lack them; the read must
+ // still return the documented empty array.
+ const offset = vi.fn().mockResolvedValue([
+ {
+ address: null,
+ createdAt: new Date(),
+ createdAtIso: '2026-10-30T00:00:00.000000Z',
+ finalReason: 'explicit-mention',
+ id: '11111111-1111-4111-8111-111111111111',
+ outcome: 'wake',
+ purged: false,
+ text: 'hi',
+ toTag: null,
+ verdicts: null,
+ },
+ ]);
+ // The paginated read ends with `.limit(...).offset(...)`, so the mocked
+ // chain has to expose both steps before it is awaited.
+ const limit = vi.fn().mockReturnValue({ offset });
+ vi.spyOn(serverDB, 'select').mockReturnValueOnce({
+ from: () => ({
+ leftJoin: () => ({ where: () => ({ orderBy: () => ({ limit }) }) }),
+ }),
+ } as unknown as ReturnType<LobeChatDatabase['select']>);
+
+ const { items } = await new SignalDecisionModel(serverDB, userId).listByScope({ scopeKey });
+
+ expect(items).toEqual([
+ {
+ address: null,
+ createdAt: expect.any(Date),
+ finalReason: 'explicit-mention',
+ id: '11111111-1111-4111-8111-111111111111',
+ labels: [],
+ outcome: 'wake',
+ text: 'hi',
+ textPurged: false,
+ toTag: null,
+ verdicts: [],
+ },
+ ]);
+ expect(limit).toHaveBeenCalledWith(expect.any(Number));
+ expect(offset).toHaveBeenCalledWith(0);
+ });
+});
diff --git a/packages/database/src/models/__tests__/task.bulk.test.ts b/packages/database/src/models/__tests__/task.bulk.test.ts
index 124d5c41414..e5454d2d7f9 100644
--- a/packages/database/src/models/__tests__/task.bulk.test.ts
+++ b/packages/database/src/models/__tests__/task.bulk.test.ts
@@ -44,6 +44,31 @@ describe('task bulk model methods', () => {
expect(await mine.updateFieldsForIds([], { priority: 1 })).toEqual([]);
});
+ it('updateFieldsForIds rewrites only the configs it was handed, in the same statement', async () => {
+ const { a, b, foreign, mine, theirs } = await setup();
+
+ const updated = await mine.updateFieldsForIds(
+ [a.id, b.id],
+ { priority: 2 },
+ new Map<string, unknown>([
+ [a.id, { repo: 'lobehub/lobehub' }],
+ [b.id, null],
+ // Not part of this edit: its config must not be rewritten.
+ [foreign.id, { repo: 'elsewhere' }],
+ ]),
+ );
+
+ expect(updated.map((task) => task.id).sort()).toEqual([a.id, b.id].sort());
+ expect((await mine.findById(a.id))?.config).toEqual({ repo: 'lobehub/lobehub' });
+ expect((await mine.findById(b.id))?.config).toBeNull();
+ // Untouched: a config for an id outside `ids` never reaches the statement.
+ expect((await theirs.findById(foreign.id))?.config).toEqual({});
+ });
+
+ it('lockForBulkEdit asks the database for nothing when it is handed no ids', async () => {
+ expect(await new TaskModel(serverDB, userId).lockForBulkEdit([])).toEqual([]);
+ });
+
it('lockForBulkEdit returns only owned rows with the columns a bulk edit decides on', async () => {
const { a, foreign, mine } = await setup();
diff --git a/packages/database/src/models/__tests__/taskArchive.test.ts b/packages/database/src/models/__tests__/taskArchive.test.ts
index 74812ba3a69..6661837df39 100644
--- a/packages/database/src/models/__tests__/taskArchive.test.ts
+++ b/packages/database/src/models/__tests__/taskArchive.test.ts
@@ -128,6 +128,13 @@ describe('TaskArchiveModel', () => {
expect(restored?.archivedAt).toBeNull();
});
+ it('unarchives nothing when it is handed no ids', async () => {
+ const model = new TaskArchiveModel(serverDB, userId);
+
+ // No statement to run, so the empty list must not reach the database.
+ expect(await model.unarchiveMany([])).toEqual([]);
+ });
+
it("cannot touch another user's task", async () => {
const task = await new TaskModel(serverDB, otherUserId).create({ instruction: 'Not mine' });
diff --git a/packages/database/src/models/__tests__/taskTree.lockGuards.test.ts b/packages/database/src/models/__tests__/taskTree.lockGuards.test.ts
new file mode 100644
index 00000000000..371bcd31bcd
--- /dev/null
+++ b/packages/database/src/models/__tests__/taskTree.lockGuards.test.ts
@@ -0,0 +1,36 @@
+// @vitest-environment node
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+import { getTestDB } from '../../core/getTestDB';
+import type { LobeChatDatabase } from '../../type';
+import { lockWholeSubtree, takeOverSubtree } from '../task/tree';
+
+const serverDB: LobeChatDatabase = await getTestDB();
+
+const userId = 'task-tree-guards-user';
+
+afterEach(() => {
+ vi.restoreAllMocks();
+});
+
+describe('task subtree helpers without a workspace', () => {
+ it('locks nothing when the subtree lives in personal scope', async () => {
+ // The recursive lock is scoped by `workspace_id`; a personal task has no
+ // subtree to lock and must not fall through to an unscoped `FOR UPDATE`.
+ const execute = vi.spyOn(serverDB, 'execute');
+
+ await expect(
+ lockWholeSubtree({ db: serverDB, userId }, 'task-without-workspace'),
+ ).resolves.toEqual([]);
+
+ expect(execute).not.toHaveBeenCalled();
+ });
+
+ it('is a no-op when there is no subtree to take over', async () => {
+ const update = vi.spyOn(serverDB, 'update');
+
+ await expect(takeOverSubtree({ db: serverDB, userId }, [])).resolves.toBeUndefined();
+
+ expect(update).not.toHaveBeenCalled();
+ });
+});
diff --git a/packages/database/src/models/agentSignal/__tests__/botRetro.test.ts b/packages/database/src/models/agentSignal/__tests__/botRetro.test.ts
index 101fe3b29c1..11f6f9b58f6 100644
--- a/packages/database/src/models/agentSignal/__tests__/botRetro.test.ts
+++ b/packages/database/src/models/agentSignal/__tests__/botRetro.test.ts
@@ -13,6 +13,7 @@ import {
users,
} from '../../../schemas';
import type { LobeChatDatabase } from '../../../type';
+import { createProxyTestDB } from '../../__tests__/_proxyTestDB';
import { AgentBotRetroModel } from '../botRetro';
const serverDB: LobeChatDatabase = await getTestDB();
@@ -175,6 +176,56 @@ describe('AgentBotRetroModel', () => {
expect(topic.failedMessages).toEqual([expect.stringContaining('provider overloaded')]);
});
+ it('keeps a last-activity timestamp the driver hands back as a Date', async () => {
+ await seedBase();
+ await serverDB.insert(messages).values({
+ agentId,
+ content: 'hi',
+ createdAt: inWindow,
+ id: 'm-date',
+ role: 'user',
+ topicId: botTopicId,
+ userId,
+ });
+
+ // The proxy driver parses aggregates through the Postgres type parsers, so
+ // MAX(created_at) arrives as a Date rather than the string a raw `sql` field
+ // normally carries.
+ const proxy = createProxyTestDB(serverDB);
+ const [topic] = await new AgentBotRetroModel(proxy, userId).listBotTopics(window);
+
+ expect(topic.lastActivityAt).toBeInstanceOf(Date);
+ expect(topic.lastActivityAt.toISOString()).toBe(inWindow.toISOString());
+ });
+
+ it('drops a grouped row that comes back without an agent', async () => {
+ await seedBase();
+ await serverDB.insert(messages).values({
+ agentId,
+ content: 'in the agent thread',
+ createdAt: inWindow,
+ id: 'm-agent',
+ role: 'user',
+ topicId: botTopicId,
+ userId,
+ });
+
+ // The INNER JOIN on agents keeps `topics.agent_id` non-null in practice, so
+ // a result set that still hands back none is a defensive case the query
+ // cannot produce; it must not put `null` into the review list.
+ const proxy = createProxyTestDB(serverDB, (query, result) =>
+ query.includes('group by') ? [[null, 1]] : result.rows,
+ );
+
+ await expect(
+ new AgentBotRetroModel(proxy, userId).listBotActiveAgents({
+ limit: 10,
+ windowEnd,
+ windowStart,
+ }),
+ ).resolves.toEqual([]);
+ });
+
it('lists the vent tool calls of the window, rejected ones included', async () => {
await seedBase();
await serverDB.insert(messages).values([
diff --git a/packages/database/src/models/linear/__tests__/syncJob.test.ts b/packages/database/src/models/linear/__tests__/syncJob.test.ts
new file mode 100644
index 00000000000..399b287fd7b
--- /dev/null
+++ b/packages/database/src/models/linear/__tests__/syncJob.test.ts
@@ -0,0 +1,230 @@
+// @vitest-environment node
+import type { LinearSyncJobMetadata } from '@lobechat/types';
+import { AsyncTaskStatus, AsyncTaskType } from '@lobechat/types';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+
+import { getTestDB } from '../../../core/getTestDB';
+import { asyncTasks, users, workspaces } from '../../../schemas';
+import type { LobeChatDatabase } from '../../../type';
+import type { LinearSyncJobRow } from '../syncJob';
+import { LinearSyncJobModel } from '../syncJob';
+
+const db: LobeChatDatabase = await getTestDB();
+
+const userId = 'linear-job-user';
+const otherUserId = 'linear-job-other';
+const workspaceId = 'linear-job-ws';
+const projectId = 'linear-job-project';
+const otherProjectId = 'linear-job-project-2';
+const ruleId = 'linear-job-rule-1';
+
+interface SeedJobParams {
+ createdAt?: Date;
+ projectId?: string;
+ ruleId?: string;
+ status?: AsyncTaskStatus;
+ type?: string;
+ updatedAt?: Date;
+ userId?: string;
+ workspaceId?: string | null;
+}
+
+const seedJob = async (params: SeedJobParams = {}): Promise<LinearSyncJobRow> => {
+ const metadata: LinearSyncJobMetadata = {
+ connectionId: 'linear-job-connection',
+ kind: 'rule',
+ projectId: params.projectId ?? projectId,
+ ...(params.ruleId === undefined ? { ruleId } : { ruleId: params.ruleId }),
+ };
+
+ const [row] = await db
+ .insert(asyncTasks)
+ .values({
+ metadata,
+ status: params.status ?? AsyncTaskStatus.Pending,
+ type: params.type ?? AsyncTaskType.LinearIssueSync,
+ userId: params.userId ?? userId,
+ workspaceId: params.workspaceId ?? null,
+ ...(params.createdAt ? { createdAt: params.createdAt } : {}),
+ ...(params.updatedAt ? { updatedAt: params.updatedAt } : {}),
+ })
+ .returning();
+
+ return row as LinearSyncJobRow;
+};
+
+const personalScope = { userId };
+const workspaceScope = { userId, workspaceId };
+
+beforeEach(async () => {
+ await db.delete(asyncTasks);
+ await db.delete(users);
+
+ await db.insert(users).values([{ id: userId }, { id: otherUserId }]);
+ await db
+ .insert(workspaces)
+ .values({ id: workspaceId, name: 'ws', primaryOwnerId: userId, slug: workspaceId });
+});
+
+afterEach(async () => {
+ await db.delete(asyncTasks);
+ await db.delete(users);
+});
+
+describe('LinearSyncJobModel', () => {
+ describe('listByProject', () => {
+ it('lists the syncs of one project newest first', async () => {
+ const older = await seedJob({ createdAt: new Date('2026-01-01T00:00:00Z') });
+ const newer = await seedJob({ createdAt: new Date('2026-02-01T00:00:00Z') });
+
+ const rows = await LinearSyncJobModel.listByProject(db, personalScope, projectId);
+
+ expect(rows.map((row) => row.id)).toEqual([newer.id, older.id]);
+ });
+
+ it('only lists Linear syncs of that project and scope', async () => {
+ const own = await seedJob();
+ await seedJob({ projectId: otherProjectId });
+ await seedJob({ type: 'embedding' });
+ await seedJob({ userId: otherUserId });
+ await seedJob({ workspaceId });
+
+ const rows = await LinearSyncJobModel.listByProject(db, personalScope, projectId);
+
+ expect(rows.map((row) => row.id)).toEqual([own.id]);
+ });
+
+ it('keeps workspace syncs out of the personal scope', async () => {
+ const workspaceJob = await seedJob({ workspaceId });
+ await seedJob();
+
+ const rows = await LinearSyncJobModel.listByProject(db, workspaceScope, projectId);
+
+ expect(rows.map((row) => row.id)).toEqual([workspaceJob.id]);
+ });
+
+ it('defaults to ten rows and honours an explicit limit', async () => {
+ const createdAt = (day: number) => new Date(`2026-03-${String(day).padStart(2, '0')}Z`);
+ await db.insert(asyncTasks).values(
+ Array.from({ length: 11 }, (_, index) => ({
+ createdAt: createdAt(index + 1),
+ metadata: { connectionId: 'c', kind: 'rule', projectId, ruleId } as LinearSyncJobMetadata,
+ status: AsyncTaskStatus.Pending,
+ type: AsyncTaskType.LinearIssueSync,
+ userId,
+ })),
+ );
+
+ const defaults = await LinearSyncJobModel.listByProject(db, personalScope, projectId);
+ const limited = await LinearSyncJobModel.listByProject(db, personalScope, projectId, 2);
+
+ expect(defaults).toHaveLength(10);
+ expect(defaults[0].createdAt).toEqual(createdAt(11));
+ expect(limited).toHaveLength(2);
+ expect(limited[0].createdAt).toEqual(createdAt(11));
+ });
+ });
+
+ describe('claim', () => {
+ it('moves a pending sync to processing exactly once', async () => {
+ const job = await seedJob();
+
+ const claimed = await LinearSyncJobModel.claim(db, personalScope, job.id);
+ const second = await LinearSyncJobModel.claim(db, personalScope, job.id);
+
+ expect(claimed?.id).toBe(job.id);
+ expect(claimed?.status).toBe(AsyncTaskStatus.Processing);
+ expect(claimed?.metadata.ruleId).toBe(ruleId);
+ expect(second).toBeNull();
+ });
+
+ it('refuses another type, another status, another user or a missing id', async () => {
+ const otherType = await seedJob({ type: 'embedding' });
+ const alreadyDone = await seedJob({ status: AsyncTaskStatus.Success });
+ const foreign = await seedJob({ userId: otherUserId });
+
+ expect(await LinearSyncJobModel.claim(db, personalScope, otherType.id)).toBeNull();
+ expect(await LinearSyncJobModel.claim(db, personalScope, alreadyDone.id)).toBeNull();
+ expect(await LinearSyncJobModel.claim(db, personalScope, foreign.id)).toBeNull();
+ expect(
+ await LinearSyncJobModel.claim(db, personalScope, '00000000-0000-0000-0000-000000000000'),
+ ).toBeNull();
+ });
+ });
+
+ describe('touch', () => {
+ it('bumps the heartbeat of a running sync', async () => {
+ const startedAt = new Date('2026-01-01T00:00:00Z');
+ const job = await seedJob({ status: AsyncTaskStatus.Processing, updatedAt: startedAt });
+
+ await LinearSyncJobModel.touch(db, personalScope, job.id);
+
+ const [updated] = await db.select().from(asyncTasks);
+ expect(updated.updatedAt.getTime()).toBeGreaterThan(startedAt.getTime());
+ });
+
+ it('leaves a finished, foreign or mismatched sync alone', async () => {
+ const startedAt = new Date('2026-01-01T00:00:00Z');
+ const done = await seedJob({ status: AsyncTaskStatus.Success, updatedAt: startedAt });
+ const foreign = await seedJob({
+ status: AsyncTaskStatus.Processing,
+ updatedAt: startedAt,
+ userId: otherUserId,
+ });
+
+ await LinearSyncJobModel.touch(db, personalScope, done.id);
+ await LinearSyncJobModel.touch(db, personalScope, foreign.id);
+
+ const rows = await db.select().from(asyncTasks);
+ expect(rows.map((row) => row.updatedAt.getTime())).toEqual([
+ startedAt.getTime(),
+ startedAt.getTime(),
+ ]);
+ });
+ });
+
+ describe('findActiveForRule', () => {
+ it('returns the newest unfinished run of the rule', async () => {
+ const pending = await seedJob({
+ createdAt: new Date('2026-01-01T00:00:00Z'),
+ status: AsyncTaskStatus.Pending,
+ });
+ const processing = await seedJob({
+ createdAt: new Date('2026-02-01T00:00:00Z'),
+ status: AsyncTaskStatus.Processing,
+ });
+
+ const active = await LinearSyncJobModel.findActiveForRule(
+ db,
+ personalScope,
+ projectId,
+ ruleId,
+ );
+
+ expect(active?.id).toBe(processing.id);
+ expect(active?.id).not.toBe(pending.id);
+ });
+
+ it('ignores finished runs, other rules, projects and users', async () => {
+ await seedJob({ status: AsyncTaskStatus.Success });
+ await seedJob({ ruleId: 'another-rule' });
+ await seedJob({ projectId: otherProjectId });
+ await seedJob({ userId: otherUserId });
+
+ expect(
+ await LinearSyncJobModel.findActiveForRule(db, personalScope, projectId, ruleId),
+ ).toBeNull();
+ });
+
+ it('keeps personal and workspace runs apart', async () => {
+ const workspaceJob = await seedJob({ workspaceId });
+
+ expect(
+ await LinearSyncJobModel.findActiveForRule(db, workspaceScope, projectId, ruleId),
+ ).toMatchObject({ id: workspaceJob.id });
+ expect(
+ await LinearSyncJobModel.findActiveForRule(db, personalScope, projectId, ruleId),
+ ).toBeNull();
+ });
+ });
+});
diff --git a/packages/database/src/models/linear/__tests__/syncJob.transitions.test.ts b/packages/database/src/models/linear/__tests__/syncJob.transitions.test.ts
new file mode 100644
index 00000000000..b008e8c36e3
--- /dev/null
+++ b/packages/database/src/models/linear/__tests__/syncJob.transitions.test.ts
@@ -0,0 +1,152 @@
+// @vitest-environment node
+import { AsyncTaskStatus, AsyncTaskType } from '@lobechat/types';
+import { eq, inArray } from 'drizzle-orm';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+
+import { getTestDB } from '../../../core/getTestDB';
+import { asyncTasks, users, workspaces } from '../../../schemas';
+import type { LobeChatDatabase } from '../../../type';
+import { LinearSyncJobModel } from '../syncJob';
+
+const db: LobeChatDatabase = await getTestDB();
+
+const userId = 'linear-job-transition-user';
+const otherUserId = 'linear-job-transition-other';
+const workspaceId = 'linear-job-transition-ws';
+const projectId = 'linear-job-transition-project';
+const ruleId = 'linear-job-transition-rule';
+
+const personal = { userId };
+const shared = { userId, workspaceId };
+
+/** A Linear sync job in the given status; `kind: 'rule'` is what `cancel` accepts. */
+const job = async (
+ overrides: Partial<typeof asyncTasks.$inferInsert> & {
+ kind?: 'issues' | 'rule';
+ workspace?: boolean;
+ } = {},
+) => {
+ const { kind = 'rule', workspace = false, ...values } = overrides;
+ const [row] = await db
+ .insert(asyncTasks)
+ .values({
+ metadata: { connectionId: 'conn', kind, projectId, ruleId },
+ status: AsyncTaskStatus.Pending,
+ type: AsyncTaskType.LinearIssueSync,
+ userId,
+ workspaceId: workspace ? workspaceId : null,
+ ...values,
+ })
+ .returning();
+ return row;
+};
+
+const statusOf = async (id: string) => {
+ const [row] = await db.select().from(asyncTasks).where(eq(asyncTasks.id, id));
+ return row;
+};
+
+beforeEach(async () => {
+ await db.insert(users).values([{ id: userId }, { id: otherUserId }]);
+ await db
+ .insert(workspaces)
+ .values({ id: workspaceId, name: 'ws', primaryOwnerId: userId, slug: workspaceId });
+});
+
+afterEach(async () => {
+ // Async tasks cascade with their owner and workspace.
+ await db.delete(workspaces).where(inArray(workspaces.id, [workspaceId]));
+ await db.delete(users).where(inArray(users.id, [userId, otherUserId]));
+});
+
+describe('LinearSyncJobModel transitions', () => {
+ it('transitions a job only from the statuses it may leave', async () => {
+ const pending = await job();
+
+ expect(
+ await LinearSyncJobModel.transition(db, personal, pending.id, [AsyncTaskStatus.Pending], {
+ status: AsyncTaskStatus.Processing,
+ }),
+ ).toBe(true);
+ expect((await statusOf(pending.id))?.status).toBe(AsyncTaskStatus.Processing);
+
+ // Already past `pending`: the same transition matches no row.
+ expect(
+ await LinearSyncJobModel.transition(db, personal, pending.id, [AsyncTaskStatus.Pending], {
+ status: AsyncTaskStatus.Processing,
+ }),
+ ).toBe(false);
+ });
+
+ it('will not transition a job that already carries an error', async () => {
+ const failed = await job({ error: { code: 'rate_limited' } });
+
+ expect(
+ await LinearSyncJobModel.transition(db, personal, failed.id, [AsyncTaskStatus.Pending], {
+ status: AsyncTaskStatus.Processing,
+ }),
+ ).toBe(false);
+ expect((await statusOf(failed.id))?.status).toBe(AsyncTaskStatus.Pending);
+ });
+
+ it('transitions a workspace job through the workspace scope', async () => {
+ const pending = await job({ workspace: true });
+
+ expect(
+ await LinearSyncJobModel.transition(db, shared, pending.id, [AsyncTaskStatus.Pending], {
+ duration: 1500,
+ status: AsyncTaskStatus.Success,
+ }),
+ ).toBe(true);
+ expect(await statusOf(pending.id)).toMatchObject({
+ duration: 1500,
+ status: AsyncTaskStatus.Success,
+ });
+ });
+
+ it('settles a stopped run once its round has written what it was writing', async () => {
+ const running = await job({ status: AsyncTaskStatus.Processing });
+
+ expect(await LinearSyncJobModel.cancel(db, personal, projectId, running.id)).toBe(true);
+ // A running rule is only marked as stopping: its round still holds the job.
+ expect(await statusOf(running.id)).toMatchObject({
+ error: { code: 'canceled' },
+ status: AsyncTaskStatus.Processing,
+ });
+
+ await LinearSyncJobModel.settleStopped(db, personal, running.id, { duration: 900 });
+
+ expect(await statusOf(running.id)).toMatchObject({
+ duration: 900,
+ status: AsyncTaskStatus.Error,
+ });
+ });
+
+ it('ends a queued rule run at once when it is stopped', async () => {
+ const queued = await job();
+
+ expect(await LinearSyncJobModel.cancel(db, personal, projectId, queued.id)).toBe(true);
+ expect((await statusOf(queued.id))?.status).toBe(AsyncTaskStatus.Error);
+ });
+
+ it('never cuts short an import of picked issues', async () => {
+ const importRun = await job({ kind: 'issues' });
+
+ expect(await LinearSyncJobModel.cancel(db, personal, projectId, importRun.id)).toBe(false);
+ expect(await statusOf(importRun.id)).toMatchObject({ error: null });
+ });
+
+ it('finds the unfinished run of a rule, and nothing once it ended', async () => {
+ const running = await job({ status: AsyncTaskStatus.Processing });
+
+ expect((await LinearSyncJobModel.findActiveForRule(db, personal, projectId, ruleId))?.id).toBe(
+ running.id,
+ );
+
+ await LinearSyncJobModel.transition(db, personal, running.id, [AsyncTaskStatus.Processing], {
+ status: AsyncTaskStatus.Success,
+ });
+
+ expect(await LinearSyncJobModel.findActiveForRule(db, personal, projectId, ruleId)).toBeNull();
+ });
+});
diff --git a/packages/database/src/models/linear/__tests__/syncRule.test.ts b/packages/database/src/models/linear/__tests__/syncRule.test.ts
new file mode 100644
index 00000000000..c9289d3f1f3
--- /dev/null
+++ b/packages/database/src/models/linear/__tests__/syncRule.test.ts
@@ -0,0 +1,254 @@
+// @vitest-environment node
+import type { LinearSyncResult } from '@lobechat/types';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+
+import { getTestDB } from '../../../core/getTestDB';
+import { linearConnections, linearSyncRules, projects, users, workspaces } from '../../../schemas';
+import type { LobeChatDatabase } from '../../../type';
+import { LinearConnectionModel } from '../connection';
+import { LinearSyncRuleModel } from '../syncRule';
+
+const db: LobeChatDatabase = await getTestDB();
+
+const userId = 'linear-rule-user';
+const otherUserId = 'linear-rule-other';
+const workspaceId = 'linear-rule-ws';
+const projectId = 'linear-rule-project';
+const otherProjectId = 'linear-rule-project-2';
+
+let connectionId: string;
+
+const result: LinearSyncResult = {
+ closed: 1,
+ created: 3,
+ keptLocalEdits: 0,
+ skipped: [{ identifier: 'ACE-9', reason: 'completed' }],
+ truncated: false,
+ unchanged: 2,
+};
+
+interface SeedRuleParams {
+ createdAt?: Date;
+ projectId?: string;
+ teamId?: string;
+ userId?: string;
+ workspaceId?: string | null;
+}
+
+const seedRule = async (params: SeedRuleParams = {}) => {
+ const [row] = await db
+ .insert(linearSyncRules)
+ .values({
+ connectionId,
+ projectId: params.projectId ?? projectId,
+ stateTypes: ['started'],
+ teamId: params.teamId ?? 'team-1',
+ teamName: 'Platform',
+ userId: params.userId ?? userId,
+ workspaceId: params.workspaceId ?? null,
+ ...(params.createdAt ? { createdAt: params.createdAt } : {}),
+ })
+ .returning();
+
+ return row;
+};
+
+const personalScope = { userId };
+const workspaceScope = { userId, workspaceId };
+
+beforeEach(async () => {
+ await db.delete(linearSyncRules);
+ await db.delete(linearConnections);
+ await db.delete(projects);
+ await db.delete(users);
+
+ await db.insert(users).values([{ id: userId }, { id: otherUserId }]);
+ await db
+ .insert(workspaces)
+ .values({ id: workspaceId, name: 'ws', primaryOwnerId: userId, slug: workspaceId });
+ await db.insert(projects).values([
+ { id: projectId, name: 'Rule project', userId },
+ { id: otherProjectId, name: 'Other project', userId },
+ ]);
+
+ const connection = await LinearConnectionModel.upsert(db, {
+ actorExternalId: 'linear-actor',
+ actorName: 'Ada',
+ credentials: { accessToken: 'token' },
+ organizationId: 'org-rule',
+ organizationName: 'Acme',
+ organizationUrlKey: 'acme-rule',
+ userId,
+ });
+ connectionId = connection.id;
+});
+
+afterEach(async () => {
+ await db.delete(linearSyncRules);
+ await db.delete(linearConnections);
+ await db.delete(projects);
+ await db.delete(users);
+});
+
+describe('LinearSyncRuleModel', () => {
+ describe('listByProject', () => {
+ it('lists the personal rules of one project newest first', async () => {
+ const older = await seedRule({ createdAt: new Date('2026-01-01T00:00:00Z') });
+ const newer = await seedRule({
+ createdAt: new Date('2026-02-01T00:00:00Z'),
+ teamId: 'team-2',
+ });
+ await seedRule({ projectId: otherProjectId });
+ await seedRule({ userId: otherUserId });
+
+ const rows = await LinearSyncRuleModel.listByProject(db, personalScope, projectId);
+
+ expect(rows.map((row) => row.id)).toEqual([newer.id, older.id]);
+ });
+
+ it('leaves workspace rules out of the personal scope and vice versa', async () => {
+ const personal = await seedRule();
+ const workspace = await seedRule({ workspaceId });
+
+ const personalRows = await LinearSyncRuleModel.listByProject(db, personalScope, projectId);
+ const workspaceRows = await LinearSyncRuleModel.listByProject(db, workspaceScope, projectId);
+
+ expect(personalRows.map((row) => row.id)).toEqual([personal.id]);
+ expect(workspaceRows.map((row) => row.id)).toEqual([workspace.id]);
+ });
+ });
+
+ describe('findInScope', () => {
+ it('returns the row only inside its own scope', async () => {
+ const personal = await seedRule();
+ const workspace = await seedRule({ workspaceId });
+
+ expect(await LinearSyncRuleModel.findInScope(db, personal.id, personalScope)).toMatchObject({
+ id: personal.id,
+ });
+ expect(await LinearSyncRuleModel.findInScope(db, personal.id, workspaceScope)).toBeNull();
+ expect(await LinearSyncRuleModel.findInScope(db, workspace.id, workspaceScope)).toMatchObject(
+ { id: workspace.id },
+ );
+ expect(await LinearSyncRuleModel.findInScope(db, workspace.id, personalScope)).toBeNull();
+ });
+
+ it('returns null for another user and for an id that does not exist', async () => {
+ const rule = await seedRule();
+
+ expect(
+ await LinearSyncRuleModel.findInScope(db, rule.id, { userId: otherUserId }),
+ ).toBeNull();
+ expect(
+ await LinearSyncRuleModel.findInScope(db, '00000000-0000-0000-0000-000000000000', {
+ userId,
+ }),
+ ).toBeNull();
+ });
+ });
+
+ describe('lockInScope', () => {
+ it('locks the row for the owning scope only', async () => {
+ const rule = await seedRule();
+
+ expect(await LinearSyncRuleModel.lockInScope(db, rule.id, personalScope)).toBe(true);
+ expect(await LinearSyncRuleModel.lockInScope(db, rule.id, { userId: otherUserId })).toBe(
+ false,
+ );
+ expect(
+ await LinearSyncRuleModel.lockInScope(db, '00000000-0000-0000-0000-000000000000', {
+ userId,
+ }),
+ ).toBe(false);
+ });
+ });
+
+ describe('create', () => {
+ it('stores the rule with an empty run history', async () => {
+ const row = await LinearSyncRuleModel.create(db, {
+ connectionId,
+ linearProjectId: 'linear-project-1',
+ linearProjectName: 'Q3 roadmap',
+ projectId,
+ stateTypes: ['started', 'unstarted'],
+ teamId: 'team-9',
+ teamName: 'Runtime',
+ userId,
+ workspaceId: null,
+ });
+
+ expect(row).toMatchObject({
+ lastResult: null,
+ lastRunAt: null,
+ linearProjectName: 'Q3 roadmap',
+ stateTypes: ['started', 'unstarted'],
+ teamName: 'Runtime',
+ workspaceId: null,
+ });
+ });
+ });
+
+ describe('delete', () => {
+ it('deletes only the rule that belongs to the scope', async () => {
+ const own = await seedRule();
+ const foreign = await seedRule({ userId: otherUserId });
+
+ await LinearSyncRuleModel.delete(db, foreign.id, personalScope);
+ await LinearSyncRuleModel.delete(db, own.id, personalScope);
+
+ const remaining = await db.select().from(linearSyncRules);
+ expect(remaining.map((row) => row.id)).toEqual([foreign.id]);
+ });
+ });
+
+ describe('recordRun', () => {
+ it('writes the last result and run time', async () => {
+ const rule = await seedRule();
+
+ await LinearSyncRuleModel.recordRun(db, rule.id, personalScope, result);
+
+ const [updated] = await db.select().from(linearSyncRules);
+ expect(updated.lastResult).toEqual(result);
+ expect(updated.lastRunAt).toBeInstanceOf(Date);
+ });
+
+ it('does not touch a rule outside the scope', async () => {
+ const foreign = await seedRule({ userId: otherUserId });
+
+ await LinearSyncRuleModel.recordRun(db, foreign.id, personalScope, result);
+
+ const [untouched] = await db.select().from(linearSyncRules);
+ expect(untouched.lastResult).toBeNull();
+ expect(untouched.lastRunAt).toBeNull();
+ });
+ });
+
+ describe('toView', () => {
+ it('maps a never-run rule, keeping the null result', async () => {
+ const row = await seedRule();
+
+ expect(LinearSyncRuleModel.toView(row)).toMatchObject({
+ connectionId,
+ lastResult: null,
+ lastRunAt: null,
+ linearProjectId: null,
+ linearProjectName: null,
+ projectId,
+ stateTypes: ['started'],
+ teamId: 'team-1',
+ teamName: 'Platform',
+ });
+ expect(LinearSyncRuleModel.toView(row).createdAt).toEqual(row.createdAt);
+ });
+
+ it('passes the last result through once the rule has run', async () => {
+ const row = await seedRule();
+ await LinearSyncRuleModel.recordRun(db, row.id, personalScope, result);
+
+ const [updated] = await db.select().from(linearSyncRules);
+
+ expect(LinearSyncRuleModel.toView(updated).lastResult).toEqual(result);
+ expect(LinearSyncRuleModel.toView(updated).lastRunAt).toBeInstanceOf(Date);
+ });
+ });
+});
diff --git a/packages/database/src/models/userMemory/__tests__/consolidation.pipeline.coverage.test.ts b/packages/database/src/models/userMemory/__tests__/consolidation.pipeline.coverage.test.ts
new file mode 100644
index 00000000000..a45051bf44c
--- /dev/null
+++ b/packages/database/src/models/userMemory/__tests__/consolidation.pipeline.coverage.test.ts
@@ -0,0 +1,442 @@
+// @vitest-environment node
+import { eq } from 'drizzle-orm';
+import { beforeEach, describe, expect, it } from 'vitest';
+
+import { getTestDB } from '../../../core/getTestDB';
+import {
+ userMemories,
+ userMemoriesActivities,
+ userMemoriesContexts,
+ userMemoriesDossiers,
+ userMemoriesOperations,
+ users,
+} from '../../../schemas';
+import type { LobeChatDatabase } from '../../../type';
+import { listConsolidatedUserIds, UserMemoryConsolidationModel } from '../consolidation';
+
+const userId = 'consolidation-pipeline-user';
+const otherUserId = 'consolidation-pipeline-other';
+const serverDB: LobeChatDatabase = await getTestDB();
+
+let model: UserMemoryConsolidationModel;
+
+/** A legacy per-topic context: parent row + context row linked through `user_memory_ids`. */
+const createLegacy = async (
+ title: string,
+ day: string,
+ {
+ metadata = { sourceId: `tpc_${title}` },
+ owner = userId,
+ }: {
+ metadata?: Record<string, unknown>;
+ owner?: string;
+ } = {},
+) => {
+ const capturedAt = new Date(`${day}T08:00:00.000Z`);
+ const [memory] = await serverDB
+ .insert(userMemories)
+ .values({
+ capturedAt,
+ lastAccessedAt: capturedAt,
+ memoryLayer: 'context',
+ metadata,
+ title: title || null,
+ userId: owner,
+ })
+ .returning();
+ const [context] = await serverDB
+ .insert(userMemoriesContexts)
+ .values({
+ capturedAt,
+ description: title ? `${title} details` : null,
+ title: title || null,
+ userId: owner,
+ userMemoryIds: [memory.id],
+ })
+ .returning();
+ return { context, memory };
+};
+
+/** A minimal plan that files `memberIds` into one dossier of the given title. */
+const planFor = (
+ memberIds: string[],
+ overrides: {
+ dossierTitle?: string;
+ existingContextId?: string;
+ existingDossierId?: string;
+ now?: string;
+ } = {},
+) => ({
+ dossiers: [
+ {
+ existingDossierId: overrides.existingDossierId,
+ memberIds,
+ now: overrides.now ?? 'v1',
+ title: overrides.dossierTitle ?? 'Scheduler',
+ },
+ ],
+ existingContextId: overrides.existingContextId,
+ nextSteps: [],
+ now: overrides.now ?? 'v1',
+ openQuestions: [],
+ title: 'Task system',
+});
+
+beforeEach(async () => {
+ await serverDB.delete(users);
+ await serverDB.insert(users).values([{ id: userId }, { id: otherUserId }]);
+ model = new UserMemoryConsolidationModel(serverDB, userId);
+});
+
+describe('pipeline reads', () => {
+ it('lists every consolidated user once and skips dossiers without an owner', async () => {
+ const mine = await createLegacy('scheduler backend', '2026-05-01');
+ const theirs = await createLegacy('scheduler panel', '2026-05-02', { owner: otherUserId });
+ await new UserMemoryConsolidationModel(serverDB, otherUserId).applyContextPlan(
+ 'run_theirs',
+ planFor([theirs.context.id]),
+ );
+ await model.applyContextPlan('run_mine', planFor([mine.context.id]));
+
+ // A regrouped dossier can lose its owner: it must not show up as a consolidated user.
+ await serverDB.insert(userMemoriesDossiers).values({ title: 'orphan', userId: null });
+
+ const ids = await listConsolidatedUserIds(serverDB);
+ expect(ids).toEqual(expect.arrayContaining([userId, otherUserId]));
+ expect(new Set(ids).size).toBe(ids.length);
+ });
+
+ it('reads legacy rows by id, reporting a missing source id as null', async () => {
+ const withSource = await createLegacy('with source', '2026-05-01');
+ const withoutSource = await createLegacy('no source', '2026-05-02', { metadata: {} });
+
+ expect(await model.getLegacyContextsByIds([])).toEqual([]);
+
+ const items = await model.getLegacyContextsByIds([
+ withSource.context.id,
+ withoutSource.context.id,
+ ]);
+ const byId = new Map(items.map((i) => [i.id, i]));
+ expect(byId.get(withSource.context.id)?.sourceId).toBe('tpc_with source');
+ expect(byId.get(withoutSource.context.id)?.sourceId).toBeNull();
+ });
+
+ it('answers an empty id list for filed contexts without touching the table', async () => {
+ expect(await model.listFiledContextIds('run_any', [])).toEqual([]);
+ });
+
+ it('lists recent evidence titles per dossier, capped and skipping evidence without a title', async () => {
+ const a = await createLegacy('scheduler backend', '2026-05-01');
+ const b = await createLegacy('scheduler panel', '2026-05-02');
+ const untitled = await createLegacy('', '2026-05-03');
+ const filed = await model.applyContextPlan(
+ 'run_titles',
+ planFor([a.context.id, b.context.id, untitled.context.id]),
+ );
+
+ expect(await model.listDossierEvidenceTitles([])).toEqual({});
+
+ const dossierId = filed.dossierIds[0];
+ // The evidence row for an untitled legacy context carries no title, so it is skipped.
+ expect(await model.listDossierEvidenceTitles([dossierId], 1)).toEqual({
+ [dossierId]: ['scheduler panel'],
+ });
+ expect(await model.listDossierEvidenceTitles([dossierId])).toEqual({
+ [dossierId]: ['scheduler panel', 'scheduler backend'],
+ });
+ });
+});
+
+describe('queue reads', () => {
+ it('reports a pending legacy row without a source id as null', async () => {
+ await createLegacy('no source', '2026-05-01', { metadata: {} });
+
+ const [pending] = await model.listPendingLegacyContexts();
+
+ expect(pending.sourceId).toBeNull();
+ });
+
+ it('has no resumable queue before anything was enqueued', async () => {
+ expect(await model.findResumableQueue()).toBeNull();
+ });
+});
+
+describe('queue writes are no-ops without work', () => {
+ it('ignores an empty queue, an empty route map and entries that are no longer legacy', async () => {
+ const a = await createLegacy('scheduler backend', '2026-05-01');
+
+ await expect(model.enqueue('run_empty', [])).resolves.toBeUndefined();
+ await expect(model.markRouted('run_empty', {})).resolves.toBeUndefined();
+
+ await model.enqueue('run_mixed', [
+ { id: a.context.id, key: 'product/tasks', route: 'evidence' },
+ { id: 'memory-missing', key: 'product/tasks', route: 'evidence' },
+ ]);
+ expect((await model.listQueued('run_mixed')).map((q) => q.id)).toEqual([a.context.id]);
+ });
+});
+
+describe('applyContextPlan guards', () => {
+ it('creates fresh rows when the plan points at a context and dossier that are gone', async () => {
+ const a = await createLegacy('scheduler backend', '2026-05-01');
+
+ const result = await model.applyContextPlan(
+ 'run_orphan_targets',
+ planFor([a.context.id], {
+ existingContextId: 'memory-missing-context',
+ existingDossierId: 'memory-missing-dossier',
+ }),
+ );
+
+ expect(result).toMatchObject({
+ contextsCreated: 1,
+ contextsUpdated: 0,
+ dossiersCreated: 1,
+ dossiersUpdated: 0,
+ });
+ const [dossier] = await serverDB
+ .select()
+ .from(userMemoriesDossiers)
+ .where(eq(userMemoriesDossiers.id, result.dossierIds[0]));
+ expect(dossier.contextId).toBe(result.contextId);
+ });
+
+ it('keeps the newest evidence date when a later chunk carries older evidence', async () => {
+ const newer = await createLegacy('scheduler backend', '2026-06-01');
+ const first = await model.applyContextPlan('run_newer', planFor([newer.context.id]));
+ const older = await createLegacy('scheduler panel', '2026-05-01');
+
+ await model.applyContextPlan(
+ 'run_older',
+ planFor([older.context.id], {
+ existingContextId: first.contextId!,
+ existingDossierId: first.dossierIds[0],
+ now: 'v2',
+ }),
+ );
+
+ const [ctx] = await serverDB
+ .select()
+ .from(userMemoriesContexts)
+ .where(eq(userMemoriesContexts.id, first.contextId!));
+ expect(ctx.lastEvidenceAt?.toISOString()).toBe('2026-06-01T08:00:00.000Z');
+
+ const [dossier] = await serverDB
+ .select()
+ .from(userMemoriesDossiers)
+ .where(eq(userMemoriesDossiers.id, first.dossierIds[0]));
+ expect(dossier.lastEvidenceAt?.toISOString()).toBe('2026-06-01T08:00:00.000Z');
+ });
+
+ it('stores a fresh embedding on an existing context', async () => {
+ const a = await createLegacy('scheduler backend', '2026-05-01');
+ const first = await model.applyContextPlan('run_vector_1', planFor([a.context.id]));
+ const b = await createLegacy('scheduler panel', '2026-05-02');
+
+ await model.applyContextPlan('run_vector_2', {
+ ...planFor([b.context.id], {
+ existingContextId: first.contextId!,
+ existingDossierId: first.dossierIds[0],
+ now: 'v2',
+ }),
+ descriptionVector: Array.from({ length: 1024 }, () => 0.02),
+ });
+
+ const [ctx] = await serverDB
+ .select()
+ .from(userMemoriesContexts)
+ .where(eq(userMemoriesContexts.id, first.contextId!));
+ expect(ctx.descriptionVector).toHaveLength(1024);
+ });
+
+ it('extends a synthesized context and dossier that have no parent memory', async () => {
+ const capturedAt = new Date('2026-04-01T08:00:00.000Z');
+ const [orphanMemory] = await serverDB
+ .insert(userMemories)
+ .values({
+ capturedAt,
+ lastAccessedAt: capturedAt,
+ memoryLayer: 'context',
+ title: 'orphan parent',
+ userId,
+ })
+ .returning();
+ // Rows the regroup placed before parents existed: both carry no owning memory.
+ const [context] = await serverDB
+ .insert(userMemoriesContexts)
+ .values({
+ capturedAt,
+ description: 'v1',
+ lastEvidenceAt: capturedAt,
+ now: 'v1',
+ synthesizedAt: capturedAt,
+ title: 'Task system',
+ userId,
+ userMemoryIds: [orphanMemory.id],
+ })
+ .returning();
+ const [dossier] = await serverDB
+ .insert(userMemoriesDossiers)
+ .values({
+ activityCount: 0,
+ contextId: context.id,
+ firstSeenAt: capturedAt,
+ lastEvidenceAt: capturedAt,
+ now: 'v1',
+ status: 'active',
+ summary: 'v1',
+ title: 'Scheduler',
+ userId,
+ })
+ .returning();
+
+ const a = await createLegacy('scheduler backend', '2026-05-01');
+ const b = await createLegacy('scheduler panel', '2026-05-02');
+
+ const result = await model.applyContextPlan('run_no_parents', {
+ dossiers: [
+ {
+ existingDossierId: dossier.id,
+ memberIds: [a.context.id],
+ now: 'group one',
+ title: 'Scheduler',
+ },
+ {
+ existingDossierId: dossier.id,
+ memberIds: [b.context.id],
+ now: 'group two',
+ title: 'Scheduler',
+ },
+ ],
+ existingContextId: context.id,
+ nextSteps: [],
+ now: 'v2',
+ openQuestions: [],
+ title: 'Task system',
+ });
+
+ // Both groups land on the dossier, but only the first logs a before-image.
+ expect(result).toMatchObject({
+ activities: 2,
+ contextsUpdated: 1,
+ dossiersUpdated: 1,
+ });
+ const ops = await serverDB
+ .select()
+ .from(userMemoriesOperations)
+ .where(eq(userMemoriesOperations.userId, userId));
+ expect(ops.filter((o) => o.op === 'status')).toHaveLength(2);
+ });
+
+ it('carries a member source id onto the evidence only when the legacy row had one', async () => {
+ const withSource = await createLegacy('with source', '2026-05-01');
+ const withoutSource = await createLegacy('no source', '2026-05-02', { metadata: {} });
+
+ await model.applyContextPlan(
+ 'run_source_ids',
+ planFor([withSource.context.id, withoutSource.context.id]),
+ );
+
+ const activities = await serverDB
+ .select()
+ .from(userMemoriesActivities)
+ .where(eq(userMemoriesActivities.userId, userId));
+ const byLegacy = new Map(
+ activities.map((a) => [(a.metadata as { legacyContextId?: string })?.legacyContextId, a]),
+ );
+ expect(byLegacy.get(withSource.context.id)?.metadata).toMatchObject({
+ sourceId: 'tpc_with source',
+ });
+ expect(byLegacy.get(withoutSource.context.id)?.metadata).not.toHaveProperty('sourceId');
+ });
+});
+
+describe('revertRun on before-images a stale run left', () => {
+ it('restores a dossier to its defaults and clears the parent summary', async () => {
+ const a = await createLegacy('scheduler backend', '2026-05-01');
+ const seeded = await model.applyContextPlan('run_seed', planFor([a.context.id]));
+ const [ctx] = await serverDB
+ .select()
+ .from(userMemoriesContexts)
+ .where(eq(userMemoriesContexts.id, seeded.contextId!));
+ const [dossier] = await serverDB
+ .select()
+ .from(userMemoriesDossiers)
+ .where(eq(userMemoriesDossiers.id, seeded.dossierIds[0]));
+
+ // An interrupted older run wrote before-images without the parent fields it now records.
+ await serverDB.insert(userMemoriesOperations).values([
+ {
+ actor: 'pipeline',
+ before: { parentSummary: null, userMemoryId: ctx.userMemoryId },
+ gate: 'auto',
+ metadata: { consolidationRunId: 'run_stale' },
+ op: 'status',
+ state: 'applied',
+ targets: { context: ctx.id },
+ userId,
+ },
+ {
+ actor: 'pipeline',
+ before: null,
+ gate: 'auto',
+ metadata: { consolidationRunId: 'run_stale' },
+ op: 'status',
+ state: 'applied',
+ targets: { dossier: dossier.id },
+ userId,
+ },
+ ]);
+
+ expect(await model.revertRun('run_stale')).toEqual({ deleted: 0, restored: 0 });
+
+ const [restoredCtx] = await serverDB
+ .select()
+ .from(userMemoriesContexts)
+ .where(eq(userMemoriesContexts.id, ctx.id));
+ expect(restoredCtx).toMatchObject({
+ currentStatus: null,
+ description: null,
+ lastEvidenceAt: null,
+ nextSteps: null,
+ now: null,
+ openQuestions: null,
+ synthesizedAt: null,
+ });
+
+ const [restoredDossier] = await serverDB
+ .select()
+ .from(userMemoriesDossiers)
+ .where(eq(userMemoriesDossiers.id, dossier.id));
+ expect(restoredDossier).toMatchObject({
+ activityCount: 0,
+ lastEvidenceAt: null,
+ now: null,
+ status: 'active',
+ summary: null,
+ });
+
+ const [parent] = await serverDB
+ .select()
+ .from(userMemories)
+ .where(eq(userMemories.id, ctx.userMemoryId!));
+ expect(parent.summary).toBeNull();
+ });
+
+ it('ignores a status operation that names neither a context nor a dossier', async () => {
+ // revertRun only reads `op = 'status'` rows, which this pipeline writes with a context
+ // or a dossier target. An older or malformed row that names neither must be a no-op.
+ await serverDB.insert(userMemoriesOperations).values({
+ actor: 'pipeline',
+ before: {},
+ gate: 'auto',
+ metadata: { consolidationRunId: 'run_attached_only' },
+ op: 'status',
+ state: 'applied',
+ targets: { activities: ['activity-missing'] },
+ userId,
+ });
+
+ expect(await model.revertRun('run_attached_only')).toEqual({ deleted: 0, restored: 0 });
+ });
+});
diff --git a/packages/database/src/models/userMemory/__tests__/contextStory.sparse.test.ts b/packages/database/src/models/userMemory/__tests__/contextStory.sparse.test.ts
new file mode 100644
index 00000000000..5e9d0605878
--- /dev/null
+++ b/packages/database/src/models/userMemory/__tests__/contextStory.sparse.test.ts
@@ -0,0 +1,178 @@
+// @vitest-environment node
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { getTestDB } from '../../../core/getTestDB';
+import { userMemories, userMemoriesContexts, userMemoriesDossiers, users } from '../../../schemas';
+import type { LobeChatDatabase } from '../../../type';
+import { UserMemoryContextStoryModel } from '../contextStory';
+
+const userId = 'context-story-edges-user';
+const otherUserId = 'context-story-edges-other';
+const serverDB: LobeChatDatabase = await getTestDB();
+
+let model: UserMemoryContextStoryModel;
+
+beforeEach(async () => {
+ await serverDB.delete(users);
+ await serverDB.insert(users).values([{ id: userId }, { id: otherUserId }]);
+ model = new UserMemoryContextStoryModel(serverDB, userId);
+});
+
+/** A context consolidation already synthesized, written directly so the test controls its gaps. */
+const seedStoryContext = async ({
+ day = '2026-05-01',
+ title,
+ withDossier = false,
+}: {
+ day?: string;
+ title: string;
+ withDossier?: boolean;
+}) => {
+ const capturedAt = new Date(`${day}T08:00:00.000Z`);
+ const [memory] = await serverDB
+ .insert(userMemories)
+ .values({
+ capturedAt,
+ lastAccessedAt: capturedAt,
+ memoryLayer: 'context',
+ state: 'active',
+ title,
+ userId,
+ })
+ .returning();
+ const [context] = await serverDB
+ .insert(userMemoriesContexts)
+ .values({
+ capturedAt,
+ // A regroup can leave these unset: the story must not invent a status or a plan.
+ currentStatus: null,
+ description: title,
+ lastEvidenceAt: capturedAt,
+ nextSteps: null,
+ now: title,
+ openQuestions: null,
+ synthesizedAt: capturedAt,
+ title,
+ userId,
+ userMemoryId: memory.id,
+ userMemoryIds: [memory.id],
+ })
+ .returning();
+
+ const dossier = withDossier
+ ? (
+ await serverDB
+ .insert(userMemoriesDossiers)
+ .values({
+ activityCount: 0,
+ contextId: context.id,
+ firstSeenAt: capturedAt,
+ lastEvidenceAt: null,
+ status: 'active',
+ title: `${title} dossier`,
+ userId,
+ })
+ .returning()
+ )[0]
+ : undefined;
+
+ return { context, memory, dossier };
+};
+
+describe('UserMemoryContextStoryModel on sparse stories', () => {
+ it('reads a consolidated context with no dossiers as an empty, closed story', async () => {
+ const { context } = await seedStoryContext({ title: 'Nobody filed evidence' });
+
+ const { stories } = await model.listStories();
+
+ expect(stories).toHaveLength(1);
+ expect(stories[0]).toMatchObject({
+ dossierCount: 0,
+ evidenceCount: 0,
+ nextSteps: [],
+ openQuestions: [],
+ status: 'closed',
+ title: 'Nobody filed evidence',
+ });
+
+ expect(await model.getStory(context.id)).toMatchObject({
+ dossiers: [],
+ dossierCount: 0,
+ evidenceCount: 0,
+ });
+ });
+
+ it('reads a dossier that has no evidence yet with an empty evidence list', async () => {
+ const { context } = await seedStoryContext({ title: 'Evidence pending', withDossier: true });
+
+ const story = await model.getStory(context.id);
+
+ expect(story).toMatchObject({ dossierCount: 1, evidenceCount: 0 });
+ expect(story!.dossiers).toHaveLength(1);
+ expect(story!.dossiers[0]).toMatchObject({ activityCount: 0, evidence: [], status: 'active' });
+ });
+
+ it('skips an evidence row the query could not tie to a dossier', async () => {
+ // The evidence read filters on `dossier_id IN (...)`, so a row without one is a
+ // defensive case the query itself cannot return; the story must not crash on it.
+ const context = {
+ firstSeenAt: null,
+ id: 'ctx_stubbed',
+ lastEvidenceAt: null,
+ nextSteps: [],
+ now: 'v1',
+ openQuestions: [],
+ status: 'active',
+ title: 'Stubbed',
+ };
+ const dossier = {
+ activityCount: 1,
+ firstSeenAt: null,
+ id: 'dossier_stubbed',
+ lastEvidenceAt: null,
+ now: 'v1',
+ status: 'active',
+ title: 'Stubbed dossier',
+ };
+ const select = vi.spyOn(serverDB, 'select');
+ select.mockReturnValueOnce({
+ from: () => ({ innerJoin: () => ({ where: () => ({ limit: async () => [context] }) }) }),
+ } as unknown as ReturnType<LobeChatDatabase['select']>);
+ select.mockReturnValueOnce({
+ from: () => ({ where: () => ({ orderBy: async () => [dossier] }) }),
+ } as unknown as ReturnType<LobeChatDatabase['select']>);
+ select.mockReturnValueOnce({
+ from: () => ({
+ innerJoin: () => ({
+ leftJoin: () => ({
+ where: () => ({
+ orderBy: () => ({ limit: async () => [{ dossierId: null, id: 'x' }] }),
+ }),
+ }),
+ }),
+ }),
+ } as unknown as ReturnType<LobeChatDatabase['select']>);
+
+ const story = await model.getStory('ctx_stubbed');
+
+ expect(story!.dossiers[0].evidence).toEqual([]);
+ select.mockRestore();
+ });
+
+ it('counts no legacy rows when the aggregate comes back without a row', async () => {
+ // `count(*)` always yields a row in Postgres, so an empty result set is a defensive
+ // case; the page must read 0 rather than undefined.
+ const select = vi.spyOn(serverDB, 'select');
+ select.mockReturnValueOnce({
+ from: () => ({
+ innerJoin: () => ({ where: () => ({ limit: () => ({ as: () => 'capped' }) }) }),
+ }),
+ } as unknown as ReturnType<LobeChatDatabase['select']>);
+ select.mockReturnValueOnce({
+ from: async () => [],
+ } as unknown as ReturnType<LobeChatDatabase['select']>);
+
+ expect(await model.countLegacy()).toBe(0);
+ select.mockRestore();
+ });
+});
diff --git a/packages/database/src/models/userMemory/__tests__/where.legacy.test.ts b/packages/database/src/models/userMemory/__tests__/where.legacy.test.ts
new file mode 100644
index 00000000000..11f15835650
--- /dev/null
+++ b/packages/database/src/models/userMemory/__tests__/where.legacy.test.ts
@@ -0,0 +1,57 @@
+// @vitest-environment node
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+
+import { getTestDB } from '../../../core/getTestDB';
+import { userMemories, userMemoriesContexts, users } from '../../../schemas';
+import type { LobeChatDatabase } from '../../../type';
+import { buildUserMemoryWhere } from '../where';
+
+const serverDB: LobeChatDatabase = await getTestDB();
+
+const userId = 'user-memory-where-legacy-user';
+
+/**
+ * The pre-parent shape of a context row: only the legacy `user_memory_ids` list,
+ * no single `user_memory_id` and no soft-delete column of its own. Contexts still
+ * carry both while rows migrate, so the helper has to judge the list on its own.
+ */
+const legacyShape = {
+ userId: userMemoriesContexts.userId,
+ userMemoryIds: userMemoriesContexts.userMemoryIds,
+};
+
+beforeEach(async () => {
+ await serverDB.delete(users);
+ await serverDB.insert(users).values({ id: userId });
+
+ const [live] = await serverDB
+ .insert(userMemories)
+ .values({ lastAccessedAt: new Date(), summary: 'live', userId })
+ .returning();
+ const [trashed] = await serverDB
+ .insert(userMemories)
+ .values({ isDeleted: true, lastAccessedAt: new Date(), summary: 'trashed', userId })
+ .returning();
+
+ await serverDB.insert(userMemoriesContexts).values([
+ { id: 'legacy-live', userId, userMemoryIds: [live.id] },
+ { id: 'legacy-trashed', userId, userMemoryIds: [trashed.id] },
+ { id: 'legacy-standalone', userId, userMemoryIds: [] },
+ ]);
+});
+
+afterEach(async () => {
+ await serverDB.delete(users);
+});
+
+describe('buildUserMemoryWhere on a legacy id-list-only child', () => {
+ it('keeps rows whose listed memories are live and drops the rest', async () => {
+ const rows = await serverDB
+ .select({ id: userMemoriesContexts.id })
+ .from(userMemoriesContexts)
+ .where(buildUserMemoryWhere(serverDB, userId, legacyShape));
+
+ // Standalone rows (empty list) stay: they reference nothing that was trashed.
+ expect(rows.map((row) => row.id).sort()).toEqual(['legacy-live', 'legacy-standalone']);
+ });
+});
diff --git a/packages/database/src/models/userMemory/__tests__/where.noState.test.ts b/packages/database/src/models/userMemory/__tests__/where.noState.test.ts
new file mode 100644
index 00000000000..d206cfcd3c1
--- /dev/null
+++ b/packages/database/src/models/userMemory/__tests__/where.noState.test.ts
@@ -0,0 +1,29 @@
+import { PgDialect } from 'drizzle-orm/pg-core';
+import { describe, expect, it } from 'vitest';
+
+import { getTestDB } from '../../../core/getTestDB';
+import { userMemories } from '../../../schemas';
+import type { LobeChatDatabase } from '../../../type';
+import { buildUserMemoryWhere } from '../where';
+
+const serverDB: LobeChatDatabase = await getTestDB();
+
+const toSql = (table: Parameters<typeof buildUserMemoryWhere>[2]) =>
+ new PgDialect().sqlToQuery(buildUserMemoryWhere(serverDB, 'user-1', table)).sql;
+
+describe('buildUserMemoryWhere for a table without a state column', () => {
+ it('falls back to the trash predicate instead of the visibility one', () => {
+ // Some scoped tables are recycle-bin aware but carry no `state` column; the helper must not
+ // emit a predicate for a column that does not exist.
+ const tableWithoutState = {
+ isDeleted: userMemories.isDeleted,
+ userId: userMemories.userId,
+ } as unknown as Parameters<typeof buildUserMemoryWhere>[2];
+
+ const query = toSql(tableWithoutState);
+
+ expect(query).toContain('"is_deleted" IS NOT TRUE');
+ expect(query).not.toContain('"state"');
+ expect(query).not.toContain('live_user_memories');
+ });
+});
diff --git a/packages/database/src/models/work/__tests__/canvas.test.ts b/packages/database/src/models/work/__tests__/canvas.test.ts
index 17f1d081c01..22aae76ccd6 100644
--- a/packages/database/src/models/work/__tests__/canvas.test.ts
+++ b/packages/database/src/models/work/__tests__/canvas.test.ts
@@ -3,7 +3,7 @@ import type { RegisterCanvasWorkParams } from '@lobechat/types';
import { eq } from 'drizzle-orm';
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
-import { agents, topics, workspaces } from '../../../schemas';
+import { agents, topics, works, workspaces } from '../../../schemas';
import { WorkModel } from '..';
import {
agentId,
@@ -292,6 +292,48 @@ describe('WorkModel · canvas', () => {
});
});
+ it('resolves the canvas id behind a work id, owner only', async () => {
+ const model = new WorkModel(serverDB, userId);
+ const work = await model.registerCanvas(params());
+
+ expect(await model.findCanvasIdByWorkId(work.id)).toBe('cvs_cost');
+ expect(await new WorkModel(serverDB, userId2).findCanvasIdByWorkId(work.id)).toBeNull();
+ expect(await model.findCanvasIdByWorkId('wrk_missing')).toBeNull();
+ });
+
+ it('ignores a work of another type when resolving a canvas id', async () => {
+ const model = new WorkModel(serverDB, userId);
+ await serverDB.insert(works).values({
+ id: 'wrk_task_shaped',
+ resourceId: 'tsk_shaped',
+ resourceType: 'task',
+ toolIdentifier: 'lobe-task',
+ toolName: 'createTask',
+ type: 'task',
+ userId,
+ visibility: 'private',
+ });
+
+ expect(await model.findCanvasIdByWorkId('wrk_task_shaped')).toBeNull();
+ });
+
+ it('skips canvas works that captured no resource id when mapping deployments', async () => {
+ const model = new WorkModel(serverDB, userId);
+ await serverDB.insert(works).values({
+ id: 'wrk_canvas_orphan',
+ metadata: { canvasPublish: { deploymentId: 'dep_orphan', publishedVersion: 1 } },
+ resourceId: null,
+ resourceType: 'canvas',
+ toolIdentifier: 'lobe-canvas',
+ toolName: 'createCanvas',
+ type: 'canvas',
+ userId,
+ visibility: 'private',
+ });
+
+ expect(await model.findCanvasIdsByDeploymentIds(['dep_orphan'])).toEqual({});
+ });
+
it('only surfaces canvas works to clients that opted into newer work types', async () => {
const model = new WorkModel(serverDB, userId);
await model.registerCanvas(params());
diff --git a/packages/database/src/models/work/__tests__/writes.guards.test.ts b/packages/database/src/models/work/__tests__/writes.guards.test.ts
new file mode 100644
index 00000000000..84d16281c80
--- /dev/null
+++ b/packages/database/src/models/work/__tests__/writes.guards.test.ts
@@ -0,0 +1,38 @@
+// @vitest-environment node
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+import { getTestDB } from '../../../core/getTestDB';
+import type { LobeChatDatabase } from '../../../type';
+import { reassignTaskWorksOwner } from '../writes';
+
+const serverDB: LobeChatDatabase = await getTestDB();
+
+const userId = 'work-writes-guards-user';
+
+afterEach(() => {
+ vi.restoreAllMocks();
+});
+
+describe('reassignTaskWorksOwner guards', () => {
+ it('reassigns nothing when the handover carries no task', async () => {
+ const update = vi.spyOn(serverDB, 'update');
+
+ await expect(
+ reassignTaskWorksOwner({ db: serverDB, userId, workspaceId: 'ws-1' }, [], 'previous-owner'),
+ ).resolves.toBeUndefined();
+
+ expect(update).not.toHaveBeenCalled();
+ });
+
+ it('reassigns nothing outside a workspace, where the previous creator is not a known member', async () => {
+ // The caller is authorized on the tasks, not on the previous creator's Work
+ // rows, so an unscoped handover would move rows the caller cannot see.
+ const update = vi.spyOn(serverDB, 'update');
+
+ await expect(
+ reassignTaskWorksOwner({ db: serverDB, userId }, ['task-1'], 'previous-owner'),
+ ).resolves.toBeUndefined();
+
+ expect(update).not.toHaveBeenCalled();
+ });
+});
diff --git a/packages/database/src/server/models/__tests__/user.test.ts b/packages/database/src/server/models/__tests__/user.test.ts
index 61ef0f5e98d..b1a9dc19b1b 100644
--- a/packages/database/src/server/models/__tests__/user.test.ts
+++ b/packages/database/src/server/models/__tests__/user.test.ts
@@ -19,6 +19,12 @@ const userId = 'user-db';
const userEmail = '[email protected]';
const userModel = new UserModel(serverDB, userId);
+// Capture the ambient secret so each test can restore it: assigning `undefined`
+// to `process.env` stores the literal string "undefined", which leaks into the
+// single-worker, non-isolated test process and breaks later KeyVaults consumers
+// (e.g. the OIDC adapter tests) with "must be 16, 24, or 32 bytes".
+const originalKeyVaultsSecret = process.env.KEY_VAULTS_SECRET;
+
beforeEach(async () => {
await serverDB.delete(users);
await serverDB.delete(userSettings);
@@ -28,7 +34,12 @@ beforeEach(async () => {
afterEach(async () => {
await serverDB.delete(users);
await serverDB.delete(userSettings);
- process.env.KEY_VAULTS_SECRET = undefined;
+
+ if (originalKeyVaultsSecret === undefined) {
+ delete process.env.KEY_VAULTS_SECRET;
+ } else {
+ process.env.KEY_VAULTS_SECRET = originalKeyVaultsSecret;
+ }
});
describe('UserModel', () => {