🤯 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% (#23320)
Arvin Xue2b3a236d2fe
diff --git a/packages/database/src/models/__tests__/agentOperation.dispatch.test.ts b/packages/database/src/models/__tests__/agentOperation.dispatch.test.tsindex 73181c205ad..7e2ced9675c 100644--- a/packages/database/src/models/__tests__/agentOperation.dispatch.test.ts+++ b/packages/database/src/models/__tests__/agentOperation.dispatch.test.ts@@ -79,3 +79,33 @@ describe('failed dispatch recovery boundary', () => {expect([attempt !== null, settled].filter(Boolean)).toHaveLength(1);});});++describe('trusted dispatch consumes an idle reservation', () => {+ it('starts an idle operation and merges the run metadata into it', async () => {+ await db.insert(agentOperations).values({ id: 'reserved-1', status: 'idle', userId });++ await model().recordStart({+ metadata: { agentSignal: { runId: 'run-1' } },+ operationId: 'reserved-1',+ requireReservation: true,+ trigger: 'agent',+ });++ expect(await model().findById('reserved-1')).toMatchObject({+ metadata: { agentSignal: { runId: 'run-1' } },+ status: 'running',+ });+ });++ it('refuses a reservation that was already consumed', async () => {+ await db.insert(agentOperations).values({ id: 'reserved-2', status: 'running', userId });++ await expect(+ model().recordStart({+ operationId: 'reserved-2',+ requireReservation: true,+ trigger: 'agent',+ }),+ ).rejects.toThrow('Operation reservation is no longer available');+ });+});diff --git a/packages/database/src/models/__tests__/connector.refreshLock.test.ts b/packages/database/src/models/__tests__/connector.refreshLock.test.tsnew file mode 100644index 00000000000..2d3c1b56905--- /dev/null+++ b/packages/database/src/models/__tests__/connector.refreshLock.test.ts@@ -0,0 +1,88 @@+// @vitest-environment node+import { eq } from 'drizzle-orm';+import { afterEach, beforeEach, describe, expect, it } from 'vitest';++import { getTestDB } from '../../core/getTestDB';+import { userConnectors, users, workspaces } from '../../schemas';+import type { LobeChatDatabase } from '../../type';+import { ConnectorModel } from '../connector';+import { ConnectorLinkModel } from '../connectorLink';++const serverDB: LobeChatDatabase = await getTestDB();++const userId = 'conn-refresh-user';+const workspaceId = 'conn-refresh-ws';+const missingId = '00000000-0000-4000-8000-000000000001';+const base = { name: 'Connector', sourceType: 'builtin', status: 'connected' } as const;++const cleanup = async () => {+ await serverDB.delete(users).where(eq(users.id, userId));+ await serverDB.delete(workspaces).where(eq(workspaces.id, workspaceId));+};++beforeEach(async () => {+ await cleanup();+ await serverDB.insert(users).values({ id: userId });+ await serverDB+ .insert(workspaces)+ .values({ id: workspaceId, name: 'Refresh', primaryOwnerId: userId, slug: workspaceId });+});++afterEach(async () => {+ await cleanup();+});++describe('ConnectorModel refresh lock', () => {+ it('hands out a link model for the same identity', () => {+ const model = new ConnectorModel(serverDB, userId);++ expect(model.getLinkModel()).toBeInstanceOf(ConnectorLinkModel);+ });++ it('runs the action under a row lock on the personal connector', async () => {+ const model = new ConnectorModel(serverDB, userId);+ const created = await model.create({ ...base, identifier: 'refresh-1' });++ const seen: string[] = [];+ const result = await model.withOAuthRefreshLock(+ { id: created.id, workspaceId: null },+ async (row, locked) => {+ seen.push(row.id);+ await locked.update(created.id, { name: 'Renamed' });+ return 'refreshed';+ },+ );++ expect(result).toBe('refreshed');+ expect(seen).toEqual([created.id]);+ // The write made inside the lock landed with the refresh.+ const [row] = await serverDB+ .select({ name: userConnectors.name })+ .from(userConnectors)+ .where(eq(userConnectors.id, created.id));+ expect(row.name).toBe('Renamed');+ });++ it('answers undefined when the connector is gone', async () => {+ const model = new ConnectorModel(serverDB, userId);++ expect(+ await model.withOAuthRefreshLock({ id: missingId, workspaceId: null }, async () => 'never'),+ ).toBeUndefined();+ });++ it('keeps a workspace connector in the workspace scope', async () => {+ const [row] = await serverDB+ .insert(userConnectors)+ .values({ ...base, identifier: 'refresh-ws', userId, workspaceId })+ .returning();+ const model = new ConnectorModel(serverDB, userId, workspaceId);++ const result = await model.withOAuthRefreshLock({ id: row.id, workspaceId }, async (locked) => {+ expect(locked.workspaceId).toBe(workspaceId);+ return 'ok';+ });++ expect(result).toBe('ok');+ });+});diff --git a/packages/database/src/models/__tests__/contact.test.ts b/packages/database/src/models/__tests__/contact.test.tsindex 06338f61f9f..b63763e151a 100644--- a/packages/database/src/models/__tests__/contact.test.ts+++ b/packages/database/src/models/__tests__/contact.test.ts@@ -537,3 +537,39 @@ describe('contact edge cases', () => {expect(own).toMatchObject({ agent: { agentId: aliceAgent }, relation: 'self', type: 'agent' });});});++describe('answering an invitation after the caller joined', () => {+ it('refuses the invitation once the invitee is already a member', async () => {+ const { requestId } = await aliceInTeam.sendRequest(bob, 'Join us');+ // Bob became a member by another route before answering, so the invitation is moot.+ await serverDB+ .insert(workspaceMembers)+ .values({ role: 'member', userId: bob, workspaceId: teamId });++ await expect(bobInTeam().acceptRequest(requestId)).rejects.toThrow(+ 'Already a member of this workspace',+ );+ });++ it('only a member of the workspace may open themselves to an external contact', async () => {+ // In the personal space there is nothing to open: the caller is not a member of a team.+ await expect(aliceModel.openTo(bob)).rejects.toThrow('Only members open themselves');+ });++ it('refuses an invitation whose sender is no longer a member', async () => {+ const { requestId } = await aliceInTeam.sendRequest(bob, 'Join us');+ await serverDB.delete(workspaceMembers).where(eq(workspaceMembers.userId, alice));++ await expect(bobModel.acceptRequest(requestId)).rejects.toThrow('Request not found');+ });+});++describe('removing an external contact who is not one', () => {+ it('refuses a member, and a person the workspace never paired', async () => {+ // Carol is a member of the team, not an external contact.+ await expect(aliceInTeam.removeExternal(carol)).rejects.toThrow('External contact not found');+ await expect(aliceInTeam.removeExternal('contact-test-missing')).rejects.toThrow(+ 'External contact not found',+ );+ });+});diff --git a/packages/database/src/models/__tests__/messages/message.pluginLookup.test.ts b/packages/database/src/models/__tests__/messages/message.pluginLookup.test.tsindex 6d08c9c4645..958bdfeb464 100644--- a/packages/database/src/models/__tests__/messages/message.pluginLookup.test.ts+++ b/packages/database/src/models/__tests__/messages/message.pluginLookup.test.ts@@ -492,3 +492,41 @@ describe('MessageModel.findToolMessageIdByToolCallId', () => {await expect(messageModel.findToolMessageIdByToolCallId('call-other')).resolves.toBeNull();});});++describe('MessageModel.listToolCallIndexByTopic', () => {+ it('carries the run metadata and leaves absent columns undefined', async () => {+ await seedToolMessage({+ id: 'idx-full',+ identifier: 'lobe-tool',+ metadata: {+ heterogeneousToolStateOperationId: 'op-hetero',+ heterogeneousToolStateSeq: 4,+ operationId: 'op-run',+ },+ state: { answer_render: 'streaming' },+ });+ // A row with no api name, no identifier and no intervention state at all.+ await seedToolMessage({ id: 'idx-bare' });+ await serverDB+ .update(messagePlugins)+ .set({ apiName: null, identifier: null })+ .where(eq(messagePlugins.id, 'idx-bare'));++ const rows = await messageModel.listToolCallIndexByTopic('plugin-topic', {+ interventionStateKey: 'answer_render',+ });+ const full = rows.find((row) => row.id === 'idx-full');+ const bare = rows.find((row) => row.id === 'idx-bare');++ expect(full?.metadata).toMatchObject({+ heterogeneousToolStateOperationId: 'op-hetero',+ heterogeneousToolStateSeq: 4,+ operationId: 'op-run',+ });+ expect(full?.state).toEqual({ answer_render: 'streaming' });+ expect(bare?.apiName).toBeUndefined();+ expect(bare?.identifier).toBeUndefined();+ expect(bare?.state).toBeUndefined();+ expect(bare?.metadata).toEqual({});+ });+});diff --git a/packages/database/src/models/__tests__/topics/topic.finishWorktreeStart.test.ts b/packages/database/src/models/__tests__/topics/topic.finishWorktreeStart.test.tsnew file mode 100644index 00000000000..723de395b07--- /dev/null+++ b/packages/database/src/models/__tests__/topics/topic.finishWorktreeStart.test.ts@@ -0,0 +1,219 @@+// @vitest-environment node+import type { ChatTopicMetadata, TopicScheduledRun } from '@lobechat/types';+import { eq, inArray } from 'drizzle-orm';+import { afterEach, beforeEach, describe, expect, it } from 'vitest';++import { getTestDB } from '../../../core/getTestDB';+import { topics, users } from '../../../schemas';+import type { LobeChatDatabase } from '../../../type';+import { TopicModel } from '../../topic';++const serverDB: LobeChatDatabase = await getTestDB();++const userId = 'topic-finish-wt-user';++const insert = (+ id: string,+ metadata: ChatTopicMetadata,+ extra: { isDeleted?: boolean; status?: 'active' | 'completed' | 'scheduled' } = {},+) =>+ serverDB.insert(topics).values({+ id,+ isDeleted: extra.isDeleted ?? null,+ deletedAt: extra.isDeleted ? new Date() : null,+ metadata,+ status: extra.status ?? 'scheduled',+ userId,+ });++const readTopic = async (id: string) =>+ (await serverDB.select().from(topics).where(eq(topics.id, id)))[0];++const worktreeStartRun = (claimId = 'claim-1'): TopicScheduledRun =>+ ({+ claim: {+ claimedAt: '2026-11-16T00:00:00.000Z',+ expiresAt: '2026-11-16T00:05:00.000Z',+ id: claimId,+ },+ createdAt: '2026-11-16T00:00:00.000Z',+ kind: 'worktree_start',+ operationId: 'op-1',+ runAt: '2026-11-16T00:00:00.000Z',+ updatedAt: '2026-11-16T00:00:00.000Z',+ userMessageId: 'msg-1',+ }) as TopicScheduledRun;++const finish = (+ id: string,+ claimId: string,+ result: { error?: string; retryAt?: string; retryable?: boolean; success: boolean },+) => TopicModel.finishWorktreeStart(serverDB, id, claimId, result);++beforeEach(async () => {+ await serverDB.insert(users).values([{ id: userId }]);+});++afterEach(async () => {+ await serverDB.delete(users).where(inArray(users.id, [userId]));+});++describe('TopicModel.finishWorktreeStart', () => {+ it('does nothing for a missing topic, a stale claim, or another kind of run', async () => {+ await finish('missing', 'claim-1', { success: true });+ expect(await readTopic('missing')).toBeUndefined();++ await insert('t-stale', { scheduledRun: worktreeStartRun('claim-1') });+ await finish('t-stale', 'claim-2', { success: true });+ expect((await readTopic('t-stale'))?.status).toBe('scheduled');+ expect((await readTopic('t-stale'))?.metadata?.scheduledRun?.kind).toBe('worktree_start');++ const delayedStart = {+ ...worktreeStartRun('claim-1'),+ kind: 'delayed_start',+ } as TopicScheduledRun;+ await insert('t-delayed', { scheduledRun: delayedStart });+ await finish('t-delayed', 'claim-1', { success: true });+ expect((await readTopic('t-delayed'))?.status).toBe('scheduled');+ });++ it('clears the schedule and starts running the claimed first send', async () => {+ await insert('t-ok', { scheduledRun: worktreeStartRun('claim-1') });++ await finish('t-ok', 'claim-1', { success: true });++ const topic = await readTopic('t-ok');+ expect(topic?.metadata?.scheduledRun).toBeNull();+ expect(topic?.status).toBe('running');+ });++ it('re-arms the same run for the retry time and waits for the device', async () => {+ await insert('t-retry', { scheduledRun: worktreeStartRun('claim-1') });++ await finish('t-retry', 'claim-1', {+ retryAt: '2026-11-16T01:00:00.000Z',+ success: false,+ });++ const topic = await readTopic('t-retry');+ expect(topic?.metadata?.scheduledRun).toMatchObject({+ runAt: '2026-11-16T01:00:00.000Z',+ waitingForDevice: true,+ });+ expect(topic?.metadata?.scheduledRun?.claim).toBeFalsy();+ expect(topic?.status).toBe('scheduled');+ });++ it('fails a scheduled first send that has no retry time', async () => {+ await insert('t-failed', { scheduledRun: worktreeStartRun('claim-1') });++ await finish('t-failed', 'claim-1', { error: 'checkout failed', success: false });++ const topic = await readTopic('t-failed');+ expect(topic?.metadata?.scheduledRun).toMatchObject({ error: 'checkout failed' });+ expect(topic?.metadata?.scheduledRun?.claim).toBeFalsy();+ expect(topic?.status).toBe('failed');+ });++ it('fails a first send the user started on a live topic', async () => {+ await insert('t-live', { scheduledRun: worktreeStartRun('claim-1') }, { status: 'active' });++ await finish('t-live', 'claim-1', { error: 'checkout failed', success: false });++ expect((await readTopic('t-live'))?.status).toBe('failed');+ });++ it('records an empty error when the failed dispatch carries none', async () => {+ await insert('t-failed-bare', { scheduledRun: worktreeStartRun('claim-1') });++ await finish('t-failed-bare', 'claim-1', { success: false });++ expect((await readTopic('t-failed-bare'))?.metadata?.scheduledRun).toMatchObject({ error: '' });+ });++ it('leaves a live topic active when the claim succeeded', async () => {+ await insert('t-live-ok', { scheduledRun: worktreeStartRun('claim-1') }, { status: 'active' });++ await finish('t-live-ok', 'claim-1', { success: true });++ expect((await readTopic('t-live-ok'))?.status).toBe('active');+ expect((await readTopic('t-live-ok'))?.metadata?.scheduledRun).toBeNull();+ });+});++describe('claimScheduledTopic', () => {+ const claim = {+ claimedAt: '2026-11-16T00:10:00.000Z',+ expiresAt: '2026-11-16T00:15:00.000Z',+ id: 'dispatcher-1',+ };+ const now = new Date('2026-11-16T00:10:00.000Z');++ it('claims a due worktree start and clears its waiting flag', async () => {+ await insert('c-due', {+ scheduledRun: { ...worktreeStartRun(), waitingForDevice: true } as TopicScheduledRun,+ });++ expect(await TopicModel.claimScheduledTopic(serverDB, 'c-due', claim, now)).toBe(true);++ const topic = await readTopic('c-due');+ expect(topic?.metadata?.scheduledRun?.claim?.id).toBe('dispatcher-1');+ expect(topic?.metadata?.scheduledRun).toMatchObject({ waitingForDevice: false });+ });++ it('refuses a worktree start that is not due yet', async () => {+ await insert('c-future', {+ scheduledRun: {+ ...worktreeStartRun(),+ runAt: '2026-11-16T01:00:00.000Z',+ } as TopicScheduledRun,+ });++ expect(await TopicModel.claimScheduledTopic(serverDB, 'c-future', claim, now)).toBe(false);+ expect((await readTopic('c-future'))?.metadata?.scheduledRun?.claim?.id).toBe('claim-1');+ });++ it('refuses a topic claimed by another live lease, and one with no payload', async () => {+ await insert('c-live', {+ scheduledRun: {+ ...worktreeStartRun(),+ claim: { claimedAt: 'x', expiresAt: '2026-11-16T00:20:00.000Z', id: 'other' },+ } as TopicScheduledRun,+ });+ expect(await TopicModel.claimScheduledTopic(serverDB, 'c-live', claim, now)).toBe(false);++ await insert('c-empty', {});+ expect(await TopicModel.claimScheduledTopic(serverDB, 'c-empty', claim, now)).toBe(false);+ expect(await TopicModel.claimScheduledTopic(serverDB, 'c-missing', claim, now)).toBe(false);+ });+});++describe('getDueScheduledTopics', () => {+ const now = new Date('2026-11-16T00:10:00.000Z');++ it('selects due rows, and narrows to one topic id when asked', async () => {+ await insert('d-due', {+ scheduledRun: {+ ...worktreeStartRun(),+ claim: undefined,+ runAt: '2026-11-16T00:00:00.000Z',+ } as TopicScheduledRun,+ });+ await insert('d-later', {+ scheduledRun: {+ ...worktreeStartRun(),+ claim: undefined,+ runAt: '2026-11-16T02:00:00.000Z',+ } as TopicScheduledRun,+ });++ const all = await TopicModel.getDueScheduledTopics(serverDB, now);+ expect(all.map((row) => row.id)).toContain('d-due');+ expect(all.map((row) => row.id)).not.toContain('d-later');++ const narrowed = await TopicModel.getDueScheduledTopics(serverDB, now, 'd-later');+ expect(narrowed).toEqual([]);+ const only = await TopicModel.getDueScheduledTopics(serverDB, now, 'd-due');+ expect(only.map((row) => row.id)).toEqual(['d-due']);+ });+});diff --git a/packages/database/src/models/__tests__/topics/topic.inFlightDirectory.test.ts b/packages/database/src/models/__tests__/topics/topic.inFlightDirectory.test.tsindex 0d0d5850896..d150ad289cd 100644--- a/packages/database/src/models/__tests__/topics/topic.inFlightDirectory.test.ts+++ b/packages/database/src/models/__tests__/topics/topic.inFlightDirectory.test.ts@@ -165,3 +165,54 @@ describe('TopicModel.countInFlightInDirectory', () => {).toBe(1);});});++describe('countInFlightInDirectory scope edges', () => {+ it('answers zero for a path that names no directory', async () => {+ const model = new TopicModel(serverDB, userId);++ expect(await model.countInFlightInDirectory({ deviceId: 'dev-1', path: ' ' })).toBe(0);+ });++ it('skips a run marker whose task reservation already expired', async () => {+ await insert(+ 'expired-reservation',+ {+ ...inRepo('/repo/expired'),+ taskCallbackReservation: { at: '2026-01-01T00:00:00.000Z', expiresAt: 1 },+ },+ { status: 'active' },+ );++ expect(+ await new TopicModel(serverDB, userId).countInFlightInDirectory({+ deviceId: 'dev-1',+ path: '/repo/expired',+ }),+ ).toBe(0);+ });++ it('skips a row whose run marker names another device', async () => {+ await insert(+ 'other-device',+ {+ ...inRepo('/repo/other'),+ runningOperation: { deviceId: 'dev-2', operationId: 'op', startedAt: 'x' },+ },+ { status: 'active' },+ );++ expect(+ await new TopicModel(serverDB, userId).countInFlightInDirectory({+ deviceId: 'dev-1',+ path: '/repo/other',+ }),+ ).toBe(0);+ });++ it('counts through the workspace scope', async () => {+ await insert('ws-run', inRepo('/repo/ws'), { workspaceId });+ const model = new TopicModel(serverDB, userId, workspaceId);++ expect(await model.countInFlightInDirectory({ deviceId: 'dev-1', path: '/repo/ws' })).toBe(1);+ });+});diff --git a/packages/database/src/models/__tests__/topics/topic.ownedWorktreeFirstSend.test.ts b/packages/database/src/models/__tests__/topics/topic.ownedWorktreeFirstSend.test.tsnew file mode 100644index 00000000000..05ae071cc1b--- /dev/null+++ b/packages/database/src/models/__tests__/topics/topic.ownedWorktreeFirstSend.test.ts@@ -0,0 +1,394 @@+// @vitest-environment node+import type { ChatTopicMetadata, TopicScheduledRun } from '@lobechat/types';+import { eq, inArray } from 'drizzle-orm';+import { afterEach, beforeEach, describe, expect, it } from 'vitest';++import { getTestDB } from '../../../core/getTestDB';+import { agents, sessions, topics, users } from '../../../schemas';+import type { LobeChatDatabase } from '../../../type';+import { TopicModel } from '../../topic';+import { withOwnedWorktreeClaim } from '../../topic/ownedWorktree';++const serverDB: LobeChatDatabase = await getTestDB();++const userId = 'topic-first-send-user';+const otherId = 'topic-first-send-other';+const WT = '/Users/me/.lobehub/worktrees/repo-1a2b3c4d/quiet-hill';+const SOURCE = '/code/repo';++const worktreeConfig = {+ git: {+ activeWorktree: WT,+ autoCreated: true,+ autoCreatedAt: '2026-11-16T00:00:00.000Z',+ branch: 'lobehub/quiet-hill',+ isWorktree: true,+ },+ path: SOURCE,+ sessionPath: WT,+};++const worktreeStartRun = (claimId = 'claim-1'): TopicScheduledRun =>+ ({+ claim: {+ claimedAt: '2026-11-16T00:00:00.000Z',+ expiresAt: '2026-11-16T00:05:00.000Z',+ id: claimId,+ },+ createdAt: '2026-11-16T00:00:00.000Z',+ kind: 'worktree_start',+ operationId: 'op-1',+ runAt: '2026-11-16T00:00:00.000Z',+ updatedAt: '2026-11-16T00:00:00.000Z',+ userMessageId: 'msg-1',+ }) as TopicScheduledRun;++const insert = (+ id: string,+ metadata: ChatTopicMetadata,+ extra: {+ agentId?: string | null;+ isDeleted?: boolean;+ sessionId?: string | null;+ status?: 'active' | 'completed' | 'running' | 'scheduled';+ userId?: string;+ } = {},+) =>+ serverDB.insert(topics).values({+ agentId: extra.agentId ?? null,+ id,+ isDeleted: extra.isDeleted ?? null,+ deletedAt: extra.isDeleted ? new Date() : null,+ metadata,+ sessionId: extra.sessionId ?? null,+ status: extra.status ?? 'scheduled',+ userId: extra.userId ?? userId,+ });++const autoCreatedForClear = (): ChatTopicMetadata => ({+ workingDirectoryConfig: worktreeConfig as ChatTopicMetadata['workingDirectoryConfig'],+});++const readTopic = async (id: string) =>+ (await serverDB.select().from(topics).where(eq(topics.id, id)))[0];++beforeEach(async () => {+ await serverDB.insert(users).values([{ id: userId }, { id: otherId }]);+ await serverDB.insert(agents).values([{ id: 'agent-1', userId }]);+ await serverDB.insert(sessions).values({ id: 'session-1', userId });+});++afterEach(async () => {+ await serverDB.delete(sessions).where(inArray(sessions.id, ['session-1']));+ await serverDB.delete(agents).where(inArray(agents.id, ['agent-1']));+ await serverDB.delete(users).where(inArray(users.id, [userId, otherId]));+});++const model = () => new TopicModel(serverDB, userId);++const checkout = (id: string, claimId?: string) =>+ model().recordFirstSendWorktreeCheckout(id, {+ claimId,+ deviceId: 'dev-9',+ workingDirectoryConfig: worktreeConfig,+ });++describe('recordFirstSendWorktreeCheckout', () => {+ it('declines for a topic that does not exist or belongs to someone else', async () => {+ expect(await checkout('missing', 'claim-1')).toEqual({ canDispatch: false });++ await insert('t-other', { scheduledRun: worktreeStartRun() }, { userId: otherId });+ expect(await checkout('t-other', 'claim-1')).toEqual({ canDispatch: false });+ expect((await readTopic('t-other'))?.metadata?.scheduledRun).toBeTruthy();+ });++ it('dispatches a scheduled topic that holds the claim and records the checkout', async () => {+ await insert('t-dispatch', {+ scheduledRun: worktreeStartRun('claim-1'),+ workingDirectoryConfig: worktreeConfig as ChatTopicMetadata['workingDirectoryConfig'],+ });++ expect(await checkout('t-dispatch', 'claim-1')).toEqual({ canDispatch: true });++ const topic = await readTopic('t-dispatch');+ expect(topic?.metadata?.ownedWorktrees).toEqual([+ {+ branch: 'lobehub/quiet-hill',+ createdAt: '2026-11-16T00:00:00.000Z',+ deviceId: 'dev-9',+ path: WT,+ sourcePath: SOURCE,+ },+ ]);+ // A live topic keeps its schedule: only a retirement clears the payload.+ expect(topic?.metadata?.scheduledRun?.kind).toBe('worktree_start');+ expect(topic?.status).toBe('scheduled');+ });++ it('records an archived cleanup and clears the schedule of the claimed run', async () => {+ await insert(+ 't-archived',+ {+ scheduledRun: worktreeStartRun('claim-1'),+ workingDirectoryConfig: worktreeConfig as ChatTopicMetadata['workingDirectoryConfig'],+ },+ { status: 'completed' },+ );++ expect(await checkout('t-archived', 'claim-1')).toEqual({+ canDispatch: false,+ cleanupTrigger: 'archived',+ });++ const topic = await readTopic('t-archived');+ expect(topic?.metadata?.ownedWorktrees?.[0]?.cleanup).toMatchObject({+ state: 'pending',+ trigger: 'archived',+ });+ expect(topic?.metadata?.scheduledRun).toBeNull();+ expect(topic?.status).toBe('completed');+ });++ it('records a trashed cleanup, clears the schedule and re-activates the topic', async () => {+ await insert(+ 't-trashed',+ {+ scheduledRun: worktreeStartRun('claim-1'),+ workingDirectoryConfig: worktreeConfig as ChatTopicMetadata['workingDirectoryConfig'],+ },+ { isDeleted: true },+ );++ expect(await checkout('t-trashed', 'claim-1')).toEqual({+ canDispatch: false,+ cleanupTrigger: 'trashed',+ });++ const topic = await readTopic('t-trashed');+ expect(topic?.metadata?.ownedWorktrees?.[0]?.cleanup).toMatchObject({+ state: 'pending',+ trigger: 'trashed',+ });+ expect(topic?.metadata?.scheduledRun).toBeNull();+ // Back to `active`: the row now has to be re-read as a normal trashed topic.+ expect(topic?.status).toBe('active');+ });++ it('keeps the schedule of a retired topic it does not hold the claim for', async () => {+ await insert(+ 't-no-claim',+ {+ scheduledRun: worktreeStartRun('claim-1'),+ workingDirectoryConfig: worktreeConfig as ChatTopicMetadata['workingDirectoryConfig'],+ },+ { isDeleted: true },+ );++ expect(await checkout('t-no-claim', 'claim-2')).toEqual({+ canDispatch: false,+ cleanupTrigger: 'trashed',+ });++ const topic = await readTopic('t-no-claim');+ // Not the claimant: the dispatcher owning `claim-1` still owns the payload.+ expect(topic?.metadata?.scheduledRun?.kind).toBe('worktree_start');+ expect(topic?.status).toBe('scheduled');+ // The cleanup is still recorded — the device may remove the folder, not the run.+ expect(topic?.metadata?.ownedWorktrees?.[0]?.cleanup).toMatchObject({ trigger: 'trashed' });+ });++ it('never overwrites a cleanup that already ran', async () => {+ await insert(+ 't-kept',+ {+ ownedWorktrees: [+ {+ cleanup: { at: 'earlier', state: 'kept', trigger: 'archived' },+ createdAt: '2026-11-15T00:00:00.000Z',+ path: WT,+ sourcePath: SOURCE,+ },+ ],+ scheduledRun: worktreeStartRun('claim-1'),+ workingDirectoryConfig: worktreeConfig as ChatTopicMetadata['workingDirectoryConfig'],+ },+ { status: 'completed' },+ );++ expect(await checkout('t-kept', 'claim-1')).toEqual({+ canDispatch: false,+ cleanupTrigger: 'archived',+ });++ const topic = await readTopic('t-kept');+ expect(topic?.metadata?.ownedWorktrees?.[0]?.cleanup).toMatchObject({+ at: 'earlier',+ state: 'kept',+ });+ });++ it('declines a claim of another kind or another id, leaving the topic untouched', async () => {+ const delayedStart = {+ claim: {+ claimedAt: '2026-11-16T00:00:00.000Z',+ expiresAt: '2026-11-16T00:05:00.000Z',+ id: 'claim-1',+ },+ createdAt: '2026-11-16T00:00:00.000Z',+ kind: 'delayed_start',+ runAt: '2026-11-16T00:00:00.000Z',+ updatedAt: '2026-11-16T00:00:00.000Z',+ userMessageId: 'msg-1',+ } as TopicScheduledRun;+ await insert('t-delayed', { scheduledRun: delayedStart }, { status: 'scheduled' });++ expect(await checkout('t-delayed', 'claim-1')).toEqual({ canDispatch: false });+ expect((await readTopic('t-delayed'))?.metadata?.scheduledRun?.kind).toBe('delayed_start');+ });++ it('records a checkout without dispatching when no claim is passed', async () => {+ await insert('t-anon', {+ workingDirectoryConfig: worktreeConfig as ChatTopicMetadata['workingDirectoryConfig'],+ });++ expect(await checkout('t-anon')).toEqual({ canDispatch: false });++ const topic = await readTopic('t-anon');+ expect(topic?.metadata?.ownedWorktrees?.[0]).toMatchObject({ deviceId: 'dev-9', path: WT });+ expect(topic?.metadata?.ownedWorktrees?.[0]?.cleanup).toBeUndefined();+ });+});++describe('owned worktree lookups by id and parent', () => {+ it('answers an empty id list without a query', async () => {+ expect(await model().findOwnedWorktreeTopics([])).toEqual([]);+ await insert('by-id', {+ ownedWorktrees: [{ createdAt: 'y', path: WT, sourcePath: SOURCE }],+ });+ expect((await model().findOwnedWorktreeTopics(['by-id'])).map((row) => row.id)).toEqual([+ 'by-id',+ ]);+ expect(await model().findWaitingCleanupTopicsUnder({ agentIds: [], sessionIds: [] })).toEqual(+ [],+ );+ });++ it('finds waiting cleanups under agents, legacy sessions, and both', async () => {+ const waiting = (): ChatTopicMetadata => ({+ ownedWorktrees: [+ {+ cleanup: { at: 'x', state: 'pending' },+ createdAt: 'y',+ path: WT,+ sourcePath: SOURCE,+ },+ ],+ });+ await insert('w-agent', waiting(), { agentId: 'agent-1' });+ await insert('w-session', waiting(), { sessionId: 'session-1' });+ await insert('w-idle', {+ ownedWorktrees: [{ createdAt: 'y', path: '/other', sourcePath: SOURCE }],+ });++ expect(+ (await model().findWaitingCleanupTopicsUnder({ agentIds: ['agent-1'], sessionIds: [] })).map(+ (row) => row.id,+ ),+ ).toContain('w-agent');+ expect(+ (+ await model().findWaitingCleanupTopicsUnder({ agentIds: [], sessionIds: ['session-1'] })+ ).map((row) => row.id),+ ).toContain('w-session');+ const both = await model().findWaitingCleanupTopicsUnder({+ agentIds: ['agent-1'],+ sessionIds: ['session-1'],+ });+ expect(both.map((row) => row.id).sort()).toEqual(['w-agent', 'w-session']);+ });++ it('drops rows whose pending cleanup belongs to a registered device', async () => {+ await insert('p-bound', {+ ownedWorktrees: [+ {+ cleanup: { at: 'x', state: 'pending' },+ createdAt: 'y',+ deviceId: 'dev-2',+ path: WT,+ sourcePath: SOURCE,+ },+ ],+ });++ expect(await model().findPendingOwnedWorktreeTopics(undefined)).toEqual([]);+ });++ it('counts a worktree no topic was excluded from', async () => {+ await insert('live-only', {+ workingDirectoryConfig: { git: { activeWorktree: WT }, path: SOURCE },+ });++ expect(await model().countLiveTopicsUsingWorktree({ excludeIds: [], path: WT })).toBe(1);+ });++ it('accepts a snapshot that clears the whole metadata', async () => {+ await insert('t-clear', autoCreatedForClear());++ await model().update('t-clear', { metadata: null });++ expect((await readTopic('t-clear'))?.metadata).toBeNull();+ });++ it('leaves a record alone when the path is not in it', async () => {+ await insert('t-no-path', {+ ownedWorktrees: [{ createdAt: 'y', path: '/other', sourcePath: SOURCE }],+ });++ expect(+ await model().updateOwnedWorktree('t-no-path', WT, () => ({+ createdAt: 'z',+ path: WT,+ sourcePath: SOURCE,+ })),+ ).toBeUndefined();+ });+});++describe('owned worktree helpers', () => {+ it('leaves a missing metadata payload alone', () => {+ expect(withOwnedWorktreeClaim(null)).toBeNull();+ expect(withOwnedWorktreeClaim(undefined)).toBeUndefined();+ });++ it('finds only the anonymous cleanups that are still pending or running', async () => {+ const entry = (cleanup: string, extra: Record<string, unknown> = {}) => ({+ ownedWorktrees: [+ { cleanup: { at: 'x', state: cleanup as never }, createdAt: 'y', path: WT, ...extra },+ ],+ });+ await insert('anon-running', entry('running'));+ await insert('anon-removed', entry('removed'));++ expect((await model().findPendingOwnedWorktreeTopics(undefined)).map((row) => row.id)).toEqual([+ 'anon-running',+ ]);+ });++ it('rewrites one record and leaves its sibling untouched', async () => {+ await insert('t-two', {+ ownedWorktrees: [+ { createdAt: 'y', path: '/first', sourcePath: SOURCE },+ { createdAt: 'y', path: WT, sourcePath: SOURCE },+ ],+ });++ const written = await model().updateOwnedWorktree('t-two', WT, (current) => ({+ ...current,+ deviceId: 'dev-7',+ }));++ expect(written?.deviceId).toBe('dev-7');+ expect((await readTopic('t-two'))?.metadata?.ownedWorktrees).toHaveLength(2);+ expect((await readTopic('t-two'))?.metadata?.ownedWorktrees?.[0]?.path).toBe('/first');+ });+});diff --git a/packages/database/src/models/agentDocuments/__tests__/agentDocument.bindingStates.test.ts b/packages/database/src/models/agentDocuments/__tests__/agentDocument.bindingStates.test.tsindex c6a478ef343..c35cca04c02 100644--- a/packages/database/src/models/agentDocuments/__tests__/agentDocument.bindingStates.test.ts+++ b/packages/database/src/models/agentDocuments/__tests__/agentDocument.bindingStates.test.ts@@ -123,3 +123,27 @@ describe('AgentDocumentModel binding states', () => {).toEqual([]);});});++describe('AgentDocumentModel binding-state guards', () => {+ it('ignores refs of no known shape, and a ref list of only one kind', async () => {+ const doc = await model.create(agentId, 'only.md', 'only');++ // Nothing to look up at all.+ expect(await model.listBindingStatesByRefs(agentId, [])).toEqual([]);+ // Only a binding id: the document column takes part in the query alone.+ const byBinding = await model.listBindingStatesByRefs(agentId, [doc.id]);+ expect(byBinding.map((row) => row.id)).toEqual([doc.id]);+ // Only a document id: the binding column takes part alone.+ const byDocument = await model.listBindingStatesByRefs(agentId, [doc.documentId]);+ expect(byDocument.map((row) => row.documentId)).toEqual([doc.documentId]);+ });++ it('answers empty id lists without querying', async () => {+ expect(await model.listExistingDocumentIds([])).toEqual([]);+ expect(await model.listExistingDocumentIds(['00000000-0000-4000-8000-000000000000'])).toEqual(+ [],+ );+ expect(await model.listKnowledgeBaseMemberIds([])).toEqual([]);+ expect(await model.listRevokedFromAllAgents([])).toEqual([]);+ });+});diff --git a/packages/database/src/models/scm/__tests__/changeRequest.attachEdges.test.ts b/packages/database/src/models/scm/__tests__/changeRequest.attachEdges.test.tsnew file mode 100644index 00000000000..2dffd99255f--- /dev/null+++ b/packages/database/src/models/scm/__tests__/changeRequest.attachEdges.test.ts@@ -0,0 +1,85 @@+// @vitest-environment node+import { eq } from 'drizzle-orm';+import { afterEach, beforeEach, describe, expect, it } from 'vitest';++import { getTestDB } from '../../../core/getTestDB';+import { scmChangeRequests, topics, users, works, workspaces } from '../../../schemas';+import type { LobeChatDatabase } from '../../../type';+import { ScmChangeRequestModel } from '../changeRequest';++const serverDB: LobeChatDatabase = await getTestDB();++const userId = 'scm-attach-user';+const workspaceId = 'scm-attach-ws';+const missingId = '00000000-0000-4000-8000-000000000002';++const row = (number: number, overrides: Record<string, unknown> = {}) =>+ ScmChangeRequestModel.upsert(serverDB, {+ number,+ provider: 'github',+ repoFullName: 'LobeHub/LobeHub',+ state: 'open',+ url: `https://github.com/LobeHub/LobeHub/pull/${number}`,+ userId,+ ...overrides,+ });++beforeEach(async () => {+ await serverDB.insert(users).values({ id: userId });+ await serverDB+ .insert(workspaces)+ .values({ id: workspaceId, name: 'Attach', primaryOwnerId: userId, slug: workspaceId });+});++afterEach(async () => {+ await serverDB.delete(scmChangeRequests);+ await serverDB.delete(works).where(eq(works.id, 'work-ws'));+ await serverDB.delete(topics).where(eq(topics.id, 'topic-ws'));+ await serverDB.delete(workspaces).where(eq(workspaces.id, workspaceId));+ await serverDB.delete(users).where(eq(users.id, userId));+});++describe('ScmChangeRequestModel attach edges', () => {+ it('answers null for a row that does not exist', async () => {+ expect(await ScmChangeRequestModel.findById(serverDB, missingId)).toBeNull();+ });++ it('re-reads the row when there is nothing to attach', async () => {+ const created = await row(501);++ const attached = await ScmChangeRequestModel.attachLinks(serverDB, created!.id, {});++ expect(attached?.id).toBe(created!.id);+ expect(attached?.topicId).toBeNull();+ });++ it('fills a workspace row through the workspace scope', async () => {+ await serverDB.insert(topics).values({ id: 'topic-ws', userId });+ await serverDB.insert(works).values({+ id: 'work-ws',+ resourceId: 'lobehub/lobehub#502',+ resourceType: 'github_pull_request',+ toolIdentifier: 'github',+ toolName: 'create_pull_request',+ type: 'external',+ userId,+ visibility: 'private',+ });+ const created = await row(502, { workspaceId });++ await ScmChangeRequestModel.attachPullRequestWork(serverDB, {+ number: 502,+ repoFullName: 'lobehub/lobehub',+ scope: { userId, workspaceId },+ topicId: 'topic-ws',+ workId: 'work-ws',+ });++ const [after] = await serverDB+ .select()+ .from(scmChangeRequests)+ .where(eq(scmChangeRequests.id, created!.id));+ expect(after.topicId).toBe('topic-ws');+ expect(after.workId).toBe('work-ws');+ });+});diff --git a/packages/database/src/models/task/tree.test.ts b/packages/database/src/models/task/tree.test.tsindex d5d0ee212f9..6adb9ba6d90 100644--- a/packages/database/src/models/task/tree.test.ts+++ b/packages/database/src/models/task/tree.test.ts@@ -112,6 +112,17 @@ describe('TaskModel.moveUnfiledTreeToProject', () => {expect(rows.map((row) => row.projectId)).toEqual([target, target, target]);});+ it('files a lone root with no descendants', async () => {+ const model = new TaskModel(serverDB, ownerId, workspaceId);+ const target = await projectIn('task-tree-move-single');+ const lone = await model.create({ instruction: 'lone' });++ const moved = await model.moveUnfiledTreeToProject(lone.id, target);++ expect(moved?.projectId).toBe(target);+ expect((await model.findById(lone.id))?.projectId).toBe(target);+ });+it("moves another member's private subtask the caller cannot read", async () => {const owner = new TaskModel(serverDB, ownerId, workspaceId);const member = new TaskModel(serverDB, memberId, workspaceId);diff --git a/packages/database/src/models/work/__tests__/githubToolResult.test.ts b/packages/database/src/models/work/__tests__/githubToolResult.test.tsindex 3986379eaa9..971bd5382e6 100644--- a/packages/database/src/models/work/__tests__/githubToolResult.test.ts+++ b/packages/database/src/models/work/__tests__/githubToolResult.test.ts@@ -745,3 +745,35 @@ describe('normalizeGithubToolResult (gh CLI edge cases)', () => {).toBeNull();});});++describe('normalizeGithubToolResult (pull-request lifecycle status)', () => {+ const lifecycle = (command: string, output: string) =>+ normalizeGithubShellToolResult(+ { data: { command, exitCode: 0, output }, toolName: 'Bash' },+ { pullRequestLifecycle: true },+ );++ it('reads a merge that landed from the command output', () => {+ const operation = lifecycle(+ 'gh pr merge 42 --repo lobehub/lobehub --squash',+ '✓ Merged pull request lobehub/lobehub#42',+ );++ expect(operation?.params).toMatchObject({+ changeType: 'updated',+ identifier: 'lobehub/lobehub#42',+ status: 'merged',+ });+ });++ it('leaves the status alone for a merge only queued for auto-merge', () => {+ const operation = lifecycle(+ 'gh pr merge 43 --repo lobehub/lobehub --auto --squash',+ '✓ Merged pull request lobehub/lobehub#43',+ );++ // Nothing merged yet: the queued auto-merge must not read as `merged`.+ expect(operation?.params.patchFields).not.toContain('status');+ expect(operation?.params.status).toBeUndefined();+ });+});diff --git a/packages/database/src/models/work/__tests__/pullRequests.test.ts b/packages/database/src/models/work/__tests__/pullRequests.test.tsindex 1adb6f6dd49..1f95e7c53c3 100644--- a/packages/database/src/models/work/__tests__/pullRequests.test.ts+++ b/packages/database/src/models/work/__tests__/pullRequests.test.ts@@ -283,3 +283,30 @@ describe('WorkModel.listTopicPullRequests', () => {});});});++describe('WorkModel.listTopicPullRequests with a work that lost its resource id', () => {+ it('skips a row whose pull-request identifier is gone', async () => {+ await serverDB.insert(works).values({+ id: 'work-null-resource',+ resourceId: null,+ resourceType: 'github_pull_request',+ toolIdentifier: 'github',+ toolName: 'create_pull_request',+ type: 'external',+ userId,+ visibility: 'private',+ });+ await serverDB.insert(workVersions).values({+ changeType: 'created',+ toolIdentifier: 'claude-code',+ toolName: 'Bash',+ topicId,+ version: 1,+ workId: 'work-null-resource',+ });++ const rows = await new WorkModel(serverDB, userId).listTopicPullRequests(topicId);++ expect(rows.map((row) => row.workId)).not.toContain('work-null-resource');+ });+});diff --git a/packages/database/src/models/work/__tests__/scmChangeRequestBackfill.test.ts b/packages/database/src/models/work/__tests__/scmChangeRequestBackfill.test.tsindex bfcd032a90b..975e24dcae4 100644--- a/packages/database/src/models/work/__tests__/scmChangeRequestBackfill.test.ts+++ b/packages/database/src/models/work/__tests__/scmChangeRequestBackfill.test.ts@@ -1,7 +1,7 @@// @vitest-environment nodeimport { agentShareWorkAccessScope, type ScmUpsertChangeRequestParams } from '@lobechat/types';import { eq } from 'drizzle-orm';-import { afterEach, beforeEach, describe, expect, it } from 'vitest';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { scmChangeRequests, topics } from '../../../schemas';import { ScmChangeRequestModel } from '../../scm';@@ -102,3 +102,52 @@ describe('WorkModel · pull-request work backfills the provider row', () => {expect(after?.workId).toBeNull();});});++describe('WorkModel · pull-request work survives a failing backfill', () => {+ it('keeps the work when the link backfill fails', async () => {+ const spy = vi+ .spyOn(ScmChangeRequestModel, 'attachPullRequestWork')+ .mockRejectedValueOnce(new Error('backfill unavailable'));++ const work = await registerPullRequest(new WorkModel(serverDB, userId), 'call-backfill-down');++ expect(work?.id).toBeTruthy();+ spy.mockRestore();+ });++ it('skips the backfill for an identifier that carries no pull-request number', async () => {+ const work = await new WorkModel(serverDB, userId).registerExternal({+ changeType: 'created',+ identifier: 'lobehub/lobehub',+ patchFields: ['identifier'],+ resourceId: 'lobehub/lobehub',+ resourceType: 'github_pull_request',+ toolCallId: 'call-no-number',+ toolIdentifier: 'github',+ toolName: 'create_pull_request',+ topicId,+ });++ expect(work?.id).toBeTruthy();+ });+});++describe('WorkModel · pull-request work without a topic', () => {+ it('falls back to the registration topic when the work carries none', async () => {+ const row = await pullRequestRow({ number: 8 });++ await new WorkModel(serverDB, userId).registerExternal({+ changeType: 'created',+ identifier: 'lobehub/lobehub#8',+ patchFields: ['identifier'],+ resourceId: 'lobehub/lobehub#8',+ resourceType: 'github_pull_request',+ toolCallId: 'call-no-topic',+ toolIdentifier: 'github',+ toolName: 'create_pull_request',+ });++ // Nothing to link it to, so the row keeps its empty topic slot.+ expect((await rowOf(row!.id))?.topicId).toBeNull();+ });+});