Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

✨ feat(trash): recycle bin for agents and messages (#18412)

Arvin Xucac7e4c50b82
diff --git a/apps/server/src/routers/lambda/__tests__/integration/message.integration.test.ts b/apps/server/src/routers/lambda/__tests__/integration/message.integration.test.ts
index fa17ba81220..cc2df4e0d23 100644
--- a/apps/server/src/routers/lambda/__tests__/integration/message.integration.test.ts
+++ b/apps/server/src/routers/lambda/__tests__/integration/message.integration.test.ts
@@ -3,7 +3,7 @@ import { type LobeChatDatabase } from '@lobechat/database';
import { messages, sessions, topics } from '@lobechat/database/schemas';
import { getTestDB } from '@lobechat/database/test-utils';
import { ChatErrorType } from '@lobechat/types';
-import { eq } from 'drizzle-orm';
+import { and, eq, isNull } from 'drizzle-orm';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { messageRouter } from '../../message';
@@ -946,13 +946,18 @@ describe('Message Router Integration Tests', () => {
// Delete messages
await caller.removeMessages({ ids: [msg1Result.id, msg2Result.id] });
- // Verify messages were deleted
+ // Recycle bin: rows are stamped (hidden from reads), not dropped.
const remainingMessages = await serverDB
.select()
.from(messages)
- .where(eq(messages.agentId, testAgentId));
-
+ .where(and(eq(messages.agentId, testAgentId), isNull(messages.deletedAt)));
expect(remainingMessages).toHaveLength(0);
+ const stamped = await serverDB
+ .select()
+ .from(messages)
+ .where(eq(messages.agentId, testAgentId));
+ expect(stamped).toHaveLength(2);
+ expect(await caller.getMessages({ sessionId: testSessionId })).toHaveLength(0);
});
it('should return message list when sessionId is provided', async () => {
@@ -1004,12 +1009,13 @@ describe('Message Router Integration Tests', () => {
await caller.removeMessage({ id: msgResult.id });
// Verify messages were deleted
- const deletedMessage = await serverDB
+ // Recycle bin: still on disk with a stamp, invisible to reads.
+ const [deletedMessage] = await serverDB
.select()
.from(messages)
.where(eq(messages.id, msgResult.id));
-
- expect(deletedMessage).toHaveLength(0);
+ expect(deletedMessage.deletedAt).toBeTruthy();
+ expect(await caller.getMessages({ sessionId: testSessionId })).toHaveLength(0);
});
it('should return message list when sessionId is provided', async () => {
diff --git a/apps/server/src/routers/lambda/__tests__/session.test.ts b/apps/server/src/routers/lambda/__tests__/session.test.ts
index 365b5d2bcb8..110d3669814 100644
--- a/apps/server/src/routers/lambda/__tests__/session.test.ts
+++ b/apps/server/src/routers/lambda/__tests__/session.test.ts
@@ -24,6 +24,20 @@ vi.mock('@/server/services/resourcePermission', () => ({
assertCanEditResource: vi.fn(),
}));
+const mockInvalidateForResources = vi.hoisted(() => vi.fn());
+vi.mock('@/database/models/resourceTransferRequest', () => ({
+ ResourceTransferRequestModel: vi.fn(function () {
+ return { invalidateForResources: mockInvalidateForResources };
+ }),
+}));
+
+const mockTrashAgent = vi.hoisted(() => vi.fn());
+vi.mock('@/server/services/trash', () => ({
+ TrashService: vi.fn(function () {
+ return { trashAgent: mockTrashAgent };
+ }),
+}));
+
describe('sessionRouter', () => {
const userId = 'testUserId';
let sessionModelMock: any;
@@ -125,4 +139,52 @@ describe('sessionRouter', () => {
});
});
});
+
+ describe('removeSession', () => {
+ beforeEach(() => {
+ sessionModelMock.findByIdOrSlug.mockResolvedValue({
+ agent: { id: 'agent-1' },
+ id: 'session-1',
+ userId,
+ });
+ sessionModelMock.delete = vi
+ .fn()
+ .mockResolvedValue({ orphanedAgentIds: [], result: { count: 1 } });
+ sessionModelMock.isSoleShellOfAgent = vi.fn();
+ });
+
+ it("sends the agent to the recycle bin when this is the agent's only session", async () => {
+ sessionModelMock.isSoleShellOfAgent.mockResolvedValue(true);
+
+ const caller = sessionRouter.createCaller(mockCtx);
+ await caller.removeSession({ id: 'session-1' });
+
+ expect(sessionModelMock.isSoleShellOfAgent).toHaveBeenCalledWith('session-1', 'agent-1');
+ expect(mockTrashAgent).toHaveBeenCalledWith('agent-1');
+ expect(sessionModelMock.delete).not.toHaveBeenCalled();
+ });
+
+ // The session-delete path trashes the agent too, so it must void a pending
+ // handover exactly like `agent.removeAgent` — otherwise the recipient could
+ // still accept ownership of recycle-bin content.
+ it('voids pending transfers of the agent it sends to the recycle bin', async () => {
+ sessionModelMock.isSoleShellOfAgent.mockResolvedValue(true);
+
+ const caller = sessionRouter.createCaller({ ...mockCtx, workspaceId: 'ws-1' });
+ await caller.removeSession({ id: 'session-1' });
+
+ expect(mockTrashAgent).toHaveBeenCalledWith('agent-1');
+ expect(mockInvalidateForResources).toHaveBeenCalledWith('agent', ['agent-1']);
+ });
+
+ it('removes only this session when the agent is linked to other sessions', async () => {
+ sessionModelMock.isSoleShellOfAgent.mockResolvedValue(false);
+
+ const caller = sessionRouter.createCaller(mockCtx);
+ await caller.removeSession({ id: 'session-1' });
+
+ expect(mockTrashAgent).not.toHaveBeenCalled();
+ expect(sessionModelMock.delete).toHaveBeenCalledWith('session-1');
+ });
+ });
});
diff --git a/apps/server/src/routers/lambda/agent.ts b/apps/server/src/routers/lambda/agent.ts
index 4f67bfb78c1..6b43ffbbf13 100644
--- a/apps/server/src/routers/lambda/agent.ts
+++ b/apps/server/src/routers/lambda/agent.ts
@@ -53,6 +53,7 @@ import {
buildResourcePermissionState,
} from '@/server/services/resourcePermission';
import { assertTransferRecipientValid } from '@/server/services/resourceTransferRequest';
+import { TrashService } from '@/server/services/trash';
import {
hasWorkspaceScopedPermission,
isWorkspacePrimaryOwner,
@@ -800,7 +801,13 @@ export const agentRouter = router({
}
let result;
try {
- result = await ctx.agentModel.delete(input.agentId);
+ // Recycle bin: the agent, its session shells and every topic under it
+ // are stamped, not dropped — the FK cascade only runs at purge time.
+ result = await new TrashService(
+ ctx.serverDB,
+ ctx.userId,
+ ctx.workspaceId ?? undefined,
+ ).trashAgent(input.agentId);
} catch (error) {
if (error instanceof Error && error.message === AGENT_COPY_IN_PROGRESS) {
throw new TRPCError({
@@ -820,12 +827,12 @@ export const agentRouter = router({
}
throw error;
}
+ // Sharing grants are left in place while the agent sits in the bin (the
+ // row is invisible anyway) so a restore brings them back; the purge
+ // handler removes them for good. A pending handover is different: the
+ // agent is invisible to the recipient too, so an acceptance would move
+ // ownership of trashed content — void it now, as the hard delete did.
if (ctx.workspaceId) {
- await new ResourcePermissionModel(ctx.serverDB, ctx.workspaceId).removeAll(
- 'agent',
- input.agentId,
- );
- // A deleted agent can no longer be handed over — void any live request.
await new ResourceTransferRequestModel(
ctx.serverDB,
ctx.workspaceId,
diff --git a/apps/server/src/routers/lambda/message.ts b/apps/server/src/routers/lambda/message.ts
index 60bfda7ba57..914e860964b 100644
--- a/apps/server/src/routers/lambda/message.ts
+++ b/apps/server/src/routers/lambda/message.ts
@@ -690,11 +690,13 @@ export const messageRouter = router({
z
.object({
ids: z.array(z.string()),
+ /** Skip the recycle bin: internal cleanup whose rows must never be restored. */
+ permanent: z.boolean().optional(),
})
.extend(basicContextSchema.shape),
)
.mutation(async ({ input, ctx }) => {
- const { ids, agentId, ...options } = input;
+ const { ids, agentId, permanent, ...options } = input;
await assertCanUseMessageTargets(guardCtx(ctx), ids);
const resolved = await resolveContext(
{ agentId, ...options },
@@ -703,7 +705,7 @@ export const messageRouter = router({
ctx.workspaceId ?? undefined,
);
- return ctx.messageService.removeMessages(ids, resolved);
+ return ctx.messageService.removeMessages(ids, resolved, { permanent });
}),
removeMessagesByAssistant: messageProcedure
diff --git a/apps/server/src/routers/lambda/session.ts b/apps/server/src/routers/lambda/session.ts
index ad502002451..21b0556b95b 100644
--- a/apps/server/src/routers/lambda/session.ts
+++ b/apps/server/src/routers/lambda/session.ts
@@ -6,6 +6,7 @@ import { wsCompatProcedure } from '@/business/server/trpc-middlewares/workspaceA
import { AgentModel } from '@/database/models/agent';
import { ChatGroupModel } from '@/database/models/chatGroup';
import { ResourcePermissionModel } from '@/database/models/resourcePermission';
+import { ResourceTransferRequestModel } from '@/database/models/resourceTransferRequest';
import { SessionModel } from '@/database/models/session';
import { SessionGroupModel } from '@/database/models/sessionGroup';
import { insertAgentSchema, insertSessionSchema } from '@/database/schemas';
@@ -14,6 +15,7 @@ import { router } from '@/libs/trpc/lambda';
import { serverDatabase } from '@/libs/trpc/lambda/middleware';
import { createFtsSearchRepo } from '@/server/services/ftsSearch';
import { assertCanEditResource } from '@/server/services/resourcePermission';
+import { TrashService } from '@/server/services/trash';
import { AgentChatConfigSchema } from '@/types/agent';
import { LobeMetaDataSchema } from '@/types/meta';
import { type BatchTaskResult } from '@/types/service';
@@ -239,10 +241,37 @@ export const sessionRouter = router({
}
}
- const { orphanedAgentIds, result } = await ctx.sessionModel.delete(input.id);
+ // A session is normally the legacy 1:1 shell of an agent: removing it
+ // means removing the agent, so route through the agent's recycle-bin
+ // cascade (agent + session + topics all stamped, restorable as one unit).
+ // When the agent has other shells (or this shell holds other agents),
+ // only this session goes — the agent must stay with its other sessions.
+ if (
+ session?.agent &&
+ (await ctx.sessionModel.isSoleShellOfAgent(session.id, session.agent.id))
+ ) {
+ const trashService = new TrashService(
+ ctx.serverDB,
+ ctx.userId,
+ ctx.workspaceId ?? undefined,
+ );
+ const trashed = await trashService.trashAgent(session.agent.id);
+ // Same as `agent.removeAgent`: the trashed agent is invisible to a
+ // pending handover's recipient too, so an acceptance would move
+ // ownership of recycle-bin content — void it now.
+ if (ctx.workspaceId) {
+ await new ResourceTransferRequestModel(
+ ctx.serverDB,
+ ctx.workspaceId,
+ ).invalidateForResources('agent', [session.agent.id]);
+ }
+ return trashed;
+ }
- // Mirror `agent.removeAgent`: orphan-deleted shared agents must not
- // leave dangling resource_permissions rows behind.
+ // No linked agent (a stray legacy row) or a shell the agent does not
+ // depend on: hard delete this session only, as before. An agent left
+ // without any shell is orphan-deleted by the model.
+ const { orphanedAgentIds, result } = await ctx.sessionModel.delete(input.id);
if (ctx.workspaceId && orphanedAgentIds.length > 0) {
const permissionModel = new ResourcePermissionModel(ctx.serverDB, ctx.workspaceId);
await Promise.all(orphanedAgentIds.map((id) => permissionModel.removeAll('agent', id)));
diff --git a/apps/server/src/services/message/__tests__/index.test.ts b/apps/server/src/services/message/__tests__/index.test.ts
index dcc0ab79f67..d52702d56f5 100644
--- a/apps/server/src/services/message/__tests__/index.test.ts
+++ b/apps/server/src/services/message/__tests__/index.test.ts
@@ -18,6 +18,14 @@ vi.mock('@lobechat/tool-view-model', async (importOriginal) => {
const actual = await importOriginal<typeof ToolViewModelModule>();
return { ...actual, projectToolViewModels: vi.fn(actual.projectToolViewModels) };
});
+// Message removal goes through the recycle bin: the service delegates to
+// TrashService instead of the model's hard delete.
+const mockTrashMessages = vi.hoisted(() => vi.fn());
+vi.mock('@/server/services/trash', () => ({
+ TrashService: vi.fn(function () {
+ return { trashMessages: mockTrashMessages };
+ }),
+}));
describe('MessageService', () => {
let messageService: MessageService;
@@ -144,7 +152,7 @@ describe('MessageService', () => {
const result = await messageService.removeMessage(messageId);
- expect(mockMessageModel.deleteMessage).toHaveBeenCalledWith(messageId);
+ expect(mockTrashMessages).toHaveBeenCalledWith([messageId]);
expect(result).toEqual({ success: true });
expect(mockMessageModel.query).not.toHaveBeenCalled();
});
@@ -156,7 +164,7 @@ describe('MessageService', () => {
const result = await messageService.removeMessage(messageId, { sessionId: 'session-1' });
- expect(mockMessageModel.deleteMessage).toHaveBeenCalledWith(messageId);
+ expect(mockTrashMessages).toHaveBeenCalledWith([messageId]);
expect(mockMessageModel.query).toHaveBeenCalledWith(
{ groupId: undefined, sessionId: 'session-1', topicId: undefined },
expect.objectContaining({
@@ -173,7 +181,7 @@ describe('MessageService', () => {
const result = await messageService.removeMessage(messageId, { topicId: 'topic-1' });
- expect(mockMessageModel.deleteMessage).toHaveBeenCalledWith(messageId);
+ expect(mockTrashMessages).toHaveBeenCalledWith([messageId]);
expect(mockMessageModel.query).toHaveBeenCalledWith(
{ groupId: undefined, sessionId: undefined, topicId: 'topic-1' },
expect.objectContaining({
@@ -190,7 +198,7 @@ describe('MessageService', () => {
const result = await messageService.removeMessages(messageIds);
- expect(mockMessageModel.deleteMessages).toHaveBeenCalledWith(messageIds);
+ expect(mockTrashMessages).toHaveBeenCalledWith(messageIds);
expect(result).toEqual({ success: true });
expect(mockMessageModel.query).not.toHaveBeenCalled();
});
@@ -202,10 +210,19 @@ describe('MessageService', () => {
const result = await messageService.removeMessages(messageIds, { sessionId: 'session-1' });
- expect(mockMessageModel.deleteMessages).toHaveBeenCalledWith(messageIds);
+ expect(mockTrashMessages).toHaveBeenCalledWith(messageIds);
expect(mockMessageModel.query).toHaveBeenCalled();
expect(result).toEqual({ messages: mockMessages, success: true });
});
+
+ it('hard-deletes instead of trashing when the removal is permanent', async () => {
+ const messageIds = ['msg-1', 'msg-2'];
+
+ await messageService.removeMessages(messageIds, undefined, { permanent: true });
+
+ expect(mockMessageModel.deleteMessages).toHaveBeenCalledWith(messageIds);
+ expect(mockTrashMessages).not.toHaveBeenCalled();
+ });
});
describe('updateMessageRAG', () => {
@@ -624,7 +641,7 @@ describe('MessageService', () => {
const result = await messageService.removeMessage(messageId, { groupId, topicId });
- expect(mockMessageModel.deleteMessage).toHaveBeenCalledWith(messageId);
+ expect(mockTrashMessages).toHaveBeenCalledWith([messageId]);
expect(mockMessageModel.query).toHaveBeenCalledWith(
{ groupId, sessionId: undefined, topicId },
expect.objectContaining({
@@ -641,7 +658,7 @@ describe('MessageService', () => {
const result = await messageService.removeMessages(messageIds, { groupId, topicId });
- expect(mockMessageModel.deleteMessages).toHaveBeenCalledWith(messageIds);
+ expect(mockTrashMessages).toHaveBeenCalledWith(messageIds);
expect(mockMessageModel.query).toHaveBeenCalledWith(
{ groupId, sessionId: undefined, topicId },
expect.objectContaining({
diff --git a/apps/server/src/services/message/index.ts b/apps/server/src/services/message/index.ts
index c8a822b6603..bb8b0d180f0 100644
--- a/apps/server/src/services/message/index.ts
+++ b/apps/server/src/services/message/index.ts
@@ -14,6 +14,7 @@ import { createTimingHelpers, getDurationMs } from '@lobechat/utils';
import { MessageModel } from '@/database/models/message';
import { FileService } from '../file';
+import { TrashService } from '../trash';
import { resolveMessageFileUrls } from './resolveMessageFileUrls';
/** Apply the same error contract to single and batched message writes. */
@@ -106,11 +107,13 @@ export class MessageService {
private messageModel: MessageModel;
private fileService: FileService;
private compressionRepository: CompressionRepository;
+ private trashService: TrashService;
constructor(db: LobeChatDatabase, userId: string, workspaceId?: string) {
this.messageModel = new MessageModel(db, userId, workspaceId);
this.fileService = new FileService(db, userId, workspaceId);
this.compressionRepository = new CompressionRepository(db, userId, workspaceId);
+ this.trashService = new TrashService(db, userId, workspaceId);
}
/**
@@ -348,20 +351,26 @@ export class MessageService {
}
/**
- * Remove messages with optional message list return
- * Pattern: delete + conditional query
+ * Remove messages with optional message list return.
+ * Recycle bin: the rows are stamped (children re-parented, usage recomputed)
+ * and registered so they can be restored; the hard delete runs at purge.
+ * `permanent` skips the bin for internal cleanup whose rows must never come
+ * back (e.g. the partial rows a restart recovery replaces with the
+ * authoritative transcript — restoring them would revive a stale branch).
+ * Pattern: trash + conditional query
*/
- async removeMessages(ids: string[], options?: QueryOptions) {
- await this.messageModel.deleteMessages(ids);
+ async removeMessages(ids: string[], options?: QueryOptions, removal?: { permanent?: boolean }) {
+ if (removal?.permanent) await this.messageModel.deleteMessages(ids);
+ else await this.trashService.trashMessages(ids);
return this.queryWithSuccess(options);
}
/**
* Remove single message with optional message list return
- * Pattern: delete + conditional query
+ * Pattern: trash + conditional query
*/
async removeMessage(id: string, options?: QueryOptions) {
- await this.messageModel.deleteMessage(id);
+ await this.trashService.trashMessages([id]);
return this.queryWithSuccess(options);
}
diff --git a/apps/server/src/services/trash/__tests__/index.test.ts b/apps/server/src/services/trash/__tests__/index.test.ts
index fee1d6015d9..024a5b798f8 100644
--- a/apps/server/src/services/trash/__tests__/index.test.ts
+++ b/apps/server/src/services/trash/__tests__/index.test.ts
@@ -6,13 +6,71 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { AgentModel } from '@/database/models/agent';
import { MessageModel } from '@/database/models/message';
+import { SessionModel } from '@/database/models/session';
import { TopicModel } from '@/database/models/topic';
import { TrashModel } from '@/database/models/trash';
-import { messages, topics, trashItems, users, workspaces } from '@/database/schemas';
+import { HomeRepository } from '@/database/repositories/home';
+import {
+ agents,
+ messages,
+ sessions,
+ topics,
+ trashItems,
+ users,
+ workspaces,
+} from '@/database/schemas';
import type { LobeChatDatabase } from '@/database/type';
import { TrashService } from '../index';
+// Lets a test land a concurrent purge between a restore handler's reads and its
+// write: the handlers check the owning agent right before restoring, inside the
+// restore transaction (the hook receives that transaction).
+const restoreRace = vi.hoisted(() => ({
+ afterOwnerCheck: undefined as undefined | ((db: any) => Promise<void>),
+}));
+
+vi.mock('@/database/models/agent', async (importOriginal) => {
+ const mod = await importOriginal<{ AgentModel: typeof AgentModel }>();
+ class PatchedAgentModel extends mod.AgentModel {
+ constructor(...args: ConstructorParameters<typeof AgentModel>) {
+ super(...args);
+ const hasTrashedOwner = this.hasTrashedOwner;
+ this.hasTrashedOwner = async (owner) => {
+ const result = await hasTrashedOwner(owner);
+ await restoreRace.afterOwnerCheck?.(args[0]);
+ return result;
+ };
+ }
+ }
+ return { ...mod, AgentModel: PatchedAgentModel };
+});
+
+// Lets a test make the sharing-grant cleanup of an agent purge fail once.
+const permissionCleanup = vi.hoisted(() => ({
+ calls: [] as unknown[][],
+ failNext: false,
+}));
+
+vi.mock('@/database/models/resourcePermission', async (importOriginal) => {
+ const mod = await importOriginal<{ ResourcePermissionModel: any }>();
+ class PatchedResourcePermissionModel extends mod.ResourcePermissionModel {
+ constructor(...args: any[]) {
+ super(...args);
+ const removeAll = this.removeAll;
+ this.removeAll = async (...callArgs: any[]) => {
+ permissionCleanup.calls.push(callArgs);
+ if (permissionCleanup.failNext) {
+ permissionCleanup.failNext = false;
+ throw new Error('transient');
+ }
+ return removeAll(...callArgs);
+ };
+ }
+ }
+ return { ...mod, ResourcePermissionModel: PatchedResourcePermissionModel };
+});
+
vi.mock('@/server/services/file', () => ({
FileService: vi.fn().mockImplementation(() => ({ deleteFile: vi.fn(), deleteFiles: vi.fn() })),
}));
@@ -25,6 +83,7 @@ const otherUserId = 'trash-service-other';
let service: TrashService;
let topicModel: TopicModel;
let agentModel: AgentModel;
+let sessionModel: SessionModel;
let messageModel: MessageModel;
let trashModel: TrashModel;
@@ -34,11 +93,13 @@ beforeEach(async () => {
service = new TrashService(serverDB, userId);
topicModel = new TopicModel(serverDB, userId);
agentModel = new AgentModel(serverDB, userId);
+ sessionModel = new SessionModel(serverDB, userId);
messageModel = new MessageModel(serverDB, userId);
trashModel = new TrashModel(serverDB, userId);
});
afterEach(async () => {
+ restoreRace.afterOwnerCheck = undefined;
await serverDB.delete(users);
});
@@ -77,6 +138,21 @@ describe('TrashService', () => {
expect(await serverDB.select().from(trashItems)).toHaveLength(0);
});
+ it('does not report a topic restored when a purge removed it mid-restore', async () => {
+ const agent = await agentModel.create({ title: 'Bot' });
+ const topic = await topicModel.create({ agentId: agent.id, title: 'Gone' });
+ const [root] = await service.trashTopics([topic.id]);
+ // The expiry sweep deletes the row after the handler read it as trashed.
+ restoreRace.afterOwnerCheck = async (db) => {
+ await db.delete(topics).where(eq(topics.id, topic.id));
+ };
+
+ const outcome = await service.restore([root.id]);
+
+ expect(outcome.restored).toEqual([]);
+ expect(outcome.failed).toEqual([{ code: 'notFound', id: root.id }]);
+ });
+
it('bulk sweeps become one restorable root per topic', async () => {
const agent = await agentModel.create({ title: 'Bot' });
await topicModel.create({ agentId: agent.id, title: 'a' });
@@ -88,6 +164,432 @@ describe('TrashService', () => {
});
});
+ describe('agents', () => {
+ it('cascades to topics (incl. legacy session-scoped ones), 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' });
+ const t2 = await topicModel.create({ sessionId: session.id, title: 'via session' });
+ // trashed earlier on its own — must survive the agent restore as its own root
+ const [olderRoot] = await service.trashTopics([t2.id]);
+
+ const root = await service.trashAgent(agent.id);
+ expect(root?.meta?.childCount).toBe(1);
+
+ expect(await agentModel.existsById(agent.id)).toBe(false);
+ // The legacy session shell is not stamped itself but drops out of the
+ // legacy list through the agent join.
+ expect((await sessionModel.query()).map((s) => s.id)).not.toContain(session.id);
+ expect(await topicModel.findById(t1.id)).toBeUndefined();
+ expect(await topicModel.findById(t2.id)).toBeUndefined();
+ const home = await new HomeRepository(serverDB, userId).getSidebarAgentList();
+ expect(JSON.stringify(home)).not.toContain(agent.id);
+
+ const listed = (await service.list()).items.map((i) => i.resourceId);
+ expect(listed).toEqual([agent.id, t2.id]);
+
+ await service.restore([root!.id]);
+ expect(await agentModel.existsById(agent.id)).toBe(true);
+ expect((await sessionModel.query()).map((s) => s.id)).toContain(session.id);
+ expect(await topicModel.findById(t1.id)).toBeTruthy();
+ // t2 was trashed before the agent — still in the bin
+ expect(await topicModel.findById(t2.id)).toBeUndefined();
+ expect((await service.list()).items.map((i) => i.id)).toEqual([olderRoot.id]);
+ });
+
+ it('refuses to restore a topic whose agent is still in the bin', async () => {
+ const agent = await agentModel.create({ title: 'Bot' });
+ const topic = await topicModel.create({ agentId: agent.id, title: 't' });
+ const [topicRoot] = await service.trashTopics([topic.id]);
+ await service.trashAgent(agent.id);
+
+ const outcome = await service.restore([topicRoot.id]);
+ expect(outcome.failed).toEqual([{ code: 'parentTrashed', id: topicRoot.id }]);
+ expect(await topicModel.findById(topic.id)).toBeUndefined();
+ });
+
+ it('refuses to restore a legacy session-only topic whose agent is still in the bin', async () => {
+ const session = await sessionModel.create({ config: { title: 'Legacy' }, type: 'agent' });
+ const agent = (await sessionModel.findByIdOrSlug(session.id))!.agent;
+ // no agentId: linked to the agent only through its session shell
+ const topic = await topicModel.create({ sessionId: session.id, title: 'via session' });
+ const [topicRoot] = await service.trashTopics([topic.id]);
+ await service.trashAgent(agent.id);
+
+ const outcome = await service.restore([topicRoot.id]);
+ expect(outcome.failed).toEqual([{ code: 'parentTrashed', id: topicRoot.id }]);
+ expect(await topicModel.findById(topic.id)).toBeUndefined();
+ });
+
+ it('takes topic-less messages along and brings them back with the agent', async () => {
+ const session = await sessionModel.create({ config: { title: 'Legacy' }, type: 'agent' });
+ const agent = (await sessionModel.findByIdOrSlug(session.id))!.agent;
+ const byAgent = await messageModel.create({
+ agentId: agent.id,
+ 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,
+ content: 'another agent',
+ role: 'user',
+ });
+
+ const root = await service.trashAgent(agent.id);
+ expect(root?.meta?.childCount).toBe(2);
+ 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('refuses to restore a topic-less message whose agent is still in the bin', async () => {
+ const agent = await agentModel.create({ title: 'Bot' });
+ const message = await messageModel.create({
+ agentId: agent.id,
+ content: 'loose',
+ role: 'user',
+ });
+ const [messageRoot] = await service.trashMessages([message.id]);
+ await service.trashAgent(agent.id);
+
+ const outcome = await service.restore([messageRoot.id]);
+ expect(outcome.failed).toEqual([{ code: 'parentTrashed', id: messageRoot.id }]);
+ expect(await messageModel.findById(message.id)).toBeUndefined();
+ });
+
+ it('purging an agent also drops the roots of descendants trashed before it', async () => {
+ const session = await sessionModel.create({ config: { title: 'Legacy' }, type: 'agent' });
+ const agent = (await sessionModel.findByIdOrSlug(session.id))!.agent;
+ const viaAgent = await topicModel.create({ agentId: agent.id, title: 'via agent' });
+ const viaSession = await topicModel.create({ sessionId: session.id, title: 'via session' });
+ const loose = await messageModel.create({
+ agentId: agent.id,
+ content: 'loose',
+ role: 'user',
+ });
+ // each trashed on its own first, so each keeps a separate root
+ 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);
+ });
+
+ it('rolls the whole agent purge back when grant cleanup fails, so a retry still cleans up', async () => {
+ const workspaceId = 'trash-purge-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 root = await wsService.trashAgent(agent.id);
+
+ permissionCleanup.failNext = true;
+ await expect(wsService.purge([root!.id])).rejects.toThrow('transient');
+
+ // nothing committed: the agent is still in the bin and still listed
+ expect(await wsAgents.findTrashedByIds([agent.id])).toHaveLength(1);
+ expect((await wsService.list()).items.map((i) => i.id)).toEqual([root!.id]);
+
+ await wsService.purge([root!.id]);
+ expect(permissionCleanup.calls.at(-1)).toEqual(['agent', agent.id]);
+ expect(await serverDB.select().from(agents).where(eq(agents.id, agent.id))).toHaveLength(0);
+ expect((await wsService.list()).items).toEqual([]);
+ });
+
+ it('purges the agent with its cascade', async () => {
+ const session = await sessionModel.create({ config: { title: 'Legacy' }, type: 'agent' });
+ const agent = (await sessionModel.findByIdOrSlug(session.id))!.agent;
+ const topic = await topicModel.create({ agentId: agent.id, title: 't' });
+ await messageModel.create({
+ agentId: agent.id,
+ content: 'hi',
+ role: 'user',
+ topicId: topic.id,
+ });
+
+ const root = await service.trashAgent(agent.id);
+ await service.purge([root!.id]);
+
+ expect(await serverDB.select().from(agents).where(eq(agents.id, agent.id))).toHaveLength(0);
+ expect(
+ await serverDB.select().from(sessions).where(eq(sessions.id, session.id)),
+ ).toHaveLength(0);
+ expect(await serverDB.select().from(topics).where(eq(topics.id, topic.id))).toHaveLength(0);
+ expect(await serverDB.select().from(trashItems)).toHaveLength(0);
+ });
+
+ it('a purge that lands after a concurrent restore leaves the restored agent and its session alone', async () => {
+ const session = await sessionModel.create({ config: { title: 'Legacy' }, type: 'agent' });
+ const agent = (await sessionModel.findByIdOrSlug(session.id))!.agent;
+ const root = await service.trashAgent(agent.id);
+ // restore commits between the purge's registry read and its delete
+ await agentModel.restore([agent.id]);
+
+ await service.purge([root!.id]);
+ expect(await agentModel.existsById(agent.id)).toBe(true);
+ expect(
+ await serverDB.select().from(sessions).where(eq(sessions.id, session.id)),
+ ).toHaveLength(1);
+ });
+ });
+
+ describe('messages', () => {
+ const seedChain = async () => {
+ const agent = await agentModel.create({ title: 'Bot' });
+ const topic = await topicModel.create({ agentId: agent.id, title: 't' });
+ const u1 = await messageModel.create({
+ agentId: agent.id,
+ content: 'q1',
+ role: 'user',
+ topicId: topic.id,
+ });
+ const a1 = await messageModel.create({
+ agentId: agent.id,
+ content: 'a1',
+ parentId: u1.id,
+ role: 'assistant',
+ topicId: topic.id,
+ });
+ const u2 = await messageModel.create({
+ agentId: agent.id,
+ content: 'q2',
+ parentId: a1.id,
+ role: 'user',
+ topicId: topic.id,
+ });
+ return { a1, agent, topic, u1, u2 };
+ };
+
+ it('hides the message, re-parents its child, and splices it back on restore', async () => {
+ const { a1, topic, u1, u2 } = await seedChain();
+
+ const [root] = await service.trashMessages([a1.id]);
+ expect(root.resourceType).toBe('message');
+ expect(root.title).toBe('a1');
+ expect(root.meta?.messageTree).toEqual({ childIds: [u2.id], parentId: u1.id });
+
+ // hidden from the topic's message list, child re-parented onto u1
+ const visible = await messageModel.query({ topicId: topic.id });
+ expect(visible.map((m) => m.id).sort()).toEqual([u1.id, u2.id].sort());
+ const [u2Row] = await serverDB.select().from(messages).where(eq(messages.id, u2.id));
+ expect(u2Row.parentId).toBe(u1.id);
+ // still on disk
+ const [a1Row] = await serverDB.select().from(messages).where(eq(messages.id, a1.id));
+ expect(a1Row.deletedAt).toBeTruthy();
+
+ const outcome = await service.restore([root.id]);
+ expect(outcome.failed).toEqual([]);
+ const [u2After] = await serverDB.select().from(messages).where(eq(messages.id, u2.id));
+ expect(u2After.parentId).toBe(a1.id);
+ expect((await messageModel.query({ topicId: topic.id })).map((m) => m.id).sort()).toEqual(
+ [u1.id, a1.id, u2.id].sort(),
+ );
+ });
+
+ it('refuses to restore a message whose topic is in the bin, then purges it for good', async () => {
+ const { a1, topic } = await seedChain();
+ const [msgRoot] = await service.trashMessages([a1.id]);
+ const [topicRoot] = await service.trashTopics([topic.id]);
+
+ const blocked = await service.restore([msgRoot.id]);
+ expect(blocked.failed).toEqual([{ code: 'parentTrashed', id: msgRoot.id }]);
+
+ await service.purge([msgRoot.id]);
+ expect(await serverDB.select().from(messages).where(eq(messages.id, a1.id))).toHaveLength(0);
+ expect((await service.list()).items.map((i) => i.id)).toEqual([topicRoot.id]);
+ });
+
+ it('does not report a message restored when a purge removed it mid-restore', async () => {
+ const { a1 } = await seedChain();
+ const [msgRoot] = await service.trashMessages([a1.id]);
+ restoreRace.afterOwnerCheck = async (db) => {
+ await db.delete(messages).where(eq(messages.id, a1.id));
+ };
+
+ const outcome = await service.restore([msgRoot.id]);
+
+ expect(outcome.restored).toEqual([]);
+ expect(outcome.failed).toEqual([{ code: 'notFound', id: msgRoot.id }]);
+ });
+
+ it('a purge that lands after a concurrent restore leaves the restored message alone', async () => {
+ const { a1 } = await seedChain();
+ const [msgRoot] = await service.trashMessages([a1.id]);
+ await messageModel.restoreMessages([{ id: a1.id }]);
+
+ await service.purge([msgRoot.id]);
+ expect(await messageModel.findById(a1.id)).toBeTruthy();
+ });
+
+ it('keeps a branch picked while an intermediate message was in the bin', async () => {
+ const agent = await agentModel.create({ title: 'Bot' });
+ const topic = await topicModel.create({ agentId: agent.id, title: 't' });
+ const at = (s: number) => new Date(Date.UTC(2026, 8, 1, 0, 0, s));
+ const base = { agentId: agent.id, topicId: topic.id, userId };
+ await serverDB.insert(messages).values([
+ { ...base, content: 'q', createdAt: at(1), id: 'br_u', role: 'user' },
+ {
+ ...base,
+ content: 'answer x',
+ createdAt: at(2),
+ id: 'br_x',
+ parentId: 'br_u',
+ role: 'assistant',
+ },
+ {
+ ...base,
+ content: 'answer s',
+ createdAt: at(3),
+ id: 'br_s',
+ parentId: 'br_u',
+ role: 'assistant',
+ },
+ {
+ ...base,
+ content: 'follow-up',
+ createdAt: at(4),
+ id: 'br_c',
+ parentId: 'br_x',
+ role: 'user',
+ },
+ ]);
+
+ // Trash the intermediate answer: its follow-up now sits beside the sibling…
+ const [root] = await service.trashMessages(['br_x']);
+ // …and the user switches to it there (branches of br_u: [br_s, br_c]).
+ await serverDB
+ .update(messages)
+ .set({ metadata: { activeBranchIndex: 1 } })
+ .where(eq(messages.id, 'br_u'));
+
+ await service.restore([root.id]);
+
+ // br_c is back under br_x; the selection follows it (branches: [br_x, br_s])
+ const [parent] = await serverDB.select().from(messages).where(eq(messages.id, 'br_u'));
+ expect((parent.metadata as { activeBranchIndex?: number }).activeBranchIndex).toBe(0);
+ const [child] = await serverDB.select().from(messages).where(eq(messages.id, 'br_c'));
+ expect(child.parentId).toBe('br_x');
+ });
+
+ it('takes tool companions along as children of the assistant turn', async () => {
+ const { agent, topic, u1 } = await seedChain();
+ const assistant = await messageModel.create({
+ agentId: agent.id,
+ content: '',
+ parentId: u1.id,
+ role: 'assistant',
+ tools: [
+ { apiName: 'search', arguments: '{}', id: 'call_1', identifier: 'web', type: 'default' },
+ ],
+ topicId: topic.id,
+ });
+ const tool = await messageModel.create({
+ agentId: agent.id,
+ content: 'result',
+ parentId: assistant.id,
+ plugin: { apiName: 'search', arguments: '{}', identifier: 'web', type: 'default' },
+ role: 'tool',
+ tool_call_id: 'call_1',
+ topicId: topic.id,
+ } as any);
+
+ const [root] = await service.trashMessages([assistant.id]);
+ const children = await trashModel.findChildren(root.id);
+ expect(children.map((c) => c.resourceId)).toEqual([tool.id]);
+ const [toolRow] = await serverDB.select().from(messages).where(eq(messages.id, tool.id));
+ expect(toolRow.deletedAt).toBeTruthy();
+
+ await service.restore([root.id]);
+ const [toolAfter] = await serverDB.select().from(messages).where(eq(messages.id, tool.id));
+ expect(toolAfter.deletedAt).toBeNull();
+ });
+
+ it('files each tool companion under its own assistant turn in a multi-select delete', async () => {
+ const { agent, topic, u1 } = await seedChain();
+ const turn = async (callId: string) => {
+ const assistant = await messageModel.create({
+ agentId: agent.id,
+ content: '',
+ parentId: u1.id,
+ role: 'assistant',
+ tools: [
+ { apiName: 'search', arguments: '{}', id: callId, identifier: 'web', type: 'default' },
+ ],
+ topicId: topic.id,
+ });
+ const tool = await messageModel.create({
+ agentId: agent.id,
+ content: 'result',
+ parentId: assistant.id,
+ plugin: { apiName: 'search', arguments: '{}', identifier: 'web', type: 'default' },
+ role: 'tool',
+ tool_call_id: callId,
+ topicId: topic.id,
+ } as any);
+ return { assistant, tool };
+ };
+ const first = await turn('call_a');
+ const second = await turn('call_b');
+
+ const roots = await service.trashMessages([first.assistant.id, second.assistant.id]);
+ const rootOf = (id: string) => roots.find((r) => r.resourceId === id)!;
+ const childrenOf = async (id: string) =>
+ (await trashModel.findChildren(rootOf(id).id)).map((c) => c.resourceId);
+ expect(await childrenOf(first.assistant.id)).toEqual([first.tool.id]);
+ expect(await childrenOf(second.assistant.id)).toEqual([second.tool.id]);
+
+ // Restoring the second turn alone brings its own tool result back …
+ await service.restore([rootOf(second.assistant.id).id]);
+ const toolRow = async (id: string) =>
+ (await serverDB.select().from(messages).where(eq(messages.id, id)))[0];
+ expect((await toolRow(second.tool.id)).deletedAt).toBeNull();
+ // … and purging the first turn leaves it alone.
+ await service.purge([rootOf(first.assistant.id).id]);
+ expect(await toolRow(first.tool.id)).toBeUndefined();
+ expect(await toolRow(second.tool.id)).toBeTruthy();
+ });
+
+ it('refuses to restore a message whose parent message is still in the bin', async () => {
+ const { a1, u2 } = await seedChain();
+ const roots = await service.trashMessages([a1.id, u2.id]);
+ const ancestorRoot = roots.find((r) => r.resourceId === a1.id)!;
+ const descendantRoot = roots.find((r) => r.resourceId === u2.id)!;
+
+ const blocked = await service.restore([descendantRoot.id]);
+ expect(blocked.failed).toEqual([{ code: 'parentTrashed', id: descendantRoot.id }]);
+ const [u2Row] = await serverDB.select().from(messages).where(eq(messages.id, u2.id));
+ expect(u2Row.deletedAt).toBeTruthy();
+
+ // Restored together, the order they are handed over in does not matter.
+ const outcome = await service.restore([descendantRoot.id, ancestorRoot.id]);
+ expect(outcome.failed).toEqual([]);
+ expect(outcome.restored.map((i) => i.id).sort()).toEqual(
+ [ancestorRoot.id, descendantRoot.id].sort(),
+ );
+ const [u2After] = await serverDB.select().from(messages).where(eq(messages.id, u2.id));
+ expect(u2After.deletedAt).toBeNull();
+ expect(u2After.parentId).toBe(a1.id);
+ });
+ });
+
describe('sweep', () => {
it('purges only expired roots, across users, and prunes stale registry rows', async () => {
const otherService = new TrashService(serverDB, otherUserId);
diff --git a/apps/server/src/services/trash/handlers/agent.ts b/apps/server/src/services/trash/handlers/agent.ts
new file mode 100644
index 00000000000..9717bb31804
--- /dev/null
+++ b/apps/server/src/services/trash/handlers/agent.ts
@@ -0,0 +1,127 @@
+import { AgentModel } from '@/database/models/agent';
+import { MessageModel } from '@/database/models/message';
+import { ResourcePermissionModel } from '@/database/models/resourcePermission';
+import { SessionModel } from '@/database/models/session';
+import { TopicModel } from '@/database/models/topic';
+import { TrashModel } from '@/database/models/trash';
+import type { AgentItem } from '@/database/schemas';
+import type { LobeChatDatabase } from '@/database/type';
+import type { SoftDeleteOptions } from '@/database/utils/softDelete';
+
+import { MESSAGE_TITLE_LENGTH } from './message';
+import { topicEntry } from './topic';
+import {
+ type TrashCascade,
+ type TrashHandler,
+ type TrashHandlerContext,
+ TrashRestoreError,
+} from './types';
+
+export const agentEntry = (agent: AgentItem, childCount: number) => ({
+ meta: {
+ avatar: agent.avatar,
+ backgroundColor: agent.backgroundColor,
+ childCount,
+ },
+ resourceId: agent.id,
+ resourceType: 'agent' as const,
+ title: agent.title,
+});
+
+/**
+ * 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.
+ */
+export const softDeleteAgent = async (
+ ctx: TrashHandlerContext,
+ agentId: string,
+ options: SoftDeleteOptions,
+): Promise<TrashCascade | null> => {
+ const agentModel = new AgentModel(ctx.db, ctx.userId, ctx.workspaceId);
+ const topicModel = new TopicModel(ctx.db, ctx.userId, ctx.workspaceId);
+
+ // Same pre-flight as the hard delete: never pull an agent out from under a
+ // history copy / transfer that is still running.
+ await agentModel.assertDeletable([agentId]);
+
+ 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
+ // already refused a non-owner delete of an agent that carries teammates'
+ // conversations, so whatever is left is the caller's to take.
+ const topics = await topicModel.softDeleteByParents(
+ { agentIds: [agentId], sessionIds },
+ { deletedAt: options.deletedAt },
+ );
+ const topiclessMessages = await new MessageModel(
+ ctx.db,
+ ctx.userId,
+ ctx.workspaceId,
+ ).softDeleteTopicless({ agentIds: [agentId], sessionIds }, { deletedAt: options.deletedAt });
+
+ return {
+ children: [
+ ...topics.map((topic) => topicEntry(topic)),
+ ...topiclessMessages.map((message) => ({
+ meta: { role: message.role },
+ resourceId: message.id,
+ resourceType: 'message' as const,
+ title: message.content?.trim().slice(0, MESSAGE_TITLE_LENGTH) || null,
+ })),
+ ],
+ root: agentEntry(agent, topics.length + topiclessMessages.length),
+ };
+};
+
+export const agentHandler: TrashHandler = {
+ /**
+ * One transaction across the agent, its legacy session shells, stale
+ * descendant roots and its sharing grants: a failure leaves the whole unit
+ * in place for the next retry, and a restore that won the race (nothing
+ * left stamped) keeps all of it.
+ */
+ purge: async (ctx, root) => {
+ await ctx.db.transaction(async (tx) => {
+ const db = tx as unknown as LobeChatDatabase;
+ const agentModel = new AgentModel(db, ctx.userId, ctx.workspaceId);
+
+ const agentIds = await agentModel.lockTrashedForPurge([root.resourceId]);
+ if (agentIds.length === 0) return;
+ const sessionIds = await agentModel.findSessionIdsByAgentIds(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.
+ await agentModel.purge(agentIds);
+ await new SessionModel(db, ctx.userId, ctx.workspaceId).deleteShellsByIds(sessionIds);
+ if (ctx.workspaceId) {
+ await new ResourcePermissionModel(db, ctx.workspaceId).removeAll('agent', root.resourceId);
+ }
+ });
+ },
+ restore: async (ctx, root, children) => {
+ const agentModel = new AgentModel(ctx.db, ctx.userId, ctx.workspaceId);
+ const [restored] = await agentModel.restore([root.resourceId]);
+ if (!restored) throw new TrashRestoreError('notFound');
+
+ const topicIds = children.filter((c) => c.resourceType === 'topic').map((c) => c.resourceId);
+ await new TopicModel(ctx.db, ctx.userId, ctx.workspaceId).restore(topicIds);
+
+ const messageIds = children.filter((c) => c.resourceType === 'message');
+ await new MessageModel(ctx.db, ctx.userId, ctx.workspaceId).restoreMessages(
+ messageIds.map((c) => ({ id: c.resourceId })),
+ );
+ },
+ type: 'agent',
+};
diff --git a/apps/server/src/services/trash/handlers/index.ts b/apps/server/src/services/trash/handlers/index.ts
index 7fae218d324..21f88f1c21c 100644
--- a/apps/server/src/services/trash/handlers/index.ts
+++ b/apps/server/src/services/trash/handlers/index.ts
@@ -1,17 +1,21 @@
import type { TrashResourceType } from '@lobechat/types';
+import { agentHandler } from './agent';
+import { messageHandler } from './message';
import { topicHandler } from './topic';
import type { TrashHandler } from './types';
/**
* One handler per trashable kind. `Partial` on purpose: `TrashResourceType`
* already names the kinds this feature will cover, and they are wired in one
- * at a time (topic first — see the phasing table in
+ * at a time (see the phasing table in
* docs/development/soft-delete-recycle-bin-design.md). Nothing can register a
* registry row for a kind with no handler, since registration happens inside
* the handler itself.
*/
export const TRASH_HANDLERS: Partial<Record<TrashResourceType, TrashHandler>> = {
+ agent: agentHandler,
+ message: messageHandler,
topic: topicHandler,
};
@@ -26,5 +30,7 @@ export const resolveTrashHandler = (resourceType: TrashResourceType): TrashHandl
return handler;
};
+export { softDeleteAgent } from './agent';
+export { softDeleteMessages } from './message';
export { topicCascades } from './topic';
export * from './types';
diff --git a/apps/server/src/services/trash/handlers/message.ts b/apps/server/src/services/trash/handlers/message.ts
new file mode 100644
index 00000000000..13cccd79970
--- /dev/null
+++ b/apps/server/src/services/trash/handlers/message.ts
@@ -0,0 +1,95 @@
+import { AgentModel } from '@/database/models/agent';
+import { MessageModel } from '@/database/models/message';
+import { TopicModel } from '@/database/models/topic';
+import type { TrashRegisterEntry } from '@/database/models/trash';
+import type { SoftDeleteOptions } from '@/database/utils/softDelete';
+
+import {
+ type TrashCascade,
+ type TrashHandler,
+ type TrashHandlerContext,
+ TrashRestoreError,
+} from './types';
+
+export const MESSAGE_TITLE_LENGTH = 120;
+
+/**
+ * Trash messages. Each requested message is its own root; the tool-result
+ * companions pulled in with an assistant turn are registered as its children.
+ * The tree data needed to splice a message back is kept in `meta.messageTree`.
+ */
+export const softDeleteMessages = async (
+ ctx: TrashHandlerContext,
+ ids: string[],
+ options: SoftDeleteOptions,
+): Promise<TrashCascade[]> => {
+ const rows = await new MessageModel(ctx.db, ctx.userId, ctx.workspaceId).softDeleteMessages(
+ ids,
+ options,
+ );
+ const entry = (row: (typeof rows)[number]): TrashRegisterEntry => ({
+ meta: {
+ messageTree: { childIds: row.childIds, parentId: row.parentId },
+ parentTitle: row.topicId,
+ role: row.role,
+ },
+ resourceId: row.id,
+ resourceType: 'message',
+ title: row.content?.trim().slice(0, MESSAGE_TITLE_LENGTH) || null,
+ });
+
+ const roots = rows.filter((row) => !row.isCompanion);
+ const companions = rows.filter((row) => row.isCompanion);
+ return roots.map((root) => ({
+ // Companions go under the assistant turn whose tool call produced them:
+ // roots are restored and purged independently, so filing them under any
+ // other root would strand or destroy them out of step with their turn.
+ children: companions.filter((row) => row.ownerId === root.id).map(entry),
+ root: entry(root),
+ }));
+};
+
+export const messageHandler: TrashHandler = {
+ purge: async (ctx, root, children) => {
+ await new MessageModel(ctx.db, ctx.userId, ctx.workspaceId).purgeMessages([
+ root.resourceId,
+ ...children.filter((c) => c.resourceType === 'message').map((c) => c.resourceId),
+ ]);
+ },
+ restore: async (ctx, root, children) => {
+ const messageModel = new MessageModel(ctx.db, ctx.userId, ctx.workspaceId);
+ const [message] = await messageModel.findTrashedByIds([root.resourceId]);
+ if (!message) throw new TrashRestoreError('notFound');
+
+ // The parent message must be live too: when an ancestor and its descendant
+ // are trashed in one batch, the descendant keeps pointing at the ancestor,
+ // so restoring it first would leave a branch hanging off a hidden row.
+ if (message.parentId) {
+ const [parent] = await messageModel.findTrashedByIds([message.parentId]);
+ if (parent) throw new TrashRestoreError('parentTrashed');
+ }
+
+ // The topic the message lives in must itself be live.
+ if (message.topicId) {
+ const topicModel = new TopicModel(ctx.db, ctx.userId, ctx.workspaceId);
+ const [topic] = await topicModel.findTrashedByIds([message.topicId]);
+ if (topic) throw new TrashRestoreError('parentTrashed');
+ }
+
+ // Nor may its owning agent be in the bin (topic-less rows have no topic
+ // check to fall back on).
+ const agentModel = new AgentModel(ctx.db, ctx.userId, ctx.workspaceId);
+ if (await agentModel.hasTrashedOwner(message)) throw new TrashRestoreError('parentTrashed');
+
+ const entries = [root, ...children.filter((c) => c.resourceType === 'message')].map((row) => ({
+ childIds: row.meta?.messageTree?.childIds,
+ id: row.resourceId,
+ parentId: row.meta?.messageTree?.parentId,
+ }));
+ // Same purge race as the topic handler: only a root this write actually
+ // brought back is a successful restore.
+ const restored = await messageModel.restoreMessages(entries);
+ if (!restored.includes(root.resourceId)) throw new TrashRestoreError('notFound');
+ },
+ type: 'message',
+};
diff --git a/apps/server/src/services/trash/handlers/topic.ts b/apps/server/src/services/trash/handlers/topic.ts
index c39423bf5d7..b072febeb7e 100644
--- a/apps/server/src/services/trash/handlers/topic.ts
+++ b/apps/server/src/services/trash/handlers/topic.ts
@@ -1,4 +1,5 @@
import { serverDBEnv } from '@/config/db';
+import { AgentModel } from '@/database/models/agent';
import { FileModel } from '@/database/models/file';
import { TopicModel } from '@/database/models/topic';
import type { TrashRegisterEntry } from '@/database/models/trash';
@@ -56,11 +57,17 @@ export const topicHandler: TrashHandler = {
const [topic] = await topicModel.findTrashedByIds([root.resourceId]);
if (!topic) throw new TrashRestoreError('notFound');
- // No parent-in-bin check yet: a topic's containers (agent, chat group) are
- // not trashable in this phase, so they can never be sitting in the bin.
- // The check goes in with the agent handler — see `TrashRestoreError`'s
- // `parentTrashed` code, which the client already renders.
- await topicModel.restore([root.resourceId]);
+ // A topic that hangs off an agent sitting in the bin — directly, or only
+ // through a legacy session shell — would come back into an invisible
+ // container: restore the agent first.
+ const agentModel = new AgentModel(ctx.db, ctx.userId, ctx.workspaceId);
+ if (await agentModel.hasTrashedOwner(topic)) throw new TrashRestoreError('parentTrashed');
+
+ // The row can be purged between the read above and this write (an expiry
+ // sweep or another request). Only a row this update actually brought back
+ // counts; otherwise the registry entry must not be dropped as "restored".
+ const restored = await topicModel.restore([root.resourceId]);
+ if (restored.length === 0) throw new TrashRestoreError('notFound');
},
type: 'topic',
};
diff --git a/apps/server/src/services/trash/index.ts b/apps/server/src/services/trash/index.ts
index b4c687e924f..d8315fbddc4 100644
--- a/apps/server/src/services/trash/index.ts
+++ b/apps/server/src/services/trash/index.ts
@@ -18,6 +18,8 @@ import { FileService } from '@/server/services/file';
import {
resolveTrashHandler,
+ softDeleteAgent,
+ softDeleteMessages,
topicCascades,
type TrashCascade,
type TrashHandlerContext,
@@ -183,6 +185,20 @@ export class TrashService {
}, stamp.deletedAt);
};
+ trashAgent = async (agentId: string, options?: TrashOptions) => {
+ const stamp = this.stampOptions(options);
+ const [root] = await this.commit(
+ (ctx) => softDeleteAgent(ctx, agentId, stamp),
+ stamp.deletedAt,
+ );
+ return root ?? null;
+ };
+
+ trashMessages = async (ids: string[], options?: TrashOptions) => {
+ const stamp = this.stampOptions(options);
+ return this.commit((ctx) => softDeleteMessages(ctx, ids, stamp), stamp.deletedAt);
+ };
+
// ─────────────────────────── list ───────────────────────────
list = (params?: TrashListParams): Promise<TrashListResult> => this.trashModel.list(params);
@@ -208,33 +224,52 @@ export class TrashService {
if (!known.has(id)) outcome.failed.push({ code: 'notFound', id });
}
- for (const root of roots) {
- if (root.rootId) {
- // Children are restored through their root, never on their own.
- outcome.failed.push({ code: 'parentTrashed', id: root.id });
- continue;
- }
- try {
- await this.db.transaction(async (tx) => {
- const db = tx as unknown as LobeChatDatabase;
- const registry = new TrashModel(db, this.userId, this.workspaceId);
- const children = await registry.findChildren(root.id, tx);
- await resolveTrashHandler(root.resourceType).restore(this.ctx(db), root, children);
- await registry.removeByIds([root.id], tx);
- });
- outcome.restored.push(this.toItem(root));
- } catch (error) {
- if (error instanceof TrashRestoreError) {
- if (error.code === 'notFound') {
- // Nothing to bring back — drop the stale registry row so the bin
- // stops advertising it.
- await this.trashModel.removeByIds([root.id]);
- }
- outcome.failed.push({ code: error.code, id: root.id });
+ // Roots restored in one call may depend on each other (a message and its
+ // trashed ancestor, a topic and its agent) and come back in whatever order
+ // the registry hands them over. A root blocked on a trashed parent is
+ // retried as long as the previous pass brought something back.
+ let pending = roots;
+ while (pending.length > 0) {
+ const blocked: typeof roots = [];
+ let progressed = false;
+ for (const root of pending) {
+ if (root.rootId) {
+ // Children are restored through their root, never on their own.
+ outcome.failed.push({ code: 'parentTrashed', id: root.id });
continue;
}
- throw error;
+ try {
+ await this.db.transaction(async (tx) => {
+ const db = tx as unknown as LobeChatDatabase;
+ const registry = new TrashModel(db, this.userId, this.workspaceId);
+ const children = await registry.findChildren(root.id, tx);
+ await resolveTrashHandler(root.resourceType).restore(this.ctx(db), root, children);
+ await registry.removeByIds([root.id], tx);
+ });
+ outcome.restored.push(this.toItem(root));
+ progressed = true;
+ } catch (error) {
+ if (error instanceof TrashRestoreError) {
+ if (error.code === 'parentTrashed') {
+ blocked.push(root);
+ continue;
+ }
+ if (error.code === 'notFound') {
+ // Nothing to bring back — drop the stale registry row so the bin
+ // stops advertising it.
+ await this.trashModel.removeByIds([root.id]);
+ }
+ outcome.failed.push({ code: error.code, id: root.id });
+ continue;
+ }
+ throw error;
+ }
+ }
+ if (!progressed) {
+ for (const root of blocked) outcome.failed.push({ code: 'parentTrashed', id: root.id });
+ break;
}
+ pending = blocked;
}
return outcome;
};
diff --git a/docs/development/soft-delete-recycle-bin-design.md b/docs/development/soft-delete-recycle-bin-design.md
index 41a014a11de..e9e709423b1 100644
--- a/docs/development/soft-delete-recycle-bin-design.md
+++ b/docs/development/soft-delete-recycle-bin-design.md
@@ -22,27 +22,23 @@ The one-line contract:
The mechanism is generic, but it lands one layer — and then one entity — at a time, so each step is
small enough to verify on its own:
-| Step | Scope | Where |
-| ---- | -------------------------------------------------------------------------------------------------- | -------------------------------- |
-| 1 | Schema: `trash_items` + `is_deleted` / `deleted_at` on 19 content tables | merged (`0152`) |
-| 2 | Read side: every ownership-scoped read hides stamped rows | `feat/soft-delete-schema` |
-| 3 | **Topics** end to end — stamp, register, restore, purge, sweep — plus the recycle-bin UI | `feat/trash-topic` (this branch) |
-| 4 | Agents (cascading to their topics) and messages (tree rewrite) | `feat/soft-delete-mvp` |
-| 5 | Chat groups, Pages / documents, files, knowledge bases, projects, tasks + goals, generation topics | `feat/soft-delete-recycle-bin` |
+| Step | Scope | Where |
+| ---- | -------------------------------------------------------------------------------------------------- | ------------------------------ |
+| 1 | Schema: `trash_items` + `is_deleted` / `deleted_at` on 19 content tables | merged (`0152`) |
+| 2 | Read side: every ownership-scoped read hides stamped rows | `feat/soft-delete-schema` |
+| 3 | **Topics** end to end — stamp, register, restore, purge, sweep — plus the recycle-bin UI | `feat/trash-topic` |
+| 4 | Agents (cascading to their topics) and messages (tree rewrite) | `feat/soft-delete-mvp` |
+| 5 | Chat groups, Pages / documents, files, knowledge bases, projects, tasks + goals, generation topics | `feat/soft-delete-recycle-bin` |
Step 3 is the smallest slice that is useful on its own: deleting a conversation is the most frequent
destructive action in the product, and a topic's cascade is the simplest one (messages and threads
are hidden by their parent and hard-cascade at purge, so nothing below the topic needs a stamp).
-While only topics are trashable, a few edges stay deliberately simple:
-
-- `removeTopic({ removeFiles })` no longer deletes attachments at delete time — the flag is
- remembered on the registry row and the still-exclusive attachments are removed when the topic is
- **purged**. Files have no stamp yet, so they stay visible in the meantime.
-- The restore path has no parent-in-bin check: a topic's containers (agent, chat group) cannot be
- trashed yet, so they can never be sitting in the bin. The check arrives with the agent handler.
-- Bulk "clear conversation" sweeps (`removeMessagesByAssistant/ByGroup`) and every non-topic delete
- remain hard deletes.
+With agents and messages wired in, the topic restore path regains its
+parent-in-bin check (a topic under a trashed agent cannot come back on its own), and messages carry
+the tree data a restore needs. Still deliberately simple: `removeTopic({ removeFiles })` removes the
+still-exclusive attachments at **purge** time rather than at delete time (files have no stamp yet),
+and bulk "clear conversation" sweeps (`removeMessagesByAssistant/ByGroup`) remain hard deletes.
## 1. Audit — what deletion looked like before
diff --git a/locales/en-US/chat.json b/locales/en-US/chat.json
index 8db4eb00f5d..a7d9bbe9391 100644
--- a/locales/en-US/chat.json
+++ b/locales/en-US/chat.json
@@ -205,7 +205,7 @@
"confirmRemoveChatGroupItemAlert": "This Group will be deleted. Group-specific assistants will also be deleted, while external assistants will not be affected.",
"confirmRemoveGroupItemAlert": "You are about to delete this category. After deletion, its agents will be moved to the default list. Please confirm your action.",
"confirmRemoveGroupSuccess": "Group deleted successfully",
- "confirmRemoveSessionItemAlert": "You are about to delete this agent. Once deleted, it cannot be retrieved. Please confirm your action.",
+ "confirmRemoveSessionItemAlert": "You are about to delete this agent and its conversations. They will be moved to the trash and can be restored within 30 days.",
"confirmRemoveSessionSuccess": "Agent removed successfully",
"connectAgent.create.back": "Back",
"connectAgent.create.connect": "Connect",
@@ -1421,7 +1421,7 @@
"messageForward.bar.forward": "Forward",
"messageForward.bar.selectToHere": "Select to here",
"messageForward.bar.selected": "Selected {{count}}",
- "messageForward.deleteConfirm.desc": "Delete the selected {{count}} messages? This cannot be undone.",
+ "messageForward.deleteConfirm.desc": "Delete the selected {{count}} messages? They move to the trash and can be restored within 30 days.",
"messageForward.deleteConfirm.success": "Deleted {{count}} messages",
"messageForward.deleteConfirm.title": "Delete messages",
"messageForward.empty": "Select at least one message to forward",
diff --git a/locales/en-US/setting.json b/locales/en-US/setting.json
index 8569486e02e..75099bdf528 100644
--- a/locales/en-US/setting.json
+++ b/locales/en-US/setting.json
@@ -1776,7 +1776,7 @@
"trash.purgeConfirm.content": "Permanently delete \"{{title}}\"? This cannot be undone.",
"trash.purgeConfirm.title": "Delete forever",
"trash.restore.failed.notFound": "This item no longer exists.",
- "trash.restore.failed.parentTrashed": "Restore the container it belongs to first — that item is also in the trash.",
+ "trash.restore.failed.parentTrashed": "Its agent, topic or previous message is still in the trash. Restore that first.",
"trash.restore.success": "Restored",
"trash.title": "Trash",
"trash.type.agent": "Agent",
diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.json
index f6f2d4a289b..9cd0985c4f8 100644
--- a/locales/zh-CN/chat.json
+++ b/locales/zh-CN/chat.json
@@ -205,7 +205,7 @@
"confirmRemoveChatGroupItemAlert": "确认删除该群组吗?群组专有助理将会被同样删除,外部助理不受影响",
"confirmRemoveGroupItemAlert": "确认删除该分类吗?分类内的助理会移回默认列表",
"confirmRemoveGroupSuccess": "群组已删除",
- "confirmRemoveSessionItemAlert": "确认删除该助理吗?删除后无法恢复",
+ "confirmRemoveSessionItemAlert": "即将删除此助手及其会话。它们会移入回收站,30 天内可以恢复。",
"confirmRemoveSessionSuccess": "助理已删除",
"connectAgent.create.back": "上一步",
"connectAgent.create.connect": "接入",
@@ -1421,7 +1421,7 @@
"messageForward.bar.forward": "转发",
"messageForward.bar.selectToHere": "选择到这里",
"messageForward.bar.selected": "已选 {{count}} 条",
- "messageForward.deleteConfirm.desc": "确定删除选中的 {{count}} 条消息?此操作不可撤销。",
+ "messageForward.deleteConfirm.desc": "删除选中的 {{count}} 条消息?它们会移入回收站,30 天内可以恢复。",
"messageForward.deleteConfirm.success": "已删除 {{count}} 条消息",
"messageForward.deleteConfirm.title": "删除消息",
"messageForward.empty": "请至少选择一条消息进行转发",
diff --git a/locales/zh-CN/setting.json b/locales/zh-CN/setting.json
index 8877cd88be9..875a01aef7c 100644
--- a/locales/zh-CN/setting.json
+++ b/locales/zh-CN/setting.json
@@ -1776,7 +1776,7 @@
"trash.purgeConfirm.content": "永久删除「{{title}}」?此操作无法撤销。",
"trash.purgeConfirm.title": "彻底删除",
"trash.restore.failed.notFound": "该项目已不存在。",
- "trash.restore.failed.parentTrashed": "它所属的容器也在回收站中,请先恢复该容器。",
+ "trash.restore.failed.parentTrashed": "它所属的助手、话题或上一条消息还在回收站中,请先恢复它们。",
"trash.restore.success": "已恢复",
"trash.title": "回收站",
"trash.type.agent": "助手",
diff --git a/packages/database/src/models/__tests__/session.test.ts b/packages/database/src/models/__tests__/session.test.ts
index 18499287d79..024accb963e 100644
--- a/packages/database/src/models/__tests__/session.test.ts
+++ b/packages/database/src/models/__tests__/session.test.ts
@@ -663,6 +663,47 @@ describe('SessionModel', () => {
});
});
+ describe('isSoleShellOfAgent', () => {
+ beforeEach(async () => {
+ await serverDB.insert(sessions).values([
+ { id: 's1', userId },
+ { id: 's2', userId },
+ ]);
+ await serverDB.insert(agents).values([
+ { id: 'a1', userId },
+ { id: 'a2', userId },
+ ]);
+ });
+
+ it("is true for the agent's one and only shell", async () => {
+ await serverDB.insert(agentsToSessions).values([{ agentId: 'a1', sessionId: 's1', userId }]);
+
+ expect(await sessionModel.isSoleShellOfAgent('s1', 'a1')).toBe(true);
+ });
+
+ it('is false when the agent is linked to another session too', async () => {
+ await serverDB.insert(agentsToSessions).values([
+ { agentId: 'a1', sessionId: 's1', userId },
+ { agentId: 'a1', sessionId: 's2', userId },
+ ]);
+
+ expect(await sessionModel.isSoleShellOfAgent('s1', 'a1')).toBe(false);
+ });
+
+ it('is false when the session also holds another agent', async () => {
+ await serverDB.insert(agentsToSessions).values([
+ { agentId: 'a1', sessionId: 's1', userId },
+ { agentId: 'a2', sessionId: 's1', userId },
+ ]);
+
+ expect(await sessionModel.isSoleShellOfAgent('s1', 'a1')).toBe(false);
+ });
+
+ it('is false when the session is not linked to the agent at all', async () => {
+ expect(await sessionModel.isSoleShellOfAgent('s1', 'a1')).toBe(false);
+ });
+ });
+
describe('delete', () => {
it('should handle deleting a session with no associated messages or topics', async () => {
// Create test data
diff --git a/packages/database/src/models/agent.ts b/packages/database/src/models/agent.ts
index b9355c17884..4828ca45f59 100644
--- a/packages/database/src/models/agent.ts
+++ b/packages/database/src/models/agent.ts
@@ -89,7 +89,13 @@ import { normalizeInboxAgentMeta } from '../utils/inboxAgent';
import { readOriginalCharCount } from '../utils/parsedDocument';
import { sanitizeAgentApiConfig } from '../utils/sanitizeAgentApiConfig';
import { notShareVisitorTopic } from '../utils/shareVisitor';
-import { notTrashed } from '../utils/softDelete';
+import {
+ isTrashed,
+ notTrashed,
+ restoreStamp,
+ type SoftDeleteOptions,
+ trashStamp,
+} from '../utils/softDelete';
import { buildWorkspacePayload, buildWorkspaceWhere } from '../utils/workspace';
import { AGENT_COPY_IN_PROGRESS, AgentCopyJobModel } from './agentCopyJob';
import {
@@ -332,6 +338,21 @@ export class AgentModel {
},
);
+ /**
+ * {@link ownership} without the recycle-bin filter — restore / purge / the
+ * trash pre-flight lock only.
+ */
+ private trashScope = () =>
+ buildWorkspaceWhere(
+ { includeTrashed: true, userId: this.userId, workspaceId: this.workspaceId },
+ {
+ isDeleted: agents.isDeleted,
+ userId: agents.userId,
+ workspaceId: agents.workspaceId,
+ visibility: agents.visibility,
+ },
+ );
+
/** Same predicate but for the `sessions` table (used in delete cascade). */
private sessionsOwnership = () =>
buildWorkspaceWhere({ userId: this.userId, workspaceId: this.workspaceId }, sessions);
@@ -1064,6 +1085,145 @@ export class AgentModel {
});
};
+ // **************** Recycle bin *************** //
+
+ /**
+ * Same pre-flight as {@link delete}: an agent whose history is mid-copy or
+ * mid-transfer must not disappear from under the job. Runs the guards under
+ * the same row lock so the check cannot race an enqueue. Throws
+ * `AGENT_TRANSFER_IN_PROGRESS` / `AGENT_COPY_IN_PROGRESS`.
+ */
+ assertDeletable = async (agentIds: string[], trx?: Transaction) => {
+ if (agentIds.length === 0) return;
+ const run = async (tx: Transaction | LobeChatDatabase) => {
+ await tx
+ .select({ id: agents.id })
+ .from(agents)
+ .where(and(inArray(agents.id, agentIds), this.trashScope()))
+ .for('update');
+ if (await AgentTransferJobModel.hasPendingJobForAgents(tx, agentIds)) {
+ throw new Error(AGENT_TRANSFER_IN_PROGRESS);
+ }
+ if (await AgentTransferJobModel.hasPendingRemapForSourceAgents(tx, agentIds)) {
+ throw new Error(AGENT_TRANSFER_IN_PROGRESS);
+ }
+ if (await AgentCopyJobModel.hasPendingCopyJobForSourceAgents(tx, agentIds)) {
+ throw new Error(AGENT_COPY_IN_PROGRESS);
+ }
+ };
+ return trx ? run(trx) : run(this.db);
+ };
+
+ /** Legacy session shells linked to the given agents (used to stamp `topics.session_id` rows). */
+ findSessionIdsByAgentIds = async (agentIds: string[]): Promise<string[]> => {
+ if (agentIds.length === 0) return [];
+ const links = await this.db
+ .select({ sessionId: agentsToSessions.sessionId })
+ .from(agentsToSessions)
+ .where(and(inArray(agentsToSessions.agentId, agentIds), this.agentsToSessionsOwnership()));
+ return [...new Set(links.map((link) => link.sessionId))];
+ };
+
+ /** Agents linked to the given legacy session shells — the reverse of {@link findSessionIdsByAgentIds}. */
+ findAgentIdsBySessionIds = async (sessionIds: string[]): Promise<string[]> => {
+ if (sessionIds.length === 0) return [];
+ const links = await this.db
+ .select({ agentId: agentsToSessions.agentId })
+ .from(agentsToSessions)
+ .where(
+ and(inArray(agentsToSessions.sessionId, sessionIds), this.agentsToSessionsOwnership()),
+ );
+ return [...new Set(links.map((link) => link.agentId))];
+ };
+
+ /**
+ * Whether the agent that owns a row is sitting in the bin — reached either
+ * directly (`agent_id`) or, for legacy rows that only carry `session_id`,
+ * through the session shell's agent link. Restoring such a row first would
+ * bring it back under an invisible container.
+ */
+ hasTrashedOwner = async (owner: {
+ agentId?: string | null;
+ sessionId?: string | null;
+ }): Promise<boolean> => {
+ const agentIds = [
+ ...(owner.agentId ? [owner.agentId] : []),
+ ...(owner.sessionId ? await this.findAgentIdsBySessionIds([owner.sessionId]) : []),
+ ];
+ return (await this.findTrashedByIds([...new Set(agentIds)])).length > 0;
+ };
+
+ /**
+ * Move agents to the recycle bin. Only the `agents` rows are stamped here —
+ * the server-side trash handler cascades to sessions / topics through their
+ * own models so the registry can record each child.
+ */
+ softDelete = async (agentIds: string[], options: SoftDeleteOptions): Promise<AgentItem[]> => {
+ if (agentIds.length === 0) return [];
+ return this.db
+ .update(agents)
+ .set(trashStamp(options.deletedAt))
+ .where(
+ and(
+ inArray(agents.id, agentIds),
+ this.ownership(),
+ options.restrictToCreator ? eq(agents.userId, this.userId) : undefined,
+ ),
+ )
+ .returning();
+ };
+
+ restore = async (agentIds: string[]): Promise<AgentItem[]> => {
+ if (agentIds.length === 0) return [];
+ return this.db
+ .update(agents)
+ .set(restoreStamp())
+ .where(and(inArray(agents.id, agentIds), this.trashScope(), isTrashed(agents.isDeleted)))
+ .returning();
+ };
+
+ findTrashedByIds = async (agentIds: string[]): Promise<AgentItem[]> => {
+ if (agentIds.length === 0) return [];
+ return this.db
+ .select()
+ .from(agents)
+ .where(and(inArray(agents.id, agentIds), this.trashScope(), isTrashed(agents.isDeleted)));
+ };
+
+ /**
+ * Lock the given agents for a purge and return the ones still in the bin.
+ * Run inside the caller's transaction: the row lock holds until the purge
+ * commits, so a restore racing it waits and then finds nothing to restore,
+ * while a restore that already committed makes this return no ids.
+ */
+ lockTrashedForPurge = async (agentIds: string[]): Promise<string[]> => {
+ if (agentIds.length === 0) return [];
+ const stamped = await this.db
+ .select({ id: agents.id })
+ .from(agents)
+ .where(and(inArray(agents.id, agentIds), this.trashScope(), isTrashed(agents.isDeleted)))
+ .for('update');
+ return stamped.map((row) => row.id);
+ };
+
+ /**
+ * Hard delete for the purge sweep: the agent rows and their session links,
+ * still-stamped rows only. FK cascades take topics / messages / threads.
+ * The legacy session shells are another aggregate — the trash handler
+ * drops them through `SessionModel` in the same transaction.
+ */
+ purge = async (agentIds: string[]): Promise<string[]> => {
+ if (agentIds.length === 0) return [];
+ await this.db
+ .delete(agentsToSessions)
+ .where(and(inArray(agentsToSessions.agentId, agentIds), this.agentsToSessionsOwnership()));
+ const rows = await this.db
+ .delete(agents)
+ .where(and(inArray(agents.id, agentIds), this.trashScope(), isTrashed(agents.isDeleted)))
+ .returning({ id: agents.id });
+ return rows.map((row) => row.id);
+ };
+
/**
* Batch delete agents by IDs.
* This is a simpler delete that only removes the agent records.
diff --git a/packages/database/src/models/message.ts b/packages/database/src/models/message.ts
index 96ebfc700b6..4a9082a51f5 100644
--- a/packages/database/src/models/message.ts
+++ b/packages/database/src/models/message.ts
@@ -103,6 +103,7 @@ import { inJsonStringArray } from '../utils/inJsonStringArray';
import { documentOriginalCharCount } from '../utils/originalCharCount';
import { searchableMessage } from '../utils/searchableMessage';
import { notShareVisitorMessage, notShareVisitorTopicRef } from '../utils/shareVisitor';
+import { isTrashed, restoreStamp, type SoftDeleteOptions, trashStamp } from '../utils/softDelete';
import { buildWorkspacePayload, buildWorkspaceWhere } from '../utils/workspace';
import { recomputeTopicUsage } from './topicUsage';
import { WorkModel } from './work';
@@ -1062,6 +1063,23 @@ export const toVisitorMessage = (
} as UIChatMessage;
};
+export interface SoftDeletedMessage {
+ /** Live children that were re-parented away from this message at trash time. */
+ childIds: string[];
+ content: string | null;
+ id: string;
+ /** Pulled in as a tool companion of a requested message (never a root of its own). */
+ isCompanion: boolean;
+ /**
+ * For a companion: the requested message whose tool call produced it, so the
+ * caller can file it under the right root. `null` for requested rows.
+ */
+ ownerId: string | null;
+ parentId: string | null;
+ role: string;
+ topicId: string | null;
+}
+
export class MessageModel {
private userId: string;
private db: LobeChatDatabase;
@@ -1153,6 +1171,20 @@ export class MessageModel {
return rows[0].senderId === null ? 'creator' : 'visitor';
};
+ /**
+ * Scope predicate without the recycle-bin filter — restore / purge internals
+ * only. Keeps the visitor exclusion of {@link ownership} so a creator-facing
+ * restore or purge can never reach an agent-share visitor row.
+ */
+ private trashScope = () =>
+ and(
+ buildWorkspaceWhere(
+ { includeTrashed: true, userId: this.userId, workspaceId: this.workspaceId },
+ messages,
+ ),
+ this.notShareVisitor(),
+ );
+
private pluginsOwnership = () =>
buildWorkspaceWhere({ userId: this.userId, workspaceId: this.workspaceId }, messagePlugins);
@@ -5317,6 +5349,284 @@ export class MessageModel {
),
);
+ // **************** Recycle bin *************** //
+
+ /**
+ * Move messages to the recycle bin. Mirrors {@link deleteMessages} step for
+ * step — tool companions are pulled in, live children are re-parented onto
+ * the nearest surviving ancestor, the active-branch pointer is reconciled and
+ * the topic usage rollup recomputed — but the rows are stamped instead of
+ * dropped. Returns one entry per stamped row with the tree data a restore
+ * needs to splice it back (`parentId` + the child ids that were re-parented
+ * away from it), and whether the row was an explicitly requested root or a
+ * tool companion pulled in with it.
+ */
+ softDeleteMessages = async (
+ ids: string[],
+ options: SoftDeleteOptions,
+ ): Promise<SoftDeletedMessage[]> => {
+ if (ids.length === 0) return [];
+
+ return this.db.transaction(async (tx) => {
+ const requested = await tx
+ .select({
+ content: messages.content,
+ id: messages.id,
+ parentId: messages.parentId,
+ role: messages.role,
+ tools: messages.tools,
+ topicId: messages.topicId,
+ })
+ .from(messages)
+ .where(and(this.ownership(), inArray(messages.id, ids)));
+ if (requested.length === 0) return [];
+
+ // Tool companions: the tool-result rows of a trashed assistant turn go
+ // with it (same rule as the hard delete).
+ const toolCallIds = requested
+ .flatMap((row) => ((row.tools as ChatToolPayload[]) ?? []).map((tool) => tool.id))
+ .filter(Boolean);
+ const requestedIds = new Set(requested.map((row) => row.id));
+ // toolCallId → the requested row that issued it, so each companion is
+ // attributed to its own assistant turn rather than to the batch.
+ const toolCallOwner = new Map<string, string>();
+ for (const row of requested) {
+ for (const tool of (row.tools as ChatToolPayload[]) ?? []) {
+ if (tool.id) toolCallOwner.set(tool.id, row.id);
+ }
+ }
+ const companionOwner = new Map<string, string>();
+ let companions: typeof requested = [];
+ if (toolCallIds.length > 0) {
+ const companionRows = await tx
+ .select({ id: messagePlugins.id, toolCallId: messagePlugins.toolCallId })
+ .from(messagePlugins)
+ .where(inArray(messagePlugins.toolCallId, toolCallIds));
+ for (const row of companionRows) {
+ const owner = row.toolCallId ? toolCallOwner.get(row.toolCallId) : undefined;
+ if (owner && !requestedIds.has(row.id)) companionOwner.set(row.id, owner);
+ }
+ const companionIds = [...companionOwner.keys()];
+ if (companionIds.length > 0) {
+ companions = await tx
+ .select({
+ content: messages.content,
+ id: messages.id,
+ parentId: messages.parentId,
+ role: messages.role,
+ tools: messages.tools,
+ topicId: messages.topicId,
+ })
+ .from(messages)
+ .where(and(this.ownership(), inArray(messages.id, companionIds)));
+ }
+ }
+
+ const toDelete = [...requested, ...companions];
+ const deleteIds = toDelete.map((row) => row.id);
+ const deleteSet = new Set(deleteIds);
+ const parentMap = new Map(toDelete.map((row) => [row.id, row.parentId] as const));
+
+ const finalAncestorMap = new Map<string, string | null>();
+ const findFinalAncestor = (id: string): string | null => {
+ if (finalAncestorMap.has(id)) return finalAncestorMap.get(id)!;
+ const parentId = parentMap.get(id);
+ if (parentId === null || parentId === undefined) {
+ finalAncestorMap.set(id, null);
+ return null;
+ }
+ if (!deleteSet.has(parentId)) {
+ finalAncestorMap.set(id, parentId);
+ return parentId;
+ }
+ const ancestor = findFinalAncestor(parentId);
+ finalAncestorMap.set(id, ancestor);
+ return ancestor;
+ };
+ for (const id of deleteSet) findFinalAncestor(id);
+
+ const activeBranchSnapshots = await this.captureActiveBranchSnapshots(
+ tx,
+ [...new Set(finalAncestorMap.values())].filter((id): id is string => id !== null),
+ );
+
+ // Live children re-parented onto the nearest surviving ancestor —
+ // remembered per message so a restore can hand them back.
+ const children = await tx
+ .select({ id: messages.id, parentId: messages.parentId })
+ .from(messages)
+ .where(
+ and(
+ this.ownership(),
+ inArray(messages.parentId, deleteIds),
+ not(inArray(messages.id, deleteIds)),
+ ),
+ );
+ const childIdsByParent = new Map<string, string[]>();
+ for (const child of children) {
+ const list = childIdsByParent.get(child.parentId!) ?? [];
+ list.push(child.id);
+ childIdsByParent.set(child.parentId!, list);
+ await tx
+ .update(messages)
+ .set({ parentId: finalAncestorMap.get(child.parentId!) ?? null })
+ .where(and(eq(messages.id, child.id), this.ownership()));
+ }
+
+ await tx
+ .update(messages)
+ .set(trashStamp(options.deletedAt))
+ .where(and(this.ownership(), inArray(messages.id, deleteIds)));
+
+ await this.reconcileActiveBranchSnapshots(tx, activeBranchSnapshots);
+
+ const affectedTopicIds = [
+ ...new Set(toDelete.map((m) => m.topicId).filter(Boolean) as string[]),
+ ];
+ for (const topicId of affectedTopicIds) {
+ await recomputeTopicUsage(tx, this.userId, topicId, this.workspaceId);
+ }
+
+ return toDelete.map((row) => ({
+ childIds: childIdsByParent.get(row.id) ?? [],
+ content: row.content,
+ id: row.id,
+ isCompanion: !requestedIds.has(row.id),
+ ownerId: companionOwner.get(row.id) ?? null,
+ parentId: row.parentId,
+ role: row.role,
+ topicId: row.topicId,
+ }));
+ });
+ };
+
+ /**
+ * Bring trashed messages back and splice them into their branch: the stamp
+ * is cleared and the children recorded at trash time are re-parented onto
+ * the message again (best effort — a child that has since moved or gone is
+ * left alone). The active-branch pointer of the parent keeps pointing at
+ * whatever branch is active today.
+ */
+ restoreMessages = async (
+ entries: { childIds?: string[]; id: string; parentId?: string | null }[],
+ ): Promise<string[]> => {
+ if (entries.length === 0) return [];
+ return this.db.transaction(async (tx) => {
+ const ids = entries.map((entry) => entry.id);
+ const rows = await tx
+ .select({ id: messages.id, parentId: messages.parentId, topicId: messages.topicId })
+ .from(messages)
+ .where(and(this.trashScope(), inArray(messages.id, ids), isTrashed(messages.isDeleted)));
+ if (rows.length === 0) return [];
+
+ const parentIds = rows.map((row) => row.parentId).filter((id): id is string => !!id);
+ const activeBranchSnapshots = await this.captureActiveBranchSnapshots(tx, parentIds);
+
+ // Report what the write restored, not what the read saw: a purge that
+ // commits in between leaves nothing to update, and the caller must not
+ // count that row as restored.
+ const updated = await tx
+ .update(messages)
+ .set(restoreStamp())
+ .where(
+ and(
+ this.trashScope(),
+ inArray(
+ messages.id,
+ rows.map((row) => row.id),
+ ),
+ isTrashed(messages.isDeleted),
+ ),
+ )
+ .returning({ id: messages.id });
+ const restoredIds = new Set(updated.map((row) => row.id));
+
+ for (const entry of entries) {
+ if (!restoredIds.has(entry.id) || !entry.childIds?.length) continue;
+ await tx
+ .update(messages)
+ .set({ parentId: entry.id })
+ .where(and(inArray(messages.id, entry.childIds), this.trashScope()));
+ }
+
+ // While the row was in the bin its children hung off its parent, and the
+ // user may have picked one of them as the active branch there. They now
+ // move back under the restored row, so carry that choice up to it —
+ // otherwise reconciliation cannot find the child among the parent's
+ // branches, drops the selection and the view can jump to a sibling.
+ const restoredAncestorOf = new Map<string, string>();
+ for (const entry of entries) {
+ if (!restoredIds.has(entry.id)) continue;
+ for (const childId of entry.childIds ?? []) restoredAncestorOf.set(childId, entry.id);
+ }
+ for (const snapshot of activeBranchSnapshots) {
+ const ancestor = snapshot.activeBranchId && restoredAncestorOf.get(snapshot.activeBranchId);
+ if (ancestor) snapshot.activeBranchId = ancestor;
+ }
+
+ await this.reconcileActiveBranchSnapshots(tx, activeBranchSnapshots);
+
+ const affectedTopicIds = [...new Set(rows.map((m) => m.topicId).filter(Boolean) as string[])];
+ for (const topicId of affectedTopicIds) {
+ await recomputeTopicUsage(tx, this.userId, topicId, this.workspaceId);
+ }
+ return [...restoredIds];
+ });
+ };
+
+ findTrashedByIds = async (ids: string[]) => {
+ if (ids.length === 0) return [];
+ return this.db
+ .select({
+ agentId: messages.agentId,
+ id: messages.id,
+ parentId: messages.parentId,
+ sessionId: messages.sessionId,
+ topicId: messages.topicId,
+ })
+ .from(messages)
+ .where(and(this.trashScope(), inArray(messages.id, ids), isTrashed(messages.isDeleted)));
+ };
+
+ /**
+ * 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
+ * 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 [];
+
+ return this.db
+ .update(messages)
+ .set(trashStamp(options.deletedAt))
+ .where(and(isNull(messages.topicId), or(...conditions), this.ownership()))
+ .returning({ content: messages.content, id: messages.id, role: messages.role });
+ };
+
+ /**
+ * Hard delete for the purge sweep. Children were already re-parented at trash
+ * time and usage already excludes stamped rows, so this is a plain delete
+ * keyed on `scope()`.
+ */
+ purgeMessages = async (ids: string[]) => {
+ if (ids.length === 0) return;
+ // Only rows still stamped: a restore that commits between the purge's
+ // registry read and this delete must win.
+ return this.db
+ .delete(messages)
+ .where(and(this.trashScope(), inArray(messages.id, ids), isTrashed(messages.isDeleted)));
+ };
+
/**
* Creator-facing "clear this session/topic/group" sweep.
*
diff --git a/packages/database/src/models/session.ts b/packages/database/src/models/session.ts
index 74dc7a6c019..3e1d795a923 100644
--- a/packages/database/src/models/session.ts
+++ b/packages/database/src/models/session.ts
@@ -545,6 +545,25 @@ export class SessionModel {
return links.map((link) => link.agentId);
};
+ /**
+ * Whether `sessionId` is the agent's one and only shell and carries no other
+ * agent — i.e. removing the session means removing the agent. The schema
+ * allows an agent to be linked to several sessions (and a group shell to
+ * several agents); in either case only the selected shell may go. Link
+ * counting mirrors {@link clearOrphanAgent}: every link counts, so an agent
+ * is never treated as orphaned while anything still points at it.
+ */
+ isSoleShellOfAgent = async (sessionId: string, agentId: string): Promise<boolean> => {
+ const links = await this.db
+ .select({ agentId: agentsToSessions.agentId, sessionId: agentsToSessions.sessionId })
+ .from(agentsToSessions)
+ .where(or(eq(agentsToSessions.agentId, agentId), eq(agentsToSessions.sessionId, sessionId)));
+ return (
+ links.length > 0 &&
+ links.every((link) => link.agentId === agentId && link.sessionId === sessionId)
+ );
+ };
+
clearOrphanAgent = async (agentIds: string[], trx: any): Promise<string[]> => {
if (agentIds.length === 0) return [];
@@ -570,6 +589,16 @@ export class SessionModel {
return orphanedAgentIds;
};
+ /**
+ * 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.
+ */
+ deleteShellsByIds = async (ids: string[]) => {
+ if (ids.length === 0) return;
+ await this.db.delete(sessions).where(and(inArray(sessions.id, ids), this.scope()));
+ };
+
// **************** Update *************** //
update = async (id: string, data: Partial<SessionItem>) => {
diff --git a/packages/database/src/models/trash.ts b/packages/database/src/models/trash.ts
index 6dfd0dd78c8..e783c0da117 100644
--- a/packages/database/src/models/trash.ts
+++ b/packages/database/src/models/trash.ts
@@ -190,6 +190,56 @@ export class TrashModel {
await db.delete(trashItems).where(inArray(trashItems.id, ids));
};
+ /**
+ * 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.
+ */
+ removeRootsUnderAgents = async (
+ parents: { agentIds: string[]; sessionIds: 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 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),
+ );
+
+ await db
+ .delete(trashItems)
+ .where(
+ and(
+ this.ownership(),
+ isNull(trashItems.rootId),
+ or(
+ and(
+ eq(trashItems.resourceType, 'topic'),
+ inArray(trashItems.resourceId, ownedTopicIds),
+ ),
+ and(
+ eq(trashItems.resourceType, 'message'),
+ inArray(
+ trashItems.resourceId,
+ db.select({ id: messages.id }).from(messages).where(messageOwner),
+ ),
+ ),
+ ),
+ ),
+ );
+ };
+
removeByResources = async (
entries: { resourceId: string; resourceType: TrashResourceType }[],
trx?: Transaction,
diff --git a/packages/locales/src/default/chat.ts b/packages/locales/src/default/chat.ts
index f40ccc27904..1d086e34a6d 100644
--- a/packages/locales/src/default/chat.ts
+++ b/packages/locales/src/default/chat.ts
@@ -186,7 +186,7 @@ export default {
'You are about to delete this category. After deletion, its agents will be moved to the default list. Please confirm your action.',
'confirmRemoveGroupSuccess': 'Group deleted successfully',
'confirmRemoveSessionItemAlert':
- 'You are about to delete this agent. Once deleted, it cannot be retrieved. Please confirm your action.',
+ 'You are about to delete this agent and its conversations. They will be moved to the trash and can be restored within 30 days.',
'confirmRemoveSessionSuccess': 'Agent removed successfully',
'defaultAgent': 'Default Agent',
'defaultGroupChat': 'Group',
@@ -862,7 +862,7 @@ export default {
'messageForward.bar.selectToHere': 'Select to here',
'messageForward.bar.selected': 'Selected {{count}}',
'messageForward.deleteConfirm.desc':
- 'Delete the selected {{count}} messages? This cannot be undone.',
+ 'Delete the selected {{count}} messages? They move to the trash and can be restored within 30 days.',
'messageForward.deleteConfirm.success': 'Deleted {{count}} messages',
'messageForward.deleteConfirm.title': 'Delete messages',
'messageForward.empty': 'Select at least one message to forward',
diff --git a/packages/locales/src/default/setting.ts b/packages/locales/src/default/setting.ts
index eae10171381..5a72356692a 100644
--- a/packages/locales/src/default/setting.ts
+++ b/packages/locales/src/default/setting.ts
@@ -1840,7 +1840,7 @@ When I am ___, I need ___
'trash.purgeConfirm.title': 'Delete forever',
'trash.restore.failed.notFound': 'This item no longer exists.',
'trash.restore.failed.parentTrashed':
- 'Restore the container it belongs to first — that item is also in the trash.',
+ 'Its agent, topic or previous message is still in the trash. Restore that first.',
'trash.restore.success': 'Restored',
'trash.purge.success': 'Deleted permanently',
'trash.title': 'Trash',
diff --git a/src/features/Electron/HeterogeneousAgent/RestartRecovery/recoverInterruptedRuns.test.ts b/src/features/Electron/HeterogeneousAgent/RestartRecovery/recoverInterruptedRuns.test.ts
index cae4c15849d..095a3cc8f9a 100644
--- a/src/features/Electron/HeterogeneousAgent/RestartRecovery/recoverInterruptedRuns.test.ts
+++ b/src/features/Electron/HeterogeneousAgent/RestartRecovery/recoverInterruptedRuns.test.ts
@@ -173,10 +173,12 @@ describe('recoverInterruptedHeteroRuns', () => {
expect(mockResolveRunContext).toHaveBeenCalled();
expect(chatStore.updateTopicMetadata).not.toHaveBeenCalled();
// Only the interrupted turn's own rows go; earlier turns and thread rows stay.
- expect(mockRemoveMessages).toHaveBeenCalledWith(['a1', 't1'], {
- agentId: 'agent-1',
- topicId: 'topic-1',
- });
+ expect(mockRemoveMessages).toHaveBeenCalledWith(
+ ['a1', 't1'],
+ { agentId: 'agent-1', topicId: 'topic-1' },
+ // superseded partial rows must not land in the recycle bin
+ { permanent: true },
+ );
// The surviving rows are seeded into the store before the run, so the user
// turn renders while the topic's own fetch is gated off by the running op.
expect(chatStore.replaceMessages).toHaveBeenCalledWith(
@@ -414,10 +416,12 @@ describe('recoverInterruptedHeteroRuns', () => {
const results = await recoverInterruptedHeteroRuns();
expect(results).toEqual([{ outcome: 'replayed', topicId: 'topic-1' }]);
- expect(mockRemoveMessages).toHaveBeenCalledWith(['a1', 't1'], {
- agentId: 'agent-1',
- topicId: 'topic-1',
- });
+ expect(mockRemoveMessages).toHaveBeenCalledWith(
+ ['a1', 't1'],
+ { agentId: 'agent-1', topicId: 'topic-1' },
+ // superseded partial rows must not land in the recycle bin
+ { permanent: true },
+ );
});
it('leaves the topic alone when another device added a newer assistant branch', async () => {
@@ -491,10 +495,12 @@ describe('recoverInterruptedHeteroRuns', () => {
const results = await recoverInterruptedHeteroRuns();
expect(results).toEqual([{ outcome: 'replayed', topicId: 'topic-1' }]);
- expect(mockRemoveMessages).toHaveBeenCalledWith(['a1', 't1'], {
- agentId: 'agent-1',
- topicId: 'topic-1',
- });
+ expect(mockRemoveMessages).toHaveBeenCalledWith(
+ ['a1', 't1'],
+ { agentId: 'agent-1', topicId: 'topic-1' },
+ // superseded partial rows must not land in the recycle bin
+ { permanent: true },
+ );
});
it('does not settle a topic another device took over, even when the probe fails', async () => {
@@ -723,9 +729,11 @@ describe('recoverInterruptedHeteroRuns', () => {
const results = await recoverInterruptedHeteroRuns();
expect(results).toEqual([{ outcome: 'replayed', topicId: 'topic-1' }]);
- expect(mockRemoveMessages).toHaveBeenCalledWith(['a1', 't1'], {
- agentId: 'agent-1',
- topicId: 'topic-1',
- });
+ expect(mockRemoveMessages).toHaveBeenCalledWith(
+ ['a1', 't1'],
+ { agentId: 'agent-1', topicId: 'topic-1' },
+ // superseded partial rows must not land in the recycle bin
+ { permanent: true },
+ );
});
});
diff --git a/src/features/Electron/HeterogeneousAgent/RestartRecovery/recoverInterruptedRuns.ts b/src/features/Electron/HeterogeneousAgent/RestartRecovery/recoverInterruptedRuns.ts
index 06213dbbc27..21bd8fa54e6 100644
--- a/src/features/Electron/HeterogeneousAgent/RestartRecovery/recoverInterruptedRuns.ts
+++ b/src/features/Electron/HeterogeneousAgent/RestartRecovery/recoverInterruptedRuns.ts
@@ -335,7 +335,10 @@ const recoverRun = async (run: InterruptedRun): Promise<RestartRecoveryResult> =
// row are somebody's history, not this run's leftovers.
const branchRootId = ownRoot?.id ?? newestRoot?.id;
const staleIds = branchRootId ? collectBranch(mainChain, branchRootId) : [];
- if (staleIds.length > 0) await messageService.removeMessages(staleIds, context);
+ // Hard delete, not the recycle bin: these partial rows are superseded by
+ // the replay, and restoring them would bring back a stale branch.
+ if (staleIds.length > 0)
+ await messageService.removeMessages(staleIds, context, { permanent: true });
// Seed the in-memory list ourselves: while the recovery op is running, the
// topic's own fetch is gated off (a mid-run snapshot would clobber streamed
diff --git a/src/features/Settings/trash/features/TrashList.tsx b/src/features/Settings/trash/features/TrashList.tsx
index 52ba6b63f47..7172faf20c9 100644
--- a/src/features/Settings/trash/features/TrashList.tsx
+++ b/src/features/Settings/trash/features/TrashList.tsx
@@ -303,7 +303,12 @@ const TrashList = () => {
/>
{nextCursor && (
<Center style={{ paddingBlockStart: 12 }}>
- <Button loading={isLoadingMore} size={'small'} type={'text'} onClick={() => loadMore()}>
+ <Button
+ loading={isLoadingMore}
+ size={'small'}
+ type={'text'}
+ onClick={() => loadMore().catch(reportFailure)}
+ >
{t('trash.actions.loadMore')}
</Button>
</Center>
diff --git a/src/services/message/index.ts b/src/services/message/index.ts
index 3f5cb44191c..521415f2d0b 100644
--- a/src/services/message/index.ts
+++ b/src/services/message/index.ts
@@ -446,11 +446,20 @@ export class MessageService {
return lambdaClient.message.removeMessage.mutate({ ...ctx, id });
};
+ /**
+ * Moves the messages to the recycle bin. `permanent` hard-deletes instead —
+ * only for internal cleanup whose rows must never be restorable.
+ */
removeMessages = async (
ids: string[],
ctx?: MessageQueryContext,
+ options?: { permanent?: boolean },
): Promise<UpdateMessageResult> => {
- return lambdaClient.message.removeMessages.mutate({ ...ctx, ids });
+ return lambdaClient.message.removeMessages.mutate({
+ ...ctx,
+ ids,
+ ...(options?.permanent ? { permanent: true } : {}),
+ });
};
removeMessagesByAssistant = async (sessionId: string, topicId?: string) => {
diff --git a/src/store/trash/action.test.ts b/src/store/trash/action.test.ts
index 912ac5d46e1..e4feca5ffbb 100644
--- a/src/store/trash/action.test.ts
+++ b/src/store/trash/action.test.ts
@@ -78,6 +78,7 @@ describe('TrashAction', () => {
// Local-first sync keys (topic list) and the agent sidebar sync key
expect(filter(['replica:sync', 'topicList', 1, 'scope', 'agent_x', {}])).toBe(true);
expect(filter(['agentSync:list', true, 'scope'])).toBe(true);
+ expect(filter(['message:list', { agentId: 'a', topicId: 't' }, 1])).toBe(true);
expect(filter(['trash:list', 'all'])).toBe(false);
expect(filter('not-an-array')).toBe(false);
});
diff --git a/src/store/trash/action.ts b/src/store/trash/action.ts
index 0603b3044e2..f76e5833aea 100644
--- a/src/store/trash/action.ts
+++ b/src/store/trash/action.ts
@@ -30,6 +30,8 @@ const RESTORE_AFFECTED_KEY_PREFIXES = [
'knowledgeBase:',
// Replicas (topic list, …) sync through `replica:sync` keys (`@lobechat/replica`).
'replica:',
+ // conversation transcripts — a restored message must reappear in its thread
+ 'message:',
'page',
'project',
'recent:',