🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
test(database): raise coverage back to 100% (#22219)
Arvin Xub5f82445e803
diff --git a/packages/database/src/models/__tests__/agentOperation.coverage.test.ts b/packages/database/src/models/__tests__/agentOperation.coverage.test.tsindex c6125e6efc0..72ab3c55f43 100644--- a/packages/database/src/models/__tests__/agentOperation.coverage.test.ts+++ b/packages/database/src/models/__tests__/agentOperation.coverage.test.ts@@ -92,4 +92,59 @@ describe('AgentOperationModel coverage', () => {expect(await proxied.getMaxDurationSeconds()).toBe(0);});++ it('retires the abandonment claim without dropping the existing metadata', async () => {+ await model.recordStart({+ metadata: { keep: true },+ operationId: 'op-cov-abandon-finalize',+ });++ await model.markAbandonmentFinalized('op-cov-abandon-finalize');++ const [row] = await serverDB+ .select({ metadata: agentOperations.metadata })+ .from(agentOperations)+ .where(eq(agentOperations.id, 'op-cov-abandon-finalize'));+ expect(row.metadata).toMatchObject({ abandonment: { phase: 'finalized' }, keep: true });+ });++ it('persists the parent hand-off while marking the abandonment as pending', async () => {+ await model.recordStart({+ metadata: { keep: 'value' },+ operationId: 'op-cov-abandon-handoff',+ });++ await model.markAbandonmentHandoffPending('op-cov-abandon-handoff', {+ childOperationId: 'op-cov-abandon-handoff',+ parentOperationId: 'op-cov-parent-handoff',+ });++ const [row] = await serverDB+ .select({ metadata: agentOperations.metadata })+ .from(agentOperations)+ .where(eq(agentOperations.id, 'op-cov-abandon-handoff'));+ const abandonment = (+ row.metadata as { abandonment?: { at?: string; handoff?: unknown; phase?: string } }+ ).abandonment;+ expect(abandonment?.phase).toBe('handoff_pending');+ expect(abandonment?.handoff).toEqual({+ childOperationId: 'op-cov-abandon-handoff',+ parentOperationId: 'op-cov-parent-handoff',+ });+ expect(Number.isNaN(Date.parse(abandonment?.at ?? ''))).toBe(false);+ expect(row.metadata).toMatchObject({ keep: 'value' });+ });++ it('ignores abandonment marks for an operation owned by another user', async () => {+ await model.recordStart({ operationId: 'op-cov-abandon-foreign' });+ const otherModel = new AgentOperationModel(serverDB, 'agent-operation-cov-user-2');++ await otherModel.markAbandonmentFinalized('op-cov-abandon-foreign');++ const [row] = await serverDB+ .select({ metadata: agentOperations.metadata })+ .from(agentOperations)+ .where(eq(agentOperations.id, 'op-cov-abandon-foreign'));+ expect(row.metadata).not.toMatchObject({ abandonment: { phase: 'finalized' } });+ });});diff --git a/packages/database/src/models/__tests__/task.trash.test.ts b/packages/database/src/models/__tests__/task.trash.test.tsnew file mode 100644index 00000000000..dafd9230eb2--- /dev/null+++ b/packages/database/src/models/__tests__/task.trash.test.ts@@ -0,0 +1,182 @@+// @vitest-environment node+import { afterEach, beforeEach, describe, expect, it } from 'vitest';++import { getTestDB } from '../../core/getTestDB';+import { users, workspaces } from '../../schemas';+import type { LobeChatDatabase } from '../../type';+import { TaskModel } from '../task';++const serverDB: LobeChatDatabase = await getTestDB();++const userId = 'task-trash-user';+const otherUserId = 'task-trash-user-2';+const workspaceId = 'task-trash-ws';+const otherWorkspaceId = 'task-trash-ws-2';++const personal = new TaskModel(serverDB, userId);+const workspace = new TaskModel(serverDB, userId, workspaceId);+const member = new TaskModel(serverDB, otherUserId, workspaceId);++const deletedAt = new Date('2026-11-01T00:00:00Z');+const stamp = { deletedAt };++beforeEach(async () => {+ await serverDB.delete(users);+ await serverDB.insert(users).values([{ id: userId }, { id: otherUserId }]);+ await serverDB.insert(workspaces).values([+ { id: workspaceId, name: 'WS', primaryOwnerId: userId, slug: workspaceId },+ { id: otherWorkspaceId, name: 'WS 2', primaryOwnerId: userId, slug: otherWorkspaceId },+ ]);+});++afterEach(async () => {+ await serverDB.delete(users);+});++describe('TaskModel recycle bin', () => {+ describe('softDeleteIfStatusForIds', () => {+ it('stamps only the rows still sitting on the status the caller decided on', async () => {+ const done = await personal.create({ instruction: 'done', status: 'done' });+ const backlog = await personal.create({ instruction: 'backlog' });++ const stamped = await personal.softDeleteIfStatusForIds(+ [+ // `done` moved on since the caller read it, so the compare-and-set loses.+ { id: done.id, status: 'backlog' },+ { id: backlog.id, status: 'backlog' },+ ],+ stamp,+ );++ expect(stamped.map((task) => task.id)).toEqual([backlog.id]);+ expect(stamped[0]).toMatchObject({ deletedAt, isDeleted: true });++ const live = await personal.findById(done.id);+ expect(live?.isDeleted).toBeNull();+ expect(live?.deletedAt).toBeNull();+ });++ it('leaves rows already in the bin alone and is a no-op for an empty list', async () => {+ const task = await personal.create({ instruction: 'a' });+ await personal.softDeleteIfStatusForIds([{ id: task.id, status: 'backlog' }], stamp);++ expect(+ await personal.softDeleteIfStatusForIds([{ id: task.id, status: 'backlog' }], {+ deletedAt: new Date('2026-11-02T00:00:00Z'),+ }),+ ).toEqual([]);+ expect(await personal.softDeleteIfStatusForIds([], stamp)).toEqual([]);++ const [row] = await personal.findTrashedByIds([task.id]);+ // The first stamp wins; the second call never touched the row.+ expect(row).toMatchObject({ deletedAt, isDeleted: true });+ });++ it('never stamps a personal task of another owner', async () => {+ const theirs = await new TaskModel(serverDB, otherUserId).create({ instruction: 'theirs' });++ expect(+ await personal.softDeleteIfStatusForIds([{ id: theirs.id, status: 'backlog' }], stamp),+ ).toEqual([]);+ expect(await new TaskModel(serverDB, otherUserId).findById(theirs.id)).toMatchObject({+ isDeleted: null,+ });+ });++ it("skips a teammate's private task the caller cannot see", async () => {+ const secret = await member.create({ instruction: 'secret', visibility: 'private' });+ const shared = await workspace.create({ instruction: 'shared', visibility: 'public' });++ const stamped = await workspace.softDeleteIfStatusForIds(+ [+ { id: secret.id, status: 'backlog' },+ { id: shared.id, status: 'backlog' },+ ],+ stamp,+ );++ expect(stamped.map((task) => task.id)).toEqual([shared.id]);+ expect(await member.findById(secret.id)).toMatchObject({ isDeleted: null });+ });+ });++ describe('restore', () => {+ it('brings stamped rows back and ignores live ones', async () => {+ const trashed = await personal.create({ instruction: 'trashed' });+ const live = await personal.create({ instruction: 'live' });+ await personal.softDeleteIfStatusForIds([{ id: trashed.id, status: 'backlog' }], stamp);++ const restored = await personal.restore([trashed.id, live.id]);++ expect(restored.map((task) => task.id)).toEqual([trashed.id]);+ expect(restored[0]).toMatchObject({ deletedAt: null, isDeleted: null });+ // A restored row is indistinguishable from one that was never trashed.+ expect(await personal.findById(trashed.id)).toMatchObject({ status: 'backlog' });+ });++ it('is a no-op for an empty list and stays in scope', async () => {+ const theirs = await new TaskModel(serverDB, otherUserId).create({ instruction: 'theirs' });+ await new TaskModel(serverDB, otherUserId).softDeleteIfStatusForIds(+ [{ id: theirs.id, status: 'backlog' }],+ stamp,+ );++ expect(await personal.restore([])).toEqual([]);+ expect(await personal.restore([theirs.id])).toEqual([]);+ expect(await new TaskModel(serverDB, otherUserId).findTrashedIds([theirs.id])).toEqual([+ theirs.id,+ ]);+ });+ });++ describe('findTrashedByIds / findTrashedIds', () => {+ it('reads the bin through the scope without the recycle-bin filter', async () => {+ const trashed = await personal.create({ instruction: 'trashed' });+ const live = await personal.create({ instruction: 'live' });+ await personal.softDeleteIfStatusForIds([{ id: trashed.id, status: 'backlog' }], stamp);++ expect((await personal.findTrashedByIds([trashed.id, live.id])).map((t) => t.id)).toEqual([+ trashed.id,+ ]);+ expect(await personal.findTrashedIds([trashed.id, live.id])).toEqual([trashed.id]);+ expect(await personal.findTrashedByIds([])).toEqual([]);+ expect(await personal.findTrashedIds([])).toEqual([]);+ });++ it('hides a teammate private task from the bin query', async () => {+ const secret = await member.create({ instruction: 'secret', visibility: 'private' });+ await member.softDeleteIfStatusForIds([{ id: secret.id, status: 'backlog' }], stamp);++ expect(await workspace.findTrashedByIds([secret.id])).toEqual([]);+ expect(await workspace.findTrashedIds([secret.id])).toEqual([]);+ expect((await member.findTrashedByIds([secret.id])).map((t) => t.id)).toEqual([secret.id]);+ });+ });++ describe('purge', () => {+ it('hard deletes stamped rows only and reports their ids', async () => {+ const trashed = await personal.create({ instruction: 'trashed' });+ const live = await personal.create({ instruction: 'live' });+ await personal.softDeleteIfStatusForIds([{ id: trashed.id, status: 'backlog' }], stamp);++ expect(await personal.purge([trashed.id, live.id])).toEqual([trashed.id]);+ expect(await personal.findById(trashed.id)).toBeNull();+ expect(await personal.findById(live.id)).toMatchObject({ status: 'backlog' });+ // Purged rows are gone, so a second sweep reports nothing.+ expect(await personal.purge([trashed.id])).toEqual([]);+ expect(await personal.purge([])).toEqual([]);+ });++ it('never purges another scope row', async () => {+ const theirs = await new TaskModel(serverDB, otherUserId).create({ instruction: 'theirs' });+ await new TaskModel(serverDB, otherUserId).softDeleteIfStatusForIds(+ [{ id: theirs.id, status: 'backlog' }],+ stamp,+ );++ expect(await personal.purge([theirs.id])).toEqual([]);+ expect(await personal.purge([])).toEqual([]);+ expect(await new TaskModel(serverDB, otherUserId).findById(theirs.id)).toBeNull();+ });+ });+});diff --git a/packages/database/src/models/__tests__/taskArchive.test.ts b/packages/database/src/models/__tests__/taskArchive.test.tsindex 6661837df39..dd5e9dbd5f4 100644--- a/packages/database/src/models/__tests__/taskArchive.test.ts+++ b/packages/database/src/models/__tests__/taskArchive.test.ts@@ -1,8 +1,10 @@// @vitest-environment node+import { eq, sql } from 'drizzle-orm';import { afterEach, beforeEach, describe, expect, it } from 'vitest';import { getTestDB } from '../../core/getTestDB';import { users } from '../../schemas';+import { tasks as tasksTable } from '../../schemas/task';import type { LobeChatDatabase } from '../../type';import { TaskModel } from '../task';import { TaskArchiveModel } from '../taskArchive';@@ -141,4 +143,26 @@ describe('TaskArchiveModel', () => {expect(await new TaskArchiveModel(serverDB, userId).archive(task.id)).toBeNull();expect(await new TaskArchiveModel(serverDB, userId).unarchive(task.id)).toBeNull();});++ it('restores only the tasks stamped with the given archive time', async () => {+ const tasks = new TaskModel(serverDB, userId);+ const model = new TaskArchiveModel(serverDB, userId);+ // A goal archiving itself passes its own stamp instead of `now()`.+ const goalArchivedAt = sql`'2026-11-01T00:00:00Z'::timestamptz`;+ const withGoal = await tasks.create({ instruction: 'Archived with its goal' });+ const onItsOwn = await tasks.create({ instruction: 'Archived on its own' });++ await model.archiveMany([withGoal.id], { at: goalArchivedAt });+ await model.archive(onItsOwn.id);++ const restored = await model.unarchiveMany([withGoal.id, onItsOwn.id], {+ onlyArchivedAt: goalArchivedAt,+ });++ expect(restored.map((task) => task.id)).toEqual([withGoal.id]);+ expect(restored[0].archivedAt).toBeNull();+ // The task archived on its own keeps its archive.+ const [kept] = await serverDB.select().from(tasksTable).where(eq(tasksTable.id, onItsOwn.id));+ expect(kept.archivedAt).toBeInstanceOf(Date);+ });});diff --git a/packages/database/src/models/__tests__/taskLabel.test.ts b/packages/database/src/models/__tests__/taskLabel.test.tsindex 3d994101fbd..a034148dae7 100644--- a/packages/database/src/models/__tests__/taskLabel.test.ts+++ b/packages/database/src/models/__tests__/taskLabel.test.ts@@ -374,3 +374,119 @@ describe('TaskLabelModel task assignments', () => {expect(links[0].userId).toBe(otherUserId);});});++describe('TaskLabelModel id guards', () => {+ it('treats a malformed id as absent instead of raising a uuid cast error', async () => {+ const label = await workspace.create({ name: 'Bug' });++ expect(await workspace.findById('not-a-uuid')).toBeUndefined();+ expect(await workspace.findByIds(['not-a-uuid'])).toEqual([]);+ await expect(workspace.delete('not-a-uuid')).resolves.toBeUndefined();++ // A mixed list keeps the rows that do resolve.+ expect((await workspace.findByIds([label.id, 'not-a-uuid'])).map((l) => l.id)).toEqual([+ label.id,+ ]);+ expect(await workspace.findByIds([label.id])).toHaveLength(1);+ });++ it('resolves no names when every entry is blank', async () => {+ await workspace.create({ name: 'Bug' });++ expect(await workspace.findByNames(['', ' '])).toEqual([]);+ });++ it('reports a malformed parent id as a missing group', async () => {+ await expectCode(+ workspace.create({ name: 'Orphan', parentId: 'not-a-uuid' }),+ 'INVALID_PARENT',+ );+ });++ it('checks an assignment set without writing anything', async () => {+ const group = await workspace.create({ isGroup: true, name: 'Type' });+ const bug = await workspace.create({ name: 'Bug', parentId: group.id });+ const feature = await workspace.create({ name: 'Feature', parentId: group.id });+ const loose = await workspace.create({ name: 'Loose' });++ await expect(workspace.assertAssignable([loose.id, bug.id])).resolves.toBeUndefined();+ await expectCode(workspace.assertAssignable([group.id]), 'GROUP_NOT_ASSIGNABLE');+ await expectCode(workspace.assertAssignable([bug.id, feature.id]), 'GROUP_CONFLICT');+ });+});++describe('TaskLabelModel sparse updates', () => {+ it('writes a patch without a parent change straight through', async () => {+ const label = await workspace.create({ name: 'Bug' });++ // No `parentId` in the patch: no parent or conflict checks run.+ expect(await workspace.update(label.id, { color: '#123456' })).toMatchObject({+ color: '#123456',+ name: 'Bug',+ });+ // A name-only patch is trimmed and the parent left alone.+ expect(await workspace.update(label.id, { name: ' Bugfix ' })).toMatchObject({+ name: 'Bugfix',+ });+ });++ it('reports a missing label as LABEL_NOT_FOUND', async () => {+ const group = await workspace.create({ isGroup: true, name: 'Type' });+ const label = await workspace.create({ name: 'Bug' });+ await workspace.delete(label.id);++ await expectCode(workspace.update(label.id, { name: 'Gone' }), 'LABEL_NOT_FOUND');+ await expectCode(workspace.update(label.id, { parentId: group.id }), 'LABEL_NOT_FOUND');+ });++ it('reports LABEL_NOT_FOUND when the row vanishes under the lock', async () => {+ const group = await workspace.create({ isGroup: true, name: 'Type' });+ const label = await workspace.create({ name: 'Bug' });+ const snapshot = await workspace.findById(label.id);++ // A writer that already read the label, which another request then deletes.+ const racy = new TaskLabelModel(serverDB, userId, workspaceId);+ racy.findById = async () => snapshot;+ await workspace.delete(label.id);++ await expectCode(racy.update(label.id, { parentId: group.id }), 'LABEL_NOT_FOUND');+ });++ it('writes a move to the parent the label already sits in without a conflict check', async () => {+ const group = await workspace.create({ isGroup: true, name: 'Type' });+ const label = await workspace.create({ name: 'Bug', parentId: group.id });++ expect(await workspace.update(label.id, { parentId: group.id })).toMatchObject({+ parentId: group.id,+ });+ });++ it('returns the current set for an empty label list', async () => {+ const task = await new TaskModel(serverDB, userId, workspaceId).create({ instruction: 'a' });+ const label = await workspace.create({ name: 'Bug' });+ await workspace.addTaskLabels(task.id, [label.id]);++ expect(await workspace.getLabelsForTasks([])).toEqual({});+ expect((await workspace.addTaskLabels(task.id, [])).map((l) => l.id)).toEqual([label.id]);+ });+});++describe('TaskLabelModel personal handover', () => {+ it('keeps label links on a same-owner move and drops them for another owner', async () => {+ const personalTasks = new TaskModel(serverDB, userId);+ const toSameOwner = await personalTasks.create({ instruction: 'same owner' });+ const toAnotherOwner = await personalTasks.create({ instruction: 'another owner' });+ const label = await personal.create({ name: 'Mine' });+ await personal.addTaskLabels(toSameOwner.id, [label.id]);+ await personal.addTaskLabels(toAnotherOwner.id, [label.id]);++ // A personal label registry is not visible to another user, so only the+ // same-owner handover can keep its links.+ await personalTasks.transferTo(toSameOwner.id, null, userId);+ await personalTasks.transferTo(toAnotherOwner.id, null, otherUserId);++ const links = await serverDB.select().from(taskLabelLinks);+ expect(links.map((link) => link.taskId)).toEqual([toSameOwner.id]);+ expect(links[0].userId).toBe(userId);+ });+});diff --git a/packages/database/src/models/__tests__/topicAnalysis.test.ts b/packages/database/src/models/__tests__/topicAnalysis.test.tsindex 7b3856d091e..3c58f0c2271 100644--- a/packages/database/src/models/__tests__/topicAnalysis.test.ts+++ b/packages/database/src/models/__tests__/topicAnalysis.test.ts@@ -96,6 +96,27 @@ describe('TopicAnalysisModel', () => {expect(row?.lastMessageUpdatedAt?.toISOString()).toBe('2026-10-30T10:00:00.000Z');});+ it('stores nulls when the optional classification fields are omitted', async () => {+ await personalModel.save({+ ...snapshot,+ result: {+ category: 'coding',+ model: 'model-a',+ provider: 'provider-a',+ taxonomyVersion: 'v1',+ },+ topicId,+ });++ expect(await personalModel.findByTopic(topicId, 'v1')).toMatchObject({+ intent: null,+ labels: null,+ metadata: null,+ outcome: null,+ secondaryCategory: null,+ });+ });+it('replaces the analysis for the same taxonomy version instead of duplicating it', async () => {await addNewerMessage();await personalModel.save({ ...snapshot, result: result(), topicId });@@ -255,6 +276,10 @@ describe('TopicAnalysisModel', () => {});});+ it('returns undefined when the topic no longer exists', async () => {+ expect(await personalModel.snapshotTopicUsage('tpc_missing')).toBeUndefined();+ });+it('stores the snapshot with the analysis', async () => {const usage = {assistantMessages: 4,diff --git a/packages/database/src/models/__tests__/trash.coverage.test.ts b/packages/database/src/models/__tests__/trash.coverage.test.tsindex f17eb110cd2..821c029ab65 100644--- a/packages/database/src/models/__tests__/trash.coverage.test.ts+++ b/packages/database/src/models/__tests__/trash.coverage.test.ts@@ -66,4 +66,56 @@ describe('TrashModel coverage', () => {expect(await model.findPrivateIds([root.id])).toEqual(new Set());});});++ describe('findRootsByResources', () => {+ it('returns only the registered roots of one kind for the given resource ids', async () => {+ const model = new TrashModel(serverDB, userId, workspaceId);+ await serverDB+ .insert(agents)+ .values({ id: 'trc-roots-agent', userId, visibility: 'public', workspaceId });++ const root = await model.register({+ children: [+ { meta: {}, projectId: null, resourceId: 'trc-roots-topic', resourceType: 'topic' },+ ],+ deletedAt: new Date('2026-08-01T00:00:00Z'),+ root: {+ meta: {},+ projectId: null,+ resourceId: 'trc-roots-agent',+ resourceType: 'agent',+ },+ });++ // The cascaded child carries a `rootId`, so it never matches as a root.+ expect(+ (await model.findRootsByResources('agent', ['trc-roots-agent', 'trc-roots-topic'])).map(+ (row) => row.id,+ ),+ ).toEqual([root.id]);+ // Another kind with the same ids resolves to nothing.+ expect(await model.findRootsByResources('topic', ['trc-roots-agent'])).toEqual([]);+ expect(await model.findRootsByResources('agent', [])).toEqual([]);+ });++ it('stays inside the bin scope it was opened on', async () => {+ const otherWorkspace = 'trash-coverage-ws-2';+ await serverDB.insert(workspaces).values({+ id: otherWorkspace,+ name: 'Trash coverage 2',+ primaryOwnerId: userId,+ slug: otherWorkspace,+ });+ const mine = new TrashModel(serverDB, userId, workspaceId);+ const theirs = new TrashModel(serverDB, userId, otherWorkspace);++ await mine.register({+ deletedAt: new Date('2026-08-01T00:00:00Z'),+ root: { meta: {}, projectId: null, resourceId: 'trc-scope-task', resourceType: 'task' },+ });++ expect(await theirs.findRootsByResources('task', ['trc-scope-task'])).toEqual([]);+ expect(await mine.findRootsByResources('task', ['trc-scope-task'])).toHaveLength(1);+ });+ });});