π€― 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
β‘οΈ perf(agent): scope delete impact and cascades to agent_id (#23616)
Lobehub Coder938fe4d41673
diff --git a/apps/server/src/services/trash/__tests__/inboundWebhook.test.ts b/apps/server/src/services/trash/__tests__/inboundWebhook.test.tsindex ec377f464fe..26ef6f1712b 100644--- a/apps/server/src/services/trash/__tests__/inboundWebhook.test.ts+++ b/apps/server/src/services/trash/__tests__/inboundWebhook.test.ts@@ -158,7 +158,7 @@ describe('TrashService inbound webhook hooks', () => {expect(boundary.unsubscribe).toHaveBeenCalledTimes(2);});- it('cleans agent roots and child topics in its linked sessions without deleting retained subscriptions', async () => {+ it("cleans the agent's own topics and leaves another agent's topic in its linked session", async () => {const crossLinkedTopic = 'trash-webhook-cascaded-other-agent-topic';await db.insert(topics)@@ -171,13 +171,13 @@ describe('TrashService inbound webhook hooks', () => {expect(root).toMatchObject({ resourceType: 'agent', resourceId: agentId });if (!root) throw new Error('Expected the agent trash root');const children = await db.select().from(trashItems).where(eq(trashItems.rootId, root.id));- expect(children.map((item) => item.resourceId)).toEqual(- expect.arrayContaining([topicId, crossLinkedTopic]),- );+ const childIds = children.map((item) => item.resourceId);+ expect(childIds).toContain(topicId);+ expect(childIds).not.toContain(crossLinkedTopic);expect(await model.findById(native.id)).toBeUndefined();- expect(await model.findById(child.id)).toBeUndefined();+ expect(await model.findById(child.id)).toMatchObject({ status: 'active' });expect(await model.findById(retained.id)).toMatchObject({ status: 'active' });- expect(boundary.unsubscribe).toHaveBeenCalledTimes(2);+ expect(boundary.unsubscribe).toHaveBeenCalledTimes(1);});it.each(['topic', 'agent'] as const)(diff --git a/apps/server/src/services/trash/__tests__/index.test.ts b/apps/server/src/services/trash/__tests__/index.test.tsindex 2e616103402..16cf46bfa12 100644--- a/apps/server/src/services/trash/__tests__/index.test.ts+++ b/apps/server/src/services/trash/__tests__/index.test.ts@@ -14,9 +14,11 @@ import { WidgetModel } from '@/database/models/widget';import { HomeRepository } from '@/database/repositories/home';import {agents,+ agentsToSessions,dashboards,messages,sessions,+ threads,topics,trashItems,users,@@ -247,7 +249,7 @@ describe('TrashService', () => {expect((await service.trashAgent(unnamed.id))?.title).toBe('Bot');});- it('cascades to topics (incl. legacy session-scoped ones), hides the session shell, and restores the whole unit', async () => {+ it("cascades to the agent's topics, hides the session shell, and restores the whole unit", async () => {const session = await sessionModel.create({ config: { title: 'Legacy' }, type: 'agent' });const agent = (await sessionModel.findByIdOrSlug(session.id))!.agent;const t1 = await topicModel.create({ agentId: agent.id, title: 'via agent' });@@ -311,11 +313,6 @@ describe('TrashService', () => {content: 'topic-less via agent',role: 'user',});- const bySession = await messageModel.create({- content: 'topic-less via session',- role: 'user',- sessionId: session.id,- });const other = await agentModel.create({ title: 'Other' });const bystander = await messageModel.create({agentId: other.id,@@ -324,14 +321,165 @@ describe('TrashService', () => {});const root = await service.trashAgent(agent.id);- expect(root?.meta?.childCount).toBe(2);+ expect(root?.meta?.childCount).toBe(1);expect(await messageModel.findById(byAgent.id)).toBeUndefined();- expect(await messageModel.findById(bySession.id)).toBeUndefined();expect(await messageModel.findById(bystander.id)).toBeTruthy();await service.restore([root!.id]);expect(await messageModel.findById(byAgent.id)).toBeTruthy();- expect(await messageModel.findById(bySession.id)).toBeTruthy();+ });++ it('deletes exactly what the impact reports and never destroys session-only rows', async () => {+ const workspaceId = 'trash-impact-ws';+ await serverDB+ .insert(workspaces)+ .values({ id: workspaceId, name: 'ws', primaryOwnerId: userId, slug: workspaceId });+ const wsService = new TrashService(serverDB, userId, workspaceId);+ const wsAgents = new AgentModel(serverDB, userId, workspaceId);+ const agent = await wsAgents.create({ title: 'Shared bot' });+ const sessionId = 'trash-impact-session';+ await serverDB+ .insert(sessions)+ .values({ id: sessionId, slug: sessionId, userId, workspaceId });+ await serverDB+ .insert(agentsToSessions)+ .values({ agentId: agent.id, sessionId, userId, workspaceId });+ const foreignTopic = 'trash-impact-foreign-topic';+ const legacyTopic = 'trash-impact-legacy-topic';+ const legacyMessage = 'trash-impact-legacy-message';+ await serverDB.insert(topics).values([+ { agentId: agent.id, id: foreignTopic, userId: otherUserId, workspaceId },+ { id: legacyTopic, sessionId, userId: otherUserId, workspaceId },+ ]);+ await serverDB.insert(messages).values({+ id: legacyMessage,+ role: 'user',+ sessionId,+ userId: otherUserId,+ workspaceId,+ });+ const legacyState = async () => ({+ message: (await serverDB.select().from(messages).where(eq(messages.id, legacyMessage)))[0]+ ?.isDeleted,+ topic: (await serverDB.select().from(topics).where(eq(topics.id, legacyTopic)))[0]+ ?.isDeleted,+ });++ // The dialog counts the agent's topic and nothing that only has the session.+ expect(await wsAgents.getDeleteImpact(agent.id)).toEqual({+ foreignTopicCount: 1,+ hasForeignContent: true,+ });++ const root = await wsService.trashAgent(agent.id);+ const wsTrash = new TrashModel(serverDB, userId, workspaceId);+ expect((await wsTrash.findChildren(root!.id)).map((c) => c.resourceId)).toEqual([+ foreignTopic,+ ]);+ expect(await legacyState()).toEqual({ message: null, topic: null });++ await wsService.purge([root!.id]);+ expect(await serverDB.select().from(topics).where(eq(topics.id, foreignTopic))).toEqual([]);+ expect(await legacyState()).toEqual({ message: null, topic: null });+ // The shell stays because it still holds them.+ expect(await serverDB.select().from(sessions).where(eq(sessions.id, sessionId))).toHaveLength(+ 1,+ );+ });++ it('keeps messages and threads carrying the agent inside a surviving legacy topic', async () => {+ const session = await sessionModel.create({ config: { title: 'Legacy' }, type: 'agent' });+ const agent = (await sessionModel.findByIdOrSlug(session.id))!.agent;+ const legacy = await topicModel.create({ sessionId: session.id, title: 'old chat' });+ const tagged = await messageModel.create({+ agentId: agent.id,+ content: 'continued later',+ role: 'user',+ topicId: legacy.id,+ });+ await serverDB.insert(threads).values({+ agentId: agent.id,+ id: 'trash-legacy-thread',+ topicId: legacy.id,+ type: 'standalone',+ userId,+ });++ const root = await service.trashAgent(agent.id);+ await service.purge([root!.id]);++ const [message] = await serverDB.select().from(messages).where(eq(messages.id, tagged.id));+ const [thread] = await serverDB+ .select()+ .from(threads)+ .where(eq(threads.id, 'trash-legacy-thread'));+ expect(message.agentId).toBeNull();+ expect(thread.agentId).toBeNull();+ expect(await serverDB.select().from(topics).where(eq(topics.id, legacy.id))).toHaveLength(1);+ });++ it('keeps the bin entry of a message trashed on its own inside a surviving topic', async () => {+ const session = await sessionModel.create({ config: { title: 'Legacy' }, type: 'agent' });+ const agent = (await sessionModel.findByIdOrSlug(session.id))!.agent;+ const legacy = await topicModel.create({ sessionId: session.id, title: 'old chat' });+ const tagged = await messageModel.create({+ agentId: agent.id,+ content: 'trashed alone',+ role: 'user',+ topicId: legacy.id,+ });+ const [messageRoot] = await service.trashMessages([tagged.id]);++ const root = await service.trashAgent(agent.id);+ await service.purge([root!.id]);++ expect((await service.list()).items.map((item) => item.id)).toEqual([messageRoot.id]);+ expect((await service.restore([messageRoot.id])).failed).toEqual([]);+ expect(await messageModel.findById(tagged.id)).toBeTruthy();+ });++ it('purges session-only children an earlier cascade already put in the bin', async () => {+ const session = await sessionModel.create({ config: { title: 'Legacy' }, type: 'agent' });+ const agent = (await sessionModel.findByIdOrSlug(session.id))!.agent;+ const deletedAt = new Date();+ await serverDB.insert(topics).values({+ deletedAt,+ id: 'trash-old-topic',+ isDeleted: true,+ sessionId: session.id,+ userId,+ });+ await serverDB.insert(messages).values({+ deletedAt,+ id: 'trash-old-message',+ isDeleted: true,+ role: 'user',+ sessionId: session.id,+ userId,+ });+ const root = await service.trashAgent(agent.id);+ await serverDB.insert(trashItems).values(+ (['topic', 'message'] as const).map((resourceType) => ({+ deletedAt,+ expiresAt: root!.expiresAt,+ resourceId: resourceType === 'topic' ? 'trash-old-topic' : 'trash-old-message',+ resourceType,+ rootId: root!.id,+ userId,+ })),+ );++ await service.purge([root!.id]);++ expect(await serverDB.select().from(topics).where(eq(topics.id, 'trash-old-topic'))).toEqual(+ [],+ );+ expect(+ await serverDB.select().from(messages).where(eq(messages.id, 'trash-old-message')),+ ).toEqual([]);+ expect(+ await serverDB.select().from(sessions).where(eq(sessions.id, session.id)),+ ).toHaveLength(0);});it('refuses to restore a topic-less message whose agent is still in the bin', async () => {@@ -360,17 +508,21 @@ describe('TrashService', () => {role: 'user',});// each trashed on its own first, so each keeps a separate root- await service.trashTopics([viaAgent.id, viaSession.id]);+ const [, viaSessionRoot] = await service.trashTopics([viaAgent.id, viaSession.id]);await service.trashMessages([loose.id]);const root = await service.trashAgent(agent.id);expect((await service.list()).items).toHaveLength(4);await service.purge([root!.id]);- // the cascade deleted all three resources, so none of their rows may linger- expect((await service.list()).items).toEqual([]);- expect(await service.countByType()).toEqual({});- expect(await serverDB.select().from(trashItems)).toHaveLength(0);+ // The cascade deleted the agent's rows. The session-only topic survives,+ // so its own bin entry stays valid and can still be restored.+ expect((await service.list()).items.map((item) => item.id)).toEqual([viaSessionRoot.id]);+ expect(await serverDB.select().from(topics).where(eq(topics.id, viaSession.id))).toHaveLength(+ 1,+ );+ expect((await service.restore([viaSessionRoot.id])).failed).toEqual([]);+ expect(await topicModel.findById(viaSession.id)).toBeTruthy();});it('rolls the whole agent purge back when grant cleanup fails, so a retry still cleans up', async () => {diff --git a/apps/server/src/services/trash/handlers/agent.ts b/apps/server/src/services/trash/handlers/agent.tsindex 16975701bb1..a23ebe8640a 100644--- a/apps/server/src/services/trash/handlers/agent.ts+++ b/apps/server/src/services/trash/handlers/agent.ts@@ -1,4 +1,5 @@import { agentDisplayName } from '@lobechat/types';+import { chunk } from 'es-toolkit/compat';import { AgentModel } from '@/database/models/agent';import { MessageModel } from '@/database/models/message';@@ -20,6 +21,9 @@ import {TrashRestoreError,} from './types';+/** Ids per purge statement β well under Postgres' bind-parameter cap. */+const PURGE_CHUNK_SIZE = 1000;+export const agentEntry = (agent: AgentItem, childCount: number) => ({meta: {avatar: agent.avatar,@@ -35,11 +39,10 @@ export const agentEntry = (agent: AgentItem, childCount: number) => ({});/**- * Trash an agent with everything the hard delete would cascade through: every- * topic that hangs off it directly (`agent_id`) or through its legacy session- * shell (`session_id`), plus the topic-less messages under either (no topic- * stamp hides those). Both are registered as children so a restore brings the- * whole conversation history back in one go.+ * Trash an agent with its conversation history: every topic with its+ * `agent_id`, plus its topic-less messages (no topic stamp hides those). Both+ * are registered as children so a restore brings the whole history back in+ * one go. Rows carrying only a legacy `session_id` are not part of the cascade.*/export const softDeleteAgent = async (ctx: TrashHandlerContext,@@ -56,22 +59,19 @@ export const softDeleteAgent = async (const [agent] = await agentModel.softDelete([agentId], options);if (!agent) return null;- // Legacy session shells are not stamped (the agent is the restorable unit- // and the list hides them through the agent join); their topics are.- const sessionIds = await agentModel.findSessionIdsByAgentIds([agentId]);// The cascade is scope-wide on purpose (no `restrictToCreator`): the router// only lets a non-owner through when nothing foreign rides along, or when// the agent's author (or an Admin overriding on another member's agent)// acknowledged that teammates' topics go with it.const topics = await topicModel.softDeleteByParents(- { agentIds: [agentId], sessionIds },+ { agentIds: [agentId] },{ deletedAt: options.deletedAt },);const topiclessMessages = await new MessageModel(ctx.db,ctx.userId,ctx.workspaceId,- ).softDeleteTopicless({ agentIds: [agentId], sessionIds }, { deletedAt: options.deletedAt });+ ).softDeleteTopicless({ agentIds: [agentId] }, { deletedAt: options.deletedAt });return {children: [@@ -102,28 +102,37 @@ export const agentHandler: TrashHandler = {const agentIds = await agentModel.lockTrashedForPurge([root.resourceId]);if (agentIds.length === 0) return;+ const topicModel = new TopicModel(db, ctx.userId, ctx.workspaceId);+ const trashModel = new TrashModel(db, ctx.userId, ctx.workspaceId);const sessionIds = await agentModel.findSessionIdsByAgentIds(agentIds);+ // Bin entries from before the cascade went agent-only can list rows that+ // only carry `session_id`. The FK below no longer reaches those.+ const stranded = await trashModel.findChildrenOutsideAgents(root.id, agentIds);// The cascade below takes the agent's topics with it β including the// only record of a worktree cleanup still waiting on an offline device.// Hold the whole purge until those have run (see `./topic`).- const waiting = await new TopicModel(- db,- ctx.userId,- ctx.workspaceId,- ).findWaitingCleanupTopicsUnder({ agentIds, sessionIds });+ const waiting = await topicModel.findWaitingCleanupTopicsUnder({+ agentIds,+ topicIds: stranded.topicIds,+ });if (hasWaitingWorktreeCleanup(waiting))throw new TrashPurgeBlockedError(WORKTREE_CLEANUP_WAITING_MESSAGE);+ // Topics outside the cascade keep their messages and threads. Runs before+ // the root cleanup so a message trashed on its own there keeps its entry.+ await agentModel.detachFromSurvivingTopics(agentIds);// Topics / messages trashed on their own before this agent keep separate- // roots; the cascade below deletes them, so drop those rows first.- await new TrashModel(db, ctx.userId, ctx.workspaceId).removeRootsUnderAgents({- agentIds,- sessionIds,- });- // FK cascades take topics / messages / threads with the agent + session rows.+ // roots; the deletes below remove them, so drop those rows first.+ await trashModel.removeRootsUnderAgents({ agentIds, topicIds: stranded.topicIds });+ await topicModel.purge(stranded.topicIds);+ // FK cascades take the topics / messages / threads carrying the agent.await agentModel.purge(agentIds);- await new SessionModel(db, ctx.userId, ctx.workspaceId).deleteShellsByIds(sessionIds);+ const messageModel = new MessageModel(db, ctx.userId, ctx.workspaceId);+ for (const ids of chunk(stranded.messageIds, PURGE_CHUNK_SIZE)) {+ await messageModel.purgeMessages(ids);+ }+ await new SessionModel(db, ctx.userId, ctx.workspaceId).deleteEmptyShellsByIds(sessionIds);if (ctx.workspaceId) {await new ResourcePermissionModel(db, ctx.workspaceId).removeAll('agent', root.resourceId);}diff --git a/packages/database/src/models/__tests__/agent.characterization.test.ts b/packages/database/src/models/__tests__/agent.characterization.test.tsindex 6f137e2d0ea..b5e0377cdcc 100644--- a/packages/database/src/models/__tests__/agent.characterization.test.ts+++ b/packages/database/src/models/__tests__/agent.characterization.test.ts@@ -58,6 +58,7 @@ const PUBLIC_METHODS = ['delete','deleteAgentFile','deleteAgentKnowledgeBase',+ 'detachFromSurvivingTopics','duplicate','existsById','existsOwnedById',diff --git a/packages/database/src/models/__tests__/agent.transferGuards.test.ts b/packages/database/src/models/__tests__/agent.transferGuards.test.tsindex 6eb361de9e4..06b66050c7a 100644--- a/packages/database/src/models/__tests__/agent.transferGuards.test.ts+++ b/packages/database/src/models/__tests__/agent.transferGuards.test.ts@@ -85,7 +85,7 @@ describe('AgentModel.transferHasForeignRows', () => {expect(await ownerModel.transferHasForeignRows(agentId)).toBe(true);});- it('is true for a teammate topic reached only through a linked session', async () => {+ it('ignores a teammate topic carrying only a legacy session id, which stays behind', async () => {await linkSession('agtg-own-session', ownerId);await serverDB.insert(topics).values({id: 'agtg-teammate-topic',@@ -94,7 +94,7 @@ describe('AgentModel.transferHasForeignRows', () => {workspaceId: wsId,});- expect(await ownerModel.transferHasForeignRows(agentId)).toBe(true);+ expect(await ownerModel.transferHasForeignRows(agentId)).toBe(false);});it('is true for a teammate topic on an agent with no linked session', async () => {@@ -120,7 +120,7 @@ describe('AgentModel.transferHasForeignRows', () => {expect(await ownerModel.transferHasForeignRows(agentId)).toBe(true);});- it('is true for a teammate message on a linked session', async () => {+ it('ignores a teammate message carrying only a legacy session id, which stays behind', async () => {await linkSession('agtg-own-session', ownerId);await serverDB.insert(messages).values({id: 'agtg-teammate-message',@@ -129,6 +129,20 @@ describe('AgentModel.transferHasForeignRows', () => {userId: teammateId,});+ expect(await ownerModel.transferHasForeignRows(agentId)).toBe(false);+ });++ it("is true for a teammate message without an agent id inside the agent's topic", async () => {+ await serverDB+ .insert(topics)+ .values({ agentId, id: 'agtg-own-topic', userId: ownerId, workspaceId: wsId });+ await serverDB.insert(messages).values({+ id: 'agtg-teammate-message',+ role: 'user',+ topicId: 'agtg-own-topic',+ userId: teammateId,+ });+expect(await ownerModel.transferHasForeignRows(agentId)).toBe(true);});@@ -182,7 +196,7 @@ describe('AgentModel.getDeleteImpact', () => {});});- it("counts teammates' live topics reached via the agent or its sessions", async () => {+ it("counts teammates' live topics on the agent, not ones carrying only a session id", async () => {await linkSession('agtg-teammate-session', teammateId);await serverDB.insert(topics).values([{ agentId, id: 'agtg-own-topic', userId: ownerId, workspaceId: wsId },@@ -203,7 +217,7 @@ describe('AgentModel.getDeleteImpact', () => {]);expect(await ownerModel.getDeleteImpact(agentId)).toEqual({- foreignTopicCount: 2,+ foreignTopicCount: 1,hasForeignContent: true,});});@@ -339,6 +353,21 @@ describe('AgentModel.getDeleteImpact', () => {});});+ it("ignores a teammate's topicless message carrying only a legacy session id", async () => {+ await linkSession('agtg-own-session', ownerId);+ await serverDB.insert(messages).values({+ id: 'agtg-teammate-message',+ role: 'user',+ sessionId: 'agtg-own-session',+ userId: teammateId,+ });++ expect(await ownerModel.getDeleteImpact(agentId)).toEqual({+ foreignTopicCount: 0,+ hasForeignContent: false,+ });+ });+it("ignores a teammate's message that is already in the trash", async () => {await serverDB.insert(messages).values({agentId,@@ -355,6 +384,166 @@ describe('AgentModel.getDeleteImpact', () => {});});+describe('AgentModel.transferAgent with legacy session-only rows', () => {+ const targetWs = 'agtg-target-ws';++ beforeEach(async () => {+ await serverDB+ .insert(workspaces)+ .values({ id: targetWs, name: 'target', primaryOwnerId: ownerId, slug: targetWs });+ });++ it('leaves them and their shell in the source scope and drops the link', async () => {+ await linkSession('agtg-legacy-session', ownerId);+ await serverDB.insert(topics).values([+ { agentId, id: 'agtg-moved-topic', userId: ownerId, workspaceId: wsId },+ {+ id: 'agtg-legacy-topic',+ sessionId: 'agtg-legacy-session',+ userId: ownerId,+ workspaceId: wsId,+ },+ ]);++ await ownerModel.transferAgent(agentId, targetWs, ownerId, 'public');++ const scopeOf = async (id: string) =>+ (await serverDB.select().from(topics).where(eq(topics.id, id)))[0]?.workspaceId;+ expect(await scopeOf('agtg-moved-topic')).toBe(targetWs);+ expect(await scopeOf('agtg-legacy-topic')).toBe(wsId);+ const [shell] = await serverDB+ .select()+ .from(sessions)+ .where(eq(sessions.id, 'agtg-legacy-session'));+ expect(shell.workspaceId).toBe(wsId);+ expect(+ await serverDB.select().from(agentsToSessions).where(eq(agentsToSessions.agentId, agentId)),+ ).toEqual([]);+ });++ it('keeps a held topic whole, and a later delete of the moved agent does not empty it', async () => {+ await linkSession('agtg-legacy-session', ownerId);+ await serverDB.insert(topics).values({+ id: 'agtg-legacy-topic',+ sessionId: 'agtg-legacy-session',+ userId: ownerId,+ workspaceId: wsId,+ });+ await serverDB.insert(messages).values({+ agentId,+ id: 'agtg-tagged-message',+ role: 'user',+ topicId: 'agtg-legacy-topic',+ userId: ownerId,+ workspaceId: wsId,+ });+ await serverDB.insert(threads).values({+ agentId,+ id: 'agtg-tagged-thread',+ topicId: 'agtg-legacy-topic',+ type: 'standalone',+ userId: ownerId,+ workspaceId: wsId,+ });++ await ownerModel.transferAgent(agentId, targetWs, ownerId, 'public');++ const threadRow = async () =>+ (await serverDB.select().from(threads).where(eq(threads.id, 'agtg-tagged-thread')))[0];+ const messageRow = async () =>+ (await serverDB.select().from(messages).where(eq(messages.id, 'agtg-tagged-message')))[0];+ expect((await threadRow()).workspaceId).toBe(wsId);+ expect((await messageRow()).workspaceId).toBe(wsId);++ await new AgentModel(serverDB, ownerId, targetWs).delete(agentId);++ expect(await serverDB.select().from(agents).where(eq(agents.id, agentId))).toEqual([]);+ expect((await threadRow()).agentId).toBeNull();+ expect((await messageRow()).agentId).toBeNull();+ });++ it('moved rows drop a held shell, so deleting the source session cannot cascade into them', async () => {+ await linkSession('agtg-shared-session', ownerId);+ await serverDB.insert(topics).values([+ {+ id: 'agtg-stays-topic',+ sessionId: 'agtg-shared-session',+ userId: ownerId,+ workspaceId: wsId,+ },+ {+ agentId,+ id: 'agtg-moves-topic',+ sessionId: 'agtg-shared-session',+ userId: ownerId,+ workspaceId: wsId,+ },+ ]);+ await serverDB.insert(messages).values([+ {+ agentId,+ id: 'agtg-moves-in-topic',+ role: 'user',+ sessionId: 'agtg-shared-session',+ topicId: 'agtg-moves-topic',+ userId: ownerId,+ workspaceId: wsId,+ },+ {+ agentId,+ id: 'agtg-moves-topicless',+ role: 'user',+ sessionId: 'agtg-shared-session',+ userId: ownerId,+ workspaceId: wsId,+ },+ ]);++ await ownerModel.transferAgent(agentId, targetWs, ownerId, 'public');+ await serverDB.delete(sessions).where(eq(sessions.id, 'agtg-shared-session'));++ const [movedTopic] = await serverDB+ .select()+ .from(topics)+ .where(eq(topics.id, 'agtg-moves-topic'));+ expect(movedTopic).toMatchObject({ sessionId: null, workspaceId: targetWs });+ const moved = await serverDB+ .select()+ .from(messages)+ .where(inArray(messages.id, ['agtg-moves-in-topic', 'agtg-moves-topicless']));+ expect(moved).toHaveLength(2);+ expect(moved.every((row) => row.sessionId === null && row.workspaceId === targetWs)).toBe(true);+ // The row that stayed went with its own session, as any session delete does.+ expect(await serverDB.select().from(topics).where(eq(topics.id, 'agtg-stays-topic'))).toEqual(+ [],+ );+ });++ it('still moves a linked shell that holds nothing outside the agent', async () => {+ await linkSession('agtg-clean-session', ownerId);+ await serverDB.insert(topics).values({+ agentId,+ id: 'agtg-clean-topic',+ sessionId: 'agtg-clean-session',+ userId: ownerId,+ workspaceId: wsId,+ });++ await ownerModel.transferAgent(agentId, targetWs, ownerId, 'public');++ const [shell] = await serverDB+ .select()+ .from(sessions)+ .where(eq(sessions.id, 'agtg-clean-session'));+ expect(shell.workspaceId).toBe(targetWs);+ const [link] = await serverDB+ .select()+ .from(agentsToSessions)+ .where(eq(agentsToSessions.agentId, agentId));+ expect(link.workspaceId).toBe(targetWs);+ });+});+describe('AgentModel.transferAgentOwnership guards', () => {const handover = (model: AgentModel) =>serverDB.transaction((trx) =>diff --git a/packages/database/src/models/__tests__/agentHistoryJob.test.ts b/packages/database/src/models/__tests__/agentHistoryJob.test.tsindex a1745895773..5fb88d9069e 100644--- a/packages/database/src/models/__tests__/agentHistoryJob.test.ts+++ b/packages/database/src/models/__tests__/agentHistoryJob.test.ts@@ -16,7 +16,6 @@ const topicId = 'ahj-dispatch-topic';const createTransferJob = () =>AgentTransferJobModel.createJob(serverDB, {agentIds: [],- sessionIds: [],source: { userId, workspaceId: null },target: { userId, workspaceId: null },topics: [{ activityAt: new Date(), id: topicId }],diff --git a/packages/database/src/models/__tests__/agentTransferJob.coverage.test.ts b/packages/database/src/models/__tests__/agentTransferJob.coverage.test.tsindex dad399db27c..172ac10535d 100644--- a/packages/database/src/models/__tests__/agentTransferJob.coverage.test.ts+++ b/packages/database/src/models/__tests__/agentTransferJob.coverage.test.ts@@ -3,7 +3,7 @@ import { eq, inArray } from 'drizzle-orm';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { getTestDB } from '../../core/getTestDB';-import { agentHistoryJobs, topics, users } from '../../schemas';+import { agentHistoryJobs, agents, messages, sessions, topics, users } from '../../schemas';import type { LobeChatDatabase } from '../../type';import {AgentTransferJobModel,@@ -54,6 +54,65 @@ describe('AgentTransferJobModel coverage edges', () => {expect(executor.execute).not.toHaveBeenCalled();});+ it('rewriteResidualMessageScope still moves the session residual of an already queued job', async () => {+ await serverDB.insert(users).values({ id: 'atjcov-target' });+ await serverDB.insert(sessions).values({ id: 'atjcov-s', slug: 'atjcov-s', userId });+ await serverDB+ .insert(messages)+ .values({ id: 'atjcov-m', role: 'user', sessionId: 'atjcov-s', userId });++ await rewriteResidualMessageScope(+ serverDB,+ { agentIds: [], sessionIds: ['atjcov-s'] },+ { userId: 'atjcov-target', workspaceId: null },+ );++ const [row] = await serverDB.select().from(messages).where(eq(messages.id, 'atjcov-m'));+ expect(row.userId).toBe('atjcov-target');+ await serverDB.delete(users).where(eq(users.id, 'atjcov-target'));+ });++ it('a queued job clears held session references from in-topic and topicless rows', async () => {+ await serverDB.insert(users).values({ id: 'atjcov-target' });+ await serverDB.insert(sessions).values({ id: 'atjcov-held', slug: 'atjcov-held', userId });+ await serverDB.insert(agents).values({ id: 'atjcov-agent', userId });+ await serverDB.insert(messages).values([+ {+ agentId: 'atjcov-agent',+ id: 'atjcov-in-topic',+ role: 'user',+ sessionId: 'atjcov-held',+ topicId: topicIds[0],+ userId,+ },+ {+ agentId: 'atjcov-agent',+ id: 'atjcov-topicless',+ role: 'user',+ sessionId: 'atjcov-held',+ userId,+ },+ ]);+ const jobId = await AgentTransferJobModel.createJob(serverDB, {+ agentIds: ['atjcov-agent'],+ detachSessionIds: ['atjcov-held'],+ source: target,+ target: { userId: 'atjcov-target', workspaceId: null },+ topics: [{ activityAt: new Date(), id: topicIds[0] }],+ });+ createdJobIds.push(jobId);++ await AgentTransferJobModel.drain(serverDB, jobId);++ const rows = await serverDB+ .select()+ .from(messages)+ .where(inArray(messages.id, ['atjcov-in-topic', 'atjcov-topicless']));+ expect(rows).toHaveLength(2);+ expect(rows.every((r) => r.sessionId === null && r.userId === 'atjcov-target')).toBe(true);+ await serverDB.delete(users).where(eq(users.id, 'atjcov-target'));+ });+it('remapMessageAgentIdsForTopics issues no statement without remap pairs', async () => {const executor = { execute: vi.fn() };@@ -101,7 +160,6 @@ describe('AgentTransferJobModel coverage edges', () => {const createJob = async () => {const jobId = await AgentTransferJobModel.createJob(serverDB, {agentIds: [],- sessionIds: [],source: target,target,topics: topicIds.map((id, index) => ({ activityAt: new Date(2026, 0, index + 1), id })),diff --git a/packages/database/src/models/__tests__/agentTransferOwnership.test.ts b/packages/database/src/models/__tests__/agentTransferOwnership.test.tsindex 1381909f0df..41a2f8d5684 100644--- a/packages/database/src/models/__tests__/agentTransferOwnership.test.ts+++ b/packages/database/src/models/__tests__/agentTransferOwnership.test.ts@@ -977,7 +977,6 @@ describe('AgentModel.transferAgentOwnership', () => {await serverDB.transaction((trx) =>AgentTransferJobModel.createJob(trx, {agentIds: [agent.id],- sessionIds: [],source: { userId: ownerId, workspaceId: wsId },target: { userId: teammateId, workspaceId: wsId },topics: [],diff --git a/packages/database/src/models/__tests__/messages/message.trash.test.ts b/packages/database/src/models/__tests__/messages/message.trash.test.tsindex 50445a22147..c4f78820e2b 100644--- a/packages/database/src/models/__tests__/messages/message.trash.test.ts+++ b/packages/database/src/models/__tests__/messages/message.trash.test.ts@@ -426,7 +426,7 @@ describe('MessageTrashMutations.softDeleteTopicless', () => {await expect(messageModel.softDeleteTopicless({}, { deletedAt })).resolves.toEqual([]);});- it('stamps topic-less rows of the given agents and sessions only', async () => {+ it('stamps topic-less rows of the given agents only, not session-only rows', async () => {await serverDB.insert(agents).values([{ id: 'agent-a', title: 'Agent A', userId }]);await serverDB.insert(sessions).values([{ id: 'sess-a', userId }]);await serverDB.insert(messages).values([@@ -455,38 +455,14 @@ describe('MessageTrashMutations.softDeleteTopicless', () => {},]);- const result = await messageModel.softDeleteTopicless(- { agentIds: ['agent-a'], sessionIds: ['sess-a'] },- { deletedAt },- );+ const result = await messageModel.softDeleteTopicless({ agentIds: ['agent-a'] }, { deletedAt });- expect(result.map((entry) => entry.id).sort()).toEqual(['tl-1', 'tl-2']);+ expect(result.map((entry) => entry.id)).toEqual(['tl-1']);expect((await row('tl-1')).isDeleted).toBe(true);- expect((await row('tl-2')).isDeleted).toBe(true);+ expect((await row('tl-2')).isDeleted).toBeNull();expect((await row('tl-3')).isDeleted).toBeNull();expect((await row('tl-4')).isDeleted).toBeNull();});-- it('supports filtering by a single parent kind', async () => {- await serverDB.insert(agents).values([{ id: 'agent-b', title: 'Agent B', userId }]);- await serverDB.insert(sessions).values([{ id: 'sess-b', userId }]);- await serverDB.insert(messages).values([- { agentId: 'agent-b', content: 'agentless', id: 'tl-5', role: 'user', userId },- { content: 'sessionless', id: 'tl-6', role: 'user', sessionId: 'sess-b', userId },- ]);-- const byAgent = await messageModel.softDeleteTopicless(- { agentIds: ['agent-b'] },- { deletedAt },- );- expect(byAgent.map((entry) => entry.id)).toEqual(['tl-5']);-- const bySession = await messageModel.softDeleteTopicless(- { sessionIds: ['sess-b'] },- { deletedAt },- );- expect(bySession.map((entry) => entry.id)).toEqual(['tl-6']);- });});describe('MessageTrashMutations.purgeMessages', () => {diff --git a/packages/database/src/models/__tests__/session.coverage.test.ts b/packages/database/src/models/__tests__/session.coverage.test.tsindex 28322d8450b..39ee301e3d1 100644--- a/packages/database/src/models/__tests__/session.coverage.test.ts+++ b/packages/database/src/models/__tests__/session.coverage.test.ts@@ -3,7 +3,7 @@ import { eq, inArray } from 'drizzle-orm';import { afterEach, beforeEach, describe, expect, it } from 'vitest';import { getTestDB } from '../../core/getTestDB';-import { agents, agentsToSessions, sessions, users } from '../../schemas';+import { agents, agentsToSessions, messages, sessions, topics, users } from '../../schemas';import type { LobeChatDatabase } from '../../type';import { SessionModel } from '../session';@@ -111,11 +111,11 @@ describe('SessionModel coverage', () => {});});- describe('deleteShellsByIds', () => {+ describe('deleteEmptyShellsByIds', () => {it('does nothing for no ids', async () => {await serverDB.insert(sessions).values({ id: 'sc-shell', userId });- await sessionModel.deleteShellsByIds([]);+ await sessionModel.deleteEmptyShellsByIds([]);expect(await findSession('sc-shell')).toBeDefined();});@@ -126,10 +126,28 @@ describe('SessionModel coverage', () => {{ id: 'sc-foreign', userId: otherUserId },]);- await sessionModel.deleteShellsByIds(['sc-shell', 'sc-foreign']);+ await sessionModel.deleteEmptyShellsByIds(['sc-shell', 'sc-foreign']);expect(await findSession('sc-shell')).toBeUndefined();expect(await findSession('sc-foreign')).toBeDefined();});++ it('keeps a shell that still holds session-only topics or messages', async () => {+ await serverDB.insert(sessions).values([+ { id: 'sc-with-topic', userId },+ { id: 'sc-with-message', userId },+ { id: 'sc-empty', userId },+ ]);+ await serverDB.insert(topics).values({ id: 'sc-topic', sessionId: 'sc-with-topic', userId });+ await serverDB+ .insert(messages)+ .values({ id: 'sc-message', role: 'user', sessionId: 'sc-with-message', userId });++ await sessionModel.deleteEmptyShellsByIds(['sc-with-topic', 'sc-with-message', 'sc-empty']);++ expect(await findSession('sc-with-topic')).toBeDefined();+ expect(await findSession('sc-with-message')).toBeDefined();+ expect(await findSession('sc-empty')).toBeUndefined();+ });});});diff --git a/packages/database/src/models/__tests__/topics/topic.characterization.test.ts b/packages/database/src/models/__tests__/topics/topic.characterization.test.tsindex 2e50ef709bb..32ba859c199 100644--- a/packages/database/src/models/__tests__/topics/topic.characterization.test.ts+++ b/packages/database/src/models/__tests__/topics/topic.characterization.test.ts@@ -219,12 +219,8 @@ describe('TopicModel - characterization', () => {],['softDeleteByParents',- () =>- topicModel.softDeleteByParents(- { groupIds: [groupId], sessionIds: [sessionId] },- { deletedAt },- ),- ['group-topic', 'session-topic'],+ () => topicModel.softDeleteByParents({ groupIds: [groupId] }, { deletedAt }),+ ['group-topic'],],['softDeleteByParents({})', () => topicModel.softDeleteByParents({}, { deletedAt }), []],[diff --git a/packages/database/src/models/__tests__/topics/topic.ownedWorktreeFirstSend.test.ts b/packages/database/src/models/__tests__/topics/topic.ownedWorktreeFirstSend.test.tsindex 05ae071cc1b..a117081331e 100644--- a/packages/database/src/models/__tests__/topics/topic.ownedWorktreeFirstSend.test.ts+++ b/packages/database/src/models/__tests__/topics/topic.ownedWorktreeFirstSend.test.ts@@ -268,12 +268,10 @@ describe('owned worktree lookups by id and parent', () => {expect((await model().findOwnedWorktreeTopics(['by-id'])).map((row) => row.id)).toEqual(['by-id',]);- expect(await model().findWaitingCleanupTopicsUnder({ agentIds: [], sessionIds: [] })).toEqual(- [],- );+ expect(await model().findWaitingCleanupTopicsUnder({ agentIds: [], topicIds: [] })).toEqual([]);});- it('finds waiting cleanups under agents, legacy sessions, and both', async () => {+ it('finds waiting cleanups under agents, by topic id, and both', async () => {const waiting = (): ChatTopicMetadata => ({ownedWorktrees: [{@@ -291,18 +289,18 @@ describe('owned worktree lookups by id and parent', () => {});expect(- (await model().findWaitingCleanupTopicsUnder({ agentIds: ['agent-1'], sessionIds: [] })).map(+ (await model().findWaitingCleanupTopicsUnder({ agentIds: ['agent-1'], topicIds: [] })).map((row) => row.id,),- ).toContain('w-agent');+ ).toEqual(['w-agent']);expect(- (- await model().findWaitingCleanupTopicsUnder({ agentIds: [], sessionIds: ['session-1'] })- ).map((row) => row.id),- ).toContain('w-session');+ (await model().findWaitingCleanupTopicsUnder({ agentIds: [], topicIds: ['w-session'] })).map(+ (row) => row.id,+ ),+ ).toEqual(['w-session']);const both = await model().findWaitingCleanupTopicsUnder({agentIds: ['agent-1'],- sessionIds: ['session-1'],+ topicIds: ['w-session'],});expect(both.map((row) => row.id).sort()).toEqual(['w-agent', 'w-session']);});diff --git a/packages/database/src/models/__tests__/trash.test.ts b/packages/database/src/models/__tests__/trash.test.tsindex 34b42adf096..d92f5e9fc85 100644--- a/packages/database/src/models/__tests__/trash.test.ts+++ b/packages/database/src/models/__tests__/trash.test.ts@@ -680,7 +680,7 @@ describe('TrashModel', () => {describe('removeRootsUnderAgents', () => {it('is a no-op without agents and drops topic/message roots owned by the purged agents', async () => {- await model.removeRootsUnderAgents({ agentIds: [], sessionIds: [] });+ await model.removeRootsUnderAgents({ agentIds: [] });await serverDB.insert(agents).values({ id: 'agt_purged', userId });await serverDB.insert(topics).values({ agentId: 'agt_purged', id: 'tpc_root', userId });@@ -706,14 +706,14 @@ describe('TrashModel', () => {root: { projectId: null, resourceId: 'tpc_keep', resourceType: 'topic' },});- await model.removeRootsUnderAgents({ agentIds: ['agt_purged'], sessionIds: [] });+ await model.removeRootsUnderAgents({ agentIds: ['agt_purged'] });expect(await model.findById(topicRoot.id)).toBeUndefined();expect(await model.findById(messageRoot.id)).toBeUndefined();expect(await model.findById(unrelated.id)).toBeDefined();});- it('matches legacy session shells and runs inside a caller transaction', async () => {+ it('matches topics listed by id and runs inside a caller transaction', async () => {await serverDB.insert(sessions).values({ id: 'sess_1', slug: 'sess-1', userId });await serverDB.insert(topics).values({ id: 'tpc_sess', sessionId: 'sess_1', userId });const root = await model.register({@@ -722,11 +722,57 @@ describe('TrashModel', () => {});await serverDB.transaction(async (tx) => {- await model.removeRootsUnderAgents({ agentIds: ['agt_x'], sessionIds: ['sess_1'] }, tx);+ await model.removeRootsUnderAgents({ agentIds: ['agt_x'], topicIds: ['tpc_sess'] }, tx);});expect(await model.findById(root.id)).toBeUndefined();});++ it('leaves the root of a session-only topic the purge does not remove', async () => {+ await serverDB.insert(sessions).values({ id: 'sess_2', slug: 'sess-2', userId });+ await serverDB.insert(topics).values({ id: 'tpc_keep2', sessionId: 'sess_2', userId });+ const root = await model.register({+ deletedAt: at('2026-08-01T00:00:00Z'),+ root: { projectId: null, resourceId: 'tpc_keep2', resourceType: 'topic' },+ });++ await model.removeRootsUnderAgents({ agentIds: ['agt_x'] });++ expect(await model.findById(root.id)).toBeDefined();+ });+ });++ describe('findChildrenOutsideAgents', () => {+ it('lists only the children the agent FK cascade will not reach', async () => {+ await serverDB.insert(agents).values({ id: 'agt_root', userId });+ await serverDB.insert(sessions).values({ id: 'sess_3', slug: 'sess-3', userId });+ await serverDB.insert(topics).values([+ { agentId: 'agt_root', id: 'tpc_by_agent', userId },+ { id: 'tpc_by_session', sessionId: 'sess_3', userId },+ ]);+ await serverDB.insert(messages).values([+ { agentId: 'agt_root', id: 'msg_by_agent', role: 'user', userId },+ { id: 'msg_by_session', role: 'user', sessionId: 'sess_3', userId },+ ]);+ const root = await model.register({+ children: ['tpc_by_agent', 'tpc_by_session']+ .map((resourceId) => ({ projectId: null, resourceId, resourceType: 'topic' as const }))+ .concat(+ ['msg_by_agent', 'msg_by_session'].map((resourceId) => ({+ projectId: null,+ resourceId,+ resourceType: 'message' as any,+ })),+ ),+ deletedAt: at('2026-08-01T00:00:00Z'),+ root: { projectId: null, resourceId: 'agt_root', resourceType: 'agent' },+ });++ expect(await model.findChildrenOutsideAgents(root.id, ['agt_root'])).toEqual({+ messageIds: ['msg_by_session'],+ topicIds: ['tpc_by_session'],+ });+ });});describe('list cursor decoding', () => {diff --git a/packages/database/src/models/agent/delete.ts b/packages/database/src/models/agent/delete.tsindex 6658e2cd963..fd14dff08d7 100644--- a/packages/database/src/models/agent/delete.ts+++ b/packages/database/src/models/agent/delete.ts@@ -1,6 +1,6 @@-import { and, inArray } from 'drizzle-orm';+import { and, eq, exists, inArray, isNull, notInArray, or } from 'drizzle-orm';-import { agents, agentsToSessions } from '../../schemas';+import { agents, agentsToSessions, messages, threads, topics } from '../../schemas';import type { LobeChatDatabase, Transaction } from '../../type';import { AGENT_COPY_IN_PROGRESS, AgentCopyJobModel } from '../agentCopyJob';import { AGENT_TRANSFER_IN_PROGRESS, AgentTransferJobModel } from '../agentTransferJob';@@ -39,6 +39,41 @@ export const assertDeletable = async (return trx ? run(trx) : run(ctx.db);};+/**+ * Clear these agents from messages and threads inside a topic that outlives+ * them. An old topic can carry only `session_id` while later messages carry+ * `agent_id`; the `agent_id` FK cascade would empty a topic that is meant to+ * stay. Group topics are left alone: their members' rows keep today's cascade.+ */+export const detachFromSurvivingTopics = async (+ ctx: Pick<AgentModelContext, 'db'>,+ agentIds: string[],+) => {+ if (agentIds.length === 0) return;+ const survivingTopic = (topicId: typeof messages.topicId | typeof threads.topicId) =>+ exists(+ ctx.db+ .select({ id: topics.id })+ .from(topics)+ .where(+ and(+ eq(topics.id, topicId),+ isNull(topics.groupId),+ or(isNull(topics.agentId), notInArray(topics.agentId, agentIds)),+ ),+ ),+ );++ await ctx.db+ .update(messages)+ .set({ agentId: null, updatedAt: messages.updatedAt })+ .where(and(inArray(messages.agentId, agentIds), survivingTopic(messages.topicId)));+ await ctx.db+ .update(threads)+ .set({ agentId: null, updatedAt: threads.updatedAt })+ .where(and(inArray(threads.agentId, agentIds), survivingTopic(threads.topicId)));+};+/** Legacy session shells linked to the given agents (used to stamp `topics.session_id` rows). */export const findSessionIdsByAgentIds = async (ctx: AgentModelContext,diff --git a/packages/database/src/models/agent/index.ts b/packages/database/src/models/agent/index.tsindex a39664acb09..2b7b904e273 100644--- a/packages/database/src/models/agent/index.ts+++ b/packages/database/src/models/agent/index.ts@@ -110,6 +110,7 @@ export class AgentModel {agentId,);assertDeletable = this.withContext(remove.assertDeletable);+ detachFromSurvivingTopics = this.withContext(remove.detachFromSurvivingTopics);findSessionIdsByAgentIds = this.withContext(remove.findSessionIdsByAgentIds);findAgentIdsBySessionIds = this.withContext(remove.findAgentIdsBySessionIds);batchDelete = this.withContext(remove.batchDelete);diff --git a/packages/database/src/models/agent/transfer.ts b/packages/database/src/models/agent/transfer.tsindex 374193fe08a..d1f476b6c04 100644--- a/packages/database/src/models/agent/transfer.ts+++ b/packages/database/src/models/agent/transfer.ts@@ -1,10 +1,45 @@-import { and, count, eq, inArray, isNotNull, isNull, ne, or } from 'drizzle-orm';+import type { SQL } from 'drizzle-orm';+import { and, count, eq, inArray, isNull, ne, or, sql } from 'drizzle-orm';import { agentsToSessions, messages, sessions, tasks, threads, topics } from '../../schemas';import { notTrashed } from '../../utils/softDelete';import { hasForeignTopicComments } from '../topicComment';import { type AgentModelContext } from './context';+/**+ * Whether any topic matching `topicWhere` holds a message by someone else.+ *+ * LATERAL with its own LIMIT keeps this a per-topic probe of+ * `messages_topic_id_idx`. A plain join or EXISTS is flattened, and for an+ * agent holding a large share of the table the planner then hashes a Seq Scan+ * of `messages`, the cost this lookup exists to avoid.+ */+const hasForeignMessageInTopics = async (+ ctx: AgentModelContext,+ topicWhere: SQL,+ options: { liveOnly: boolean },+): Promise<boolean> => {+ const foreignMessage = ctx.db+ .select({ id: messages.id })+ .from(messages)+ .where(+ and(+ eq(messages.topicId, topics.id),+ ne(messages.userId, ctx.userId),+ options.liveOnly ? notTrashed(messages.isDeleted) : undefined,+ ),+ )+ .limit(1)+ .as('foreign_message');+ const [row] = await ctx.db+ .select({ id: foreignMessage.id })+ .from(topics)+ .innerJoinLateral(foreignMessage, sql`true`)+ .where(topicWhere)+ .limit(1);+ return !!row;+};+/*** Transfer an agent and all its associated data to a different workspace or personal account.* Runs in a single transaction to ensure atomicity.@@ -26,28 +61,17 @@ export const transferHasForeignRows = async (const agentIds = Array.isArray(agentId) ? agentId : [agentId];if (agentIds.length === 0) return false;- const links = await ctx.db- .select({ sessionId: agentsToSessions.sessionId })+ // The transfer still rehomes the linked session shells, and a member who+ // merely opened the shared agent owns one even with no topics/messages yet.+ const [foreignSession] = await ctx.db+ .select({ id: sessions.id }).from(agentsToSessions)- .where(inArray(agentsToSessions.agentId, agentIds));- const sessionIds = [...new Set(links.map((link) => link.sessionId))];-- // A member who merely opened the shared agent already owns a linked- // session, even with no topics/messages yet β the transfer would rewrite- // that session row too.- if (sessionIds.length > 0) {- const [foreignSession] = await ctx.db- .select({ id: sessions.id })- .from(sessions)- .where(and(inArray(sessions.id, sessionIds), ne(sessions.userId, ctx.userId)))- .limit(1);- if (foreignSession) return true;- }+ .innerJoin(sessions, eq(agentsToSessions.sessionId, sessions.id))+ .where(and(inArray(agentsToSessions.agentId, agentIds), ne(sessions.userId, ctx.userId)))+ .limit(1);+ if (foreignSession) return true;- const topicWhere =- sessionIds.length > 0- ? or(inArray(topics.sessionId, sessionIds), inArray(topics.agentId, agentIds))- : inArray(topics.agentId, agentIds);+ const topicWhere = inArray(topics.agentId, agentIds);const [foreignTopic] = await ctx.db.select({ id: topics.id }).from(topics)@@ -58,16 +82,16 @@ export const transferHasForeignRows = async (// Comments move (or die, when the target is personal scope) with their// topics β a teammate's comment on the caller's own topic is still their// work. NULL authors (deleted accounts) count as foreign too.- if (await hasForeignTopicComments(ctx.db, ctx.userId, topicWhere!)) return true;+ if (await hasForeignTopicComments(ctx.db, ctx.userId, topicWhere)) return true;++ // Messages move with their topic whatever agent they carry, and by their+ // own `agent_id` otherwise. Two queries so each one can use its index.+ if (await hasForeignMessageInTopics(ctx, topicWhere, { liveOnly: false })) return true;- const messageWhere =- sessionIds.length > 0- ? or(inArray(messages.sessionId, sessionIds), inArray(messages.agentId, agentIds))- : inArray(messages.agentId, agentIds);const [foreignMessage] = await ctx.db.select({ id: messages.id }).from(messages)- .where(and(messageWhere, ne(messages.userId, ctx.userId)))+ .where(and(inArray(messages.agentId, agentIds), ne(messages.userId, ctx.userId))).limit(1);if (foreignMessage) return true;@@ -95,8 +119,9 @@ export const transferHasForeignRows = async (* What deleting the agent takes down besides the caller's own work, for the* delete confirmation and the author's delete guard. Mirrors the trash* cascade (`softDeleteAgent`), which stamps only the agent, every live topic- * under it (with its messages and comments) and its topicless messages β- * linked sessions, threads and tasks stay where they are, so they never count:+ * with its `agent_id` (with its messages and comments) and its topicless+ * messages β linked sessions, rows carrying only a legacy `session_id`,+ * threads and tasks stay where they are, so they never count:* - `foreignTopicCount`: live topics other members started under the agent;* - `hasForeignContent`: that, or a teammate's comment / message riding along* inside the caller's own topics or among the topicless messages.@@ -105,54 +130,43 @@ export const getDeleteImpact = async (ctx: AgentModelContext,agentId: string,): Promise<{ foreignTopicCount: number; hasForeignContent: boolean }> => {- const links = await ctx.db- .select({ sessionId: agentsToSessions.sessionId })- .from(agentsToSessions)- .where(eq(agentsToSessions.agentId, agentId));- const sessionIds = [...new Set(links.map((link) => link.sessionId))];+ const topicWhere = and(eq(topics.agentId, agentId), notTrashed(topics.isDeleted))!;- const topicWhere = and(- sessionIds.length > 0- ? or(inArray(topics.sessionId, sessionIds), eq(topics.agentId, agentId))- : eq(topics.agentId, agentId),- notTrashed(topics.isDeleted),- )!;- const [row] = await ctx.db- .select({ count: count() })- .from(topics)- .where(and(topicWhere, ne(topics.userId, ctx.userId)));- const foreignTopicCount = Number(row?.count ?? 0);- if (foreignTopicCount > 0) return { foreignTopicCount, hasForeignContent: true };-- // Every live topic here is the caller's, so a foreign comment rides along- // inside one of them. NULL authors (deleted accounts) count as foreign.- if (await hasForeignTopicComments(ctx.db, ctx.userId, topicWhere))- return { foreignTopicCount, hasForeignContent: true };-- // Mirror the cascade exactly: every message inside an affected live topic- // (matched through the topic, whatever agent / session the message itself- // carries), plus the topicless messages `softDeleteTopicless` stamps by- // agent or session. A message in a topic outside the cascade, or inside an- // already-trashed topic, stays where it is and does not count.- const topiclessScope =- sessionIds.length > 0- ? or(inArray(messages.sessionId, sessionIds), eq(messages.agentId, agentId))- : eq(messages.agentId, agentId);- const [foreignMessage] = await ctx.db- .select({ id: messages.id })- .from(messages)- .leftJoin(topics, eq(messages.topicId, topics.id))- .where(- and(- ne(messages.userId, ctx.userId),- notTrashed(messages.isDeleted),- or(- and(isNull(messages.topicId), topiclessScope),- and(isNotNull(messages.topicId), topicWhere),- ),- ),- )- .limit(1);+ // Independent lookups, each on its own index. The message check is split in+ // two because one LEFT JOIN with an OR across both tables can use neither+ // and walks the whole messages table when nothing foreign exists.+ const [[topicRow], hasForeignComment, hasForeignTopicMessage, [foreignTopiclessMessage]] =+ await Promise.all([+ ctx.db+ .select({ count: count() })+ .from(topics)+ .where(and(topicWhere, ne(topics.userId, ctx.userId))),+ // NULL authors (deleted accounts) count as foreign.+ hasForeignTopicComments(ctx.db, ctx.userId, topicWhere),+ // Every message inside an affected live topic, whatever agent it carries.+ hasForeignMessageInTopics(ctx, topicWhere, { liveOnly: true }),+ // The topicless messages `softDeleteTopicless` stamps.+ ctx.db+ .select({ id: messages.id })+ .from(messages)+ .where(+ and(+ eq(messages.agentId, agentId),+ isNull(messages.topicId),+ ne(messages.userId, ctx.userId),+ notTrashed(messages.isDeleted),+ ),+ )+ .limit(1),+ ]);+ const foreignTopicCount = Number(topicRow?.count ?? 0);- return { foreignTopicCount, hasForeignContent: !!foreignMessage };+ return {+ foreignTopicCount,+ hasForeignContent:+ foreignTopicCount > 0 ||+ hasForeignComment ||+ hasForeignTopicMessage ||+ !!foreignTopiclessMessage,+ };};diff --git a/packages/database/src/models/agentTransferJob.ts b/packages/database/src/models/agentTransferJob.tsindex ef50d304df2..be6dd49d3d8 100644--- a/packages/database/src/models/agentTransferJob.ts+++ b/packages/database/src/models/agentTransferJob.ts@@ -56,6 +56,16 @@ const MESSAGE_CHILD_ANCHORS = [{ anchor: messageChunks.messageId, table: messageChunks },] as const;+/**+ * SET fragment clearing references to session shells that stayed in the source+ * scope, so deleting that scope cannot cascade into rows that moved away.+ * Applied in the scope rewrite because that already updates every row.+ */+const detachSessionsSet = (detachSessionIds?: string[]) =>+ detachSessionIds?.length+ ? sql`, session_id = CASE WHEN session_id IN ${detachSessionIds} THEN NULL ELSE session_id END`+ : sql``;+/*** Move ALL message rows anchored to the given topics β plus their child-table* rows and the topics' message_groups β into the target scope.@@ -73,6 +83,7 @@ export const rewriteMessageScopeForTopics = async (executor: Executor,topicIds: string[],target: AgentTransferTargetScope,+ detachSessionIds?: string[],): Promise<void> => {if (topicIds.length === 0) return;@@ -80,7 +91,7 @@ export const rewriteMessageScopeForTopics = async (await executor.execute(sql`UPDATE ${messages}- SET user_id = ${target.userId}, workspace_id = ${target.workspaceId}+ SET user_id = ${target.userId}, workspace_id = ${target.workspaceId}${detachSessionsSet(detachSessionIds)}WHERE ${inTopics}`);@@ -108,11 +119,13 @@ export const rewriteMessageScopeForTopics = async (*/export const rewriteResidualMessageScope = async (executor: Executor,- linkage: { agentIds: string[]; groupIds?: string[]; sessionIds: string[] },+ /** `sessionIds` is only set by jobs enqueued before transfers went agent-only. */+ linkage: { agentIds: string[]; groupIds?: string[]; sessionIds?: string[] },target: AgentTransferTargetScope,+ detachSessionIds?: string[],): Promise<void> => {const arms: SQL[] = [];- if (linkage.sessionIds.length > 0) arms.push(inArray(messages.sessionId, linkage.sessionIds));+ if (linkage.sessionIds?.length) arms.push(inArray(messages.sessionId, linkage.sessionIds));if (linkage.agentIds.length > 0) arms.push(inArray(messages.agentId, linkage.agentIds));if (linkage.groupIds && linkage.groupIds.length > 0)arms.push(inArray(messages.groupId, linkage.groupIds));@@ -122,7 +135,7 @@ export const rewriteResidualMessageScope = async (await executor.execute(sql`UPDATE ${messages}- SET user_id = ${target.userId}, workspace_id = ${target.workspaceId}+ SET user_id = ${target.userId}, workspace_id = ${target.workspaceId}${detachSessionsSet(detachSessionIds)}WHERE ${residual}`);@@ -254,6 +267,8 @@ export interface CreateAgentTransferJobParams {* `residualAgentIds`.*/agentIds: string[];+ /** Session shells that stayed in the source scope; moved rows drop their reference. */+ detachSessionIds?: string[];groupIds?: string[];/*** Agent linkage for the final topicless-residual rewrite; defaults to@@ -267,7 +282,6 @@ export interface CreateAgentTransferJobParams {* drift this framework exists to avoid.*/residualAgentIds?: string[];- sessionIds: string[];source: AgentTransferTargetScope;target: AgentTransferTargetScope;/** Topics whose messages await rewrite; `activityAt` orders the drain. */@@ -306,10 +320,16 @@ export class AgentTransferJobModel {// `payload` is the generic per-job slot; the remap only exists for// group transfers, so it stays out of the columns.payload:- params.agentIdRemap && params.agentIdRemap.length > 0- ? { agentIdRemap: params.agentIdRemap }+ params.agentIdRemap?.length || params.detachSessionIds?.length+ ? {+ ...(params.agentIdRemap?.length ? { agentIdRemap: params.agentIdRemap } : {}),+ ...(params.detachSessionIds?.length+ ? { detachSessionIds: params.detachSessionIds }+ : {}),+ }: undefined,- sessionIds: params.sessionIds,+ // NOT NULL column kept for jobs already queued; new jobs are agent-only.+ sessionIds: [],sourceUserId: params.source.userId,sourceWorkspaceId: params.source.workspaceId,targetUserId: params.target.userId,@@ -662,6 +682,7 @@ export class AgentTransferJobModel {// contract as the scope rewrite itself: the synchronous branch does this// inline, so the drain must do it on exactly the same rows.const agentIdRemap = job.payload?.agentIdRemap;+ const detachSessionIds = job.payload?.detachSessionIds;const [next] = await trx.select({ topicId: agentHistoryJobTopics.topicId })@@ -675,6 +696,7 @@ export class AgentTransferJobModel {trx,{ agentIds: job.agentIds, groupIds: job.groupIds, sessionIds: job.sessionIds },target,+ detachSessionIds,);if (agentIdRemap) await remapResidualMessageAgentIds(trx, job.groupIds, agentIdRemap);await trx@@ -690,7 +712,7 @@ export class AgentTransferJobModel {return { done: true };}- await rewriteMessageScopeForTopics(trx, [next.topicId], target);+ await rewriteMessageScopeForTopics(trx, [next.topicId], target, detachSessionIds);if (agentIdRemap) await remapMessageAgentIdsForTopics(trx, [next.topicId], agentIdRemap);await trx.delete(agentHistoryJobTopics)diff --git a/packages/database/src/models/message/trash.ts b/packages/database/src/models/message/trash.tsindex e6d8035623e..e5cfd57f339 100644--- a/packages/database/src/models/message/trash.ts+++ b/packages/database/src/models/message/trash.ts@@ -1,6 +1,5 @@import type { ChatToolPayload } from '@lobechat/types';-import type { SQL } from 'drizzle-orm';-import { and, eq, inArray, isNull, not, or } from 'drizzle-orm';+import { and, eq, inArray, isNull, not } from 'drizzle-orm';import { messagePlugins, messages, topics } from '../../schemas';import {@@ -285,26 +284,24 @@ export class MessageTrashMutations extends MessageScope {/*** Cascade helper for trashing an agent: stamps the live messages that hang- * off the given agents or their legacy session shells WITHOUT a topic. Rows- * inside a topic are hidden by that topic's own stamp; topic-less rows have+ * off the given agents WITHOUT a topic. Rows inside a topic are hidden by that topic's own stamp; topic-less rows have* no parent to hide them (`workspaceScope()` treats them as live), so they* are stamped directly and registered as the agent's children. Their branch* stays intact, so a plain restore of the same ids brings them back.*/- softDeleteTopicless = async (- parents: { agentIds?: string[]; sessionIds?: string[] },- options: SoftDeleteOptions,- ) => {- const conditions: SQL[] = [];- if (parents.agentIds?.length) conditions.push(inArray(messages.agentId, parents.agentIds));- if (parents.sessionIds?.length)- conditions.push(inArray(messages.sessionId, parents.sessionIds));- if (conditions.length === 0) return [];+ softDeleteTopicless = async (parents: { agentIds?: string[] }, options: SoftDeleteOptions) => {+ if (!parents.agentIds?.length) return [];return this.db.update(messages).set(trashStamp(options.deletedAt))- .where(and(isNull(messages.topicId), or(...conditions), this.ownership()))+ .where(+ and(+ isNull(messages.topicId),+ inArray(messages.agentId, parents.agentIds),+ this.ownership(),+ ),+ ).returning({ content: messages.content, id: messages.id, role: messages.role });};diff --git a/packages/database/src/models/session.ts b/packages/database/src/models/session.tsindex 895bccbf458..4f3b35d8084 100644--- a/packages/database/src/models/session.ts+++ b/packages/database/src/models/session.ts@@ -6,7 +6,7 @@ import type { PartialDeep } from 'type-fest';import { merge } from '@/utils/merge';import type { AgentItem, NewAgent, NewSession, SessionItem } from '../schemas';-import { agents, agentsToSessions, sessionGroups, sessions } from '../schemas';+import { agents, agentsToSessions, messages, sessionGroups, sessions, topics } from '../schemas';import type { LobeChatDatabase } from '../type';import { idGenerator } from '../utils/idGenerator';import { isTrashed, notTrashed } from '../utils/softDelete';@@ -451,10 +451,30 @@ export class SessionModel {* Drop the legacy session shells of an agent being purged from the recycle* bin. Their links are already gone by then, so the trashed-agent gate no* longer applies; the trash handler composes this with the agent purge.+ *+ * A shell that still holds topics or messages stays: those rows carry only+ * `session_id`, sit outside the agent's delete cascade, and the FK would+ * destroy them with the shell although nobody was told they would go.*/- deleteShellsByIds = async (ids: string[]) => {+ deleteEmptyShellsByIds = async (ids: string[]) => {if (ids.length === 0) return;- await this.db.delete(sessions).where(and(inArray(sessions.id, ids), this.scope()));+ await this.db+ .delete(sessions)+ .where(+ and(+ inArray(sessions.id, ids),+ this.scope(),+ notExists(+ this.db.select({ id: topics.id }).from(topics).where(eq(topics.sessionId, sessions.id)),+ ),+ notExists(+ this.db+ .select({ id: messages.id })+ .from(messages)+ .where(eq(messages.sessionId, sessions.id)),+ ),+ ),+ );};// **************** Update *************** //diff --git a/packages/database/src/models/topic/ownedWorktree.ts b/packages/database/src/models/topic/ownedWorktree.tsindex c681a8cf02a..ca3ac5ed3fc 100644--- a/packages/database/src/models/topic/ownedWorktree.ts+++ b/packages/database/src/models/topic/ownedWorktree.ts@@ -173,15 +173,15 @@ export const findPendingOwnedWorktreeTopics = async (};/**- * Topics under these agents / legacy sessions whose worktree cleanup is still+ * Topics under these agents, or listed by id, whose worktree cleanup is still* waiting (`pending` / `running`), trashed ones included: purging the parent- * would cascade them away with the only record of the folder to delete.+ * would take them with the only record of the folder to delete.*/export const findWaitingCleanupTopicsUnder = async (ctx: TopicModelContext,- { agentIds, sessionIds }: { agentIds: string[]; sessionIds: string[] },+ { agentIds, topicIds }: { agentIds: string[]; topicIds: string[] },): Promise<OwnedWorktreeTopicRow[]> => {- if (agentIds.length === 0 && sessionIds.length === 0) return [];+ if (agentIds.length === 0 && topicIds.length === 0) return [];return ctx.db.select(rowColumns).from(topics)@@ -190,7 +190,7 @@ export const findWaitingCleanupTopicsUnder = async (ctx.trashScope(),or(agentIds.length > 0 ? inArray(topics.agentId, agentIds) : undefined,- sessionIds.length > 0 ? inArray(topics.sessionId, sessionIds) : undefined,+ topicIds.length > 0 ? inArray(topics.id, topicIds) : undefined,),or(containsEntry({ cleanup: { state: 'pending' } }),diff --git a/packages/database/src/models/topic/trash.ts b/packages/database/src/models/topic/trash.tsindex aab66ed544e..d85a1c639a8 100644--- a/packages/database/src/models/topic/trash.ts+++ b/packages/database/src/models/topic/trash.ts@@ -120,17 +120,16 @@ export const softDeleteByAgentId = async (/*** Cascade helper for trashing an agent / group / session: stamps every live- * topic that hangs off any of the given parents (by `agent_id`, `session_id`- * or `group_id`) in one statement.+ * topic that hangs off any of the given parents (by `agent_id` or `group_id`)+ * in one statement.*/export const softDeleteByParents = async (ctx: TopicModelContext,- parents: { agentIds?: string[]; groupIds?: string[]; sessionIds?: string[] },+ parents: { agentIds?: string[]; groupIds?: string[] },options: SoftDeleteOptions,): Promise<TopicItem[]> => {const conditions: SQL[] = [];if (parents.agentIds?.length) conditions.push(inArray(topics.agentId, parents.agentIds));- if (parents.sessionIds?.length) conditions.push(inArray(topics.sessionId, parents.sessionIds));if (parents.groupIds?.length) conditions.push(inArray(topics.groupId, parents.groupIds));if (conditions.length === 0) return [];diff --git a/packages/database/src/models/trash.ts b/packages/database/src/models/trash.tsindex 21321cd65ce..c6dc6978645 100644--- a/packages/database/src/models/trash.ts+++ b/packages/database/src/models/trash.ts@@ -9,7 +9,21 @@ import type {TrashRootFilter,} from '@lobechat/types';import type { SQL } from 'drizzle-orm';-import { and, asc, count, desc, eq, inArray, isNull, lt, lte, not, or, sql } from 'drizzle-orm';+import {+ and,+ asc,+ count,+ desc,+ eq,+ inArray,+ isNull,+ lt,+ lte,+ not,+ notInArray,+ or,+ sql,+} from 'drizzle-orm';import type { AnyPgColumn } from 'drizzle-orm/pg-core';import type { NewTrashItemRow, TrashItemRow } from '../schemas';@@ -362,30 +376,66 @@ export class TrashModel {await db.delete(trashItems).where(inArray(trashItems.id, ids));};+ /**+ * Children registered under an agent root that its FK cascade will not reach:+ * rows an earlier cascade stamped through a legacy session shell. The bin+ * already promised to delete them, so the purge has to remove them itself.+ */+ findChildrenOutsideAgents = async (rootId: string, agentIds: string[]) => {+ const childIds = (resourceType: 'message' | 'topic') =>+ this.db+ .select({ id: trashItems.resourceId })+ .from(trashItems)+ .where(+ and(+ this.ownership(),+ eq(trashItems.rootId, rootId),+ eq(trashItems.resourceType, resourceType),+ ),+ );+ const topicRows = await this.db+ .select({ id: topics.id })+ .from(topics)+ .where(+ and(+ inArray(topics.id, childIds('topic')),+ or(isNull(topics.agentId), notInArray(topics.agentId, agentIds)),+ ),+ );+ const messageRows = await this.db+ .select({ id: messages.id })+ .from(messages)+ .where(+ and(+ inArray(messages.id, childIds('message')),+ or(isNull(messages.agentId), notInArray(messages.agentId, agentIds)),+ ),+ );+ return {+ messageIds: messageRows.map((row) => row.id),+ topicIds: topicRows.map((row) => row.id),+ };+ };+/*** Drop the roots of topics / messages that were trashed on their own before- * the agent they belong to (directly or through its legacy session shells),- * and so kept separate registry rows. Called while that agent is being- * purged: the FK cascade deletes those resources, so their rows would- * otherwise linger in the bin pointing at nothing.+ * the agent they belong to, and so kept separate registry rows. `topicIds`+ * adds the topics the purge removes by id ({@link findChildrenOutsideAgents}).+ * Called while that agent is being purged: those resources are deleted, so+ * their rows would otherwise linger in the bin pointing at nothing.*/removeRootsUnderAgents = async (- parents: { agentIds: string[]; sessionIds: string[] },+ parents: { agentIds: string[]; topicIds?: string[] },trx?: Transaction,) => {if (parents.agentIds.length === 0) return;const db = trx ?? this.db;- const topicOwner =- parents.sessionIds.length > 0- ? or(- inArray(topics.agentId, parents.agentIds),- inArray(topics.sessionId, parents.sessionIds),- )- : inArray(topics.agentId, parents.agentIds);+ const topicOwner = parents.topicIds?.length+ ? or(inArray(topics.agentId, parents.agentIds), inArray(topics.id, parents.topicIds))+ : inArray(topics.agentId, parents.agentIds);const ownedTopicIds = db.select({ id: topics.id }).from(topics).where(topicOwner);const messageOwner = or(inArray(messages.agentId, parents.agentIds),- parents.sessionIds.length > 0 ? inArray(messages.sessionId, parents.sessionIds) : undefined,inArray(messages.topicId, ownedTopicIds),);diff --git a/packages/database/src/repositories/agentDeletion/index.ts b/packages/database/src/repositories/agentDeletion/index.tsindex 470d6684ef8..7aef03fa646 100644--- a/packages/database/src/repositories/agentDeletion/index.ts+++ b/packages/database/src/repositories/agentDeletion/index.ts@@ -3,6 +3,7 @@ import { and, eq, inArray } from 'drizzle-orm';import { RESERVED_AGENT_SLUGS } from '../../models/agent/constants';import { type AgentModelContext, createAgentModelContext } from '../../models/agent/context';+import { detachFromSurvivingTopics } from '../../models/agent/delete';import { AGENT_COPY_IN_PROGRESS, AgentCopyJobModel } from '../../models/agentCopyJob';import { AGENT_TRANSFER_IN_PROGRESS, AgentTransferJobModel } from '../../models/agentTransferJob';import { agents, agentsToSessions, sessions } from '../../schemas';@@ -86,7 +87,8 @@ const deleteAgent = async (ctx: AgentModelContext, agentId: string) => {.where(and(inArray(sessions.id, sessionIds), ctx.sessionsOwnership()));}- // 4. Delete the agent itself+ // 4. Delete the agent itself, keeping what sits in topics that outlive it+ await detachFromSurvivingTopics({ db: trx as unknown as LobeChatDatabase }, [agentId]);return trx.delete(agents).where(and(eq(agents.id, agentId), ctx.ownership()));});};diff --git a/packages/database/src/repositories/agentGroup/__tests__/transferOwnership.test.ts b/packages/database/src/repositories/agentGroup/__tests__/transferOwnership.test.tsindex d1cc3427003..ec1d6fdfe1e 100644--- a/packages/database/src/repositories/agentGroup/__tests__/transferOwnership.test.ts+++ b/packages/database/src/repositories/agentGroup/__tests__/transferOwnership.test.ts@@ -254,7 +254,6 @@ describe('AgentGroupRepository.transferOwnership', () => {agentIds: [],groupIds: [group.id],residualAgentIds: [],- sessionIds: [],source: { userId: ownerId, workspaceId: wsId },target: { userId: teammateId, workspaceId: null },topics: [],diff --git a/packages/database/src/repositories/agentGroup/transfer.ts b/packages/database/src/repositories/agentGroup/transfer.tsindex bd2b0521498..b684dae01aa 100644--- a/packages/database/src/repositories/agentGroup/transfer.ts+++ b/packages/database/src/repositories/agentGroup/transfer.ts@@ -428,11 +428,7 @@ export const transferGroupToWorkspace = async (let transferJobId: string | null = null;if (affectedMessages <= getAgentTransferSyncMessageThreshold()) {await rewriteMessageScopeForTopics(trx, movedTopicIds, targetScope);- await rewriteResidualMessageScope(- trx,- { agentIds: [], groupIds: [groupId], sessionIds: [] },- targetScope,- );+ await rewriteResidualMessageScope(trx, { agentIds: [], groupIds: [groupId] }, targetScope);await remapMessageAgentIdsForTopics(trx, movedTopicIds, agentRemapPairs);await remapResidualMessageAgentIds(trx, [groupId], agentRemapPairs);} else {@@ -459,7 +455,6 @@ export const transferGroupToWorkspace = async (// the guards and the badge, but their own topicless messages are// not part of what a group transfer moves.residualAgentIds: [],- sessionIds: [],source: { userId: scope.userId, workspaceId: scope.workspaceId ?? null },target: targetScope,topics: movedTopics.map((topic) => ({diff --git a/packages/database/src/repositories/agentTransfer/index.ts b/packages/database/src/repositories/agentTransfer/index.tsindex 19fb2fe09fc..664c172986d 100644--- a/packages/database/src/repositories/agentTransfer/index.ts+++ b/packages/database/src/repositories/agentTransfer/index.ts@@ -1,5 +1,5 @@import type { LobeAgentAgencyConfig } from '@lobechat/types';-import { and, asc, count, eq, inArray, isNull, like, notInArray, or } from 'drizzle-orm';+import { and, asc, count, eq, inArray, isNull, like, notExists, notInArray, or } from 'drizzle-orm';import { type AgentModelContext, createAgentModelContext } from '../../models/agent/context';import { AGENT_SHARED_TRANSFER_BLOCKED, AgentOwnedByGroupError } from '../../models/agent/errors';@@ -49,6 +49,43 @@ import { rehomeAgentConnectorsForScopeTransfer } from '../../utils/agentConnectoimport { moveAgentDocumentsForScopeTransfer } from '../../utils/agentDocumentsOwnership';import { buildWorkspaceWhere } from '../../utils/workspace';+/**+ * Linked session shells that hold rows this transfer leaves behind: topics or+ * messages with no `agent_id` (or another agent's) that no moved topic carries.+ */+const findSessionsHoldingOtherRows = async (+ db: Pick<LobeChatDatabase, 'selectDistinct'>,+ sessionIds: string[],+ agentIds: string[],+): Promise<Set<string>> => {+ if (sessionIds.length === 0) return new Set();++ const topicRows = await db+ .selectDistinct({ sessionId: topics.sessionId })+ .from(topics)+ .where(+ and(+ inArray(topics.sessionId, sessionIds),+ or(isNull(topics.agentId), notInArray(topics.agentId, agentIds)),+ ),+ );+ const messageRows = await db+ .selectDistinct({ sessionId: messages.sessionId })+ .from(messages)+ .leftJoin(topics, eq(messages.topicId, topics.id))+ .where(+ and(+ inArray(messages.sessionId, sessionIds),+ or(isNull(messages.agentId), notInArray(messages.agentId, agentIds)),+ or(isNull(topics.agentId), notInArray(topics.agentId, agentIds)),+ ),+ );++ return new Set(+ [...topicRows, ...messageRows].flatMap((row) => (row.sessionId ? [row.sessionId] : [])),+ );+};+/*** Batch variant of {@link transferAgent}: moves several agents (and their* cascaded topics / messages / threads / tasks / β¦) in ONE transaction, with@@ -227,7 +264,23 @@ const transferAgents = async (.from(agentsToSessions).where(inArray(agentsToSessions.agentId, agentIds));- const sessionIds = [...new Set(links.map((l) => l.sessionId))];+ const linkedSessionIds = [...new Set(links.map((l) => l.sessionId))];++ // Rows carrying only a legacy `session_id` are outside the cascade and stay+ // in the source scope. Their shell stays with them and drops its link:+ // moved, it would let the target scope's session delete cascade into them.+ const heldSessionIds = await findSessionsHoldingOtherRows(trx, linkedSessionIds, agentIds);+ const sessionIds = linkedSessionIds.filter((id) => !heldSessionIds.has(id));+ if (heldSessionIds.size > 0) {+ await trx+ .delete(agentsToSessions)+ .where(+ and(+ inArray(agentsToSessions.agentId, agentIds),+ inArray(agentsToSessions.sessionId, [...heldSessionIds]),+ ),+ );+ }if (sessionIds.length > 0) {// `groupId` is cleared for the same reason as the agent's@@ -252,11 +305,8 @@ const transferAgents = async (// the device bindings stripped above.await trx.delete(agentLabelAssignments).where(inArray(agentLabelAssignments.agentId, agentIds));- // 6. Update topics (linked via sessionId or agentId)- const topicCondition =- sessionIds.length > 0- ? or(inArray(topics.sessionId, sessionIds), inArray(topics.agentId, agentIds))- : inArray(topics.agentId, agentIds);+ // 6. Update topics (linked via agentId)+ const topicCondition = inArray(topics.agentId, agentIds);// Create locks the topic before inserting a comment. Lock every topic in// the same order before the authoritative transfer authorization check,@@ -265,22 +315,31 @@ const transferAgents = async (await trx.select({ id: topics.id }).from(topics)- .where(topicCondition!)+ .where(topicCondition).orderBy(asc(topics.id)).for('update');if (options.rejectForeignTopicCommentAuthors &&- (await hasForeignTopicComments(trx, ctx.userId, topicCondition!))+ (await hasForeignTopicComments(trx, ctx.userId, topicCondition))) {throw new Error(TOPIC_COMMENT_TRANSFER_HAS_FOREIGN_AUTHORS);}const movedTopics = await trx.update(topics).set({ ...ownershipUpdate, updatedAt: topics.updatedAt })- .where(topicCondition!)+ .where(topicCondition).returning({ id: topics.id, updatedAt: topics.updatedAt });const movedTopicIds = movedTopics.map((topic) => topic.id);+ // A shell that stayed behind must not stay the FK parent of what moved:+ // deleting the source scope would cascade through it into the target.+ const detachSessionIds = [...heldSessionIds];+ if (detachSessionIds.length > 0) {+ await trx+ .update(topics)+ .set({ sessionId: null, updatedAt: topics.updatedAt })+ .where(and(topicCondition, inArray(topics.sessionId, detachSessionIds)));+ }// 6a. Topic comments denormalize the topic's workspaceId β move them// with the topic (or drop them when leaving workspace scope entirely),@@ -295,42 +354,56 @@ const transferAgents = async (// their source-scope snapshot until the job reaches them.//// Both paths anchor on the moved topics (plus a topicless residual by- // session/agent linkage) rather than the legacy session/agent-only- // condition, so topic-only rows (OpenAPI create shape) and the message- // child tables move too instead of stranding in the source scope.- const messageCondition =- sessionIds.length > 0- ? or(inArray(messages.sessionId, sessionIds), inArray(messages.agentId, agentIds))- : inArray(messages.agentId, agentIds);+ // agent) rather than an agent-only condition, so topic-only rows (OpenAPI+ // create shape) and the message child tables move too instead of stranding+ // in the source scope.+ const messageCondition = inArray(messages.agentId, agentIds);const [{ affectedMessages }] = await trx.select({ affectedMessages: count() }).from(messages).where(movedTopicIds.length > 0- ? or(inArray(messages.topicId, movedTopicIds), messageCondition!)- : messageCondition!,+ ? or(inArray(messages.topicId, movedTopicIds), messageCondition)+ : messageCondition,);const targetScope = { userId: targetUserId, workspaceId: targetWorkspaceId };let transferJobId: string | null = null;if (affectedMessages <= getAgentTransferSyncMessageThreshold()) {- await rewriteMessageScopeForTopics(trx, movedTopicIds, targetScope);- await rewriteResidualMessageScope(trx, { agentIds, sessionIds }, targetScope);+ await rewriteMessageScopeForTopics(trx, movedTopicIds, targetScope, detachSessionIds);+ await rewriteResidualMessageScope(trx, { agentIds }, targetScope, detachSessionIds);} else {transferJobId = await AgentTransferJobModel.createJob(trx, {agentIds,- sessionIds,+ detachSessionIds,source: { userId: ctx.userId, workspaceId: ctx.workspaceId ?? null },target: targetScope,topics: movedTopics.map((topic) => ({ activityAt: topic.updatedAt, id: topic.id })),});}- // 8. Update threads (linked via agentId)+ // 8. Update threads (linked via agentId). A thread inside a topic that stays+ // behind stays with it, or neither scope could load the whole conversation.await trx.update(threads).set({ ...ownershipUpdate, updatedAt: threads.updatedAt })- .where(inArray(threads.agentId, agentIds));+ .where(+ and(+ inArray(threads.agentId, agentIds),+ notExists(+ trx+ .select({ id: topics.id })+ .from(topics)+ .where(+ and(+ eq(topics.id, threads.topicId),+ or(isNull(topics.agentId), notInArray(topics.agentId, agentIds)),+ isNull(topics.groupId),+ ),+ ),+ ),+ ),+ );// 9. Update agent files associationsawait trxdiff --git a/packages/database/src/schemas/agentHistoryJob.ts b/packages/database/src/schemas/agentHistoryJob.tsindex 72368c64d2f..d0fa83167d3 100644--- a/packages/database/src/schemas/agentHistoryJob.ts+++ b/packages/database/src/schemas/agentHistoryJob.ts@@ -35,6 +35,11 @@ export interface AgentHistoryJobPayload {agentIdRemap?: { newAgentId: string; sourceAgentId: string }[];/** Agents duplicated by this job, for guards that only need the id map. */agents?: { newAgentId: string; sourceAgentId: string }[];+ /**+ * Agent transfers only: session shells that stayed in the source scope+ * because they still hold legacy rows. Moved messages drop their reference.+ */+ detachSessionIds?: string[];/*** Present only for a chat-group copy. Its presence is the discriminator the* drain uses to pick the group remap (every member agent maps through