π€― LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
β¨ feat(database): hide trashed rows from every ownership-scoped read (#18414)
Arvin Xu2e784a965d8b
diff --git a/apps/server/src/routers/lambda/_helpers/topicCommentAccess.ts b/apps/server/src/routers/lambda/_helpers/topicCommentAccess.tsindex 6837460d258..1978554f390 100644--- a/apps/server/src/routers/lambda/_helpers/topicCommentAccess.ts+++ b/apps/server/src/routers/lambda/_helpers/topicCommentAccess.ts@@ -3,6 +3,7 @@ import { and, eq } from 'drizzle-orm';import { topics } from '@/database/schemas';import type { LobeChatDatabase } from '@/database/type';+import { notTrashed } from '@/database/utils/softDelete';import { getWorkspaceScopedPermissionMatches } from '@/server/services/workspacePermission';import { assertCanViewTopicTargets } from './conversationResourceGuard';@@ -32,7 +33,13 @@ export const assertTopicCommentReadAccess = async (params: {const [topic] = await params.db.select({ id: topics.id }).from(topics)- .where(and(eq(topics.id, params.topicId), eq(topics.workspaceId, params.workspaceId)))+ .where(+ and(+ eq(topics.id, params.topicId),+ eq(topics.workspaceId, params.workspaceId),+ notTrashed(topics.isDeleted),+ ),+ ).limit(1);if (!topic) {throw new TRPCError({ code: 'NOT_FOUND', message: 'Topic comment resource not found' });diff --git a/apps/server/src/routers/lambda/_helpers/workspaceAgentGuard.ts b/apps/server/src/routers/lambda/_helpers/workspaceAgentGuard.tsindex b586608b30c..5a72f0f8298 100644--- a/apps/server/src/routers/lambda/_helpers/workspaceAgentGuard.ts+++ b/apps/server/src/routers/lambda/_helpers/workspaceAgentGuard.ts@@ -2,6 +2,7 @@ import { and, eq } from 'drizzle-orm';import { agents, chatGroupsAgents } from '@/database/schemas';import type { LobeChatDatabase } from '@/database/type';+import { notTrashed } from '@/database/utils/softDelete';import { assertCanPerformResourceAction } from '@/server/services/resourcePermission';interface WorkspaceAgentGuardParams {@@ -31,6 +32,7 @@ export const getWorkspaceAgentParentGroupIds = async ({eq(chatGroupsAgents.agentId, agentId),eq(chatGroupsAgents.workspaceId, workspaceId),eq(agents.virtual, true),+ notTrashed(agents.isDeleted),),);@@ -60,6 +62,7 @@ export const getWorkspaceGroupVirtualAgentIds = async ({eq(chatGroupsAgents.chatGroupId, groupId),eq(chatGroupsAgents.workspaceId, workspaceId),eq(agents.virtual, true),+ notTrashed(agents.isDeleted),),);@@ -90,7 +93,11 @@ export const assertCanUseWorkspaceAgent = async ({if (!resourceId && slug) {const agent = await db.query.agents.findFirst({columns: { id: true },- where: and(eq(agents.slug, slug), eq(agents.workspaceId, workspaceId)),+ where: and(+ eq(agents.slug, slug),+ eq(agents.workspaceId, workspaceId),+ notTrashed(agents.isDeleted),+ ),});resourceId = agent?.id;}diff --git a/apps/server/src/routers/lambda/aiAgent.ts b/apps/server/src/routers/lambda/aiAgent.tsindex f5cc27537c3..a54dbda1062 100644--- a/apps/server/src/routers/lambda/aiAgent.ts+++ b/apps/server/src/routers/lambda/aiAgent.ts@@ -64,6 +64,7 @@ import { UserModel } from '@/database/models/user';import { agentOperations, topics, workspaceMembers } from '@/database/schemas';import type { LobeChatDatabase } from '@/database/type';import { notShareVisitorTopicRef } from '@/database/utils/shareVisitor';+import { notTrashed } from '@/database/utils/softDelete';import { heteroAuthedProcedure, router } from '@/libs/trpc/lambda';import { serverDatabase } from '@/libs/trpc/lambda/middleware';import { signHeteroOperationJWT, signUserJWT } from '@/libs/trpc/utils/internalJwt';@@ -777,7 +778,7 @@ const resolveHeteroTopicWorkspace = async (params: {const [topic] = await db.select({ userId: topics.userId, workspaceId: topics.workspaceId }).from(topics)- .where(eq(topics.id, topicId))+ .where(and(eq(topics.id, topicId), notTrashed(topics.isDeleted))).limit(1);if (!topic || (requestedWorkspaceId != null && requestedWorkspaceId !== topic.workspaceId)) {diff --git a/apps/server/src/routers/lambda/messenger.ts b/apps/server/src/routers/lambda/messenger.tsindex 95f623cd807..6e6ab20ace2 100644--- a/apps/server/src/routers/lambda/messenger.ts+++ b/apps/server/src/routers/lambda/messenger.ts@@ -2,7 +2,7 @@ import { MESSENGER_PUSH_CONTENT_MAX_LENGTH } from '@lobechat/builtin-tool-messagimport { fetchQrCode, pollQrStatus } from '@lobechat/chat-adapter-wechat';import { INBOX_SESSION_ID } from '@lobechat/const';import { TRPCError } from '@trpc/server';-import { eq } from 'drizzle-orm';+import { and, eq } from 'drizzle-orm';import { z } from 'zod';import {@@ -32,6 +32,7 @@ import { RbacModel } from '@/database/models/rbac';import { WorkspaceModel } from '@/database/models/workspace';import { agents, users } from '@/database/schemas';import type { LobeChatDatabase } from '@/database/type';+import { notTrashed } from '@/database/utils/softDelete';import { authedProcedure, publicProcedure, router } from '@/libs/trpc/lambda';import { serverDatabase } from '@/libs/trpc/lambda/middleware';import { getServerFeatureFlagsStateFromRuntimeConfig } from '@/server/featureFlags';@@ -212,7 +213,7 @@ const resolveAuthorizedAgentScope = async (const [agentRow] = await serverDB.select({ title: agents.title, userId: agents.userId, workspaceId: agents.workspaceId }).from(agents)- .where(eq(agents.id, agentId))+ .where(and(eq(agents.id, agentId), notTrashed(agents.isDeleted))).limit(1);if (!agentRow) {throw new TRPCError({ code: 'NOT_FOUND', message: 'messenger.error.agentNotFound' });diff --git a/apps/server/src/routers/lambda/resourceTransferRequest.ts b/apps/server/src/routers/lambda/resourceTransferRequest.tsindex c0888bced58..6e11a476ab6 100644--- a/apps/server/src/routers/lambda/resourceTransferRequest.ts+++ b/apps/server/src/routers/lambda/resourceTransferRequest.ts@@ -25,6 +25,7 @@ import { buildMemberTransferManifest } from '@/database/repositories/resourceTraimport type { ResourceTransferRequestItem } from '@/database/schemas';import { agents, chatGroups, users } from '@/database/schemas';import type { LobeChatDatabase } from '@/database/type';+import { notTrashed } from '@/database/utils/softDelete';import { router } from '@/libs/trpc/lambda';import { serverDatabase } from '@/libs/trpc/lambda/middleware';import { assertCanPerformResourceAction } from '@/server/services/resourcePermission';@@ -131,7 +132,13 @@ const enrichRequests = async (db: LobeChatDatabase, requests: ResourceTransferRetitle: agents.title,}).from(agents)- .where(and(inArray(agents.id, agentIds), eq(agents.workspaceId, requestWorkspaceId)))+ .where(+ and(+ inArray(agents.id, agentIds),+ eq(agents.workspaceId, requestWorkspaceId),+ notTrashed(agents.isDeleted),+ ),+ ): Promise.resolve([]),groupIds.length > 0? db@@ -143,7 +150,11 @@ const enrichRequests = async (db: LobeChatDatabase, requests: ResourceTransferRe}).from(chatGroups).where(- and(inArray(chatGroups.id, groupIds), eq(chatGroups.workspaceId, requestWorkspaceId)),+ and(+ inArray(chatGroups.id, groupIds),+ eq(chatGroups.workspaceId, requestWorkspaceId),+ notTrashed(chatGroups.isDeleted),+ ),): Promise.resolve([]),]);diff --git a/apps/server/src/routers/lambda/topic.ts b/apps/server/src/routers/lambda/topic.tsindex 92ff2217fd8..76cad7c5b89 100644--- a/apps/server/src/routers/lambda/topic.ts+++ b/apps/server/src/routers/lambda/topic.ts@@ -12,7 +12,7 @@ import {} from '@lobechat/types';import { cleanObject } from '@lobechat/utils';import { TRPCError } from '@trpc/server';-import { inArray } from 'drizzle-orm';+import { and, inArray } from 'drizzle-orm';import { z } from 'zod';import { withScopedPermission } from '@/business/server/trpc-middlewares/rbacPermission';@@ -32,6 +32,7 @@ import { HeteroSessionImporterRepo } from '@/database/repositories/heteroSessionimport { TopicImporterRepo } from '@/database/repositories/topicImporter';import { chatGroups } from '@/database/schemas';import type { LobeChatDatabase } from '@/database/type';+import { notTrashed } from '@/database/utils/softDelete';import { router } from '@/libs/trpc/lambda';import { serverDatabase } from '@/libs/trpc/lambda/middleware';import { FileService } from '@/server/services/file';@@ -846,7 +847,7 @@ export const topicRouter = router({title: chatGroups.title,}).from(chatGroups)- .where(inArray(chatGroups.id, allGroupIds));+ .where(and(inArray(chatGroups.id, allGroupIds), notTrashed(chatGroups.isDeleted)));// Query group member avatars (already normalized for the inbox agent)const groupMembersMap: Map<string, RecentTopicGroupMember[]> =diff --git a/apps/server/src/routers/lambda/userMemories.ts b/apps/server/src/routers/lambda/userMemories.tsindex 6313e529f1d..857231a9756 100644--- a/apps/server/src/routers/lambda/userMemories.ts+++ b/apps/server/src/routers/lambda/userMemories.ts@@ -44,6 +44,7 @@ import {userMemoriesPreferences,userSettings,} from '@/database/schemas';+import { notTrashed } from '@/database/utils/softDelete';import { authedProcedure, router } from '@/libs/trpc/lambda';import { serverDatabase } from '@/libs/trpc/lambda/middleware';import { getServerDefaultFilesConfig } from '@/server/globalConfig';@@ -508,6 +509,7 @@ export const userMemoriesRouter = router({await run('userMemories', async () => {const where = combineConditions([eq(userMemories.userId, ctx.userId),+ notTrashed(userMemories.isDeleted),options.startDate ? gte(userMemories.createdAt, options.startDate) : undefined,options.endDate ? lte(userMemories.createdAt, options.endDate) : undefined,]);diff --git a/apps/server/src/services/agentSignal/policies/analyzeIntent/__tests__/completionSkillSynthesis.test.ts b/apps/server/src/services/agentSignal/policies/analyzeIntent/__tests__/completionSkillSynthesis.test.tsindex 0087acaef54..3441269eb01 100644--- a/apps/server/src/services/agentSignal/policies/analyzeIntent/__tests__/completionSkillSynthesis.test.ts+++ b/apps/server/src/services/agentSignal/policies/analyzeIntent/__tests__/completionSkillSynthesis.test.ts@@ -1,4 +1,5 @@// @vitest-environment node+import { sql } from 'drizzle-orm';import { beforeEach, describe, expect, it, vi } from 'vitest';import { CompletionLifecycle } from '@/server/services/agentRuntime/CompletionLifecycle';@@ -97,7 +98,12 @@ const USER_ROW = {const createDb = () => {const findFirst = vi.fn().mockResolvedValueOnce(ASSISTANT_ROW).mockResolvedValueOnce(USER_ROW);const findMany = vi.fn().mockResolvedValue(trajectoryRows);- return { db: { query: { messages: { findFirst, findMany } } } as never, findFirst, findMany };+ const db = {+ query: { messages: { findFirst, findMany } },+ select: () => ({ from: () => ({ where: () => sql`select 1` }) }),+ } as never;++ return { db, findFirst, findMany };};const createContext = (applied = false): RuntimeProcessorContext =>diff --git a/apps/server/src/services/expertise/ingestion.ts b/apps/server/src/services/expertise/ingestion.tsindex 399a3035e9e..37e224ecbbc 100644--- a/apps/server/src/services/expertise/ingestion.ts+++ b/apps/server/src/services/expertise/ingestion.ts@@ -34,6 +34,8 @@ import { FileModel } from '@/database/models/file';import { VerifyEvidenceModel } from '@/database/models/verifyEvidence';import type { LobeChatDatabase } from '@/database/type';import { notShareVisitorMessage, notShareVisitorTopic } from '@/database/utils/shareVisitor';+import { notTrashed } from '@/database/utils/softDelete';+import { buildWorkspaceWhere } from '@/database/utils/workspace';import type { CompletionCallbackParams } from '@/server/services/agentSignal/policies/completionPolicy';import { AiGenerationService } from '@/server/services/aiGeneration';import { FileService } from '@/server/services/file';@@ -279,11 +281,13 @@ export class ExpertiseIngestionService {const byMessageAgent = this.db.select({ topicId: messages.topicId }).from(messages)+ .innerJoin(topics, and(eq(topics.id, messages.topicId), notTrashed(topics.isDeleted))).where(and(scope,eq(messages.agentId, agentId),isNotNull(messages.topicId),+ notTrashed(messages.isDeleted),notShareVisitorMessage(),),);@@ -292,7 +296,14 @@ export class ExpertiseIngestionService {.from(messages).innerJoin(topics, eq(topics.id, messages.topicId)).where(- and(scope, isNull(messages.agentId), eq(topics.agentId, agentId), notShareVisitorTopic()),+ and(+ scope,+ isNull(messages.agentId),+ eq(topics.agentId, agentId),+ notTrashed(messages.isDeleted),+ notTrashed(topics.isDeleted),+ notShareVisitorTopic(),+ ),);return byMessageAgent.union(byTopicAgent).as('historical_topic_candidates');@@ -316,7 +327,7 @@ export class ExpertiseIngestionService {}).from(messages).innerJoin(candidates, eq(candidates.topicId, messages.topicId))- .where(scope)+ .where(and(scope, notTrashed(messages.isDeleted))).groupBy(messages.topicId).having(options.cursor@@ -746,6 +757,18 @@ export class ExpertiseIngestionService {};private readTopicContext = async (topicId: string) => {+ const [topic] = await this.db+ .select({ id: topics.id })+ .from(topics)+ .where(+ and(+ eq(topics.id, topicId),+ buildWorkspaceWhere({ userId: this.userId, workspaceId: this.workspaceId }, topics),+ ),+ )+ .limit(1);+ if (!topic) return { hadHumanInLoop: false, serializedContext: '' };+const rows = await this.db.query.messages.findMany({columns: { content: true, createdAt: true, role: true },limit: MAX_CONTEXT_MESSAGES,@@ -756,6 +779,7 @@ export class ExpertiseIngestionService {: and(eq(messages.userId, this.userId), isNull(messages.workspaceId)),eq(messages.topicId, topicId),isNull(messages.threadId),+ notTrashed(messages.isDeleted),// Same rule as `historicalTopicCandidates` above β exclude share-visitor messages.notShareVisitorMessage(),),diff --git a/apps/server/src/services/memory/userMemory/persona/service.ts b/apps/server/src/services/memory/userMemory/persona/service.tsindex 754ba1e67f2..f54c89502a6 100644--- a/apps/server/src/services/memory/userMemory/persona/service.ts+++ b/apps/server/src/services/memory/userMemory/persona/service.ts@@ -10,7 +10,7 @@ import {UserPersonaExtractor,} from '@lobechat/memory-user-memory';import type { UserServiceModelConfig } from '@lobechat/types';-import { desc, eq } from 'drizzle-orm';+import { and, desc, eq } from 'drizzle-orm';import { getBusinessModelRuntimeHooks } from '@/business/server/model-runtime';import { UserModel } from '@/database/models/user';@@ -18,6 +18,7 @@ import { UserMemoryModel } from '@/database/models/userMemory';import { UserPersonaModel } from '@/database/models/userMemory/persona';import { AiInfraRepos } from '@/database/repositories/aiInfra';import { type LobeChatDatabase } from '@/database/type';+import { notTrashed } from '@/database/utils/softDelete';import { type MemoryAgentConfig } from '@/server/globalConfig/parseMemoryExtractionConfig';import { parseMemoryExtractionConfig } from '@/server/globalConfig/parseMemoryExtractionConfig';import { KeyVaultsGateKeeper } from '@/server/modules/KeyVaultsEncrypt';@@ -197,7 +198,7 @@ export const buildUserPersonaJobInput = async (db: LobeChatDatabase, userId: strdb.query.userMemories.findMany({limit: 20,orderBy: [desc(userMemories.capturedAt)],- where: eq(userMemories.userId, userId),+ where: and(eq(userMemories.userId, userId), notTrashed(userMemories.isDeleted)),}),]);diff --git a/apps/server/src/services/onboarding/index.test.ts b/apps/server/src/services/onboarding/index.test.tsindex 707e813882e..35f377c0f0a 100644--- a/apps/server/src/services/onboarding/index.test.ts+++ b/apps/server/src/services/onboarding/index.test.ts@@ -94,10 +94,12 @@ describe('OnboardingService', () => {updateUser: ReturnType<typeof vi.fn>;};let transactionUpdateCalls: Array<{+ returning: ReturnType<typeof vi.fn>;set: ReturnType<typeof vi.fn>;table: unknown;where: ReturnType<typeof vi.fn>;}>;+ let transactionTopicUpdateRows: unknown[];beforeEach(() => {persistedUserState = {@@ -110,6 +112,7 @@ describe('OnboardingService', () => {};persistedTopics = {};transactionUpdateCalls = [];+ transactionTopicUpdateRows = [{ id: 'topic-1' }];mockDb = {delete: vi.fn(function () {@@ -129,12 +132,13 @@ describe('OnboardingService', () => {callback({execute: vi.fn(async () => undefined),update: vi.fn(function (table) {- const where = vi.fn(async () => undefined);+ const returning = vi.fn(async () => transactionTopicUpdateRows);+ const where = vi.fn(() => ({ returning }));const set = vi.fn(function () {return { where };});- transactionUpdateCalls.push({ set, table, where });+ transactionUpdateCalls.push({ returning, set, table, where });return { set };}),@@ -639,6 +643,28 @@ describe('OnboardingService', () => {});});+ it('does not re-parent children when the topic is trashed after the pre-read', async () => {+ persistedUserState.agentOnboarding = {+ activeTopicId: 'topic-1',+ version: CURRENT_ONBOARDING_VERSION,+ };+ persistedTopics['topic-1'] = {+ agentId: 'web-onboarding-agent',+ id: 'topic-1',+ metadata: {},+ };+ // Simulate the live-row guarded topic update losing a race with trashing.+ transactionTopicUpdateRows = [];++ const service = new OnboardingService(mockDb as any, userId);+ const result = await service.finishOnboarding();++ expect(result.success).toBe(true);+ expect(mockDb.transaction).toHaveBeenCalledTimes(1);+ expect(transactionUpdateCalls).toHaveLength(1);+ expect(transactionUpdateCalls[0].returning).toHaveBeenCalledWith({ id: expect.anything() });+ });+it('is idempotent when finishOnboarding is called after completion', async () => {persistedUserState.agentOnboarding = {activeTopicId: 'topic-1',diff --git a/apps/server/src/services/onboarding/index.ts b/apps/server/src/services/onboarding/index.tsindex 9c025cca763..452f4392849 100644--- a/apps/server/src/services/onboarding/index.ts+++ b/apps/server/src/services/onboarding/index.ts@@ -37,6 +37,7 @@ import {} from '@/database/schemas';import type { LobeChatDatabase } from '@/database/type';import { notShareVisitorTopic, notShareVisitorTopicRef } from '@/database/utils/shareVisitor';+import { notTrashed } from '@/database/utils/softDelete';import { KeyVaultsGateKeeper } from '@/server/modules/KeyVaultsEncrypt';import { AgentService } from '@/server/services/agent';import { AgentDocumentsService } from '@/server/services/agentDocuments';@@ -206,10 +207,23 @@ export class OnboardingService {if (!topic || topic.agentId === inboxAgentId) return;await this.db.transaction(async (tx) => {- await tx+ const [updatedTopic] = await tx.update(topics).set({ agentId: inboxAgentId, updatedAt: topics.updatedAt })- .where(and(eq(topics.id, topicId), eq(topics.userId, this.userId), notShareVisitorTopic()));+ .where(+ and(+ eq(topics.id, topicId),+ eq(topics.userId, this.userId),+ notTrashed(topics.isDeleted),+ notShareVisitorTopic(),+ ),+ )+ .returning({ id: topics.id });++ // The topic may have been trashed after the creator-scoped pre-read.+ // The guarded update is the transaction's serialization point: when it+ // loses that race, do not re-parent children behind the hidden topic.+ if (!updatedTopic) return;await tx.update(messages)@@ -218,6 +232,7 @@ export class OnboardingService {and(eq(messages.topicId, topicId),eq(messages.userId, this.userId),+ notTrashed(messages.isDeleted),notShareVisitorTopicRef(messages.topicId),),);@@ -229,6 +244,7 @@ export class OnboardingService {and(eq(threads.topicId, topicId),eq(threads.userId, this.userId),+ notTrashed(threads.isDeleted),notShareVisitorTopicRef(threads.topicId),),);@@ -339,6 +355,7 @@ export class OnboardingService {eq(messages.topicId, topicId),eq(messages.userId, this.userId),eq(messages.role, 'user'),+ notTrashed(messages.isDeleted),),);diff --git a/apps/server/src/services/resourcePermission/index.ts b/apps/server/src/services/resourcePermission/index.tsindex a211c1b0cbe..17b7cb03d9f 100644--- a/apps/server/src/services/resourcePermission/index.ts+++ b/apps/server/src/services/resourcePermission/index.ts@@ -1,7 +1,7 @@import { isCollaborativeBuiltinAgentRow } from '@lobechat/builtin-agents';import type { PERMISSION_ACTIONS } from '@lobechat/const/rbac';import { TRPCError } from '@trpc/server';-import { eq } from 'drizzle-orm';+import { and, eq } from 'drizzle-orm';import { ResourcePermissionModel } from '@/database/models/resourcePermission';import type { PermissionResourceType, ResourceAccessLevel } from '@/database/schemas';@@ -13,6 +13,7 @@ import {knowledgeBases,} from '@/database/schemas';import type { LobeChatDatabase } from '@/database/type';+import { notTrashed } from '@/database/utils/softDelete';import {getWorkspaceScopedPermissionMatches,isWorkspacePrimaryOwner,@@ -106,7 +107,7 @@ export const getResourceMeta = async (workspaceId: agents.workspaceId,}).from(agents)- .where(eq(agents.id, resourceId))+ .where(and(eq(agents.id, resourceId), notTrashed(agents.isDeleted))).limit(1);return row ?? null;@@ -119,7 +120,7 @@ export const getResourceMeta = async (const [row] = await db.select({ userId: table.userId, visibility: table.visibility, workspaceId: table.workspaceId }).from(table)- .where(eq(table.id, resourceId))+ .where(and(eq(table.id, resourceId), notTrashed(table.isDeleted))).limit(1);return row ?? null;@@ -140,7 +141,7 @@ const resolveAgentBuiltinMarkers = async (const [row] = await db.select({ slug: agents.slug, virtual: agents.virtual }).from(agents)- .where(eq(agents.id, resourceId))+ .where(and(eq(agents.id, resourceId), notTrashed(agents.isDeleted))).limit(1);return { slug: row?.slug ?? null, virtual: row?.virtual ?? null };diff --git a/apps/server/src/services/taskRecommendation/materializer.ts b/apps/server/src/services/taskRecommendation/materializer.tsindex f21c5e5139b..d7886208218 100644--- a/apps/server/src/services/taskRecommendation/materializer.ts+++ b/apps/server/src/services/taskRecommendation/materializer.ts@@ -4,6 +4,7 @@ import { and, eq, isNull } from 'drizzle-orm';import { topics } from '@/database/schemas';import type { LobeChatDatabase } from '@/database/type';+import { notTrashed } from '@/database/utils/softDelete';import type { CreateTaskInput } from '@/server/services/task';import { TaskService } from '@/server/services/task';@@ -67,6 +68,7 @@ export class TaskRecommendationMaterializer {eq(topics.id, input.topicId),eq(topics.userId, this.userId),isNull(topics.workspaceId),+ notTrashed(topics.isDeleted),),).for('update');@@ -125,6 +127,7 @@ export class TaskRecommendationMaterializer {eq(topics.id, input.topicId),eq(topics.userId, this.userId),isNull(topics.workspaceId),+ notTrashed(topics.isDeleted),),);diff --git a/apps/server/src/services/taskRunner/heartbeatTick.test.ts b/apps/server/src/services/taskRunner/heartbeatTick.test.tsindex 6c1d258a2ab..c61667f1440 100644--- a/apps/server/src/services/taskRunner/heartbeatTick.test.ts+++ b/apps/server/src/services/taskRunner/heartbeatTick.test.ts@@ -1,5 +1,7 @@// @vitest-environment nodeimport { TRPCError } from '@trpc/server';+import type { SQL } from 'drizzle-orm';+import { PgDialect } from 'drizzle-orm/pg-core';import { beforeEach, describe, expect, it, vi } from 'vitest';import { BriefModel } from '@/database/models/brief';@@ -7,18 +9,19 @@ import { BriefModel } from '@/database/models/brief';import { runHeartbeatTick } from './heartbeatTick';import { TaskRunnerService } from './index';-const { mockSelectTask, mockSetTaskSchedulerExecutionCallback } = vi.hoisted(() => ({+const { mockSelectTask, mockSetTaskSchedulerExecutionCallback, mockWhereTask } = vi.hoisted(() => ({mockSelectTask: vi.fn(),mockSetTaskSchedulerExecutionCallback: vi.fn(),+ mockWhereTask: vi.fn((_condition: SQL) => ({+ limit: () => mockSelectTask(),+ })),}));vi.mock('@/database/server', () => ({getServerDB: vi.fn().mockResolvedValue({select: () => ({from: () => ({- where: () => ({- limit: () => mockSelectTask(),- }),+ where: mockWhereTask,}),}),}),@@ -81,6 +84,14 @@ describe('runHeartbeatTick', () => {expect(mockRunner.runTask).toHaveBeenCalledWith({ taskId, trigger: 'heartbeat' });});+ it('excludes trashed tasks from the queued tick lookup', async () => {+ const outcome = await runHeartbeatTick(taskId, userId);++ const condition = mockWhereTask.mock.calls[0][0];+ expect(new PgDialect().sqlToQuery(condition).sql).toContain('"tasks"."is_deleted" IS NOT TRUE');+ expect(outcome).toEqual({ ran: false, reason: 'not-found' });+ });+it('still skips when a non-error urgent brief requires human input', async () => {mockSelectTask.mockResolvedValue([baseTask()]);mockBriefModel.hasUnresolvedUrgentByTask.mockResolvedValue(true);diff --git a/apps/server/src/services/taskRunner/heartbeatTick.ts b/apps/server/src/services/taskRunner/heartbeatTick.tsindex d5a522af218..75925f6b19e 100644--- a/apps/server/src/services/taskRunner/heartbeatTick.ts+++ b/apps/server/src/services/taskRunner/heartbeatTick.ts@@ -5,6 +5,7 @@ import { and, eq } from 'drizzle-orm';import { BriefModel } from '@/database/models/brief';import { tasks } from '@/database/schemas';import { getServerDB } from '@/database/server';+import { notTrashed } from '@/database/utils/softDelete';import { setTaskSchedulerExecutionCallback } from '@/server/services/taskScheduler';import { TaskRunnerService } from './index';@@ -46,7 +47,9 @@ export async function runHeartbeatTick(const [task] = await db.select().from(tasks)- .where(and(eq(tasks.id, taskId), eq(tasks.createdByUserId, userId)))+ .where(+ and(eq(tasks.id, taskId), eq(tasks.createdByUserId, userId), notTrashed(tasks.isDeleted)),+ ).limit(1);if (!task) {log('skip task=%s reason=not-found', taskId);diff --git a/apps/server/src/services/taskRunner/scheduleTick.test.ts b/apps/server/src/services/taskRunner/scheduleTick.test.tsindex fc2ed7d050c..61c884b5eba 100644--- a/apps/server/src/services/taskRunner/scheduleTick.test.ts+++ b/apps/server/src/services/taskRunner/scheduleTick.test.ts@@ -1,5 +1,7 @@// @vitest-environment nodeimport { TRPCError } from '@trpc/server';+import type { SQL } from 'drizzle-orm';+import { PgDialect } from 'drizzle-orm/pg-core';import { beforeEach, describe, expect, it, vi } from 'vitest';import { BriefModel } from '@/database/models/brief';@@ -10,14 +12,15 @@ import { TaskRunnerService } from './index';import { runScheduleTick } from './scheduleTick';const mockSelectTask = vi.fn();+const mockWhereTask = vi.fn((_condition: SQL) => ({+ limit: () => mockSelectTask(),+}));vi.mock('@/database/server', () => ({getServerDB: vi.fn().mockResolvedValue({select: () => ({from: () => ({- where: () => ({- limit: () => mockSelectTask(),- }),+ where: mockWhereTask,}),}),}),@@ -94,6 +97,14 @@ describe('runScheduleTick', () => {expect(mockRunner.runTask).not.toHaveBeenCalled();});+ it('excludes trashed tasks from the queued tick lookup', async () => {+ const outcome = await runScheduleTick(taskId, userId);++ const condition = mockWhereTask.mock.calls[0][0];+ expect(new PgDialect().sqlToQuery(condition).sql).toContain('"tasks"."is_deleted" IS NOT TRUE');+ expect(outcome).toEqual({ ran: false, reason: 'not-found' });+ });+it('skips when automationMode has been changed away from schedule', async () => {mockSelectTask.mockResolvedValue([baseTask({ automationMode: 'heartbeat' })]);diff --git a/apps/server/src/services/taskRunner/scheduleTick.ts b/apps/server/src/services/taskRunner/scheduleTick.tsindex 68e305fd5ad..5f4634bc1fd 100644--- a/apps/server/src/services/taskRunner/scheduleTick.ts+++ b/apps/server/src/services/taskRunner/scheduleTick.ts@@ -7,6 +7,7 @@ import { TaskModel } from '@/database/models/task';import { TaskTopicModel } from '@/database/models/taskTopic';import { tasks } from '@/database/schemas';import { getServerDB } from '@/database/server';+import { notTrashed } from '@/database/utils/softDelete';import { TaskRunnerService } from './index';@@ -48,7 +49,9 @@ export async function runScheduleTick(const [task] = await db.select().from(tasks)- .where(and(eq(tasks.id, taskId), eq(tasks.createdByUserId, userId)))+ .where(+ and(eq(tasks.id, taskId), eq(tasks.createdByUserId, userId), notTrashed(tasks.isDeleted)),+ ).limit(1);if (!task) {log('skip task=%s reason=not-found', taskId);diff --git a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/agentDocuments.test.ts b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/agentDocuments.test.tsindex 81951ebaade..de827256807 100644--- a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/agentDocuments.test.ts+++ b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/agentDocuments.test.ts@@ -101,11 +101,12 @@ describe('agentDocumentsRuntime auto-pin to task', () => {const buildContext = (taskId?: string,workspaceId?: string,+ taskRows: Array<{ workspaceId: string | null }> = [{ workspaceId: null }],overrides?: Partial<ToolExecutionContext>,) => {// Mock the workspace lookup chain that `pinToTask` runs against the task// row. Returning `workspaceId: null` reproduces personal-mode behavior.- const limit = vi.fn().mockResolvedValue([{ workspaceId: null }]);+ const limit = vi.fn().mockResolvedValue(taskRows);const where = vi.fn().mockReturnValue({ limit });const from = vi.fn().mockReturnValue({ where });const select = vi.fn().mockReturnValue({ from });@@ -127,6 +128,63 @@ describe('agentDocumentsRuntime auto-pin to task', () => {expect(pinDocument).toHaveBeenCalledWith('task-1', 'documents-row-id', 'agent');});+ it('fails before document mutation when a legacy task anchor was trashed', async () => {+ const runtime = agentDocumentsRuntime.factory(buildContext('trashed-task', undefined, []));++ await expect(+ runtime.createDocument(+ { content: 'body', title: 'Must not write to personal scope' },+ { agentId: 'agent-1' },+ ),+ ).rejects.toThrow('missing or trashed task trashed-task');+ expect(serviceImpl.createDocument).not.toHaveBeenCalled();+ expect(pinDocument).not.toHaveBeenCalled();+ });++ it('validates a trashed task before mutation when workspace context is present', async () => {+ const runtime = agentDocumentsRuntime.factory(buildContext('trashed-task', 'workspace-1', []));++ await expect(+ runtime.createDocument(+ { content: 'body', title: 'Must not write before task validation' },+ { agentId: 'agent-1' },+ ),+ ).rejects.toThrow('missing or trashed task trashed-task');+ expect(serviceImpl.createDocument).not.toHaveBeenCalled();+ expect(pinDocument).not.toHaveBeenCalled();+ });++ it('fails before document mutation when task and context workspaces differ', async () => {+ const runtime = agentDocumentsRuntime.factory(+ buildContext('task-1', 'workspace-1', [{ workspaceId: 'workspace-2' }]),+ );++ await expect(+ runtime.createDocument(+ { content: 'body', title: 'Must not cross workspace scopes' },+ { agentId: 'agent-1' },+ ),+ ).rejects.toThrow('Task task-1 belongs to workspace workspace-2, not workspace-1');+ expect(serviceImpl.createDocument).not.toHaveBeenCalled();+ expect(pinDocument).not.toHaveBeenCalled();+ });++ it('uses the recovered task workspace for both document mutation and pinning', async () => {+ const context = buildContext('task-1', undefined, [{ workspaceId: 'workspace-1' }]);+ const runtime = agentDocumentsRuntime.factory(context);++ await runtime.createDocument({ content: 'body', title: 'Scoped' }, { agentId: 'agent-1' });++ expect(AgentDocumentsService).toHaveBeenLastCalledWith(+ context.serverDB,+ 'user-1',+ 'workspace-1',+ undefined,+ { type: 'ordinary' },+ );+ expect(TaskModel).toHaveBeenLastCalledWith(context.serverDB, 'user-1', 'workspace-1');+ });+it('emits create outcomes with the agent document binding id', async () => {const runtime = agentDocumentsRuntime.factory(buildContext('task-1'));@@ -258,7 +316,7 @@ describe('agentDocumentsRuntime auto-pin to task', () => {it('forces Share creation and listing into the visitor current-topic scope', async () => {const runtime = agentDocumentsRuntime.factory(- buildContext(undefined, undefined, {+ buildContext(undefined, undefined, undefined, {agentShareVisitor: {agentId: 'agent-1',shareId: 'share-1',diff --git a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/brief.test.ts b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/brief.test.tsnew file mode 100644index 00000000000..20320b9151f--- /dev/null+++ b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/brief.test.ts@@ -0,0 +1,44 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { BriefModel } from '@/database/models/brief';++import { briefRuntime } from '../brief';++vi.mock('@/database/models/brief');+vi.mock('@/database/models/task');++describe('briefRuntime', () => {+ const create = vi.fn();++ beforeEach(() => {+ create.mockReset();+ vi.mocked(BriefModel).mockImplementation(function () {+ return { create } as never;+ });+ });++ it('validates a trashed task before writing when workspace context is present', async () => {+ const limit = vi.fn().mockResolvedValue([]);+ const serverDB = {+ select: vi.fn(() => ({+ from: vi.fn(() => ({ where: vi.fn(() => ({ limit })) })),+ })),+ };+ const runtime = briefRuntime.factory({+ agentId: 'agent-1',+ serverDB,+ taskId: 'trashed-task',+ userId: 'user-1',+ workspaceId: 'workspace-1',+ } as never);++ await expect(+ runtime.createBrief({+ summary: 'Must not persist',+ title: 'Blocked brief',+ type: 'info',+ }),+ ).rejects.toThrow('missing or trashed task trashed-task');+ expect(create).not.toHaveBeenCalled();+ });+});diff --git a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/browser.test.ts b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/browser.test.tsindex 7e751b0d7ea..b5b2e16c466 100644--- a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/browser.test.ts+++ b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/browser.test.ts@@ -24,6 +24,15 @@ vi.mock('@/server/services/file', () => ({// Import after mock setupconst { browserRuntime } = await import('../browser');+/** Minimal drizzle chain for the live personal agent used by these tests. */+const personalAgentServerDB = {+ select: () => ({+ from: () => ({+ where: () => ({ limit: () => Promise.resolve([{ workspaceId: null }]) }),+ }),+ }),+} as any;+describe('browserRuntime', () => {beforeEach(() => {vi.clearAllMocks();@@ -35,7 +44,7 @@ describe('browserRuntime', () => {activeDeviceId: 'vm-cli',agentId: 'agt-1',operationId: 'op-1',- serverDB: {} as any,+ serverDB: personalAgentServerDB,toolManifestMap: {},topicId: 'tpc-1',userId: 'user-1',@@ -117,7 +126,7 @@ describe('browserRuntime', () => {activeDeviceId: 'device-1',agentId: 'agt-1',operationId: 'op-1',- serverDB: {} as any,+ serverDB: personalAgentServerDB,toolManifestMap: {},topicId: 'tpc-1',userId: 'user-1',diff --git a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/remoteDevice.test.ts b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/remoteDevice.test.tsindex 39df0919a7f..8cfaddede6f 100644--- a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/remoteDevice.test.ts+++ b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/remoteDevice.test.ts@@ -29,13 +29,13 @@ vi.mock('@/database/models/device', () => ({// Import after mock setupconst { remoteDeviceRuntime } = await import('../remoteDevice');-/** Minimal drizzle-like chain that resolves the agent's workspace_id lookup. */+/** Minimal drizzle-like chain that resolves a live agent's workspace_id lookup. */const makeServerDB = (workspaceId: string | null) =>({select: () => ({from: () => ({where: () => ({- limit: () => Promise.resolve(workspaceId === null ? [] : [{ workspaceId }]),+ limit: () => Promise.resolve([{ workspaceId }]),}),}),}),diff --git a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/resolveWorkspaceScope.test.ts b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/resolveWorkspaceScope.test.tsnew file mode 100644index 00000000000..f872d7daf1d--- /dev/null+++ b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/resolveWorkspaceScope.test.ts@@ -0,0 +1,47 @@+import { describe, expect, it, vi } from 'vitest';++import type { LobeChatDatabase } from '@/database/type';++import { resolveContentWorkspaceId, resolveTaskWorkspaceId } from '../resolveWorkspaceScope';++const createDb = (rows: Array<{ workspaceId: string | null }>) =>+ ({+ select: vi.fn(() => ({+ from: vi.fn(() => ({+ where: vi.fn(() => ({ limit: vi.fn().mockResolvedValue(rows) })),+ })),+ })),+ }) as unknown as LobeChatDatabase;++describe('workspace scope recovery', () => {+ it('distinguishes a live personal task from a missing or trashed task', async () => {+ await expect(resolveTaskWorkspaceId(createDb([{ workspaceId: null }]), 'task-1')).resolves.toBe(+ undefined,+ );+ await expect(resolveTaskWorkspaceId(createDb([]), 'task-1')).rejects.toThrow(+ 'missing or trashed task task-1',+ );+ });++ it('recovers a live task workspace and keeps no-task runs in personal scope', async () => {+ await expect(+ resolveTaskWorkspaceId(createDb([{ workspaceId: 'workspace-1' }]), 'task-1'),+ ).resolves.toBe('workspace-1');+ await expect(resolveTaskWorkspaceId(createDb([]), undefined)).resolves.toBe(undefined);+ });++ it('validates a supplied workspace against the live task anchor', async () => {+ await expect(+ resolveTaskWorkspaceId(createDb([{ workspaceId: 'workspace-1' }]), 'task-1', 'workspace-1'),+ ).resolves.toBe('workspace-1');+ await expect(+ resolveTaskWorkspaceId(createDb([{ workspaceId: 'workspace-2' }]), 'task-1', 'workspace-1'),+ ).rejects.toThrow('Task task-1 belongs to workspace workspace-2, not workspace-1');+ });++ it('fails closed when an anchored agent is missing or trashed', async () => {+ await expect(+ resolveContentWorkspaceId({ agentId: 'agent-1', serverDB: createDb([]) }),+ ).rejects.toThrow('missing or trashed agent agent-1');+ });+});diff --git a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/task.test.ts b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/task.test.tsindex 0701e15be99..31d489946f1 100644--- a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/task.test.ts+++ b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/task.test.ts@@ -102,6 +102,58 @@ describe('taskRuntime.factory', () => {expect(ctx).toMatchObject({ actingAgentId: 'agt-manager' });}});++ it('fails closed when a task anchor was trashed before workspace recovery', async () => {+ const limit = vi.fn().mockResolvedValue([]);+ const serverDB = {+ select: vi.fn(() => ({+ from: vi.fn(() => ({ where: vi.fn(() => ({ limit })) })),+ })),+ };+ const runtime = taskRuntime.factory({+ agentId: 'agt-manager',+ serverDB,+ taskId: 'trashed-task',+ userId: 'user-1',+ } as never);++ await expect(+ (runtime as unknown as { editTask: (a: unknown) => Promise<unknown> }).editTask({+ identifier: 'T-1',+ name: 'Must not write to personal scope',+ }),+ ).rejects.toThrow('missing or trashed task trashed-task');+ });++ it('still validates a trashed task anchor when workspace context is present', async () => {+ const limit = vi.fn().mockResolvedValue([]);+ const serverDB = {+ select: vi.fn(() => ({+ from: vi.fn(() => ({ where: vi.fn(() => ({ limit })) })),+ })),+ };+ const runtime = taskRuntime.factory({+ agentId: 'agt-manager',+ serverDB,+ taskId: 'trashed-task',+ userId: 'user-1',+ workspaceId: 'ws-1',+ } as never);++ await expect(+ (runtime as unknown as { editTask: (a: unknown) => Promise<unknown> }).editTask({+ identifier: 'T-1',+ name: 'Must not write after task deletion',+ }),+ ).rejects.toThrow('missing or trashed task trashed-task');++ await expect(+ (runtime as unknown as { editTask: (a: unknown) => Promise<unknown> }).editTask({+ identifier: 'T-1',+ name: 'A retry must remain fail-closed',+ }),+ ).rejects.toThrow('missing or trashed task trashed-task');+ });});describe('createTaskRuntime', () => {diff --git a/apps/server/src/services/toolExecution/serverRuntimes/agentDocuments.ts b/apps/server/src/services/toolExecution/serverRuntimes/agentDocuments.tsindex 5d2d694a1bd..cd87f1f6e59 100644--- a/apps/server/src/services/toolExecution/serverRuntimes/agentDocuments.ts+++ b/apps/server/src/services/toolExecution/serverRuntimes/agentDocuments.ts@@ -2,14 +2,13 @@ import type { DocumentLoadRule } from '@lobechat/agent-templates';import { AgentDocumentsIdentifier } from '@lobechat/builtin-tool-agent-documents';import { AgentDocumentsExecutionRuntime } from '@lobechat/builtin-tool-agent-documents/executionRuntime';import { agentShareDocumentAccessScope, ordinaryDocumentAccessScope } from '@lobechat/types';-import { eq } from 'drizzle-orm';import { TaskModel } from '@/database/models/task';-import { tasks } from '@/database/schemas';import { AgentDocumentsService } from '@/server/services/agentDocuments';import { createDocumentWorkRegistrar } from '@/server/services/agentDocuments/documentWork';import { emitAgentDocumentToolOutcomeSafely } from '@/server/services/agentDocuments/toolOutcome';+import { resolveTaskWorkspaceId } from './resolveWorkspaceScope';import { type ServerRuntimeRegistration } from './types';export const agentDocumentsRuntime: ServerRuntimeRegistration = {@@ -32,20 +31,35 @@ export const agentDocumentsRuntime: ServerRuntimeRegistration = {visitorUserId: context.agentShareVisitor.visitorUserId,}): ordinaryDocumentAccessScope;- const service = new AgentDocumentsService(- db,- userId,- context.workspaceId,- context.agentVisibility,- documentAccessScope,- );const { taskId } = context;- const workRegistrar = createDocumentWorkRegistrar({- db,- logPrefix: '[agentDocumentsRuntime]',- userId,- workspaceId: context.workspaceId,- });+ // Resolve and validate the task-derived scope once, before any document+ // read or write. Even when the pipeline supplied workspaceId, a task that+ // was trashed after dispatch or belongs to another scope must fail closed.+ let workspaceIdPromise: Promise<string | undefined> | undefined;+ const resolveWorkspaceId = () =>+ (workspaceIdPromise ??= resolveTaskWorkspaceId(db, taskId, context.workspaceId));+ let servicePromise: Promise<AgentDocumentsService> | undefined;+ const getService = () =>+ (servicePromise ??= resolveWorkspaceId().then(+ (workspaceId) =>+ new AgentDocumentsService(+ db,+ userId,+ workspaceId,+ context.agentVisibility,+ documentAccessScope,+ ),+ ));+ let workRegistrarPromise: Promise<ReturnType<typeof createDocumentWorkRegistrar>> | undefined;+ const getWorkRegistrar = () =>+ (workRegistrarPromise ??= resolveWorkspaceId().then((workspaceId) =>+ createDocumentWorkRegistrar({+ db,+ logPrefix: '[agentDocumentsRuntime]',+ userId,+ workspaceId,+ }),+ ));const emitDocumentOutcome = async (input: {agentId?: string;agentDocumentId?: string;@@ -118,18 +132,7 @@ export const agentDocumentsRuntime: ServerRuntimeRegistration = {const pinToTask = async <T extends { documentId?: string } | undefined>(doc: T): Promise<T> => {if (taskId && doc?.documentId) {- // Prefer the workspaceId already threaded through the pipeline; fall- // back to the owning task row for legacy callers.- let wsId = context.workspaceId;- if (!wsId) {- const [row] = await db- .select({ workspaceId: tasks.workspaceId })- .from(tasks)- .where(eq(tasks.id, taskId))- .limit(1);- wsId = row?.workspaceId ?? undefined;- }- const taskModel = new TaskModel(db, userId, wsId);+ const taskModel = new TaskModel(db, userId, await resolveWorkspaceId());await taskModel.pinDocument(taskId, doc.documentId, 'agent');}return doc;@@ -155,7 +158,7 @@ export const agentDocumentsRuntime: ServerRuntimeRegistration = {summary: 'Agent documents copied a document.',toolAction: 'copy',},- () => service.copyDocumentById(id, newTitle, agentId),+ async () => (await getService()).copyDocumentById(id, newTitle, agentId),),);return doc;@@ -172,10 +175,12 @@ export const agentDocumentsRuntime: ServerRuntimeRegistration = {summary: 'Agent documents created a document.',toolAction: 'create',},- () =>- shareTopicId+ async () => {+ const service = await getService();+ return shareTopicId? service.createForTopic(agentId, title, content, shareTopicId)- : service.createDocument(agentId, title, content, { hintIsSkill, parentId }),+ : service.createDocument(agentId, title, content, { hintIsSkill, parentId });+ },),);return doc;@@ -199,8 +204,8 @@ export const agentDocumentsRuntime: ServerRuntimeRegistration = {summary: 'Agent documents created a topic document.',toolAction: 'create',},- () =>- service.createForTopic(+ async () =>+ (await getService()).createForTopic(agentId,title,content,@@ -212,6 +217,7 @@ export const agentDocumentsRuntime: ServerRuntimeRegistration = {return doc;},listDocuments: async ({ agentId, parentId, sourceType }) => {+ const service = await getService();// Agents discover archived tool results via this path (see// `excludeArchivedToolResults`), so keep the `.tool-results` archive visible.const docs = shareTopicId@@ -230,6 +236,7 @@ export const agentDocumentsRuntime: ServerRuntimeRegistration = {}));},listTopicDocuments: async ({ agentId, parentId, sourceType, topicId }) => {+ const service = await getService();const docs = await service.listDocumentsForTopic(agentId,shareTopicId ?? topicId,@@ -258,11 +265,12 @@ export const agentDocumentsRuntime: ServerRuntimeRegistration = {summary: 'Agent documents modified document nodes.',toolAction: 'edit',},- () => service.modifyDocumentNodesById(id, operations, agentId),+ async () => (await getService()).modifyDocumentNodesById(id, operations, agentId),);return doc;},- readDocument: ({ agentId, id }) => service.getDocumentSnapshotById(id, agentId),+ readDocument: async ({ agentId, id }) =>+ (await getService()).getDocumentSnapshotById(id, agentId),removeDocument: ({ agentId, id }) =>withDocumentOutcome({@@ -273,7 +281,7 @@ export const agentDocumentsRuntime: ServerRuntimeRegistration = {summary: 'Agent documents removed a document.',toolAction: 'remove',},- () => service.removeDocumentById(id, agentId),+ async () => (await getService()).removeDocumentById(id, agentId),),renameDocument: async ({ agentId, id, newTitle }) => {const doc = await withDocumentOutcome(@@ -285,7 +293,7 @@ export const agentDocumentsRuntime: ServerRuntimeRegistration = {summary: 'Agent documents renamed a document.',toolAction: 'rename',},- () => service.renameDocumentById(id, newTitle, agentId),+ async () => (await getService()).renameDocumentById(id, newTitle, agentId),);return doc;},@@ -299,7 +307,7 @@ export const agentDocumentsRuntime: ServerRuntimeRegistration = {summary: 'Agent documents replaced document content.',toolAction: 'replace',},- () => service.replaceDocumentContentById(id, content, agentId),+ async () => (await getService()).replaceDocumentContentById(id, content, agentId),);return doc;},@@ -313,8 +321,8 @@ export const agentDocumentsRuntime: ServerRuntimeRegistration = {summary: 'Agent documents updated a load rule.',toolAction: 'update',},- () =>- service.updateLoadRuleById(+ async () =>+ (await getService()).updateLoadRuleById(id,{ ...rule, rule: rule.rule as DocumentLoadRule | undefined },agentId,@@ -325,8 +333,8 @@ export const agentDocumentsRuntime: ServerRuntimeRegistration = {documentReadonly: Boolean(context.agentShareVisitor),getDocumentUrl: context.agentShareVisitor? undefined- : ({ agentId, documentId }) =>- workRegistrar.buildRegisteredDocumentUrl(agentId, documentId),+ : async ({ agentId, documentId }) =>+ (await getWorkRegistrar()).buildRegisteredDocumentUrl(agentId, documentId),},);},diff --git a/apps/server/src/services/toolExecution/serverRuntimes/brief.ts b/apps/server/src/services/toolExecution/serverRuntimes/brief.tsindex ddd0f482b6b..9123bf5e083 100644--- a/apps/server/src/services/toolExecution/serverRuntimes/brief.ts+++ b/apps/server/src/services/toolExecution/serverRuntimes/brief.ts@@ -1,32 +1,13 @@import { BriefIdentifier } from '@lobechat/builtin-tool-brief';-import type { LobeChatDatabase } from '@lobechat/database';import { formatBriefCreated, formatCheckpointCreated } from '@lobechat/prompts';import { DEFAULT_BRIEF_ACTIONS } from '@lobechat/types';-import { eq } from 'drizzle-orm';import { BriefModel } from '@/database/models/brief';import { TaskModel } from '@/database/models/task';-import { tasks } from '@/database/schemas';+import { resolveTaskWorkspaceId } from './resolveWorkspaceScope';import { type ServerRuntimeRegistration } from './types';-// Row-level fallback: the agent-runtime hasn't threaded `workspaceId` into-// `ToolExecutionContext` yet, so we resolve it from the task row when the-// runtime fires inside a task. Falls back to undefined (personal mode) when-// there is no task association.-const resolveWorkspaceId = async (- db: LobeChatDatabase,- taskId: string | undefined,-): Promise<string | undefined> => {- if (!taskId) return undefined;- const [row] = await db- .select({ workspaceId: tasks.workspaceId })- .from(tasks)- .where(eq(tasks.id, taskId))- .limit(1);- return row?.workspaceId ?? undefined;-};-export const briefRuntime: ServerRuntimeRegistration = {factory: (context) => {if (!context.userId || !context.serverDB) {@@ -36,9 +17,9 @@ export const briefRuntime: ServerRuntimeRegistration = {const db = context.serverDB;const userId = context.userId;const { agentId, taskId } = context;- // Prefer the workspaceId threaded through the pipeline. Fall back to the- // owning task row when an older caller still doesn't populate it.- const resolveWs = async () => context.workspaceId ?? (await resolveWorkspaceId(db, taskId));+ // A present task remains the durable scope anchor even when the pipeline+ // supplied workspaceId; validate both liveness and scope before writes.+ const resolveWs = async () => resolveTaskWorkspaceId(db, taskId, context.workspaceId);return {createBrief: async (args: {diff --git a/apps/server/src/services/toolExecution/serverRuntimes/message/index.ts b/apps/server/src/services/toolExecution/serverRuntimes/message/index.tsindex 6827ecc8351..b22d0bcf8d6 100644--- a/apps/server/src/services/toolExecution/serverRuntimes/message/index.ts+++ b/apps/server/src/services/toolExecution/serverRuntimes/message/index.ts@@ -24,6 +24,7 @@ import { MessengerAccountLinkModel } from '@/database/models/messengerAccountLinimport { MessengerInstallationModel } from '@/database/models/messengerInstallation';import { TopicModel } from '@/database/models/topic';import { agents } from '@/database/schemas';+import { notTrashed } from '@/database/utils/softDelete';import { getAgentRuntimeRedisClient } from '@/server/modules/AgentRuntime/redis';import { KeyVaultsGateKeeper } from '@/server/modules/KeyVaultsEncrypt';import {@@ -790,7 +791,13 @@ export const messageRuntime: ServerRuntimeRegistration = {const [agentRow] = await context.serverDB.select({ id: agents.id }).from(agents)- .where(and(eq(agents.id, params.agentId), eq(agents.userId, context.userId)))+ .where(+ and(+ eq(agents.id, params.agentId),+ eq(agents.userId, context.userId),+ notTrashed(agents.isDeleted),+ ),+ ).limit(1);if (!agentRow) {throw new TRPCError({diff --git a/apps/server/src/services/toolExecution/serverRuntimes/resolveWorkspaceScope.ts b/apps/server/src/services/toolExecution/serverRuntimes/resolveWorkspaceScope.tsindex f4727ec275b..c4773fc918e 100644--- a/apps/server/src/services/toolExecution/serverRuntimes/resolveWorkspaceScope.ts+++ b/apps/server/src/services/toolExecution/serverRuntimes/resolveWorkspaceScope.ts@@ -1,7 +1,9 @@import debug from 'debug';-import { eq } from 'drizzle-orm';+import { and, eq } from 'drizzle-orm';-import { agents } from '@/database/schemas';+import { agents, tasks } from '@/database/schemas';+import type { LobeChatDatabase } from '@/database/type';+import { notTrashed } from '@/database/utils/softDelete';import { type ToolExecutionContext } from '../types';@@ -12,6 +14,38 @@ type DeviceScopeContext = Pick<'activeDeviceScope' | 'agentId' | 'serverDB' | 'workspaceId'>;+/**+ * Recover a task's content scope for runtimes whose older execution context+ * did not preserve workspaceId. A present task anchor must fail closed when+ * its live row has disappeared; only a live personal task resolves to+ * `undefined` legitimately.+ */+export const resolveTaskWorkspaceId = async (+ db: LobeChatDatabase,+ taskId: string | undefined,+ expectedWorkspaceId?: string,+): Promise<string | undefined> => {+ if (!taskId) return expectedWorkspaceId;++ const [row] = await db+ .select({ workspaceId: tasks.workspaceId })+ .from(tasks)+ .where(and(eq(tasks.id, taskId), notTrashed(tasks.isDeleted)))+ .limit(1);++ if (!row)+ throw new Error(`Cannot recover workspace scope from missing or trashed task ${taskId}`);++ const taskWorkspaceId = row.workspaceId ?? undefined;+ if (expectedWorkspaceId !== undefined && taskWorkspaceId !== expectedWorkspaceId) {+ throw new Error(+ `Task ${taskId} belongs to workspace ${taskWorkspaceId ?? 'personal'}, not ${expectedWorkspaceId}`,+ );+ }++ return taskWorkspaceId;+};+/*** The workspace whose CONTENT this run reads and writes: the run-scoped* `context.workspaceId`, or β when that was lost on the way to this tool call@@ -40,12 +74,14 @@ export const resolveContentWorkspaceId = async (const [row] = await serverDB.select({ workspaceId: agents.workspaceId }).from(agents)- .where(eq(agents.id, agentId))+ .where(and(eq(agents.id, agentId), notTrashed(agents.isDeleted))).limit(1);- return row?.workspaceId ?? undefined;+ if (!row)+ throw new Error(`Cannot recover workspace scope from missing or trashed agent ${agentId}`);+ return row.workspaceId ?? undefined;} catch (error) {log('failed to recover workspaceId from agent %s: %O', agentId, error);- return undefined;+ throw error;}};diff --git a/apps/server/src/services/toolExecution/serverRuntimes/task.ts b/apps/server/src/services/toolExecution/serverRuntimes/task.tsindex dea81081167..7536f53d9c8 100644--- a/apps/server/src/services/toolExecution/serverRuntimes/task.ts+++ b/apps/server/src/services/toolExecution/serverRuntimes/task.ts@@ -23,7 +23,6 @@ import {} from '@lobechat/prompts';import type { TaskAutomationMode, TaskStatus } from '@lobechat/types';import { formatInvalidScheduleMessage, validateScheduleUpdate } from '@lobechat/utils/cronEval';-import { eq } from 'drizzle-orm';import { notifyTaskAssigned } from '@/business/server/task/notifyTaskAssigned';import { AgentModel } from '@/database/models/agent';@@ -32,32 +31,15 @@ import { TaskModel } from '@/database/models/task';import { UserModel } from '@/database/models/user';import { WorkspaceModel } from '@/database/models/workspace';import { WorkspaceMemberModel } from '@/database/models/workspaceMember';-import { tasks } from '@/database/schemas';import { appEnv } from '@/envs/app';import { formatPgError, unwrapPgError } from '@/server/modules/AgentRuntime/pgError';import { taskRouter } from '@/server/routers/lambda/task';import { TaskService } from '@/server/services/task';import { after } from '@/server/utils/scheduleAfterResponse';+import { resolveTaskWorkspaceId } from './resolveWorkspaceScope';import { type ServerRuntimeRegistration } from './types';-// Row-level workspace resolution: the agent runtime hasn't threaded-// `workspaceId` into `ToolExecutionContext` yet. When the tool fires inside a-// task we derive the workspace from that task row; otherwise we fall back to-// personal mode.-const resolveWorkspaceId = async (- db: LobeChatDatabase,- taskId: string | undefined,-): Promise<string | undefined> => {- if (!taskId) return undefined;- const [row] = await db- .select({ workspaceId: tasks.workspaceId })- .from(tasks)- .where(eq(tasks.id, taskId))- .limit(1);- return row?.workspaceId ?? undefined;-};-export interface TaskRuntimeDeps {agentId?: string;agentModel: AgentModel;@@ -1030,28 +1012,26 @@ export const taskRuntime: ServerRuntimeRegistration = {taskCaller: taskRouter.createCaller({ actingAgentId: agentId, userId }),} as TaskRuntimeDeps;- let resolved = false;- const ensureModels = async () => {- if (resolved) return;- resolved = true;- // Prefer pipeline-threaded `context.workspaceId`. Fall back to looking- // up the owning task row for callers that pre-date the propagation work- // and still construct `ToolExecutionContext` without `workspaceId`.- const wsId = context.workspaceId ?? (await resolveWorkspaceId(db, taskId));- workspaceId = wsId;- deps.workspaceId = wsId;- deps.agentModel = new AgentModel(db, userId, wsId);- deps.taskModel = new TaskModel(db, userId, wsId);- deps.taskService = new TaskService(db, userId, wsId);- // MUST keep `actingAgentId`: this replaces the caller built above, and- // every exported method awaits `ensureModels()` first β dropping it here- // silently attributes every agent-driven task edit to the session user.- deps.taskCaller = taskRouter.createCaller({- actingAgentId: agentId,- userId,- workspaceId: wsId,- });- };+ let modelsPromise: Promise<void> | undefined;+ const ensureModels = () =>+ (modelsPromise ??= (async () => {+ // A present task remains the durable scope anchor even when the pipeline+ // supplied workspaceId; validate both liveness and scope before writes.+ const wsId = await resolveTaskWorkspaceId(db, taskId, context.workspaceId);+ workspaceId = wsId;+ deps.workspaceId = wsId;+ deps.agentModel = new AgentModel(db, userId, wsId);+ deps.taskModel = new TaskModel(db, userId, wsId);+ deps.taskService = new TaskService(db, userId, wsId);+ // MUST keep `actingAgentId`: this replaces the caller built above, and+ // every exported method awaits `ensureModels()` first β dropping it here+ // silently attributes every agent-driven task edit to the session user.+ deps.taskCaller = taskRouter.createCaller({+ actingAgentId: agentId,+ userId,+ workspaceId: wsId,+ });+ })());const baseRuntime = createTaskRuntime(deps);diff --git a/apps/server/src/services/topicAutoSummary/index.test.ts b/apps/server/src/services/topicAutoSummary/index.test.tsindex da2fae98192..ff54335bf22 100644--- a/apps/server/src/services/topicAutoSummary/index.test.ts+++ b/apps/server/src/services/topicAutoSummary/index.test.ts@@ -1,10 +1,13 @@import { beforeEach, describe, expect, it, vi } from 'vitest';+import type { LobeChatDatabase } from '@/database/type';+import { TopicAutoSummaryService } from './index';const mocks = vi.hoisted(() => ({generateObject: vi.fn(),getUserSettings: vi.fn(),+ resolveSystemAgentModelConfig: vi.fn(),updateSummaryIfCurrent: vi.fn(),}));@@ -25,10 +28,7 @@ vi.mock('@/server/services/aiGeneration', () => ({},}));vi.mock('@/server/services/systemAgent/modelConfig', () => ({- resolveSystemAgentModelConfig: vi.fn().mockResolvedValue({- model: 'deepseek-v4-flash',- provider: 'deepseek',- }),+ resolveSystemAgentModelConfig: mocks.resolveSystemAgentModelConfig,}));const createDb = (@@ -44,7 +44,7 @@ const createDb = (],],) => {- return {+ const db = {select: vi.fn(() => ({from: vi.fn(() => ({where: vi.fn(() => ({@@ -53,7 +53,9 @@ const createDb = (})),})),})),- } as never;+ };++ return db as typeof db & LobeChatDatabase;};describe('TopicAutoSummaryService', () => {@@ -63,6 +65,10 @@ describe('TopicAutoSummaryService', () => {systemAgent: { topicAutoSummary: { enabled: true } },});mocks.generateObject.mockResolvedValue({ description: 'Next steps', summary: 'Combined' });+ mocks.resolveSystemAgentModelConfig.mockResolvedValue({+ model: 'deepseek-v4-flash',+ provider: 'deepseek',+ });mocks.updateSummaryIfCurrent.mockResolvedValue(true);});@@ -112,6 +118,19 @@ describe('TopicAutoSummaryService', () => {expect(mocks.updateSummaryIfCurrent).not.toHaveBeenCalled();});+ it('stops before reading messages or resolving a model when the topic was trashed', async () => {+ const db = createDb([[]]);+ const service = new TopicAutoSummaryService(db, 'user-1');++ const result = await service.summarize('trashed-topic');++ expect(result).toEqual({ reason: 'stale', summarized: false });+ expect(db.select).toHaveBeenCalledTimes(1);+ expect(mocks.resolveSystemAgentModelConfig).not.toHaveBeenCalled();+ expect(mocks.generateObject).not.toHaveBeenCalled();+ expect(mocks.updateSummaryIfCurrent).not.toHaveBeenCalled();+ });+it('still summarizes an opted-out user when forced', async () => {mocks.getUserSettings.mockResolvedValue({systemAgent: { topicAutoSummary: { enabled: false } },diff --git a/apps/server/src/services/topicAutoSummary/index.ts b/apps/server/src/services/topicAutoSummary/index.tsindex 19cb41336a0..69d36b01ec9 100644--- a/apps/server/src/services/topicAutoSummary/index.ts+++ b/apps/server/src/services/topicAutoSummary/index.ts@@ -14,6 +14,7 @@ import { topicSummaryEligibleMessage, TopicSummaryModel } from '@/database/modelimport { UserModel } from '@/database/models/user';import { messages, topics } from '@/database/schemas';import type { LobeChatDatabase } from '@/database/type';+import { notTrashed } from '@/database/utils/softDelete';import { AiGenerationService } from '@/server/services/aiGeneration';import { resolveSystemAgentModelConfig } from '@/server/services/systemAgent/modelConfig';@@ -57,13 +58,20 @@ export class TopicAutoSummaryService {const [topic] = await this.db.select({ historySummary: topics.historySummary, senderId: topics.senderId }).from(topics)- .where(and(eq(topics.id, topicId), topicOwnership))+ .where(and(eq(topics.id, topicId), topicOwnership, notTrashed(topics.isDeleted))).limit(1);+ // The job may have been queued before the topic was moved to trash. Stop+ // before loading child messages or resolving a billable model when the+ // live-topic fence no longer finds it.+ if (!topic) {+ log('skipping missing or trashed topic %s', topicId);+ return { reason: 'stale', summarized: false };+ }// Share-visitor topics are creator-billed only through the share spend// gate. Reject them defensively before any LLM call β the dispatch query// and TopicSummaryModel.updateSummaryIfCurrent both filter them out, this// guard covers replays / direct callers that skip the dispatch path.- if (topic?.senderId) {+ if (topic.senderId) {log('skipping share-visitor topic %s: visitor turns are outside the auto-summary scope',topicId,diff --git a/apps/server/src/services/usage/index.test.ts b/apps/server/src/services/usage/index.test.tsindex 6553e73597d..0555d9a6dcc 100644--- a/apps/server/src/services/usage/index.test.ts+++ b/apps/server/src/services/usage/index.test.ts@@ -442,4 +442,21 @@ describe('UsageRecordService', () => {expect(deepIncludes(whereArgs[0], `is distinct from`)).toBe(false);});});++ describe('trashed topic parents', () => {+ it.each([+ ['usage records', () => service.findByDateRange('2024-01-01', '2024-01-31')],+ [+ 'agent stats',+ () => service.getAgentUsageStats('agt_123', '2024-01-01', '2024-01-31', 'day'),+ ],+ ])('adds the live parent-topic fence to %s', async (_name, run) => {+ const { whereArgs } = setupCapturingMock([]);++ await run();++ expect(deepIncludes(whereArgs[0], 'topic_id')).toBe(true);+ expect(deepIncludes(whereArgs[0], 'is_deleted')).toBe(true);+ });+ });});diff --git a/apps/server/src/services/usage/index.ts b/apps/server/src/services/usage/index.tsindex 00403f17fa6..b95eb98a681 100644--- a/apps/server/src/services/usage/index.ts+++ b/apps/server/src/services/usage/index.ts@@ -6,6 +6,7 @@ import { messages } from '@/database/schemas';import { type LobeChatDatabase } from '@/database/type';import { notCopiedTranscript } from '@/database/utils/copiedTranscript';import { genRangeWhere, genWhere } from '@/database/utils/genWhere';+import { hasLiveParentTopic } from '@/database/utils/topicVisibility';import { buildWorkspaceWhere } from '@/database/utils/workspace';import { type MessageMetadata, type ModelUsage } from '@/types/message';import {@@ -32,6 +33,19 @@ export class UsageRecordService {this.db = db;}+ private messageScope = () =>+ genWhere([+ buildWorkspaceWhere(+ { userId: this.userId, workspaceId: this.workspaceId },+ {+ isDeleted: messages.isDeleted,+ userId: messages.userId,+ workspaceId: messages.workspaceId,+ },+ ),+ hasLiveParentTopic(messages.topicId),+ ]);+/*** @description Find usage records by date range.* @param agentId Optional agent id to attribute usage to a single agent.@@ -56,10 +70,7 @@ export class UsageRecordService {.from(messages).where(genWhere([- buildWorkspaceWhere(- { userId: this.userId, workspaceId: this.workspaceId },- { userId: messages.userId, workspaceId: messages.workspaceId },- ),+ this.messageScope(),eq(messages.role, 'assistant'),notCopiedTranscript(),agentId ? eq(messages.agentId, agentId) : undefined,@@ -239,10 +250,7 @@ export class UsageRecordService {.from(messages).where(genWhere([- buildWorkspaceWhere(- { userId: this.userId, workspaceId: this.workspaceId },- { userId: messages.userId, workspaceId: messages.workspaceId },- ),+ this.messageScope(),eq(messages.role, 'assistant'),notCopiedTranscript(),eq(messages.agentId, agentId),diff --git a/docs/development/soft-delete-recycle-bin-design.md b/docs/development/soft-delete-recycle-bin-design.mdnew file mode 100644index 00000000000..437b9629ebc--- /dev/null+++ b/docs/development/soft-delete-recycle-bin-design.md@@ -0,0 +1,298 @@+# Soft Delete & Recycle Bin++## Summary++Until this change every user-facing delete in LobeHub was a hard `DELETE` that relied on FK+cascades: removing an agent took its sessions, topics, messages, threads and comments with it in+one statement, and the S3 objects behind trashed files were dropped in the same request. Nothing+was recoverable.++This document records the audit of that state, the design chosen for soft delete, and how the+recycle bin (`/settings/trash`) is built on top of it.++The one-line contract:++> A user-facing delete **stamps** `deleted_at` on the row (and the rows its hard delete would have+> cascaded through) and **registers** the root in `trash_items`. Every ownership-scoped read+> filters the stamp out. Restore clears the stamp. The FK cascade and the storage cleanup only run+> at **purge** β on demand from the bin, or from a cron sweep after 30 days.++## 0. Phasing++The mechanism is generic, but it lands in two steps so the pattern can prove itself on the+highest-traffic domain before it touches every content table:++| Phase | Scope | Status |+| ----- | -------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------- |+| 1 | Chat domain: **topics**, **agents**, **messages**; the bin UI; purge sweep | this branch (`feat/soft-delete-mvp`) |+| 2 | chat groups, Pages / documents, files, knowledge bases, projects, tasks + goals, generation topics | already implemented end-to-end on `feat/soft-delete-recycle-bin`, held back until 1 ships |++Phase 1 deliberately keeps a few phase-2 edges 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 stay live and visible in+the meantime, since `files` has no stamp yet); and bulk "clear conversation" sweeps+(`removeMessagesByAssistant/ByGroup`) remain hard deletes.++## 1. Audit β what deletion looked like before++### 1.1 Existing soft-delete-ish mechanisms (all entity-local, none reusable as a bin)++| Table | Column(s) | Semantics |+| ------------------- | ----------------------------------------------------------------- | ------------------------------------------------------------------------------ |+| `agent_documents` | `deleted_at`, `deleted_by_user_id`, `deleted_by_agent_id`, reason | Full soft delete + restore + purge, exposed only through path-based tool APIs |+| `topic_comments` | `deleted_at` (+ `moderated_at` / `moderation_expires_at`) | Tombstone when replies exist; moderation window is a separate recoverable axis |+| `workspace_members` | `deleted_at` | Membership tombstone, no restore |+| `projects` | `archived_at` + `status = 'archived'` | Archive, not delete |+| `notifications` | `is_archived` | Archive |+| `agent_labels` | `archived` | Archive; unique indexes are partial on `archived = false` |+| `expertise_*` | `retired_at` / `status = 'dismissed'` | Never hard-deleted |++Three vocabularies (`deleted_at`, `archived_at`, `retired_at`) with three different read rules. None+of them index across entities, none of them expire, and only `agent_documents` restores.++### 1.2 Hard-delete cascade trees (what a single `DELETE` destroyed)++- **`agents`** β the dangerous node. `topics.agent_id`, `agents_to_sessions`, `agents_files`,+ `agents_knowledge_bases`, `agent_documents`, `chat_groups_agents`, `agent_cron_jobs`,+ `agent_shares`, `messages.agent_id`, β¦ all cascade. `projects.coordinator_agent_id` is the only+ `RESTRICT` in the schema.+- **`sessions`** (legacy 1:1 shell of an agent) β `topics.session_id`, `messages.session_id`,+ `files_to_sessions` cascade. `SessionModel.delete` additionally hard-deletes the orphaned agent.+- **`topics`** β `messages`, `threads`, `message_groups`, `topic_documents`, `topic_shares`,+ `topic_comments`, `task_topics`, eval/history job junctions cascade. `agent_operations`,+ `tasks.current_topic_id`, `works.origin_topic_id` are `SET NULL`.+- **`chat_groups`** β `topics.group_id`, `threads`, `chat_groups_agents` cascade; the model also+ hard-deletes the group-owned virtual member agents (no FK β done in code).+- **`documents`** β `document_histories`, `document_shares`, `document_chunks`, `task_documents`,+ `topic_documents` cascade; `documents.parent_id` self-FK is `SET NULL` (folder delete orphans+ children to root at the DB level β the service layer recursed manually).+- **`files`** β `messages_files`, `knowledge_base_files`, `generations.file_id`, chunk tables+ cascade. `global_files` refcount and S3 deletion are manual, in the router.+- **`knowledge_bases`** β only junctions cascade; the model deletes "exclusive" files (linked to+ this KB only) in code.+- **`projects`** β `project_agents/chat_groups/knowledge_bases` cascade; **`tasks.project_id` and+ `goals.project_id` are `SET NULL`** (tasks survive project deletion). Model also deletes the+ coordinator agent.+- **`tasks`** β `task_dependencies`, `task_documents`, `task_topics`, `briefs`, `task_comments`+ cascade; `tasks.parent_task_id` self-FK is `SET NULL`; `goals` (polymorphic, no FK) and+ `acceptances` are swept in code.+- **`generation_topics`** β `generation_batches` β `generations` cascade; asset URLs collected and+ deleted from S3 in the router.++### 1.3 Delete flow inventory (per entity: model β router β client)++Every entity had a `Model.delete*` (plain `db.delete` + FK cascade), a lambda-router procedure that+ran permission checks (`withScopedPermission('<x>:delete')`, `assertWorkspaceRowManageable`,+`assertCanPerformResourceAction`, non-owner `transferHasForeignRows` gate) and then called the+model, and a client service + store action that awaited it and refreshed. Only `messages`,+`page.removePage`, `file/document.removeDocument` and `task.deleteTask` were optimistic.++External side effects that a restore could never undo, and therefore had to move to purge time:+S3 object deletion (`FileService.deleteFiles`), `global_files` refcount collapse,+`ResourcePermissionModel.removeAll` (sharing grants), IndexedDB message-cache eviction.++### 1.4 Horizontal reads++Rows are read from far more places than their own model: `HomeRepository` (sidebar),+`SearchRepository`, `RecentModel`, `KnowledgeRepo`, `AgentGroupRepository`, usage / memory / expertise+services, and dozens of `db.query.*` joins in services. Almost all of them scope through+`buildWorkspaceWhere(ctx, table)` β 237 call sites at the time of writing. That single funnel is what+made a systemic soft-delete filter feasible.++## 2. Design++### 2.1 Options considered++| Option | Verdict |+| --------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |+| A. `deleted_at` per table only, UNION for the bin | Filtering works, but the bin needs a UNION over N tables per page, cascades can only be inferred by matching timestamps, and expiry has no single clock. |+| B. Central `trash_items` only (move rows to JSON) | Restore has to re-insert rows across FKs in the right order; every entity needs a serializer/deserializer; children (messages, chunks) would have to be moved too. Far too invasive. |+| **C. `deleted_at` per table + `trash_items` index** | Rows stay in place (restore is one `UPDATE`), FK cascades still do the heavy lifting at purge, and the registry gives the bin a single indexed list, explicit cascade membership (`root_id`), and one expiry clock. **Chosen.** |++### 2.2 Data model++**Source tables** β every user-content table gets the same pair via `softDeleteColumns()` in+`schemas/_helpers.ts`, added up front in one migration even though only phase-1 kinds are trashable+today:++| column | type | role |+| ------------ | ------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------- |+| `is_deleted` | `boolean NULL` | nullable compatibility flag; live rows are `NULL` or `false`, so ownership-scoped reads use `is_deleted IS NOT TRUE` (normally through `notTrashed`) |+| `deleted_at` | `timestamptz NULL` | when the row was trashed; drives the retention clock and the "deleted 3 days ago" copy |++The two are written together by `trashStamp()` / `restoreStamp()` (`utils/softDelete.ts`) β+`is_deleted IS TRUE` iff `deleted_at IS NOT NULL` is an invariant enforced in code, not by a CHECK (a+CHECK would full-scan `messages` at migration time).++Which tables carry them β the rule is _user-visible content with its own delete action and an+independent lifecycle_:++| Group | Tables | Reason |+| ---------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |+| Chat | `agents`, `session_groups`, `chat_groups`, `topics`, `threads`, `messages` | phase-1 kinds plus their siblings a user deletes one by one |+| Knowledge / Pages | `documents`, `files`, `knowledge_bases` | phase-2 kinds |+| Work management | `projects`, `tasks`, `goals`, `works` | phase-2 kinds; `works` because `deleteTaskWork` is a user action |+| Generation | `generation_topics`, `generation_batches`, `generations` | each level is deletable on its own in the image/video UI |+| Agent config the user authors | `agent_skills`, `agent_cron_jobs`, `user_memories` | user-created, user-deleted, worth a second chance |+| **Deliberately without** (junctions) | `agents_to_sessions`, `agents_files`, `chat_groups_agents`, `knowledge_base_files`, `messages_files`, `task_*`, `project_*`, `file_chunks`, `topic_documents`, β¦ | no lifecycle of their own β they hide with their parent and cascade at purge |+| **Deliberately without** (children) | `message_plugins/tts/translates/queries`, `document_histories/shares/chunks`, `chunks/embeddings`, `briefs`, `task_comments`, `verify_*`, `acceptances`, `expertise_*`, `user_memories_*` | hidden by their parent; a "restore" never targets them individually |+| **Deliberately without** (deprecated) | `sessions` | legacy 1:1 shell of an agent (`@deprecated`); the agent is the restorable unit β the legacy list hides shells whose agent is in the bin, purge drops them with the agent |+| **Deliberately without** (own rules) | `agent_documents`, `topic_comments`, `workspace_members`, `notifications`, `agent_labels` | already carry `deleted_at` / `archived` with tombstone or archive semantics that must not change |+| **Deliberately without** (config / security / infra) | `api_keys`, `devices`, `user_connectors`, `user_installed_plugins`, `ai_providers/models`, `oidc_*`, `rbac_*`, `auth_*`, `push_tokens`, `resource_permissions`, `*_jobs`, `*_tracing`, `workspace_*`, eval tables | revoke / audit / cache semantics β a hard delete is the right behaviour, and nothing to "restore" |++No new indexes: hot list queries already hit `(user_id | workspace_id, β¦)` indexes and the extra+`is_deleted IS NOT TRUE` predicate is a cheap filter on the matched rows; the bin never scans source+tables. Adding nullable columns without a default is metadata-only, so the migration is instant even+on `messages`.++**`trash_items`** (`schemas/trash.ts`):++| column | role |+| -------------------------- | ------------------------------------------------------------------------------------------------ |+| `resource_type/_id` | polymorphic pointer (`TrashResourceType` in `@lobechat/types`); unique together |+| `title`, `meta` | denormalised display data (avatar, kind, size, `childCount`) so the list renders without joins |+| `root_id` | NULL = the row the user deleted; set = cascaded child. `ON DELETE CASCADE` on the root |+| `user_id/workspace_id` | same compat scope as content tables |+| `deleted_by_user_id` | actor (differs from `user_id` when an owner tidies a member's rows) |+| `deleted_at`, `expires_at` | the stamp shared by the whole cascade, and the purge clock (`deleted_at + TRASH_RETENTION_DAYS`) |++Indexes: `(resource_type, resource_id)` unique; `(user_id, workspace_id, deleted_at) WHERE root_id IS NULL`+for listing; `(expires_at) WHERE root_id IS NULL` for the sweep; `(root_id)`.++### 2.3 Cascade rules β what goes into the bin with what++The soft-delete cascade mirrors the hard-delete cascade **one level down**, and stops where the hard+delete stopped:++| Root | Stamped + registered as children | Stamped, not registered (restored by parent key) | Hidden by parent only (no stamp) |+| ----------------- | ------------------------------------------------------------------------------------- | -------------------------------------------------- | ----------------------------------------------------------------------------------------------------------- |+| `topic` | β (phase 2: attachments only this topic references, when `removeFiles`) | β | messages, threads, comments, topic\_documents |+| `agent` | topics (via `agent_id` and via legacy `session_id`) | β | everything under topics; the legacy `sessions` shell (hidden through the agent join, hard-deleted at purge) |+| `message` | tool-result companions of a trashed assistant turn | β | plugins / tts / translate rows |+| `chatGroup` | topics (group + owned virtual member agents) | owned virtual member agents | β |+| `document` | descendant documents, files anchored under them, the mirror file of a file-backed doc | β | histories, shares, chunks |+| `file` | β | BM25 mirror `documents` row (`source_type='file'`) | chunks, embeddings, junctions |+| `knowledgeBase` | files linked to this KB only | β | junctions |+| `project` | β | coordinator agent | tasks/goals are **not** cascaded (hard delete `SET NULL`) |+| `task` | descendants (only for the goal-root delete, `subtree: true`) | goals rows carried by the stamped tasks | briefs, comments, dependencies |+| `generationTopic` | β | β | batches, generations |++Messages are the one kind whose hard delete rewrote the tree (children re-parented onto the nearest+surviving ancestor, active-branch pointer reconciled, topic usage recomputed). The soft delete does+exactly the same rewrite, remembers `{ parentId, childIds }` in `meta.messageTree`, and a restore+splices the row back by re-parenting those children onto it again (best effort β a child that has+since moved is left alone).++Two invariants:++- **A child trashed earlier keeps its own root row.** `register` uses `ON CONFLICT DO NOTHING` for+ children, so a topic deleted last week stays in the bin after its agent (deleted today) is+ restored.+- **A root cannot be restored into a trashed container.** Restoring a topic whose agent/group is in+ the bin, a document/file whose parent folder is in the bin, or a subtask whose parent task is in+ the bin fails with `parentTrashed`; the UI tells the user to restore the container first.++### 2.4 Read-side filtering β one funnel, not 250 patches++`buildWorkspaceWhere(ctx, cols)` now appends `is_deleted IS NOT TRUE` via `notTrashed` whenever+`cols.isDeleted` is the+flag of a table in `TRASH_AWARE_TABLES` (matched by the original table name β the nineteen+trashable tables above plus later filterable tables such as `metrics`;+`agent_documents`, `topic_comments`, `workspace_members` never carry `is_deleted` and are therefore+never matched). Passing the whole table object β the dominant style β opts in automatically; the few+explicit `{ userId, workspaceId, visibility }` call sites (agents, chat groups, tasks, goals, works,+session groups β¦) were given an `isDeleted` entry. Raw-SQL scopes (`TaskModel.ownershipSql`, chat-group member+`EXISTS`) were patched by hand.++Restore / purge internals pass `includeTrashed: true`. Each trash-aware model exposes a `scope()`+(no filter) next to its `ownership()` (filter) so those internals are explicit and greppable.++Consequence to keep in mind: a relational query that reuses another table's predicate+(`db.query.sessionGroups.findMany({ where: sessionsPredicate })`) now fails loudly instead of+silently rebinding β one such case in `SessionModel.queryWithGroups` was fixed.++### 2.5 Server architecture++```+apps/server/src/services/trash/+ index.ts TrashService β trashXxx() / list / restore / purge / emptyTrash / static sweepExpired+ handlers/<type>.ts one TrashHandler per TrashResourceType: softDelete cascade, restore, purge (incl. S3, permission grants)+apps/server/src/routers/lambda/trash.ts list / countByType / restore / purge / emptyTrash+apps/server/src/router-hono/workflows/trash/ POST /api/workflows/trash/purge (QStash schedule)+packages/database/src/models/trash.ts TrashModel β registry reads/writes, listExpiredRoots, pruneOrphans+```++- `TrashService.trashXxx` runs the handler's stamping and the registry insert **in one+ transaction**, so rows can never end up hidden but unlisted.+- Every user-facing delete procedure in scope (phase 1: `topic.removeTopic`/`batchDelete*`/+ `removeAllTopics`, `agent.removeAgent`, `session.removeSession`, `message.removeMessage(s)` via+ `MessageService`; phase 2 adds `group.deleteGroup`, `document.deleteDocument(s)`,+ `notebook.deleteDocument`, `file.removeFile(s)`, `knowledgeBase.removeKnowledgeBase`,+ `project.delete`, `task.delete`/`deleteGoal`, `generationTopic.deleteTopic`) keeps its permission+ gates and calls the trash service instead of the model. Model `delete*` methods are unchanged and+ still used by internal cleanups and by purge.+- Sharing grants (`resource_permissions`) are kept while a row sits in the bin and removed by the+ purge handler, so a restore is whole.+- Pre-flight guards that protected the hard delete (`AGENT_TRANSFER_IN_PROGRESS`,+ `AGENT_COPY_IN_PROGRESS`, non-owner `transferHasForeignRows`) run before the stamp.+- Purge = model `purge()` / `deleteMany(..., { includeTrashed })` keyed on `scope()`, then+ `FileService.deleteFiles` for storage, then the registry rows. Not transactional across S3 by+ nature; a failing purge leaves the root listed and the sweep retries.+- Sweep (`TrashService.sweepExpired`) walks expired roots across users under each owner's scope,+ then `pruneOrphans` drops registry rows whose resource vanished through a non-trash path.++### 2.6 Permissions++- List: same scope as the content (own rows in personal mode, workspace-wide in team mode).+- Restore / purge / empty: the member who trashed the row or any workspace owner+ (`assertWorkspaceRowManageable` on `deleted_by_user_id`); a non-owner "empty trash" only purges+ their own roots.+- The trash procedures don't need a new RBAC scope: reaching them already required the+ corresponding `<x>:delete` scope at delete time, and the row-level rule above governs the rest.++### 2.7 Client++- `src/services/trash.ts` β `src/store/trash` (`useFetchTrash`, `restore`, `purge`, `emptyTrash`,+ keyset `loadMore`, per-row `loadingIds`). A restore revalidates every mounted SWR key under the+ affected namespaces (`agent:`, `topic:`, `document:`, `file:`, `task:`, β¦) so lists pick the row up+ without a reload.+- `Settings β System β Trash` (`src/features/Settings/trash`): type filter with counts, `LiteTable`+ (name/avatar, type, deleted-ago, auto-deletes-in, Restore / Delete forever), "Empty trash" with a+ danger confirm, load-more paging. Empty state explains the retention window.+- Delete-confirm copy across topics / agents / pages / tasks / goals / generation topics now says+ "moved to the trash, restorable within 30 days" instead of "cannot be undone".++## 3. Rollout++- Migration `0151_recycle_bin`: `CREATE TABLE IF NOT EXISTS trash_items` + `is_deleted` /+ `deleted_at` on all nineteen tables above (metadata-only, no rewrite). No backfill. Phase 2 needs+ no further schema change β only handlers.+- Register a QStash schedule (e.g. hourly) β `POST /api/workflows/trash/purge`. Until it exists,+ nothing is purged automatically; the bin still works and users can purge manually.+- Retention is `TRASH_RETENTION_DAYS = 30` in `@lobechat/const`.++## 4. Known trade-offs / follow-ups++- **Scope-unique names stay reserved while trashed.** `agents.slug`, `documents.slug`,+ `projects.identifier`, `tasks.identifier` unique indexes are not partial on `deleted_at`, so a+ trashed row still holds its slug. This is what makes restore collision-free; the cost is that a+ user cannot reuse the exact slug of something in the bin. If that becomes a complaint, add+ `AND deleted_at IS NULL` to those partial indexes and resolve collisions on restore (the+ `agent_labels` precedent).+- **`updated_at` bumps on stamp/restore** (`$onUpdate`). Restored rows surface at the top of+ updated-at ordered lists β acceptable, arguably desirable.+- **Message attachments of a trashed file** stay attached (`messages_files` is not filtered) until+ purge, since the storage object is intentionally still there. Restore therefore round-trips+ perfectly; the cost is that a trashed file is still viewable from an old message for up to 30 days.+- **Not routed through the bin (still hard delete):** bulk conversation clears+ (`removeMessagesByAssistant/ByGroup`), threads, session groups+ (folders β deleting one re-parents, never destroys), plugins/skills, API keys, devices,+ notifications, `knowledgeBase.removeAllKnowledgeBases`, `task.clearAll`, transient+ `file.removeUnreferencedFile`, and workspace deletion. Each is either non-content, already+ non-destructive, or a deliberate "wipe" whose semantics shouldn't change silently.+- **Background analytics** (usage, memory extraction, expertise ingestion, nightly review) read+ through the same funnel and therefore skip trashed rows. If a job must see them it should build+ its predicate with `includeTrashed: true` explicitly.+- **Bulk sweeps produce one root per topic**, like a multi-select delete in a file manager. A+ "clear 400 topics" lands 400 rows in the bin; the list is keyset-paged so this is fine, but a+ grouped "batch" root is a possible refinement.diff --git a/packages/database/src/models/__tests__/agent.test.ts b/packages/database/src/models/__tests__/agent.test.tsindex aae81bdb527..ea6e3d2eb7e 100644--- a/packages/database/src/models/__tests__/agent.test.ts+++ b/packages/database/src/models/__tests__/agent.test.ts@@ -96,6 +96,17 @@ describe('AgentModel', () => {// Its actual creator passes.expect(await agentModel2.existsOwnedById(othersAgent)).toBe(true);});++ it('rejects an agent owned by the caller when it is in the recycle bin', async () => {+ const agentId = 'trashed-owned-agent-id';+ await serverDB.insert(agents).values({ id: agentId, userId });+ await serverDB+ .update(agents)+ .set({ deletedAt: new Date(), isDeleted: true })+ .where(eq(agents.id, agentId));++ expect(await agentModel.existsOwnedById(agentId)).toBe(false);+ });});describe('getAgentConfigById', () => {diff --git a/packages/database/src/models/__tests__/agentShare.test.ts b/packages/database/src/models/__tests__/agentShare.test.tsindex 3811ed33d69..20371cad010 100644--- a/packages/database/src/models/__tests__/agentShare.test.ts+++ b/packages/database/src/models/__tests__/agentShare.test.ts@@ -686,6 +686,21 @@ describe('AgentShareModel', () => {});});+ it('hides a share and revokes its run when the agent is in the recycle bin', async () => {+ const share = await agentShareModel.create(agentId, 'link');+ await serverDB+ .update(agents)+ .set({ deletedAt: new Date(), isDeleted: true })+ .where(eq(agents.id, agentId));++ expect(await AgentShareModel.findByShareId(serverDB, share.id)).toBeNull();+ expect(await AgentShareModel.findBySlugOrId(serverDB, 'shareable-agent')).toBeNull();+ expect(await agentShareModel.getByAgentId(agentId)).toBeNull();+ expect(+ await AgentShareModel.isRunStillAuthorized(serverDB, { agentId, shareId: share.id }),+ ).toBe(false);+ });+it('returns null for an unknown UUID', async () => {expect(await AgentShareModel.findByShareId(serverDB, '00000000-0000-0000-0000-000000000000'),diff --git a/packages/database/src/models/__tests__/documentComment.test.ts b/packages/database/src/models/__tests__/documentComment.test.tsindex af5201fb426..0bce6d00038 100644--- a/packages/database/src/models/__tests__/documentComment.test.ts+++ b/packages/database/src/models/__tests__/documentComment.test.ts@@ -161,6 +161,17 @@ describe('DocumentCommentModel', () => {expect(root.comment.selectionAnchor).toBeNull();});+ it('rejects a document in the recycle bin', async () => {+ await serverDB+ .update(documents)+ .set({ deletedAt: new Date(), isDeleted: true })+ .where(eq(documents.id, documentId));++ await expect(+ authorModel.create({ clientId: 'trashed', content: 'no', documentId }),+ ).rejects.toThrow(DOCUMENT_COMMENT_DOCUMENT_NOT_FOUND);+ });+it('rejects foreign parents and flattens replies to replies into the root thread', async () => {await expect(authorModel.create({ clientId: 'foreign', content: 'no', documentId: foreignDocumentId }),diff --git a/packages/database/src/models/__tests__/documentLike.test.ts b/packages/database/src/models/__tests__/documentLike.test.tsindex aad4eab43b2..f47f797aa63 100644--- a/packages/database/src/models/__tests__/documentLike.test.ts+++ b/packages/database/src/models/__tests__/documentLike.test.ts@@ -76,6 +76,16 @@ describe('DocumentLikeModel', () => {);});+ it('rejects a document in the recycle bin', async () => {+ await serverDB+ .update(documents)+ .set({ deletedAt: new Date(), isDeleted: true })+ .where(eq(documents.id, documentId));++ await expect(memberModel.summary(documentId)).rejects.toThrow(DOCUMENT_LIKE_DOCUMENT_NOT_FOUND);+ await expect(memberModel.like(documentId)).rejects.toThrow(DOCUMENT_LIKE_DOCUMENT_NOT_FOUND);+ });+it('likes idempotently, reports the document author, and stamps the workspace', async () => {await expect(memberModel.like(documentId)).resolves.toMatchObject({created: true,diff --git a/packages/database/src/models/__tests__/messages/message.operationLookup.test.ts b/packages/database/src/models/__tests__/messages/message.operationLookup.test.tsindex 942a18114ae..b97c235977c 100644--- a/packages/database/src/models/__tests__/messages/message.operationLookup.test.ts+++ b/packages/database/src/models/__tests__/messages/message.operationLookup.test.ts@@ -3,7 +3,7 @@ import { eq } from 'drizzle-orm';import { afterEach, beforeEach, describe, expect, it } from 'vitest';import { getTestDB } from '../../../core/getTestDB';-import { topics, users } from '../../../schemas';+import { messages, topics, users } from '../../../schemas';import type { LobeChatDatabase } from '../../../type';import { MessageModel } from '../../message';@@ -107,4 +107,76 @@ describe('MessageModel.findLatestAssistantByOperationId', () => {expect(asOther).toBeUndefined();});++ it('does not return a reply in the recycle bin', async () => {+ const message = await messageModel.create({+ content: 'trashed reply',+ metadata: { operationId: 'op-trashed' },+ role: 'assistant',+ topicId,+ });+ await serverDB+ .update(messages)+ .set({ deletedAt: new Date(), isDeleted: true })+ .where(eq(messages.id, message.id));++ await expect(+ messageModel.findLatestAssistantByOperationId({+ operationId: 'op-trashed',+ topicId,+ }),+ ).resolves.toBeUndefined();+ });++ it('does not return a reply whose topic is in the recycle bin', async () => {+ await messageModel.create({+ content: 'reply under trashed topic',+ metadata: { operationId: 'op-trashed-topic' },+ role: 'assistant',+ topicId,+ });+ await serverDB+ .update(topics)+ .set({ deletedAt: new Date(), isDeleted: true })+ .where(eq(topics.id, topicId));++ await expect(+ messageModel.findLatestAssistantByOperationId({+ operationId: 'op-trashed-topic',+ topicId,+ }),+ ).resolves.toBeUndefined();+ });+});++describe('MessageModel.findVerifyMessageByOperationId', () => {+ it('resolves a verify card under a live topic', async () => {+ const verifyMessage = await messageModel.create({+ content: 'verify result',+ metadata: { verifyOperationId: 'verify-live-topic' },+ role: 'verify',+ topicId,+ });++ await expect(+ messageModel.findVerifyMessageByOperationId('verify-live-topic'),+ ).resolves.toMatchObject({ id: verifyMessage.id });+ });++ it('does not resolve a verify card whose parent topic is in the recycle bin', async () => {+ await messageModel.create({+ content: 'hidden verify result',+ metadata: { verifyOperationId: 'verify-trashed-topic' },+ role: 'verify',+ topicId,+ });+ await serverDB+ .update(topics)+ .set({ deletedAt: new Date(), isDeleted: true })+ .where(eq(topics.id, topicId));++ await expect(+ messageModel.findVerifyMessageByOperationId('verify-trashed-topic'),+ ).resolves.toBeUndefined();+ });});diff --git a/packages/database/src/models/__tests__/messages/message.stats.test.ts b/packages/database/src/models/__tests__/messages/message.stats.test.tsindex 4777e6a6446..5888bbd8397 100644--- a/packages/database/src/models/__tests__/messages/message.stats.test.ts+++ b/packages/database/src/models/__tests__/messages/message.stats.test.ts@@ -1034,9 +1034,9 @@ describe('MessageModel Statistics Tests', () => {it('does not leak other usersβ topics', async () => {const otherModel = new MessageModel(serverDB, otherUserId);const stats = await otherModel.topicMessageStats({ role: 'user' });- // otherUser only has the single leaked message in s-t1- expect(stats.topics).toBe(1);- expect(stats.totalMessages).toBe(1);+ // The mismatched message snapshot cannot grant access to a topic owned by another user.+ expect(stats.topics).toBe(0);+ expect(stats.totalMessages).toBe(0);});});diff --git a/packages/database/src/models/__tests__/messages/message.topic-transcript.test.ts b/packages/database/src/models/__tests__/messages/message.topic-transcript.test.tsindex f56b3a5a4aa..3f09f136fbc 100644--- a/packages/database/src/models/__tests__/messages/message.topic-transcript.test.ts+++ b/packages/database/src/models/__tests__/messages/message.topic-transcript.test.ts@@ -163,10 +163,7 @@ describe('MessageModel.queryTopicTranscript', () => {offset: 0,topicId,}),- ).resolves.toEqual({- items: [expect.objectContaining({ id: 'topic-transcript-other-owner-message' })],- total: 1,- });+ ).resolves.toEqual({ items: [], total: 0 });});it('isolates personal and workspace transcripts for the same user', async () => {diff --git a/packages/database/src/models/__tests__/metric.test.ts b/packages/database/src/models/__tests__/metric.test.tsindex 175f479b795..ca90cdecf27 100644--- a/packages/database/src/models/__tests__/metric.test.ts+++ b/packages/database/src/models/__tests__/metric.test.ts@@ -1,8 +1,9 @@// @vitest-environment node+import { eq } from 'drizzle-orm';import { afterEach, beforeEach, describe, expect, it } from 'vitest';import { getTestDB } from '../../core/getTestDB';-import { users } from '../../schemas';+import { metrics, users } from '../../schemas';import type { LobeChatDatabase } from '../../type';import { MetricModel } from '../metric';@@ -63,6 +64,17 @@ describe('MetricModel', () => {expect(await otherModel.findBySubject('goal', 'goal_metric_test')).toEqual([]);});+ it('hides a series stamped into the recycle bin', async () => {+ const series = (await seed())!;+ await serverDB+ .update(metrics)+ .set({ deletedAt: new Date(), isDeleted: true })+ .where(eq(metrics.id, series.id));++ expect(await model.findById(series.id)).toBeUndefined();+ expect(await model.findBySubject('goal', 'goal_metric_test')).toEqual([]);+ });+it('updates definition fields under ownership only', async () => {const series = (await seed())!;diff --git a/packages/database/src/models/__tests__/session.test.ts b/packages/database/src/models/__tests__/session.test.tsindex 4992702539a..18499287d79 100644--- a/packages/database/src/models/__tests__/session.test.ts+++ b/packages/database/src/models/__tests__/session.test.ts@@ -583,7 +583,7 @@ describe('SessionModel', () => {groupId: 'non-existent-group',},];- const result = await sessionModel.batchCreate(sessions);+ await sessionModel.batchCreate(sessions);// Assert results// expect(result[0].group).toBe('default');@@ -771,6 +771,114 @@ describe('SessionModel', () => {});});+ describe('recycle-bin gate (linked agent trashed)', () => {+ const seedTrashedShell = async () => {+ // A shell whose agent sits in the recycle bin: the agent is the+ // restorable unit, so the session must vanish from every legacy read+ // and write until the agent comes back.+ await serverDB.insert(sessions).values([+ { id: 'trashed-shell', slug: 'trashed-shell', userId },+ { id: 'live-shell', userId },+ ]);+ await serverDB.insert(agents).values([+ { deletedAt: new Date(), id: 'trashed-agent', isDeleted: true, userId },+ { id: 'live-agent', userId },+ ]);+ await serverDB.insert(agentsToSessions).values([+ { agentId: 'trashed-agent', sessionId: 'trashed-shell', userId },+ { agentId: 'live-agent', sessionId: 'live-shell', userId },+ ]);+ await serverDB+ .insert(topics)+ .values({ id: 'recoverable', sessionId: 'trashed-shell', userId });+ };++ it('hides the shell from list, lookup and count', async () => {+ await seedTrashedShell();+ expect((await sessionModel.query()).map((s) => s.id)).toEqual(['live-shell']);+ expect(await sessionModel.findByIdOrSlug('trashed-shell')).toBeUndefined();+ expect(await sessionModel.findByIdOrSlug('live-shell')).toBeTruthy();+ expect(await sessionModel.count()).toBe(1);+ });++ it('turns delete / batchDelete / update into no-ops so the recoverable topics survive', async () => {+ await seedTrashedShell();++ const single = await sessionModel.delete('trashed-shell');+ expect(single.orphanedAgentIds).toEqual([]);+ const batch = await sessionModel.batchDelete(['trashed-shell', 'live-shell']);+ expect(batch.orphanedAgentIds).toEqual(['live-agent']);+ await sessionModel.update('trashed-shell', { title: 'renamed' });++ const [shell] = await serverDB+ .select()+ .from(sessions)+ .where(eq(sessions.id, 'trashed-shell'));+ expect(shell).toBeTruthy();+ expect(shell.title).toBeNull();+ // the link and the topics behind it are untouched β restoring the agent brings everything back+ expect(+ await serverDB+ .select()+ .from(agentsToSessions)+ .where(eq(agentsToSessions.sessionId, 'trashed-shell')),+ ).toHaveLength(1);+ expect(await serverDB.select().from(topics).where(eq(topics.id, 'recoverable'))).toHaveLength(+ 1,+ );+ expect(+ await serverDB.select().from(sessions).where(eq(sessions.id, 'live-shell')),+ ).toHaveLength(0);+ });++ it('keeps a legacy group session with live members reachable, minus the trashed member', async () => {+ await serverDB.insert(sessions).values({ id: 'group-shell', type: 'group', userId });+ await serverDB.insert(agents).values([+ { deletedAt: new Date(), id: 'trashed-member', isDeleted: true, userId },+ { id: 'live-member', userId },+ ]);+ await serverDB.insert(agentsToSessions).values([+ { agentId: 'trashed-member', sessionId: 'group-shell', userId },+ { agentId: 'live-member', sessionId: 'group-shell', userId },+ ]);++ const [group] = await sessionModel.query();+ expect(group.id).toBe('group-shell');+ expect(group.agentsToSessions.map((l: any) => l.agent.id)).toEqual(['live-member']);+ expect((await sessionModel.findByIdOrSlug('group-shell'))?.agent.id).toBe('live-member');+ expect(await sessionModel.count()).toBe(1);++ // still write-protected: hard-deleting it would cascade the trashed member's link away+ await sessionModel.delete('group-shell');+ expect(+ await serverDB.select().from(sessions).where(eq(sessions.id, 'group-shell')),+ ).toHaveLength(1);+ });++ it('hides a legacy group session once every member is trashed', async () => {+ await serverDB.insert(sessions).values({ id: 'group-shell', type: 'group', userId });+ await serverDB+ .insert(agents)+ .values({ deletedAt: new Date(), id: 'trashed-member', isDeleted: true, userId });+ await serverDB+ .insert(agentsToSessions)+ .values({ agentId: 'trashed-member', sessionId: 'group-shell', userId });++ expect(await sessionModel.query()).toEqual([]);+ expect(await sessionModel.findByIdOrSlug('group-shell')).toBeUndefined();+ });++ it('deleteAll leaves the hidden shell in place', async () => {+ await seedTrashedShell();+ await sessionModel.deleteAll();+ const remaining = await serverDB.select().from(sessions).where(eq(sessions.userId, userId));+ expect(remaining.map((s) => s.id)).toEqual(['trashed-shell']);+ expect(await serverDB.select().from(topics).where(eq(topics.id, 'recoverable'))).toHaveLength(+ 1,+ );+ });+ });+describe('batchDelete', () => {it('should handle deleting sessions with no associated messages or topics', async () => {// Create test datadiff --git a/packages/database/src/models/__tests__/task.test.ts b/packages/database/src/models/__tests__/task.test.tsindex 94e3eb0b049..1ca0ab2dd64 100644--- a/packages/database/src/models/__tests__/task.test.ts+++ b/packages/database/src/models/__tests__/task.test.ts@@ -8,6 +8,7 @@ import {agents,briefs,documents,+ taskDocuments,tasks,topics,users,@@ -1197,6 +1198,35 @@ describe('TaskModel', () => {expect(pinned[0].documentId).toBe(doc.id);});+ it('refuses to pin a document after the task is trashed', async () => {+ const model = new TaskModel(serverDB, userId);+ const task = await model.create({ instruction: 'Soon deleted' });+ const [doc] = await serverDB+ .insert(documents)+ .values({+ content: '',+ fileType: 'text/plain',+ source: 'test',+ sourceType: 'file',+ title: 'Must not pin',+ totalCharCount: 0,+ totalLineCount: 0,+ userId,+ })+ .returning();+ await serverDB+ .update(tasks)+ .set({ deletedAt: new Date('2026-09-10T00:00:00Z'), isDeleted: true })+ .where(eq(tasks.id, task.id));++ await expect(model.pinDocument(task.id, doc.id)).rejects.toThrow('Task not found');+ const pins = await serverDB+ .select({ taskId: taskDocuments.taskId })+ .from(taskDocuments)+ .where(eq(taskDocuments.taskId, task.id));+ expect(pins).toHaveLength(0);+ });+it('tombstones a pinned document in the workspace tree once its owner flips it back to private', async () => {const workspaceId = 'task-doc-workspace';await serverDB.insert(workspaces).values({diff --git a/packages/database/src/models/__tests__/topic.test.ts b/packages/database/src/models/__tests__/topic.test.tsindex 9e38358cfc1..e3fbbf8447b 100644--- a/packages/database/src/models/__tests__/topic.test.ts+++ b/packages/database/src/models/__tests__/topic.test.ts@@ -573,6 +573,44 @@ describe('TopicModel', () => {trigger: 'chat',});});++ it('excludes trashed messages from topic card details', async () => {+ await serverDB.insert(agents).values({ id: 'agent-trash-detail', userId });+ await serverDB.insert(topics).values({+ agentId: 'agent-trash-detail',+ id: 't-trash-detail',+ title: 'detail',+ userId,+ });+ await serverDB.insert(messages).values([+ {+ content: 'trashed first message',+ deletedAt: new Date(),+ id: 'dm-trash',+ isDeleted: true,+ role: 'user',+ topicId: 't-trash-detail',+ userId,+ },+ {+ content: 'visible first message',+ id: 'dm-live',+ role: 'user',+ topicId: 't-trash-detail',+ userId,+ },+ ]);++ const detailed = await topicModel.query({+ agentId: 'agent-trash-detail',+ withDetails: true,+ });++ expect(detailed.items[0]).toMatchObject({+ firstUserMessage: 'visible first message',+ messageCount: 1,+ });+ });});describe('queryBySender', () => {diff --git a/packages/database/src/models/__tests__/topicComment.test.ts b/packages/database/src/models/__tests__/topicComment.test.tsindex cb3e614f877..168d01b1e4b 100644--- a/packages/database/src/models/__tests__/topicComment.test.ts+++ b/packages/database/src/models/__tests__/topicComment.test.ts@@ -134,6 +134,37 @@ describe('TopicCommentModel', () => {});});+ it('should reject a topic in the recycle bin', async () => {+ await serverDB+ .update(topics)+ .set({ deletedAt: new Date(), isDeleted: true })+ .where(eq(topics.id, workspaceTopicId));++ await expect(+ authorModel.createWithMentions({+ clientId: 'trashed-topic',+ content: 'no',+ topicId: workspaceTopicId,+ }),+ ).rejects.toThrow(TOPIC_COMMENT_TOPIC_NOT_FOUND);+ });++ it('should reject an anchor message in the recycle bin', async () => {+ await serverDB+ .update(messages)+ .set({ deletedAt: new Date(), isDeleted: true })+ .where(eq(messages.id, anchoredMessageId));++ await expect(+ authorModel.createWithMentions({+ clientId: 'trashed-message',+ content: 'no',+ messageId: anchoredMessageId,+ topicId: workspaceTopicId,+ }),+ ).rejects.toThrow(TOPIC_COMMENT_MESSAGE_NOT_IN_TOPIC);+ });+it('should snapshot a truncated anchorPreview for message-anchored comments', async () => {const result = await authorModel.createWithMentions({clientId: 'client-2',diff --git a/packages/database/src/models/__tests__/topicSummary.test.ts b/packages/database/src/models/__tests__/topicSummary.test.tsindex 2058a854135..15f330b4a3c 100644--- a/packages/database/src/models/__tests__/topicSummary.test.ts+++ b/packages/database/src/models/__tests__/topicSummary.test.ts@@ -306,4 +306,82 @@ describe('TopicSummaryModel', () => {expect(topic.description).toBe('Description');expect(topic.historySummary).toBe('Summary');});++ it('skips topics and messages sitting in the recycle bin', async () => {+ const stamp = { deletedAt: new Date('2026-07-31T10:30:00Z'), isDeleted: true };+ await db.insert(topics).values([+ { createdAt: new Date('2026-07-31T00:00:00Z'), id: 'trashed-topic', userId, ...stamp },+ { createdAt: new Date('2026-07-31T00:00:00Z'), id: 'live-topic', userId },+ ]);+ await db.insert(messages).values([+ // a trashed topic never becomes a candidate, however fresh its messages+ {+ content: 'a',+ id: 'm-trashed-topic',+ role: 'user',+ topicId: 'trashed-topic',+ updatedAt: new Date('2026-07-31T10:00:00Z'),+ userId,+ },+ // a trashed message neither dates nor feeds a live topic's summary+ {+ content: 'live',+ id: 'm-live',+ role: 'user',+ topicId: 'live-topic',+ updatedAt: new Date('2026-07-31T09:00:00Z'),+ userId,+ },+ {+ content: 'gone',+ id: 'm-gone',+ role: 'assistant',+ topicId: 'live-topic',+ updatedAt: new Date('2026-07-31T10:00:00Z'),+ userId,+ ...stamp,+ },+ ]);++ const result = await model.listCandidates({+ idleBefore: new Date('2026-07-31T11:00:00Z'),+ limit: 20,+ topicCreatedAfter: new Date('2026-07-30T12:00:00Z'),+ });++ expect(result).toEqual([+ expect.objectContaining({+ id: 'live-topic',+ lastMessageUpdatedAt: new Date('2026-07-31T09:00:00Z'),+ }),+ ]);+ });++ it('does not commit a summary onto a topic that was trashed after it was selected', async () => {+ await db.insert(topics).values({ id: 'late-trash', userId });+ await db.insert(messages).values({+ content: 'hello',+ id: 'm-late',+ role: 'user',+ topicId: 'late-trash',+ updatedAt: new Date('2026-07-31T10:00:00Z'),+ userId,+ });+ await db+ .update(topics)+ .set({ deletedAt: new Date(), isDeleted: true })+ .where(eq(topics.id, 'late-trash'));++ const updated = await model.updateSummaryIfCurrent({+ description: 'Description',+ lastMessageId: 'm-late',+ lastMessageUpdatedAt: new Date('2026-07-31T10:00:00Z'),+ summary: 'Summary',+ topicId: 'late-trash',+ });+ const [topic] = await db.select().from(topics).where(eq(topics.id, 'late-trash'));++ expect(updated).toBe(false);+ expect(topic.historySummary).toBeNull();+ });});diff --git a/packages/database/src/models/__tests__/user.test.ts b/packages/database/src/models/__tests__/user.test.tsindex 50f42b72f9c..a43fb1db386 100644--- a/packages/database/src/models/__tests__/user.test.ts+++ b/packages/database/src/models/__tests__/user.test.ts@@ -92,6 +92,38 @@ describe('UserModel', () => {expect(result.lastUserMessageAt).toBeNull();expect(result.userCreatedAt).toBeInstanceOf(Date);});++ it('ignores newer messages beneath a trashed topic', async () => {+ const visibleMessageAt = new Date('2026-03-01T00:00:00.000Z');+ await serverDB.insert(topics).values({+ deletedAt: new Date('2026-04-01T00:00:00.000Z'),+ id: 'activity-trashed-topic',+ isDeleted: true,+ title: 'Trashed topic',+ userId,+ });+ await serverDB.insert(messages).values([+ {+ content: 'visible topic-less activity',+ createdAt: visibleMessageAt,+ id: 'activity-visible-topicless',+ role: 'user',+ userId,+ },+ {+ content: 'hidden child activity',+ createdAt: new Date('2026-05-01T00:00:00.000Z'),+ id: 'activity-hidden-child',+ role: 'user',+ topicId: 'activity-trashed-topic',+ userId,+ },+ ]);++ await expect(userModel.getUserActivitySummary()).resolves.toMatchObject({+ lastUserMessageAt: visibleMessageAt,+ });+ });});describe('getUserRegistrationDuration', () => {diff --git a/packages/database/src/models/agent.ts b/packages/database/src/models/agent.tsindex 736c3e07bf5..22418671465 100644--- a/packages/database/src/models/agent.ts+++ b/packages/database/src/models/agent.ts@@ -89,6 +89,7 @@ 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 { buildWorkspacePayload, buildWorkspaceWhere } from '../utils/workspace';import { AGENT_COPY_IN_PROGRESS, AgentCopyJobModel } from './agentCopyJob';import {@@ -300,7 +301,10 @@ export class AgentModel {title: agents.title,}).from(agents)- .leftJoin(topics, and(eq(topics.agentId, agents.id), notShareVisitorTopic()))+ .leftJoin(+ topics,+ and(eq(topics.agentId, agents.id), notShareVisitorTopic(), notTrashed(topics.isDeleted)),+ ).where(and(this.ownership(), or(eq(agents.slug, INBOX_SESSION_ID), ne(agents.virtual, true)))).groupBy(agents.id).having(({ count }) => gt(count, 0))@@ -321,6 +325,7 @@ export class AgentModel {buildWorkspaceWhere({ userId: this.userId, workspaceId: this.workspaceId },{+ isDeleted: agents.isDeleted,userId: agents.userId,workspaceId: agents.workspaceId,visibility: agents.visibility,@@ -505,7 +510,7 @@ export class AgentModel {const rows = await this.db.select({ id: agents.id }).from(agents)- .where(and(eq(agents.id, id), eq(agents.userId, this.userId)))+ .where(and(eq(agents.id, id), eq(agents.userId, this.userId), notTrashed(agents.isDeleted))).limit(1);return rows.length > 0;@@ -1608,6 +1613,7 @@ export class AgentModel {buildWorkspaceWhere({ userId: this.userId, workspaceId: this.workspaceId },{+ isDeleted: sessionGroups.isDeleted,userId: sessionGroups.userId,visibility: sessionGroups.visibility,workspaceId: sessionGroups.workspaceId,@@ -2018,6 +2024,7 @@ export class AgentModel {visible: sql<boolean>`(${buildWorkspaceWhere({ userId: this.userId, workspaceId: this.workspaceId },{+ isDeleted: chatGroups.isDeleted,userId: chatGroups.userId,visibility: chatGroups.visibility,workspaceId: chatGroups.workspaceId,diff --git a/packages/database/src/models/agentIntervention.ts b/packages/database/src/models/agentIntervention.tsindex e3261960cab..717cb1899b6 100644--- a/packages/database/src/models/agentIntervention.ts+++ b/packages/database/src/models/agentIntervention.ts@@ -30,6 +30,7 @@ import {userSettings,} from '../schemas';import type { LobeChatDatabase, Transaction } from '../type';+import { notTrashed } from '../utils/softDelete';export const AGENT_INTERVENTION_INVALID_REVIEW_TOKEN_HASH ='AGENT_INTERVENTION_INVALID_REVIEW_TOKEN_HASH';@@ -2049,6 +2050,7 @@ export class AgentInterventionModel {this.workspaceId? eq(messages.workspaceId, this.workspaceId): isNull(messages.workspaceId),+ notTrashed(messages.isDeleted),),).limit(1)@@ -2190,6 +2192,7 @@ export class AgentInterventionModel {this.workspaceId? eq(messages.workspaceId, this.workspaceId): isNull(messages.workspaceId),+ notTrashed(messages.isDeleted),),).limit(1)diff --git a/packages/database/src/models/agentLabel.ts b/packages/database/src/models/agentLabel.tsindex 829ba66f4a9..dbba2c89e18 100644--- a/packages/database/src/models/agentLabel.ts+++ b/packages/database/src/models/agentLabel.ts@@ -38,7 +38,12 @@ export class AgentLabelModel {private agentOwnership = () =>buildWorkspaceWhere({ userId: this.userId, workspaceId: this.workspaceId },- { userId: agents.userId, workspaceId: agents.workspaceId, visibility: agents.visibility },+ {+ isDeleted: agents.isDeleted,+ userId: agents.userId,+ workspaceId: agents.workspaceId,+ visibility: agents.visibility,+ },);query = async (): Promise<AgentLabelWithUsage[]> => {diff --git a/packages/database/src/models/agentShare.ts b/packages/database/src/models/agentShare.tsindex afe9fa477ab..25d6ccb10cb 100644--- a/packages/database/src/models/agentShare.ts+++ b/packages/database/src/models/agentShare.ts@@ -19,6 +19,7 @@ import type {import { agents, agentShares, users } from '../schemas';import type { LobeChatDatabase } from '../type';import { normalizeInboxAgentAvatar, normalizeInboxAgentTitle } from '../utils/inboxAgent';+import { notTrashed } from '../utils/softDelete';import { isUuid } from '../utils/uuid';import { AgentShareProfileModel } from './agentShareProfile';@@ -127,11 +128,16 @@ export class AgentShareModel {.from(agents).where(this.workspaceId- ? and(eq(agents.id, agentShares.agentId), eq(agents.workspaceId, this.workspaceId))+ ? and(+ eq(agents.id, agentShares.agentId),+ eq(agents.workspaceId, this.workspaceId),+ notTrashed(agents.isDeleted),+ ): and(eq(agents.id, agentShares.agentId),eq(agents.userId, this.userId),isNull(agents.workspaceId),+ notTrashed(agents.isDeleted),),),);@@ -158,11 +164,16 @@ export class AgentShareModel {.from(agents).where(params.workspaceId- ? and(eq(agents.id, agentId), eq(agents.workspaceId, params.workspaceId))+ ? and(+ eq(agents.id, agentId),+ eq(agents.workspaceId, params.workspaceId),+ notTrashed(agents.isDeleted),+ ): and(eq(agents.id, agentId),eq(agents.userId, params.userId),isNull(agents.workspaceId),+ notTrashed(agents.isDeleted),),).for('update');@@ -603,7 +614,7 @@ export class AgentShareModel {.select({ id: agentShares.id, visibility: agentShares.visibility }).from(agentShares).innerJoin(agents, eq(agentShares.agentId, agents.id))- .where(eq(agentShares.agentId, params.agentId))+ .where(and(eq(agentShares.agentId, params.agentId), notTrashed(agents.isDeleted))).limit(1);return !!share && share.id === params.shareId && share.visibility === 'link';@@ -647,7 +658,7 @@ export class AgentShareModel {.from(agentShares).innerJoin(agents, eq(agentShares.agentId, agents.id)).leftJoin(users, eq(agents.userId, users.id))- .where(eq(agentShares.id, shareId))+ .where(and(eq(agentShares.id, shareId), notTrashed(agents.isDeleted))).limit(1);if (!share) return null;diff --git a/packages/database/src/models/agentSignal/nightlyReview.ts b/packages/database/src/models/agentSignal/nightlyReview.tsindex 0cb1d077858..31232d5fd5d 100644--- a/packages/database/src/models/agentSignal/nightlyReview.ts+++ b/packages/database/src/models/agentSignal/nightlyReview.ts@@ -7,6 +7,7 @@ import {eq,gte,inArray,+ isNotNull,isNull,lte,or,@@ -18,6 +19,7 @@ import { agents, messagePlugins, messages, topics, users, userSettings } from '.import type { LobeChatDatabase } from '../../type';import { normalizeInboxAgentTitle } from '../../utils/inboxAgent';import { notShareVisitorMessage } from '../../utils/shareVisitor';+import { notTrashed } from '../../utils/softDelete';/** Restores the cursor timestamp inside PostgreSQL so workflow JSON never truncates its precision. */const cursorUsers = alias(users, 'nightly_review_cursor_users');@@ -169,7 +171,15 @@ export class AgentSignalNightlyReviewModel {? this.db.selectDistinct({ userId: messages.userId }).from(messages)- .where(and(gte(messages.createdAt, options.activeSince), isNull(messages.workspaceId)))+ .leftJoin(topics, and(eq(topics.id, messages.topicId), notTrashed(topics.isDeleted)))+ .where(+ and(+ gte(messages.createdAt, options.activeSince),+ isNull(messages.workspaceId),+ notTrashed(messages.isDeleted),+ or(isNull(messages.topicId), isNotNull(topics.id)),+ ),+ ).as('nightly_review_active_users'): undefined;@@ -235,11 +245,21 @@ export class AgentSignalNightlyReviewModel {.from(messages).leftJoin(topics,- and(eq(topics.id, messages.topicId), eq(topics.userId, userId), isNull(topics.workspaceId)),+ and(+ eq(topics.id, messages.topicId),+ eq(topics.userId, userId),+ isNull(topics.workspaceId),+ notTrashed(topics.isDeleted),+ ),).innerJoin(agents,- and(eq(agents.id, effectiveAgentId), eq(agents.userId, userId), isNull(agents.workspaceId)),+ and(+ eq(agents.id, effectiveAgentId),+ eq(agents.userId, userId),+ isNull(agents.workspaceId),+ notTrashed(agents.isDeleted),+ ),).leftJoin(userSettings, eq(userSettings.id, userId)).leftJoin(@@ -254,6 +274,8 @@ export class AgentSignalNightlyReviewModel {and(eq(messages.userId, userId),isNull(messages.workspaceId),+ notTrashed(messages.isDeleted),+ or(isNull(messages.topicId), isNotNull(topics.id)),// Share-visitor traffic bills to the creator but is not the// creator's own activity β keep it out of the nightly digest.notShareVisitorMessage(),diff --git a/packages/database/src/models/agentSignal/reviewContext.ts b/packages/database/src/models/agentSignal/reviewContext.tsindex 83bfe1c28d9..132dc1c91f2 100644--- a/packages/database/src/models/agentSignal/reviewContext.ts+++ b/packages/database/src/models/agentSignal/reviewContext.ts@@ -13,6 +13,7 @@ import {} from '../../schemas';import type { LobeChatDatabase } from '../../type';import { notShareVisitorMessage } from '../../utils/shareVisitor';+import { notTrashed } from '../../utils/softDelete';import { buildWorkspaceWhere } from '../../utils/workspace';const parseAggregateTimestamp = (value: Date | string) =>@@ -143,7 +144,7 @@ export class AgentSignalReviewContextModel {updatedAt: userMemories.updatedAt,}).from(userMemories)- .where(eq(userMemories.userId, this.userId))+ .where(and(eq(userMemories.userId, this.userId), notTrashed(userMemories.isDeleted))).orderBy(desc(userMemories.updatedAt)).limit(options.limit);};diff --git a/packages/database/src/models/chatGroup.ts b/packages/database/src/models/chatGroup.tsindex 639f716026b..a832d4ccd47 100644--- a/packages/database/src/models/chatGroup.ts+++ b/packages/database/src/models/chatGroup.ts@@ -74,6 +74,7 @@ export class ChatGroupModel {buildWorkspaceWhere({ userId: this.userId, workspaceId: this.workspaceId },{+ isDeleted: chatGroups.isDeleted,userId: chatGroups.userId,workspaceId: chatGroups.workspaceId,visibility: chatGroups.visibility,@@ -91,6 +92,7 @@ export class ChatGroupModel {buildWorkspaceWhere({ userId: this.userId, workspaceId: this.workspaceId },{+ isDeleted: agents.isDeleted,userId: agents.userId,workspaceId: agents.workspaceId,visibility: agents.visibility,@@ -106,9 +108,9 @@ export class ChatGroupModel {*/private memberAgentVisibleExists = () => {if (!this.workspaceId) {- return sql`EXISTS (SELECT 1 FROM "agents" "ma" WHERE "ma"."id" = ${chatGroupsAgents.agentId} AND "ma"."user_id" = ${this.userId} AND "ma"."workspace_id" IS NULL)`;+ return sql`EXISTS (SELECT 1 FROM "agents" "ma" WHERE "ma"."id" = ${chatGroupsAgents.agentId} AND "ma"."user_id" = ${this.userId} AND "ma"."workspace_id" IS NULL AND "ma"."is_deleted" IS NOT TRUE)`;}- return sql`EXISTS (SELECT 1 FROM "agents" "ma" WHERE "ma"."id" = ${chatGroupsAgents.agentId} AND "ma"."workspace_id" = ${this.workspaceId} AND ("ma"."visibility" IS NULL OR "ma"."visibility" = 'public' OR ("ma"."visibility" = 'private' AND "ma"."user_id" = ${this.userId})))`;+ return sql`EXISTS (SELECT 1 FROM "agents" "ma" WHERE "ma"."id" = ${chatGroupsAgents.agentId} AND "ma"."workspace_id" = ${this.workspaceId} AND ("ma"."visibility" IS NULL OR "ma"."visibility" = 'public' OR ("ma"."visibility" = 'private' AND "ma"."user_id" = ${this.userId})) AND "ma"."is_deleted" IS NOT TRUE)`;};/**@@ -312,6 +314,7 @@ export class ChatGroupModel {buildWorkspaceWhere({ userId: this.userId, workspaceId: this.workspaceId },{+ isDeleted: sessionGroups.isDeleted,userId: sessionGroups.userId,visibility: sessionGroups.visibility,workspaceId: sessionGroups.workspaceId,@@ -549,6 +552,7 @@ export class ChatGroupModel {buildWorkspaceWhere({ userId: this.userId, workspaceId: this.workspaceId },{+ isDeleted: agents.isDeleted,userId: agents.userId,workspaceId: agents.workspaceId,visibility: agents.visibility,diff --git a/packages/database/src/models/document.ts b/packages/database/src/models/document.tsindex 18c9f47dfff..50534186189 100644--- a/packages/database/src/models/document.ts+++ b/packages/database/src/models/document.ts@@ -548,7 +548,7 @@ export class DocumentModel {eq(works.resourceId, rootId),buildWorkspaceWhere({ userId: this.userId, workspaceId: this.workspaceId },- { userId: works.userId, workspaceId: works.workspaceId },+ { isDeleted: works.isDeleted, userId: works.userId, workspaceId: works.workspaceId },),),);diff --git a/packages/database/src/models/documentComment.ts b/packages/database/src/models/documentComment.tsindex 81e644b60fa..bca98f1c550 100644--- a/packages/database/src/models/documentComment.ts+++ b/packages/database/src/models/documentComment.ts@@ -21,6 +21,7 @@ import type { DocumentCommentItem } from '../schemas/documentComment';import { documentCommentMentions, documentComments } from '../schemas/documentComment';import { documents } from '../schemas/file';import type { LobeChatDatabase } from '../type';+import { notTrashed } from '../utils/softDelete';export const DOCUMENT_COMMENT_WORKSPACE_REQUIRED ='Document comments are workspace-scoped; a workspaceId is required';@@ -134,7 +135,7 @@ export class DocumentCommentModel {const [document] = await tx.select({ id: documents.id, userId: documents.userId, workspaceId: documents.workspaceId }).from(documents)- .where(eq(documents.id, params.documentId))+ .where(and(eq(documents.id, params.documentId), notTrashed(documents.isDeleted))).limit(1).for('update');diff --git a/packages/database/src/models/documentLike.ts b/packages/database/src/models/documentLike.tsindex e9f3591ac92..3ed58bc9341 100644--- a/packages/database/src/models/documentLike.ts+++ b/packages/database/src/models/documentLike.ts@@ -5,6 +5,7 @@ import { documentLikes } from '../schemas/documentLike';import { documents } from '../schemas/file';import { users } from '../schemas/user';import type { LobeChatDatabase } from '../type';+import { notTrashed } from '../utils/softDelete';export const DOCUMENT_LIKE_WORKSPACE_REQUIRED ='Document likes are workspace-scoped; a workspaceId is required';@@ -68,7 +69,7 @@ export class DocumentLikeModel {const [document] = await tx.select({ id: documents.id, userId: documents.userId, workspaceId: documents.workspaceId }).from(documents)- .where(eq(documents.id, documentId))+ .where(and(eq(documents.id, documentId), notTrashed(documents.isDeleted))).limit(1).for(mode);diff --git a/packages/database/src/models/goalGraph.ts b/packages/database/src/models/goalGraph.tsindex bed1f249335..069460c94ab 100644--- a/packages/database/src/models/goalGraph.ts+++ b/packages/database/src/models/goalGraph.ts@@ -27,6 +27,7 @@ import {import { tasks } from '../schemas/task';import { works, workVersions } from '../schemas/work';import type { LobeChatDatabase, Transaction } from '../type';+import { notTrashed } from '../utils/softDelete';import { buildWorkspaceWhere } from '../utils/workspace';import { workOwnership } from './work/context';@@ -336,6 +337,7 @@ export class GoalGraphModel {eq(goalNodes.goalId, goalId),eq(goalNodes.kind, 'task'),inArray(tasks.status, ['running', 'scheduled']),+ notTrashed(tasks.isDeleted),),);return row?.count ?? 0;diff --git a/packages/database/src/models/knowledgeBase.ts b/packages/database/src/models/knowledgeBase.tsindex 3204f24f68d..8ff475123b0 100644--- a/packages/database/src/models/knowledgeBase.ts+++ b/packages/database/src/models/knowledgeBase.ts@@ -345,6 +345,7 @@ export class KnowledgeBaseModel {inArray(files.id, linkedFileIds),eq(files.userId, this.userId),buildWorkspaceWhere(creatorScope, {+ isDeleted: files.isDeleted,userId: files.userId,workspaceId: files.workspaceId,}),@@ -365,6 +366,7 @@ export class KnowledgeBaseModel {documentLink,eq(documents.userId, this.userId),buildWorkspaceWhere(creatorScope, {+ isDeleted: documents.isDeleted,userId: documents.userId,workspaceId: documents.workspaceId,}),diff --git a/packages/database/src/models/message.ts b/packages/database/src/models/message.tsindex c2d603478ae..cda2fc13627 100644--- a/packages/database/src/models/message.ts+++ b/packages/database/src/models/message.ts@@ -1024,13 +1024,28 @@ export class MessageModel {}/**- * Raw workspace/user scope, WITHOUT the visitor exclusion. Backing store- * for {@link ownership} and the escape hatch for methods that resolve the+ * Workspace/user scope plus the live parent-topic fence, WITHOUT the visitor+ * exclusion. Topic-less rows remain valid. Backing store for+ * {@link ownership} and the escape hatch for methods that resolve the* effective visitor gate per-call ({@link deleteMessage},* {@link deleteMessages}, {@link query} via `allowShareVisitor`, β¦).*/private workspaceScope = () =>- buildWorkspaceWhere({ userId: this.userId, workspaceId: this.workspaceId }, messages);+ and(+ buildWorkspaceWhere({ userId: this.userId, workspaceId: this.workspaceId }, messages),+ or(+ isNull(messages.topicId),+ inArray(+ messages.topicId,+ this.db+ .select({ id: topics.id })+ .from(topics)+ .where(+ buildWorkspaceWhere({ userId: this.userId, workspaceId: this.workspaceId }, topics),+ ),+ ),+ ),+ );/*** Default visitor exclusion applied by {@link ownership} β see@@ -2753,7 +2768,18 @@ export class MessageModel {where: and(this.ownership(),eq(messages.agentId, agentId),- eq(messages.topicId, topicId),+ inArray(+ messages.topicId,+ this.db+ .select({ id: topics.id })+ .from(topics)+ .where(+ and(+ eq(topics.id, topicId),+ buildWorkspaceWhere({ userId: this.userId, workspaceId: this.workspaceId }, topics),+ ),+ ),+ ),eq(messages.threadId, threadId),eq(messages.role, 'assistant'),),@@ -2767,7 +2793,7 @@ export class MessageModel {findVerifyMessageByOperationId = async (operationId: string) => {return this.db.query.messages.findFirst({where: and(- eq(messages.userId, this.userId),+ this.ownership(),eq(messages.role, 'verify'),sql`${messages.metadata}->>'verifyOperationId' = ${operationId}`,),@@ -2794,8 +2820,19 @@ export class MessageModel {}) => {return this.db.query.messages.findFirst({where: and(- eq(messages.userId, this.userId),- eq(messages.topicId, topicId),+ this.ownership(),+ inArray(+ messages.topicId,+ this.db+ .select({ id: topics.id })+ .from(topics)+ .where(+ and(+ eq(topics.id, topicId),+ buildWorkspaceWhere({ userId: this.userId, workspaceId: this.workspaceId }, topics),+ ),+ ),+ ),eq(messages.role, 'assistant'),sql`${messages.metadata}->>'operationId' = ${operationId}`,),diff --git a/packages/database/src/models/project.ts b/packages/database/src/models/project.tsindex ed55be8175b..86828434211 100644--- a/packages/database/src/models/project.ts+++ b/packages/database/src/models/project.ts@@ -413,6 +413,7 @@ export class ProjectModel {buildWorkspaceWhere({ userId: this.userId, workspaceId: this.workspaceId },{+ isDeleted: tasks.isDeleted,userId: tasks.createdByUserId,visibility: tasks.visibility,workspaceId: tasks.workspaceId,@@ -435,6 +436,7 @@ export class ProjectModel {buildWorkspaceWhere({ userId: this.userId, workspaceId: this.workspaceId },{+ isDeleted: tasks.isDeleted,userId: tasks.createdByUserId,visibility: tasks.visibility,workspaceId: tasks.workspaceId,@@ -467,6 +469,7 @@ export class ProjectModel {const taskScope = buildWorkspaceWhere({ userId: this.userId, workspaceId: this.workspaceId },{+ isDeleted: tasks.isDeleted,userId: tasks.createdByUserId,visibility: tasks.visibility,workspaceId: tasks.workspaceId,diff --git a/packages/database/src/models/session.ts b/packages/database/src/models/session.tsindex ff50bc2d3af..74dc7a6c019 100644--- a/packages/database/src/models/session.ts+++ b/packages/database/src/models/session.ts@@ -5,7 +5,7 @@ import type {LobeAgentSession,LobeGroupSession,} from '@lobechat/types';-import { and, asc, count, desc, eq, inArray, not, or, sql } from 'drizzle-orm';+import { and, asc, count, desc, eq, exists, inArray, not, notExists, or, sql } from 'drizzle-orm';import type { PartialDeep } from 'type-fest';import { merge } from '@/utils/merge';@@ -18,8 +18,14 @@ import { sanitizeBm25Query } from '../utils/bm25';import { genEndDateWhere, genRangeWhere, genStartDateWhere, genWhere } from '../utils/genWhere';import { idGenerator } from '../utils/idGenerator';import { inJsonStringArray } from '../utils/inJsonStringArray';+import { isTrashed, notTrashed } from '../utils/softDelete';import { buildWorkspacePayload, buildWorkspaceWhere } from '../utils/workspace';+/**+ * @deprecated Sessions are the legacy shell of an agent β see the `sessions`+ * schema note. Reads here still exist for the mobile session list and legacy+ * data; write paths should go through `AgentModel` / `TopicModel`.+ */export class SessionModel {private userId: string;private db: LobeChatDatabase;@@ -38,9 +44,56 @@ export class SessionModel {this.ftsSearchCandidateSource = ftsSearchCandidateSource;}- private ownership = () =>+ /** Compat scope only β used for the slug-uniqueness probe in {@link create}. */+ private scope = () =>buildWorkspaceWhere({ userId: this.userId, workspaceId: this.workspaceId }, sessions);+ /**+ * Sessions carry no recycle-bin flag of their own (the agent is the+ * restorable unit), so the gate goes through the linked agents' flags.+ *+ * Write gate: a shell with *any* trashed agent linked is not updatable in+ * bulk, not hard-deletable through this model β deleting it would cascade+ * away the topics the agent's restore needs β until the agent is restored+ * (or the agent purge drops the shell with it).+ */+ private noTrashedAgent = () =>+ notExists(+ this.db+ .select({ id: agentsToSessions.agentId })+ .from(agentsToSessions)+ .innerJoin(agents, eq(agentsToSessions.agentId, agents.id))+ .where(and(eq(agentsToSessions.sessionId, sessions.id), isTrashed(agents.isDeleted))),+ );++ /**+ * Read gate: a single-agent shell whose agent sits in the bin is invisible+ * (not listed, not resolvable by id / slug, not updatable). A legacy+ * `type === 'group'` shell stays reachable while any member is live; reads+ * that join agents drop the trashed members via {@link liveAgentRow}.+ */+ private visible = () =>+ or(+ this.noTrashedAgent(),+ and(+ eq(sessions.type, 'group'),+ exists(+ this.db+ .select({ id: agentsToSessions.agentId })+ .from(agentsToSessions)+ .innerJoin(agents, eq(agentsToSessions.agentId, agents.id))+ .where(and(eq(agentsToSessions.sessionId, sessions.id), notTrashed(agents.isDeleted))),+ ),+ ),+ );++ /** For reads left-joining `agents`: drop rows of trashed members (null agent = no link, kept). */+ private liveAgentRow = () => notTrashed(agents.isDeleted);++ private ownership = () => and(this.scope(), this.visible());++ private writeOwnership = () => and(this.scope(), this.noTrashedAgent());+private agentsOwnership = () =>buildWorkspaceWhere({ userId: this.userId, workspaceId: this.workspaceId }, agents);@@ -65,7 +118,7 @@ export class SessionModel {.leftJoin(agentsToSessions, eq(sessions.id, agentsToSessions.sessionId)).leftJoin(agents, eq(agentsToSessions.agentId, agents.id)).leftJoin(sessionGroups, eq(sessions.groupId, sessionGroups.id))- .where(and(this.ownership(), not(eq(sessions.slug, INBOX_SESSION_ID))))+ .where(and(this.ownership(), this.liveAgentRow(), not(eq(sessions.slug, INBOX_SESSION_ID)))).orderBy(desc(sessions.updatedAt)).limit(pageSize).offset(offset);@@ -97,7 +150,10 @@ export class SessionModel {const groups = await this.db.query.sessionGroups.findMany({orderBy: [asc(sessionGroups.sort), desc(sessionGroups.createdAt)],- where: and(this.ownership()),+ where: buildWorkspaceWhere(+ { userId: this.userId, workspaceId: this.workspaceId },+ sessionGroups,+ ),});const mappedSessions = result.map((item) => this.mapSessionItem(item as any));@@ -129,7 +185,13 @@ export class SessionModel {session: sessions,}).from(sessions)- .where(and(or(eq(sessions.id, idOrSlug), eq(sessions.slug, idOrSlug)), this.ownership()))+ .where(+ and(+ or(eq(sessions.id, idOrSlug), eq(sessions.slug, idOrSlug)),+ this.ownership(),+ this.liveAgentRow(),+ ),+ ).leftJoin(agentsToSessions, eq(sessions.id, agentsToSessions.sessionId)).leftJoin(agents, eq(agentsToSessions.agentId, agents.id)).leftJoin(sessionGroups, eq(sessions.groupId, sessionGroups.id))@@ -199,8 +261,11 @@ export class SessionModel {}): Promise<SessionItem> => {return this.db.transaction(async (trx) => {if (slug) {+ // Probe with the bare scope: a shell whose agent is in the bin still+ // holds its slug (the unique index is not partial), so hiding it here+ // would make the insert below collide.const existResult = await trx.query.sessions.findFirst({- where: and(eq(sessions.slug, slug), this.ownership()),+ where: and(eq(sessions.slug, slug), this.scope()),});if (existResult) return existResult;@@ -374,6 +439,16 @@ export class SessionModel {*/delete = async (id: string) => {return this.db.transaction(async (trx) => {+ // Resolve visibility BEFORE touching the links: the recycle-bin gate is+ // evaluated through those links, so dropping them first would un-hide a+ // shell whose agent is in the bin and let the cascade take its topics.+ const [target] = await trx+ .select({ id: sessions.id })+ .from(sessions)+ .where(and(eq(sessions.id, id), this.writeOwnership()))+ .limit(1);+ if (!target) return { orphanedAgentIds: [] as string[], result: { count: 0 } };+// First get the agent IDs associated with this sessionconst links = await trx.select({ agentId: agentsToSessions.agentId })@@ -388,7 +463,9 @@ export class SessionModel {.where(and(eq(agentsToSessions.sessionId, id), this.agentsToSessionsOwnership()));// Delete the session (this will cascade delete messages, topics, etc.)- const result = await trx.delete(sessions).where(and(eq(sessions.id, id), this.ownership()));+ const result = await trx+ .delete(sessions)+ .where(and(eq(sessions.id, id), this.writeOwnership()));// Delete orphaned agentsconst orphanedAgentIds = await this.clearOrphanAgent(agentIds, trx);@@ -404,6 +481,15 @@ export class SessionModel {if (ids.length === 0) return { orphanedAgentIds: [] as string[], result: { count: 0 } };return this.db.transaction(async (trx) => {+ // Same ordering rule as `delete`: settle which shells are visible before+ // the links (that the visibility gate reads through) are removed.+ const visible = await trx+ .select({ id: sessions.id })+ .from(sessions)+ .where(and(inArray(sessions.id, ids), this.writeOwnership()));+ ids = visible.map((row) => row.id);+ if (ids.length === 0) return { orphanedAgentIds: [] as string[], result: { count: 0 } };+// Get agent IDs associated with these sessionsconst links = await trx.select({ agentId: agentsToSessions.agentId })@@ -420,7 +506,7 @@ export class SessionModel {// Delete the sessionsconst result = await trx.delete(sessions)- .where(and(inArray(sessions.id, ids), this.ownership()));+ .where(and(inArray(sessions.id, ids), this.writeOwnership()));// Delete orphaned agentsconst orphanedAgentIds = await this.clearOrphanAgent(agentIds, trx);@@ -434,12 +520,31 @@ export class SessionModel {*/deleteAll = async () => {return this.db.transaction(async (trx) => {- await trx.delete(agentsToSessions).where(this.agentsToSessionsOwnership());+ // Shells of trashed agents stay (their agent is still restorable); only+ // visible shells and their links go.+ const visible = await trx+ .select({ id: sessions.id })+ .from(sessions)+ .where(this.writeOwnership());+ const ids = visible.map((row) => row.id);+ if (ids.length === 0) return { count: 0 };+ await trx+ .delete(agentsToSessions)+ .where(and(inArray(agentsToSessions.sessionId, ids), this.agentsToSessionsOwnership()));await trx.delete(agents).where(this.agentsOwnership());- return trx.delete(sessions).where(this.ownership());+ return trx.delete(sessions).where(and(inArray(sessions.id, ids), this.scope()));});};+ /** Agents linked to a session β lets `removeSession` route through the agent trash handler. */+ findLinkedAgentIds = async (sessionId: string): Promise<string[]> => {+ const links = await this.db+ .select({ agentId: agentsToSessions.agentId })+ .from(agentsToSessions)+ .where(and(eq(agentsToSessions.sessionId, sessionId), this.agentsToSessionsOwnership()));+ return links.map((link) => link.agentId);+ };+clearOrphanAgent = async (agentIds: string[], trx: any): Promise<string[]> => {if (agentIds.length === 0) return [];diff --git a/packages/database/src/models/sessionGroup.ts b/packages/database/src/models/sessionGroup.tsindex c4b1eff5ba1..400a5b14b27 100644--- a/packages/database/src/models/sessionGroup.ts+++ b/packages/database/src/models/sessionGroup.ts@@ -28,6 +28,7 @@ export class SessionGroupModel {buildWorkspaceWhere({ userId: this.userId, workspaceId: this.workspaceId },{+ isDeleted: sessionGroups.isDeleted,userId: sessionGroups.userId,workspaceId: sessionGroups.workspaceId,visibility: sessionGroups.visibility,diff --git a/packages/database/src/models/task.ts b/packages/database/src/models/task.tsindex 40c8decf603..2310d571bec 100644--- a/packages/database/src/models/task.ts+++ b/packages/database/src/models/task.ts@@ -258,6 +258,7 @@ export class TaskModel {buildWorkspaceWhere({ userId: this.userId, workspaceId: this.workspaceId },{+ isDeleted: tasks.isDeleted,userId: tasks.createdByUserId,visibility: tasks.visibility,workspaceId: tasks.workspaceId,@@ -299,8 +300,9 @@ export class TaskModel {const prefix = alias ? sql.raw(`${alias}.`) : sql.raw('');return this.workspaceId? sql`${prefix}workspace_id = ${this.workspaceId}- AND (${prefix}visibility = 'public' OR ${prefix}created_by_user_id = ${this.userId})`- : sql`${prefix}created_by_user_id = ${this.userId} AND ${prefix}workspace_id IS NULL`;+ AND (${prefix}visibility = 'public' OR ${prefix}created_by_user_id = ${this.userId})+ AND ${prefix}is_deleted IS NOT TRUE`+ : sql`${prefix}created_by_user_id = ${this.userId} AND ${prefix}workspace_id IS NULL AND ${prefix}is_deleted IS NOT TRUE`;};private buildListConditions = ({@@ -335,9 +337,9 @@ export class TaskModel {/*** Look up a task's visibility so child-row inserts (deps, docs, topics) can- * mirror it without forcing every call site to know the value. Defaults to- * `'public'` if the task is missing (keeps inserts idempotent β the- * onConflictDoNothing path stays valid).+ * mirror it without forcing every call site to know the value. Missing or+ * trashed parents fail closed so no child can be attached after deletion or+ * through a model constructed for the wrong scope.*/private async getTaskVisibility(taskId: string): Promise<'private' | 'public'> {const row = await this.db@@ -345,7 +347,8 @@ export class TaskModel {.from(tasks).where(and(eq(tasks.id, taskId), this.ownership())).limit(1);- return row[0]?.visibility ?? 'public';+ if (!row[0]) throw new Error(`Task not found: ${taskId}`);+ return row[0].visibility;}// ========== CRUD ==========@@ -576,7 +579,7 @@ export class TaskModel {inArray(works.resourceId, taskIds),buildWorkspaceWhere({ userId: this.userId, workspaceId: this.workspaceId },- { userId: works.userId, workspaceId: works.workspaceId },+ { isDeleted: works.isDeleted, userId: works.userId, workspaceId: works.workspaceId },),),);@@ -1949,9 +1952,8 @@ export class TaskModel {async addComment(data: Omit<NewTaskComment, 'id'>): Promise<TaskCommentItem> {// Mirror the parent task's visibility onto the comment so subsequent- // reads/writes can be filtered without a JOIN. Falls back to 'public'- // if the task is somehow not visible (defensive β the caller should- // already have validated the task via `resolveOrThrow`).+ // reads/writes can be filtered without a JOIN. `getTaskVisibility` also+ // provides the final live-parent write fence.const visibility = await this.getTaskVisibility(data.taskId);const [comment] = await this.db.insert(taskComments)diff --git a/packages/database/src/models/topic.ts b/packages/database/src/models/topic.tsindex 89fef22bbf5..6a3c27d83ef 100644--- a/packages/database/src/models/topic.ts+++ b/packages/database/src/models/topic.ts@@ -59,6 +59,7 @@ import { idGenerator } from '../utils/idGenerator';import { inJsonStringArray } from '../utils/inJsonStringArray';import { searchableMessage } from '../utils/searchableMessage';import { notShareVisitorTopic } from '../utils/shareVisitor';+import { notTrashed } from '../utils/softDelete';import { buildWorkspacePayload, buildWorkspaceWhere } from '../utils/workspace';import { recomputeTopicUsage } from './topicUsage';@@ -538,13 +539,15 @@ export class TopicModel {const firstUserMessageSubquery = this.db.select({ value: messages.content }).from(messages)- .where(and(eq(messages.topicId, topics.id), eq(messages.role, 'user')))+ .where(+ and(eq(messages.topicId, topics.id), eq(messages.role, 'user'), this.messageOwnership()),+ ).orderBy(asc(messages.createdAt)).limit(1);const messageCountSubquery = this.db.select({ value: sql<number>`count(*)::int` }).from(messages)- .where(eq(messages.topicId, topics.id));+ .where(and(eq(messages.topicId, topics.id), this.messageOwnership()));const latestMessageAtSubquery = this.db.select({ value: messages.updatedAt }).from(messages)@@ -2860,6 +2863,7 @@ export class TopicModel {.where(and(eq(topics.status, 'scheduled'),+ notTrashed(topics.isDeleted),or(// `''` is the absent-runAt sentinel, and it never satisfies this pair β// an absent gate must not read as "due now", which is what keeps adiff --git a/packages/database/src/models/topicComment.ts b/packages/database/src/models/topicComment.tsindex a434716cfa7..e21d84b77c5 100644--- a/packages/database/src/models/topicComment.ts+++ b/packages/database/src/models/topicComment.ts@@ -29,6 +29,7 @@ import { topics } from '../schemas/topic';import type { TopicCommentAnchorPreview, TopicCommentItem } from '../schemas/topicComment';import { topicCommentMentions, topicComments } from '../schemas/topicComment';import type { LobeChatDatabase, Transaction } from '../type';+import { notTrashed } from '../utils/softDelete';export const TOPIC_COMMENT_WORKSPACE_REQUIRED ='Topic comments are workspace-scoped; a workspaceId is required';@@ -371,7 +372,7 @@ export class TopicCommentModel {const [topic] = await tx.select({ id: topics.id, userId: topics.userId, workspaceId: topics.workspaceId }).from(topics)- .where(eq(topics.id, params.topicId))+ .where(and(eq(topics.id, params.topicId), notTrashed(topics.isDeleted))).limit(1).for('update');@@ -417,7 +418,7 @@ export class TopicCommentModel {userId: messages.userId,}).from(messages)- .where(eq(messages.id, params.messageId))+ .where(and(eq(messages.id, params.messageId), notTrashed(messages.isDeleted))).limit(1);if (!message || message.topicId !== params.topicId)diff --git a/packages/database/src/models/topicSummary.ts b/packages/database/src/models/topicSummary.tsindex be904eeed87..cff32341ad8 100644--- a/packages/database/src/models/topicSummary.ts+++ b/packages/database/src/models/topicSummary.ts@@ -22,6 +22,7 @@ import {import { messages, topics, userSettings } from '../schemas';import type { LobeChatDatabase } from '../type';import { notShareVisitorTopic } from '../utils/shareVisitor';+import { notTrashed } from '../utils/softDelete';export interface TopicSummaryCandidateCursor {id: string;@@ -52,6 +53,8 @@ export const topicSummaryEligibleMessage = and(isNotNull(messages.content),ne(messages.content, ''),inArray(messages.role, ['assistant', 'user']),+ // A message sitting in the recycle bin must neither feed nor date the summary.+ notTrashed(messages.isDeleted),);const getAutoSummaryWatermark = () =>@@ -94,6 +97,10 @@ export class TopicSummaryModel {.where(and(gte(topics.createdAt, topicCreatedAfter),+ // System-scoped read β no `buildWorkspaceWhere` funnel here, so the+ // recycle-bin gate is spelled out: never spend an LLM call on a+ // trashed topic.+ notTrashed(topics.isDeleted),topicSummaryEligibleMessage,or(isNull(topics.trigger), not(inArray(topics.trigger, SYSTEM_TOPIC_TRIGGERS))),or(isNull(topics.status), notInArray(topics.status, ['running', 'scheduled'])),@@ -174,6 +181,8 @@ export class TopicSummaryModel {// `notShareVisitorTopic`): the write fence itself refuses to touch// a share-visitor topic keyed only by id.notShareVisitorTopic(),+ // Trashed between candidate selection and commit β leave it alone.+ notTrashed(topics.isDeleted),exists(snapshotMessage),notExists(newerMessage),),diff --git a/packages/database/src/models/topicUsage.ts b/packages/database/src/models/topicUsage.tsindex db91c753364..48d7f2b0104 100644--- a/packages/database/src/models/topicUsage.ts+++ b/packages/database/src/models/topicUsage.ts@@ -261,6 +261,7 @@ export const recomputeTopicUsage = async (FROM messagesWHERE topic_id = ${topicId}AND ${rowOwnership}+ AND is_deleted IS NOT TRUEAND role = 'assistant'AND (usage IS NOT NULL OR metadata ? 'usage')AND ${sql.raw(NOT_COPIED_TRANSCRIPT_SQL)}diff --git a/packages/database/src/models/user.ts b/packages/database/src/models/user.tsindex b0885017005..7c8dc5ac01a 100644--- a/packages/database/src/models/user.ts+++ b/packages/database/src/models/user.ts@@ -27,6 +27,8 @@ import {userSettings,} from '../schemas';import type { LobeChatDatabase } from '../type';+import { notTrashed } from '../utils/softDelete';+import { hasLiveParentTopic } from '../utils/topicVisibility';import { AGENT_TRANSFER_PENDING_OWNER_DELETE, AgentTransferJobModel } from './agentTransferJob';type DecryptUserKeyVaults = (@@ -98,7 +100,15 @@ export class UserModel {userCreatedAt: users.createdAt,}).from(users)- .leftJoin(messages, and(eq(messages.userId, users.id), eq(messages.role, 'user')))+ .leftJoin(+ messages,+ and(+ eq(messages.userId, users.id),+ eq(messages.role, 'user'),+ notTrashed(messages.isDeleted),+ hasLiveParentTopic(messages.topicId),+ ),+ ).where(eq(users.id, this.userId)).groupBy(users.createdAt);diff --git a/packages/database/src/models/userMemory/__tests__/context.test.ts b/packages/database/src/models/userMemory/__tests__/context.test.tsindex 9391dd6c0bd..6ed1b703858 100644--- a/packages/database/src/models/userMemory/__tests__/context.test.ts+++ b/packages/database/src/models/userMemory/__tests__/context.test.ts@@ -105,6 +105,36 @@ describe('UserMemoryContextModel', () => {const otherContext = result.find((c) => c.id === 'other-context');expect(otherContext).toBeUndefined();});++ it('hides contexts with only trashed parents but keeps one with a live parent', async () => {+ await serverDB.insert(userMemories).values([+ {+ deletedAt: new Date(),+ id: 'trashed-context-parent',+ isDeleted: true,+ lastAccessedAt: new Date(),+ userId,+ },+ { id: 'live-context-parent', lastAccessedAt: new Date(), userId },+ ]);+ await serverDB.insert(userMemoriesContexts).values([+ {+ id: 'context-with-only-trashed-parent',+ userId,+ userMemoryIds: ['trashed-context-parent'],+ },+ {+ id: 'context-with-live-parent',+ userId,+ userMemoryIds: ['trashed-context-parent', 'live-context-parent'],+ },+ ]);++ const result = await contextModel.query();++ expect(result.some(({ id }) => id === 'context-with-only-trashed-parent')).toBe(false);+ expect(result.some(({ id }) => id === 'context-with-live-parent')).toBe(true);+ });});describe('findById', () => {diff --git a/packages/database/src/models/userMemory/__tests__/identity.test.ts b/packages/database/src/models/userMemory/__tests__/identity.test.tsindex 54ec7a84840..4e281b14049 100644--- a/packages/database/src/models/userMemory/__tests__/identity.test.ts+++ b/packages/database/src/models/userMemory/__tests__/identity.test.ts@@ -1,5 +1,6 @@// @vitest-environment nodeimport { RelationshipEnum } from '@lobechat/types';+import { eq } from 'drizzle-orm';import { beforeEach, describe, expect, it, vi } from 'vitest';import { getTestDB } from '../../../core/getTestDB';@@ -676,5 +677,31 @@ describe('UserMemoryIdentityModel', () => {expect(result[0]).toHaveProperty('createdAt');expect(result[0]).toHaveProperty('updatedAt');});++ it('does not inject an identity whose base memory is in the recycle bin', async () => {+ const [memory] = await serverDB+ .insert(userMemories)+ .values({+ id: 'trashed-injection-memory',+ lastAccessedAt: new Date(),+ userId,+ })+ .returning();+ await serverDB.insert(userMemoriesIdentities).values({+ description: 'must stay hidden',+ id: 'trashed-injection-identity',+ relationship: RelationshipEnum.Self,+ userId,+ userMemoryId: memory.id,+ });+ await serverDB+ .update(userMemories)+ .set({ deletedAt: new Date(), isDeleted: true })+ .where(eq(userMemories.id, memory.id));++ const result = await identityModel.queryForInjection();++ expect(result.some(({ id }) => id === 'trashed-injection-identity')).toBe(false);+ });});});diff --git a/packages/database/src/models/userMemory/__tests__/model.test.ts b/packages/database/src/models/userMemory/__tests__/model.test.tsindex 94a69eb5988..6ae25a0c79f 100644--- a/packages/database/src/models/userMemory/__tests__/model.test.ts+++ b/packages/database/src/models/userMemory/__tests__/model.test.ts@@ -963,6 +963,16 @@ describe('UserMemoryModel', () => {expect(result).toHaveLength(1);});++ it('should not return memories in the recycle bin', async () => {+ const { memory } = await createExperiencePair({});+ await serverDB+ .update(userMemories)+ .set({ deletedAt: new Date(), isDeleted: true })+ .where(eq(userMemories.id, memory.id));++ expect(await memoryModel.listMemories({ layer: LayersEnum.Experience })).toEqual([]);+ });});// ========== getMemoryDetail ==========@@ -1695,6 +1705,16 @@ describe('UserMemoryModel', () => {const result = await memoryModel.getAllIdentities();expect(result).toEqual([]);});++ it('should not return an identity whose base memory is in the recycle bin', async () => {+ const { memory } = await createIdentityPair({});+ await serverDB+ .update(userMemories)+ .set({ deletedAt: new Date(), isDeleted: true })+ .where(eq(userMemories.id, memory.id));++ expect(await memoryModel.getAllIdentities()).toEqual([]);+ });});// ========== getAllIdentitiesWithMemory ==========@@ -1718,6 +1738,16 @@ describe('UserMemoryModel', () => {expect(result).toHaveLength(1);});++ it('should not join an identity whose base memory is in the recycle bin', async () => {+ const { memory } = await createIdentityPair({});+ await serverDB+ .update(userMemories)+ .set({ deletedAt: new Date(), isDeleted: true })+ .where(eq(userMemories.id, memory.id));++ expect(await memoryModel.getAllIdentitiesWithMemory()).toEqual([]);+ });});// ========== getIdentitiesByType ==========@@ -1780,7 +1810,7 @@ describe('UserMemoryModel', () => {// ========== removeExperienceEntry ==========describe('removeExperienceEntry', () => {it('should delete experience and associated base memory', async () => {- const { experience, memory } = await createExperiencePair({});+ const { experience, memory: _memory } = await createExperiencePair({});const success = await memoryModel.removeExperienceEntry(experience.id);@@ -2317,7 +2347,7 @@ describe('UserMemoryModel', () => {// ========== updateIdentityEntry with capturedAt ==========describe('updateIdentityEntry - capturedAt', () => {it('should update capturedAt on identity', async () => {- const { identity, memory } = await createIdentityPair({});+ const { identity, memory: _memory } = await createIdentityPair({});const capturedDate = new Date('2025-06-15T12:00:00Z');const result = await memoryModel.updateIdentityEntry({diff --git a/packages/database/src/models/userMemory/__tests__/where.test.ts b/packages/database/src/models/userMemory/__tests__/where.test.tsnew file mode 100644index 00000000000..ebed30d8c12--- /dev/null+++ b/packages/database/src/models/userMemory/__tests__/where.test.ts@@ -0,0 +1,44 @@+import { PgDialect } from 'drizzle-orm/pg-core';+import { describe, expect, it } from 'vitest';++import { getTestDB } from '../../../core/getTestDB';+import {+ userMemories,+ userMemoriesActivities,+ userMemoriesContexts,+ userMemoriesExperiences,+ userMemoriesIdentities,+ userMemoriesPreferences,+} from '../../../schemas';+import { buildUserMemoryWhere } from '../where';++const serverDB = await getTestDB();+const toSql = (table: Parameters<typeof buildUserMemoryWhere>[2]) =>+ new PgDialect().sqlToQuery(buildUserMemoryWhere(serverDB, 'user-1', table)).sql;++describe('buildUserMemoryWhere', () => {+ it('filters the restorable base row directly', () => {+ expect(toSql(userMemories)).toContain('"user_memories"."is_deleted" IS NOT TRUE');+ });++ it.each([+ userMemoriesActivities,+ userMemoriesExperiences,+ userMemoriesIdentities,+ userMemoriesPreferences,+ ])('filters a singular child through its live base memory', (table) => {+ const query = toSql(table);++ expect(query).toContain(' in (select ');+ expect(query).toContain('"live_user_memories"."is_deleted" IS NOT TRUE');+ expect(query).toContain('"user_memory_id"');+ });++ it('keeps a context only when it is standalone or references a live base memory', () => {+ const query = toSql(userMemoriesContexts);++ expect(query).toContain('jsonb_array_length');+ expect(query).toContain('?| ARRAY');+ expect(query).toContain('"live_user_memories"."is_deleted" IS NOT TRUE');+ });+});diff --git a/packages/database/src/models/userMemory/activity.ts b/packages/database/src/models/userMemory/activity.tsindex 6333209d45f..64c65122d28 100644--- a/packages/database/src/models/userMemory/activity.ts+++ b/packages/database/src/models/userMemory/activity.ts@@ -8,6 +8,7 @@ import { userMemories, userMemoriesActivities } from '../../schemas';import type { LobeChatDatabase } from '../../type';import { normalizeBm25MatchQuery, SAFE_BM25_QUERY_OPTIONS } from '../../utils/bm25';import { inJsonStringArray } from '../../utils/inJsonStringArray';+import { buildUserMemoryWhere } from './where';export class UserMemoryActivityModel {private userId: string;@@ -24,8 +25,8 @@ export class UserMemoryActivityModel {this.ftsSearchCandidateSource = ftsSearchCandidateSource;}- private memoryWhere(table: { userId: any }) {- return eq(table.userId, this.userId);+ private memoryWhere(table: Parameters<typeof buildUserMemoryWhere>[2]) {+ return buildUserMemoryWhere(this.db, this.userId, table);}create = async (params: Omit<NewUserMemoryActivity, 'userId'>) => {diff --git a/packages/database/src/models/userMemory/context.ts b/packages/database/src/models/userMemory/context.tsindex 242f03f44cf..1819a66ea56 100644--- a/packages/database/src/models/userMemory/context.ts+++ b/packages/database/src/models/userMemory/context.ts@@ -3,6 +3,7 @@ import { and, desc, eq } from 'drizzle-orm';import type { NewUserMemoryContext, UserMemoryContext } from '../../schemas';import { userMemories, userMemoriesContexts } from '../../schemas';import type { LobeChatDatabase } from '../../type';+import { buildUserMemoryWhere } from './where';export class UserMemoryContextModel {private userId: string;@@ -13,8 +14,8 @@ export class UserMemoryContextModel {this.db = db;}- private memoryWhere(table: { userId: any }) {- return eq(table.userId, this.userId);+ private memoryWhere(table: Parameters<typeof buildUserMemoryWhere>[2]) {+ return buildUserMemoryWhere(this.db, this.userId, table);}create = async (params: Omit<NewUserMemoryContext, 'userId'>) => {@@ -41,6 +42,11 @@ export class UserMemoryContextModel {? (context.userMemoryIds as string[]): [];+ // Delete the authorized child while its live-parent guard still matches.+ await tx+ .delete(userMemoriesContexts)+ .where(and(eq(userMemoriesContexts.id, id), this.memoryWhere(userMemoriesContexts)));+if (memoryIds.length > 0) {for (const memoryId of memoryIds) {await tx@@ -49,11 +55,6 @@ export class UserMemoryContextModel {}}- // Delete the context entry- await tx- .delete(userMemoriesContexts)- .where(and(eq(userMemoriesContexts.id, id), this.memoryWhere(userMemoriesContexts)));-return { success: true };});};diff --git a/packages/database/src/models/userMemory/experience.ts b/packages/database/src/models/userMemory/experience.tsindex 4653445c3fc..e64a68ad347 100644--- a/packages/database/src/models/userMemory/experience.ts+++ b/packages/database/src/models/userMemory/experience.ts@@ -8,6 +8,7 @@ import { userMemories, userMemoriesExperiences } from '../../schemas';import type { LobeChatDatabase } from '../../type';import { normalizeBm25MatchQuery, SAFE_BM25_QUERY_OPTIONS } from '../../utils/bm25';import { inJsonStringArray } from '../../utils/inJsonStringArray';+import { buildUserMemoryWhere } from './where';export class UserMemoryExperienceModel {private userId: string;@@ -24,8 +25,8 @@ export class UserMemoryExperienceModel {this.ftsSearchCandidateSource = ftsSearchCandidateSource;}- private memoryWhere(table: { userId: any }) {- return eq(table.userId, this.userId);+ private memoryWhere(table: Parameters<typeof buildUserMemoryWhere>[2]) {+ return buildUserMemoryWhere(this.db, this.userId, table);}create = async (params: Omit<NewUserMemoryExperience, 'userId'>) => {diff --git a/packages/database/src/models/userMemory/identity.ts b/packages/database/src/models/userMemory/identity.tsindex fb501cdce54..059d3eca325 100644--- a/packages/database/src/models/userMemory/identity.ts+++ b/packages/database/src/models/userMemory/identity.ts@@ -9,6 +9,7 @@ import { userMemories, userMemoriesIdentities } from '../../schemas';import type { LobeChatDatabase } from '../../type';import { normalizeBm25MatchQuery, SAFE_BM25_QUERY_OPTIONS } from '../../utils/bm25';import { inJsonStringArray } from '../../utils/inJsonStringArray';+import { buildUserMemoryWhere } from './where';export class UserMemoryIdentityModel {private userId: string;@@ -25,8 +26,8 @@ export class UserMemoryIdentityModel {this.ftsSearchCandidateSource = ftsSearchCandidateSource;}- private memoryWhere(table: { userId: any }) {- return eq(table.userId, this.userId);+ private memoryWhere(table: Parameters<typeof buildUserMemoryWhere>[2]) {+ return buildUserMemoryWhere(this.db, this.userId, table);}create = async (params: Omit<NewUserMemoryIdentity, 'userId'>) => {diff --git a/packages/database/src/models/userMemory/model.ts b/packages/database/src/models/userMemory/model.tsindex dfaba9b3074..0279195e1a8 100644--- a/packages/database/src/models/userMemory/model.ts+++ b/packages/database/src/models/userMemory/model.ts@@ -53,6 +53,7 @@ import { inJsonStringArray } from '../../utils/inJsonStringArray';import { TopicModel } from '../topic';import type { UserMemoryHybridSearchAggregatedResult } from './query';import { UserMemoryQueryModel } from './query';+import { buildUserMemoryWhere } from './where';const normalizeRelationshipValue = (input: unknown): RelationshipEnum | null => {if (input === null) return null;@@ -577,8 +578,8 @@ export class UserMemoryModel {this.topicModel = new TopicModel(db, userId);}- private memoryWhere(table: { userId: any }) {- return eq(table.userId, this.userId);+ private memoryWhere(table: Parameters<typeof buildUserMemoryWhere>[2]) {+ return buildUserMemoryWhere(this.db, this.userId, table);}private extractSourceMetadata(metadata?: Record<string, unknown> | null): {@@ -2539,17 +2540,18 @@ export class UserMemoryModel {const memoryIds = Array.isArray(context.userMemoryIds)? (context.userMemoryIds as string[]): [];++ // Delete the authorized child while its live-parent guard still matches.+ await tx+ .delete(userMemoriesContexts)+ .where(and(eq(userMemoriesContexts.id, contextId), this.memoryWhere(userMemoriesContexts)));+if (memoryIds.length > 0) {await tx.delete(userMemories).where(and(inArray(userMemories.id, memoryIds), this.memoryWhere(userMemories)));}- // Delete the context entry- await tx- .delete(userMemoriesContexts)- .where(and(eq(userMemoriesContexts.id, contextId), this.memoryWhere(userMemoriesContexts)));-return true;});};diff --git a/packages/database/src/models/userMemory/preference.ts b/packages/database/src/models/userMemory/preference.tsindex 1cb689b60c9..619ee2d5dca 100644--- a/packages/database/src/models/userMemory/preference.ts+++ b/packages/database/src/models/userMemory/preference.ts@@ -3,6 +3,7 @@ import { and, desc, eq } from 'drizzle-orm';import type { NewUserMemoryPreference, UserMemoryPreference } from '../../schemas';import { userMemories, userMemoriesPreferences } from '../../schemas';import type { LobeChatDatabase } from '../../type';+import { buildUserMemoryWhere } from './where';export class UserMemoryPreferenceModel {private userId: string;@@ -13,8 +14,8 @@ export class UserMemoryPreferenceModel {this.db = db;}- private memoryWhere(table: { userId: any }) {- return eq(table.userId, this.userId);+ private memoryWhere(table: Parameters<typeof buildUserMemoryWhere>[2]) {+ return buildUserMemoryWhere(this.db, this.userId, table);}create = async (params: Omit<NewUserMemoryPreference, 'userId'>) => {diff --git a/packages/database/src/models/userMemory/query.ts b/packages/database/src/models/userMemory/query.tsindex cd371a58cb4..4bdd450c673 100644--- a/packages/database/src/models/userMemory/query.ts+++ b/packages/database/src/models/userMemory/query.ts@@ -43,6 +43,7 @@ import {import type { LobeChatDatabase } from '../../type';import { normalizeBm25MatchQuery, SAFE_BM25_QUERY_OPTIONS } from '../../utils/bm25';import { inJsonStringArray } from '../../utils/inJsonStringArray';+import { buildUserMemoryWhere } from './where';const DEFAULT_HYBRID_SEARCH_LIMIT = 5;const HYBRID_SEARCH_OVERFETCH_MULTIPLIER = 3;@@ -680,8 +681,8 @@ export class UserMemoryQueryModel {private readonly ftsSearchCandidateSource?: FtsSearchCandidateSource,) {}- private memoryWhere(table: { userId: any }) {- return eq(table.userId, this.userId);+ private memoryWhere(table: Parameters<typeof buildUserMemoryWhere>[2]) {+ return buildUserMemoryWhere(this.db, this.userId, table);}private buildCandidateFilters(diff --git a/packages/database/src/models/userMemory/where.ts b/packages/database/src/models/userMemory/where.tsnew file mode 100644index 00000000000..734084b4e6c--- /dev/null+++ b/packages/database/src/models/userMemory/where.ts@@ -0,0 +1,48 @@+import { and, eq, inArray, isNull, or, type SQL, sql } from 'drizzle-orm';+import { alias, type AnyPgColumn } from 'drizzle-orm/pg-core';++import { userMemories } from '../../schemas';+import type { LobeChatDatabase } from '../../type';+import { notTrashed } from '../../utils/softDelete';++const liveUserMemories = alias(userMemories, 'live_user_memories');++interface UserMemoryScopedTable {+ isDeleted?: AnyPgColumn;+ userId: AnyPgColumn;+ userMemoryId?: AnyPgColumn;+ userMemoryIds?: AnyPgColumn;+}++const liveMemoryIds = (db: LobeChatDatabase, userId: string) =>+ db+ .select({ id: liveUserMemories.id })+ .from(liveUserMemories)+ .where(and(eq(liveUserMemories.userId, userId), notTrashed(liveUserMemories.isDeleted)));++const liveParentMemory = (db: LobeChatDatabase, userId: string, userMemoryId: AnyPgColumn): SQL =>+ or(isNull(userMemoryId), inArray(userMemoryId, liveMemoryIds(db, userId))) as SQL;++const liveContextMemory = (db: LobeChatDatabase, userId: string, userMemoryIds: AnyPgColumn): SQL =>+ or(+ isNull(userMemoryIds),+ sql`jsonb_array_length(${userMemoryIds}) = 0`,+ sql`${userMemoryIds} ?| ARRAY(${liveMemoryIds(db, userId)})`,+ ) as SQL;++/** User memories have no workspace column, so they cannot use buildWorkspaceWhere. */+export const buildUserMemoryWhere = (+ db: LobeChatDatabase,+ userId: string,+ table: UserMemoryScopedTable,+): SQL => {+ const liveMemory = table.isDeleted+ ? notTrashed(table.isDeleted)+ : table.userMemoryId+ ? liveParentMemory(db, userId, table.userMemoryId)+ : table.userMemoryIds+ ? liveContextMemory(db, userId, table.userMemoryIds)+ : undefined;++ return and(eq(table.userId, userId), liveMemory) as SQL;+};diff --git a/packages/database/src/models/work/context.ts b/packages/database/src/models/work/context.tsindex 58355b4f07c..804dffb1590 100644--- a/packages/database/src/models/work/context.ts+++ b/packages/database/src/models/work/context.ts@@ -95,7 +95,12 @@ export const workOwnership = (ctx: WorkContext) =>export const taskOwnership = (ctx: WorkContext) =>buildWorkspaceWhere({ userId: ctx.userId, workspaceId: ctx.workspaceId },- { userId: tasks.createdByUserId, visibility: tasks.visibility, workspaceId: tasks.workspaceId },+ {+ isDeleted: tasks.isDeleted,+ userId: tasks.createdByUserId,+ visibility: tasks.visibility,+ workspaceId: tasks.workspaceId,+ },);export const documentOwnership = (ctx: WorkContext) =>diff --git a/packages/database/src/repositories/agentGroup/index.ts b/packages/database/src/repositories/agentGroup/index.tsindex 876ba43fe1b..12f7d0e794a 100644--- a/packages/database/src/repositories/agentGroup/index.ts+++ b/packages/database/src/repositories/agentGroup/index.ts@@ -468,6 +468,7 @@ export class AgentGroupRepository {buildWorkspaceWhere({ userId: this.userId, workspaceId: this.workspaceId },{+ isDeleted: sessionGroups.isDeleted,userId: sessionGroups.userId,visibility: sessionGroups.visibility,workspaceId: sessionGroups.workspaceId,diff --git a/packages/database/src/repositories/dataImporter/__tests__/index.test.ts b/packages/database/src/repositories/dataImporter/__tests__/index.test.tsindex 7cffea2eb90..4af67914b58 100644--- a/packages/database/src/repositories/dataImporter/__tests__/index.test.ts+++ b/packages/database/src/repositories/dataImporter/__tests__/index.test.ts@@ -387,6 +387,34 @@ describe('DataImporter', () => {});describe('import message and topic', () => {+ it('skips a trashed message identity when the same export is imported again', async () => {+ const data = {+ data: {+ messages: [+ {+ content: 'Imported once',+ createdAt: '2026-09-10T00:00:00Z',+ id: 'trashed-import-message',+ role: 'user',+ updatedAt: '2026-09-10T00:00:00Z',+ },+ ],+ },+ mode: 'pglite',+ schemaHash: 'test',+ } as ImportPgDataStructure;+ await importer.importPgData(data);+ await clientDB+ .update(Schema.messages)+ .set({ deletedAt: new Date('2026-09-10T01:00:00Z'), isDeleted: true })+ .where(eq(Schema.messages.clientId, 'trashed-import-message'));++ const second = await new DataImporterRepos(clientDB, userId).importPgData(data);++ expect(second.success).toBe(true);+ expect(second.results.messages).toMatchObject({ added: 0, errors: 0, skips: 1 });+ });+it('should map topic agentId to the imported agent id', async () => {const exportData: ImportPgDataStructure = {data: {diff --git a/packages/database/src/repositories/dataImporter/deprecated/__tests__/index.test.ts b/packages/database/src/repositories/dataImporter/deprecated/__tests__/index.test.tsindex b8e94637af3..4ae7b61b3ad 100644--- a/packages/database/src/repositories/dataImporter/deprecated/__tests__/index.test.ts+++ b/packages/database/src/repositories/dataImporter/deprecated/__tests__/index.test.ts@@ -663,6 +663,30 @@ describe('DataImporter', () => {expect(result.messages.errors).toBe(0);});+ it('skips a trashed message identity when the same data is imported again', async () => {+ const data: ImporterEntryData = {+ messages: [+ {+ content: 'Imported once',+ createdAt: 1715186011586,+ id: 'trashed-import-message',+ role: 'user',+ updatedAt: 1715186015053,+ },+ ],+ version: CURRENT_CONFIG_VERSION,+ };+ await importer.importData(data);+ await serverDB+ .update(messages)+ .set({ deletedAt: new Date('2026-09-10T01:00:00Z'), isDeleted: true })+ .where(eq(messages.clientId, 'trashed-import-message'));++ const second = await new DataImporterRepos(serverDB, userId).importData(data);++ expect(second.messages).toMatchObject({ added: 0, errors: 0, skips: 1 });+ });+it('should associate imported messages with sessions and topics', async () => {const data: ImporterEntryData = {version: CURRENT_CONFIG_VERSION,diff --git a/packages/database/src/repositories/dataImporter/deprecated/index.ts b/packages/database/src/repositories/dataImporter/deprecated/index.tsindex 8494b7fd86f..46f0d822f48 100644--- a/packages/database/src/repositories/dataImporter/deprecated/index.ts+++ b/packages/database/src/repositories/dataImporter/deprecated/index.ts@@ -40,9 +40,16 @@ export class DeprecatedDataImporterRepos {this.db = db;}- /** Helper: scope predicate for workspace-aware tables. */+ /**+ * Import identity/mapping probes must include trashed rows: clientId unique+ * indexes still cover them, so hiding them would turn a retry into a+ * conflicting insert. This repository exposes no ordinary product reads.+ */private workspaceWhere(table: { userId: any; workspaceId: any }) {- return buildWorkspaceWhere({ userId: this.userId, workspaceId: this.workspaceId }, table);+ return buildWorkspaceWhere(+ { includeTrashed: true, userId: this.userId, workspaceId: this.workspaceId },+ table,+ );}importData = async (data: ImporterEntryData) => {diff --git a/packages/database/src/repositories/dataImporter/index.ts b/packages/database/src/repositories/dataImporter/index.tsindex 57aa615847b..70f9b1b37b8 100644--- a/packages/database/src/repositories/dataImporter/index.ts+++ b/packages/database/src/repositories/dataImporter/index.ts@@ -396,7 +396,11 @@ export class DataImporterRepos {const workspaceFilter ='workspaceId' in table? buildWorkspaceWhere(- { userId: this.userId, workspaceId: this.workspaceId },+ {+ includeTrashed: true,+ userId: this.userId,+ workspaceId: this.workspaceId,+ },table as any,): eq(table.userId, this.userId);@@ -552,7 +556,11 @@ export class DataImporterRepos {if ('workspaceId' in table) {whereConditions.push(buildWorkspaceWhere(- { userId: this.userId, workspaceId: this.workspaceId },+ {+ includeTrashed: true,+ userId: this.userId,+ workspaceId: this.workspaceId,+ },table as any,),);diff --git a/packages/database/src/repositories/ftsSearch/__tests__/elasticsearch.test.ts b/packages/database/src/repositories/ftsSearch/__tests__/elasticsearch.test.tsindex 0f0c5d7c133..551631900fc 100644--- a/packages/database/src/repositories/ftsSearch/__tests__/elasticsearch.test.ts+++ b/packages/database/src/repositories/ftsSearch/__tests__/elasticsearch.test.ts@@ -234,6 +234,15 @@ describe('ElasticsearchFtsSearchBackend', () => {title: 'Own memory',userId,},+ {+ deletedAt: new Date(),+ id: 'memory-deleted',+ isDeleted: true,+ lastAccessedAt: new Date(),+ memoryLayer: 'context',+ title: 'Deleted memory',+ userId,+ },{id: 'memory-other',lastAccessedAt: new Date(),diff --git a/packages/database/src/repositories/ftsSearch/elasticsearch/hydration.ts b/packages/database/src/repositories/ftsSearch/elasticsearch/hydration.tsindex 0b73c80c0e2..6f34dcd49a7 100644--- a/packages/database/src/repositories/ftsSearch/elasticsearch/hydration.ts+++ b/packages/database/src/repositories/ftsSearch/elasticsearch/hydration.ts@@ -32,6 +32,7 @@ import { libraryVisibleFile, notAgentShareFileReference } from '../../../utils/fimport { normalizeInboxAgentMeta, normalizeInboxAgentTitle } from '../../../utils/inboxAgent';import { searchableMessage } from '../../../utils/searchableMessage';import { notShareVisitorMessage, notShareVisitorTopic } from '../../../utils/shareVisitor';+import { notTrashed } from '../../../utils/softDelete';import { buildWorkspaceWhere } from '../../../utils/workspace';import type {FtsSearchAgentResult,@@ -115,6 +116,7 @@ export const hydrateUserMemories = async (eq(userMemories.userId, scope.userId),// Experience memory is retired and has no page to land on; keep it out of unified search.ne(userMemories.memoryLayer, LayersEnum.Experience),+ notTrashed(userMemories.isDeleted),),);diff --git a/packages/database/src/repositories/ftsSearch/index.test.ts b/packages/database/src/repositories/ftsSearch/index.test.tsindex 9b4fb3a953f..daca15d9a06 100644--- a/packages/database/src/repositories/ftsSearch/index.test.ts+++ b/packages/database/src/repositories/ftsSearch/index.test.ts@@ -1561,6 +1561,40 @@ describe.skipIf(!isServerDB)('FtsSearchRepo', () => {expect(['user', 'assistant']).toContain(message.role);}});++ it('hides messages whose parent topic is trashed and keeps topic-less messages', async () => {+ await serverDB.insert(topics).values({+ deletedAt: new Date('2026-09-10T00:00:00Z'),+ id: 'fts-trashed-parent-topic',+ isDeleted: true,+ title: 'Trashed parent',+ userId,+ });+ await serverDB.insert(messages).values([+ {+ content: 'parentfenceprobe hidden child',+ id: 'fts-trashed-parent-message',+ role: 'user',+ topicId: 'fts-trashed-parent-topic',+ userId,+ },+ {+ content: 'parentfenceprobe visible standalone',+ id: 'fts-topicless-message',+ role: 'user',+ userId,+ },+ ]);++ const results = await ftsSearchRepo.search({+ query: 'parentfenceprobe',+ type: 'message',+ });+ const resultIds = results.map(({ id }) => id);++ expect(resultIds).toContain('fts-topicless-message');+ expect(resultIds).not.toContain('fts-trashed-parent-message');+ });});// Agent-share visitor conversations are persisted under the CREATOR'sdiff --git a/packages/database/src/repositories/ftsSearch/pgSearch/scope.test.ts b/packages/database/src/repositories/ftsSearch/pgSearch/scope.test.tsnew file mode 100644index 00000000000..949179d87bc--- /dev/null+++ b/packages/database/src/repositories/ftsSearch/pgSearch/scope.test.ts@@ -0,0 +1,22 @@+import { PgDialect } from 'drizzle-orm/pg-core';+import { describe, expect, it } from 'vitest';++import { agents } from '../../../schemas';+import type { LobeChatDatabase } from '../../../type';+import { createPostgresFtsSearchContext } from '../postgres/context';+import { pgSearchDialect } from './dialect';++describe('createPostgresFtsSearchContext with pg_search', () => {+ it('keeps the trash predicate inside a personal-mode candidate scan', () => {+ const context = createPostgresFtsSearchContext(+ {} as LobeChatDatabase,+ { userId: 'user-1' },+ pgSearchDialect,+ );+ const built = new PgDialect().sqlToQuery(context.scanScopeWhere(agents));++ expect(built.sql).toBe('("agents"."user_id" = $1 and "agents"."is_deleted" IS NOT TRUE)');+ expect(built.params).toStrictEqual(['user-1']);+ expect(context.liftedScopeWhere(agents.workspaceId)).toBeDefined();+ });+});diff --git a/packages/database/src/repositories/ftsSearch/postgres/command-menu.ts b/packages/database/src/repositories/ftsSearch/postgres/command-menu.tsindex 1eed5b4abbd..06e339f825b 100644--- a/packages/database/src/repositories/ftsSearch/postgres/command-menu.ts+++ b/packages/database/src/repositories/ftsSearch/postgres/command-menu.ts@@ -1,5 +1,5 @@import type { SQLWrapper } from 'drizzle-orm';-import { and, desc, eq, inArray, ne, notInArray, sql } from 'drizzle-orm';+import { and, desc, eq, inArray, isNotNull, isNull, ne, notInArray, or, sql } from 'drizzle-orm';import {agents,@@ -328,6 +328,10 @@ export async function searchMessages(}).from(hits).leftJoin(agents, eq(hits.agentId, agents.id))+ // Keep parent visibility outside the isolated BM25 scan so ParadeDB can+ // still use TopN. A topic-less message is valid; a topic-backed message is+ // visible only when its ownership-scoped parent remains live.+ .leftJoin(topics, and(eq(hits.topicId, topics.id), buildWorkspaceWhere(context.scope, topics))).where(and(context.liftedScopeWhere(hits.workspaceId),@@ -335,6 +339,7 @@ export async function searchMessages(// ParadeDB rejects regex predicates inside the scored BM25 scan. Blank content cannot// match content @@@, so filtering after the candidate pool preserves eligible hits.searchableMessageText(hits.content, hits.summary),+ or(isNull(hits.topicId), isNotNull(topics.id)),),).orderBy(desc(hits.score))diff --git a/packages/database/src/repositories/ftsSearch/postgres/context.ts b/packages/database/src/repositories/ftsSearch/postgres/context.tsindex 174ddd7d0c6..6017ffbae01 100644--- a/packages/database/src/repositories/ftsSearch/postgres/context.ts+++ b/packages/database/src/repositories/ftsSearch/postgres/context.ts@@ -1,14 +1,16 @@import type { SQL, SQLWrapper } from 'drizzle-orm';-import { eq, isNull } from 'drizzle-orm';+import { and, eq, isNull } from 'drizzle-orm';import type { AnyPgColumn } from 'drizzle-orm/pg-core';import type { LobeChatDatabase } from '../../../type';+import { notTrashed } from '../../../utils/softDelete';import { buildWorkspaceWhere } from '../../../utils/workspace';import type { FtsSearchBackendScope } from '../types';import type { PostgresFtsSearchDialect } from './dialect';/** Columns shared by the workspace-aware tables searched by the PostgreSQL providers. */export interface PostgresFtsSearchWorkspaceScopedColumns {+ isDeleted?: AnyPgColumn;userId: AnyPgColumn;visibility?: AnyPgColumn;workspaceId: AnyPgColumn;@@ -102,7 +104,10 @@ export function createPostgresFtsSearchContext(scanScopeWhere: (cols) => {if (!liftsWorkspaceFilter) return buildWorkspaceWhere(normalizedScope, cols);- return eq(cols.userId, normalizedScope.userId) as SQL;+ return and(+ eq(cols.userId, normalizedScope.userId),+ cols.isDeleted ? notTrashed(cols.isDeleted) : undefined,+ ) as SQL;},scope: normalizedScope,userId: normalizedScope.userId,diff --git a/packages/database/src/repositories/ftsSearch/postgres/memories.ts b/packages/database/src/repositories/ftsSearch/postgres/memories.tsindex aa9caef48ad..a6ccc06c6bc 100644--- a/packages/database/src/repositories/ftsSearch/postgres/memories.ts+++ b/packages/database/src/repositories/ftsSearch/postgres/memories.ts@@ -2,6 +2,7 @@ import { LayersEnum } from '@lobechat/types';import { and, eq, ne, sql } from 'drizzle-orm';import { userMemories } from '../../../schemas';+import { notTrashed } from '../../../utils/softDelete';import type { FtsSearchBackendResponse, FtsSearchMemoryResult } from '../types';import type { PostgresFtsSearchContext } from './context';import type { PostgresFtsSearchField } from './dialect';@@ -41,6 +42,7 @@ export async function searchMemories(eq(userMemories.userId, context.userId),// Experience memory is retired and has no page to land on; keep it out of unified search.ne(userMemories.memoryLayer, LayersEnum.Experience),+ notTrashed(userMemories.isDeleted),dialect.match(MEMORY_FIELDS, preparedQuery),),)diff --git a/packages/database/src/repositories/heteroSessionImporter/__tests__/importSessions.test.ts b/packages/database/src/repositories/heteroSessionImporter/__tests__/importSessions.test.tsindex a2479e33f14..1c44295eb3d 100644--- a/packages/database/src/repositories/heteroSessionImporter/__tests__/importSessions.test.ts+++ b/packages/database/src/repositories/heteroSessionImporter/__tests__/importSessions.test.ts@@ -171,6 +171,54 @@ describe('HeteroSessionImporterRepo.importSessions', () => {expect(rows).toHaveLength(3);});+ it('treats a trashed imported message as an existing client identity on re-import', async () => {+ const repo = new HeteroSessionImporterRepo(serverDB, userId);+ await repo.importSessions({ agentId, sessions: [basePayload()] });+ await serverDB+ .update(messages)+ .set({ deletedAt: new Date('2026-09-10T00:00:00Z'), isDeleted: true })+ .where(eq(messages.clientId, 'cc-s1-a1'));++ const [second] = await repo.importSessions({ agentId, sessions: [basePayload()] });++ expect(second.insertedMessages).toBe(0);+ expect(second.skippedMessages).toBe(3);+ const rows = await serverDB+ .select({ id: messages.id })+ .from(messages)+ .where(eq(messages.clientId, 'cc-s1-a1'));+ expect(rows).toHaveLength(1);+ });++ it('rejects incremental syncs while the imported topic is trashed', async () => {+ const repo = new HeteroSessionImporterRepo(serverDB, userId);+ const [first] = await repo.importSessions({ agentId, sessions: [basePayload()] });+ await serverDB+ .update(topics)+ .set({ deletedAt: new Date('2026-09-10T00:00:00Z'), isDeleted: true })+ .where(eq(topics.id, first.topicId));++ const grown = basePayload();+ grown.workingDirectory = '/repo/after-trash';+ grown.messages.push({+ clientId: 'cc-s1-a2',+ content: 'must not be imported while trashed',+ createdAt: '2026-07-01T00:00:03.000Z',+ parentClientId: 'cc-s1-r1',+ provider: 'claude-code',+ role: 'assistant',+ });++ await expect(repo.importSessions({ agentId, sessions: [grown] })).rejects.toThrow(+ 'restore it before syncing',+ );++ const [topic] = await serverDB.select().from(topics).where(eq(topics.id, first.topicId));+ expect(topic.metadata).not.toMatchObject({ workingDirectory: '/repo/after-trash' });+ const rows = await serverDB.select().from(messages).where(eq(messages.topicId, first.topicId));+ expect(rows).toHaveLength(3);+ });+it('imports incrementally: a grown transcript only inserts the new tail', async () => {const repo = new HeteroSessionImporterRepo(serverDB, userId);const [first] = await repo.importSessions({ agentId, sessions: [basePayload()] });diff --git a/packages/database/src/repositories/heteroSessionImporter/index.ts b/packages/database/src/repositories/heteroSessionImporter/index.tsindex 46534b68f0a..e7f8ef8ce3f 100644--- a/packages/database/src/repositories/heteroSessionImporter/index.ts+++ b/packages/database/src/repositories/heteroSessionImporter/index.ts@@ -58,6 +58,17 @@ export class HeteroSessionImporterRepo {private scopeWhere = (cols: { userId: any; workspaceId: any }) =>buildWorkspaceWhere({ userId: this.userId, workspaceId: this.workspaceId }, cols);+ /**+ * Identity probes must see trashed rows because clientId uniqueness still+ * covers them. This never feeds a product read; it only prevents a retry+ * from treating an existing database identity as insertable.+ */+ private identityScopeWhere = (cols: { userId: any; workspaceId: any }) =>+ buildWorkspaceWhere(+ { includeTrashed: true, userId: this.userId, workspaceId: this.workspaceId },+ cols,+ );+/*** The agent's heterogeneous runtime type (`claude-code`, `codex`, β¦), pinned* onto every topic this importer creates. Resolved once per batch: it is the@@ -111,9 +122,15 @@ export class HeteroSessionImporterRepo {// 1. find or create the topic by clientId within the active scopeconst [existingTopic] = await tx- .select({ id: topics.id, metadata: topics.metadata })+ .select({ id: topics.id, isDeleted: topics.isDeleted, metadata: topics.metadata }).from(topics)- .where(and(eq(topics.clientId, session.topicClientId), this.scopeWhere(topics)));+ .where(and(eq(topics.clientId, session.topicClientId), this.identityScopeWhere(topics)));++ if (existingTopic?.isDeleted === true) {+ throw new Error(+ `session ${session.sessionId} is already imported into a trashed topic; restore it before syncing`,+ );+ }// the (clientId, userId) unique index makes one session = one topic per// user GLOBALLY β if it exists outside the active scope, appending there@@ -170,7 +187,7 @@ export class HeteroSessionImporterRepo {threadId: messages.threadId,}).from(messages)- .where(and(eq(messages.topicId, topicId), this.scopeWhere(messages)))+ .where(and(eq(messages.topicId, topicId), this.identityScopeWhere(messages))): [];const clientIdToDbId = new Map<string, string>();for (const row of existingRows) if (row.clientId) clientIdToDbId.set(row.clientId, row.id);@@ -202,7 +219,7 @@ export class HeteroSessionImporterRepo {const [existingThread] = await tx.select({ id: threads.id }).from(threads)- .where(and(eq(threads.clientId, thread.clientId), this.scopeWhere(threads)));+ .where(and(eq(threads.clientId, thread.clientId), this.identityScopeWhere(threads)));let threadId = existingThread?.id;if (!threadId) {diff --git a/packages/database/src/repositories/home/index.ts b/packages/database/src/repositories/home/index.tsindex 1c15c721189..a5eecedab05 100644--- a/packages/database/src/repositories/home/index.ts+++ b/packages/database/src/repositories/home/index.ts@@ -104,6 +104,7 @@ export class HomeRepository {.where(and(buildWorkspaceWhere(this.scope, {+ isDeleted: agents.isDeleted,userId: agents.userId,workspaceId: agents.workspaceId,visibility: agents.visibility,@@ -130,6 +131,7 @@ export class HomeRepository {.from(chatGroups).where(buildWorkspaceWhere(this.scope, {+ isDeleted: chatGroups.isDeleted,userId: chatGroups.userId,workspaceId: chatGroups.workspaceId,visibility: chatGroups.visibility,@@ -173,6 +175,7 @@ export class HomeRepository {.from(sessionGroups).where(buildWorkspaceWhere(this.scope, {+ isDeleted: sessionGroups.isDeleted,userId: sessionGroups.userId,workspaceId: sessionGroups.workspaceId,visibility: sessionGroups.visibility,diff --git a/packages/database/src/repositories/onboardingUnderstanding/repository.ts b/packages/database/src/repositories/onboardingUnderstanding/repository.tsindex 1429792186d..4d8710a352e 100644--- a/packages/database/src/repositories/onboardingUnderstanding/repository.ts+++ b/packages/database/src/repositories/onboardingUnderstanding/repository.ts@@ -27,6 +27,7 @@ import {} from '../../models/userMemory/persona';import { messages, threads, topics } from '../../schemas';import type { LobeChatDatabase, Transaction } from '../../type';+import { notTrashed } from '../../utils/softDelete';import { getUnderstandingSourceFingerprint } from './fingerprint';export { getUnderstandingSourceFingerprint } from './fingerprint';@@ -174,13 +175,18 @@ const assertProviderId = (providerId: string) => {};const topicOwnership = (topicId: string, userId: string) =>- and(eq(topics.id, topicId), eq(topics.userId, userId), isNull(topics.workspaceId));+ and(+ eq(topics.id, topicId),+ eq(topics.userId, userId),+ isNull(topics.workspaceId),+ notTrashed(topics.isDeleted),+ );const threadOwnership = (userId: string) =>- and(eq(threads.userId, userId), isNull(threads.workspaceId));+ and(eq(threads.userId, userId), isNull(threads.workspaceId), notTrashed(threads.isDeleted));const messageOwnership = (userId: string) =>- and(eq(messages.userId, userId), isNull(messages.workspaceId));+ and(eq(messages.userId, userId), isNull(messages.workspaceId), notTrashed(messages.isDeleted));const parseSession = (value: unknown): OnboardingUnderstandingSession => {let session: OnboardingUnderstandingSession;diff --git a/packages/database/src/repositories/resourceTransferManifest/index.test.ts b/packages/database/src/repositories/resourceTransferManifest/index.test.tsindex 168314b1e81..f2d78ce6550 100644--- a/packages/database/src/repositories/resourceTransferManifest/index.test.ts+++ b/packages/database/src/repositories/resourceTransferManifest/index.test.ts@@ -11,12 +11,15 @@ import {agents,agentsFiles,agentsKnowledgeBases,+ chatGroups,chatGroupsAgents,devices,expertiseBindings,expertiseDomains,files,knowledgeBases,+ projectAgents,+ projects,tasks,userConnectors,users,@@ -150,6 +153,52 @@ describe('buildMemberTransferManifest', () => {expect(manifest?.deviceBindingAffected).toBe(false);});+ it('counts trashed group and project links that a private-agent handover will remove', async () => {+ const agent = await ownerModel.create({ title: 'Private Agent', visibility: 'private' });+ const coordinator = await ownerModel.create({ title: 'Coordinator', visibility: 'public' });+ const deletedAt = new Date('2026-09-10T00:00:00Z');+ await serverDB.insert(chatGroups).values({+ deletedAt,+ id: 'manifest-trashed-group',+ isDeleted: true,+ title: 'Trashed Group',+ userId: teammateId,+ workspaceId: wsId,+ });+ await serverDB.insert(chatGroupsAgents).values({+ agentId: agent.id,+ chatGroupId: 'manifest-trashed-group',+ role: 'participant',+ userId: teammateId,+ workspaceId: wsId,+ });+ await serverDB.insert(projects).values({+ coordinatorAgentId: coordinator.id,+ deletedAt,+ id: 'manifest-trashed-project',+ identifier: 'TRSH01',+ isDeleted: true,+ name: 'Trashed Project',+ userId: teammateId,+ workspaceId: wsId,+ });+ await serverDB.insert(projectAgents).values({+ agentId: agent.id,+ projectId: 'manifest-trashed-project',+ workspaceId: wsId,+ });++ const manifest = await buildMemberTransferManifest(serverDB, {+ recipientId,+ resourceId: agent.id,+ resourceType: 'agent',+ workspaceId: wsId,+ });++ expect(manifest?.groupsToLeave).toBe(1);+ expect(manifest?.projectsToLeave).toBe(1);+ });+it('counts only knowledge mounts the recipient cannot access', async () => {const agent = await ownerModel.create({ title: 'Agent' });await serverDB.insert(knowledgeBases).values([@@ -326,6 +375,39 @@ describe('buildMemberTransferManifest', () => {expect(manifest?.botPlatforms).toEqual([]);});+ it('includes a trashed private referenced member in the group manifest', async () => {+ const groupModel = new ChatGroupModel(serverDB, ownerId, wsId);+ const group = await groupModel.create({ title: 'Group', visibility: 'public' });+ const [referenced] = await serverDB+ .insert(agents)+ .values({+ deletedAt: new Date(),+ isDeleted: true,+ title: 'Trashed standalone',+ userId: teammateId,+ virtual: false,+ visibility: 'private',+ workspaceId: wsId,+ })+ .returning();+ await serverDB.insert(chatGroupsAgents).values({+ agentId: referenced.id,+ chatGroupId: group.id,+ role: 'participant',+ userId: ownerId,+ workspaceId: wsId,+ });++ const manifest = await buildMemberTransferManifest(serverDB, {+ recipientId,+ resourceId: group.id,+ resourceType: 'agentGroup',+ workspaceId: wsId,+ });++ expect(manifest?.hiddenReferencedMember).toBe(true);+ });+it('returns null for a resource outside the workspace', async () => {await expect(buildMemberTransferManifest(serverDB, {diff --git a/packages/database/src/repositories/resourceTransferManifest/index.ts b/packages/database/src/repositories/resourceTransferManifest/index.tsindex 462770c93c6..876c4ba05b7 100644--- a/packages/database/src/repositories/resourceTransferManifest/index.ts+++ b/packages/database/src/repositories/resourceTransferManifest/index.ts@@ -21,6 +21,7 @@ import { countAssociatedAgentDocumentsToDetach } from '../../utils/agentDocumentimport { countAgentExpertiseAffected } from '../../utils/agentExpertise';import { countAgentKnowledgeMountsToDetach } from '../../utils/agentKnowledgeMounts';import { resolveGroupMembershipType } from '../../utils/groupMembership';+import { notTrashed } from '../../utils/softDelete';/*** What a member-to-member handover of this resource will actually carry, so@@ -90,7 +91,13 @@ export const buildMemberTransferManifest = async (visibility: agents.visibility,}).from(agents)- .where(and(eq(agents.id, resourceId), eq(agents.workspaceId, workspaceId)));+ .where(+ and(+ eq(agents.id, resourceId),+ eq(agents.workspaceId, workspaceId),+ notTrashed(agents.isDeleted),+ ),+ );if (!agent) return null;ownerId = agent.userId;agentIds = [agent.id];@@ -110,7 +117,13 @@ export const buildMemberTransferManifest = async (const [group] = await db.select({ id: chatGroups.id, userId: chatGroups.userId }).from(chatGroups)- .where(and(eq(chatGroups.id, resourceId), eq(chatGroups.workspaceId, workspaceId)));+ .where(+ and(+ eq(chatGroups.id, resourceId),+ eq(chatGroups.workspaceId, workspaceId),+ notTrashed(chatGroups.isDeleted),+ ),+ );if (!group) return null;ownerId = group.userId;@@ -169,7 +182,13 @@ export const buildMemberTransferManifest = async (? db.select({ value: count() }).from(agentCronJobs)- .where(and(inArray(agentCronJobs.agentId, agentIds), eq(agentCronJobs.userId, ownerId)))+ .where(+ and(+ inArray(agentCronJobs.agentId, agentIds),+ eq(agentCronJobs.userId, ownerId),+ notTrashed(agentCronJobs.isDeleted),+ ),+ ): Promise.resolve([{ value: 0 }]),privateAgentIds.length > 0? db@@ -179,6 +198,7 @@ export const buildMemberTransferManifest = async (and(inArray(tasks.assigneeAgentId, privateAgentIds),ne(tasks.createdByUserId, recipientId),+ notTrashed(tasks.isDeleted),),): Promise.resolve([{ value: 0 }]),diff --git a/packages/database/src/utils/agent-access.ts b/packages/database/src/utils/agent-access.tsindex a00b25d79b7..8413a8cc9aa 100644--- a/packages/database/src/utils/agent-access.ts+++ b/packages/database/src/utils/agent-access.ts@@ -35,6 +35,7 @@ export async function assertAgentUsableBy(and(eq(agents.id, agentId),buildWorkspaceWhere(ctx, {+ isDeleted: agents.isDeleted,userId: agents.userId,workspaceId: agents.workspaceId,visibility: agents.visibility,diff --git a/packages/database/src/utils/softDelete.ts b/packages/database/src/utils/softDelete.tsnew file mode 100644index 00000000000..c097b32998f--- /dev/null+++ b/packages/database/src/utils/softDelete.ts@@ -0,0 +1,46 @@+import { eq, type SQL, sql } from 'drizzle-orm';+import type { AnyPgColumn } from 'drizzle-orm/pg-core';++/**+ * Predicate every ownership-scoped read of a recycle-bin-aware table must+ * carry: `is_deleted IS NOT TRUE`.+ *+ * It is `IS NOT TRUE` and not `= false` because a live row leaves `is_deleted`+ * NULL β only a trashed row is stamped (see `softDeleteColumns()` in+ * `schemas/_helpers.ts`). `is_deleted = false` evaluates to NULL for those+ * rows, which is not true, so an equality filter would hide the entire table+ * instead of just its trashed rows. `IS NOT TRUE` is also correct for a row+ * explicitly stamped `false`, so it holds whichever way the column is written.+ *+ * Kept as a named helper (rather than an inline predicate) so the call sites+ * are greppable when auditing which reads still see trashed rows.+ * `buildWorkspaceWhere` applies it automatically for tables in+ * `TRASH_AWARE_TABLES`; use this only where that funnel is bypassed.+ */+export const notTrashed = (isDeleted: AnyPgColumn): SQL => sql`${isDeleted} IS NOT TRUE`;++/** Inverse of {@link notTrashed}: rows sitting in the recycle bin. */+export const isTrashed = (isDeleted: AnyPgColumn): SQL => eq(isDeleted, true);++/**+ * The write half of the `is_deleted IS TRUE βΊ deleted_at IS NOT NULL`+ * invariant. Every soft delete sets both columns from one stamp β¦+ */+export const trashStamp = (deletedAt: Date) => ({ deletedAt, isDeleted: true }) as const;++/**+ * β¦ and every restore clears both back to NULL β the live state β so a+ * restored row is indistinguishable from one that was never trashed.+ */+export const restoreStamp = () => ({ deletedAt: null, isDeleted: null }) as const;++/** Options shared by every model-level `softDelete*` primitive. */+export interface SoftDeleteOptions {+ /** Trash-time instant shared across a cascade so children carry the root's stamp. */+ deletedAt: Date;+ /**+ * Workspace non-owner members may only sweep their own rows (mirrors the+ * `restrictToCreator` convention of the hard-delete paths).+ */+ restrictToCreator?: boolean;+}diff --git a/packages/database/src/utils/topicVisibility.test.ts b/packages/database/src/utils/topicVisibility.test.tsnew file mode 100644index 00000000000..38d3a5459cc--- /dev/null+++ b/packages/database/src/utils/topicVisibility.test.ts@@ -0,0 +1,15 @@+import { PgDialect } from 'drizzle-orm/pg-core';+import { describe, expect, it } from 'vitest';++import { messages } from '../schemas';+import { hasLiveParentTopic } from './topicVisibility';++describe('hasLiveParentTopic', () => {+ it('keeps topic-less rows and requires a live parent for topic-backed rows', () => {+ const built = new PgDialect().sqlToQuery(hasLiveParentTopic(messages.topicId));++ expect(built.sql).toBe(+ '("messages"."topic_id" IS NULL OR EXISTS (SELECT 1 FROM "topics" WHERE "topics"."id" = "messages"."topic_id" AND "topics"."is_deleted" IS NOT TRUE))',+ );+ });+});diff --git a/packages/database/src/utils/topicVisibility.ts b/packages/database/src/utils/topicVisibility.tsnew file mode 100644index 00000000000..144e65d0a07--- /dev/null+++ b/packages/database/src/utils/topicVisibility.ts@@ -0,0 +1,15 @@+import { type AnyColumn, sql } from 'drizzle-orm';++import { topics } from '../schemas';++/**+ * Keep a row when it has no topic parent, or when that parent is still live.+ *+ * Topic soft deletion deliberately leaves child messages unstamped, so direct+ * message-table reads must carry this fence in addition to their own recycle-+ * bin predicate. The inner column names are fixed for the same reason as+ * `notShareVisitorTopicRef`: relational-query aliases must not rewrite the+ * correlated topic columns to the outer table alias.+ */+export const hasLiveParentTopic = (topicIdColumn: AnyColumn) =>+ sql`(${topicIdColumn} IS NULL OR EXISTS (SELECT 1 FROM ${topics} WHERE ${sql.raw('"topics"."id"')} = ${topicIdColumn} AND ${sql.raw('"topics"."is_deleted"')} IS NOT TRUE))`;diff --git a/packages/database/src/utils/workspace.test.ts b/packages/database/src/utils/workspace.test.tsindex 4f52e5404f9..21c3f8d0059 100644--- a/packages/database/src/utils/workspace.test.ts+++ b/packages/database/src/utils/workspace.test.ts@@ -1,7 +1,9 @@-import { PgDialect } from 'drizzle-orm/pg-core';+import { alias, PgDialect } from 'drizzle-orm/pg-core';import { describe, expect, it } from 'vitest';import { agents } from '../schemas/agent';+import { agentDocuments } from '../schemas/agentDocuments';+import { topicComments } from '../schemas/topicComment';import { buildWorkspacePayload, buildWorkspaceWhere } from './workspace';describe('workspace utils', () => {@@ -9,7 +11,7 @@ describe('workspace utils', () => {it('scopes personal reads by user and null workspace (visibility ignored)', () => {// Personal mode rows are implicitly owner-private, so the visibility// column is intentionally not part of the predicate.- const condition = buildWorkspaceWhere({ userId: 'user-1' }, agents);+ const condition = buildWorkspaceWhere({ includeTrashed: true, userId: 'user-1' }, agents);const built = new PgDialect().sqlToQuery(condition);expect(built.sql).toBe('("agents"."user_id" = $1 and "agents"."workspace_id" is null)');@@ -17,7 +19,10 @@ describe('workspace utils', () => {});it('scopes workspace reads with visibility filter when the column is present', () => {- const condition = buildWorkspaceWhere({ userId: 'user-1', workspaceId: 'ws-1' }, agents);+ const condition = buildWorkspaceWhere(+ { includeTrashed: true, userId: 'user-1', workspaceId: 'ws-1' },+ agents,+ );const built = new PgDialect().sqlToQuery(condition);// Workspace mode: every member sees public rows; private rows are@@ -47,6 +52,7 @@ describe('workspace utils', () => {const condition = buildWorkspaceWhere({callerAgentVisibility: 'public',+ includeTrashed: true,userId: 'user-1',workspaceId: 'ws-1',},@@ -66,6 +72,7 @@ describe('workspace utils', () => {const condition = buildWorkspaceWhere({callerAgentVisibility: 'private',+ includeTrashed: true,userId: 'user-1',workspaceId: 'ws-1',},@@ -85,6 +92,7 @@ describe('workspace utils', () => {const condition = buildWorkspaceWhere({callerAgentVisibility: null,+ includeTrashed: true,userId: 'user-1',workspaceId: 'ws-1',},@@ -102,7 +110,7 @@ describe('workspace utils', () => {// Personal-mode rows are already owner-private by construction; visibility// is unused, so the public-agent gate should be a no-op here.const condition = buildWorkspaceWhere(- { callerAgentVisibility: 'public', userId: 'user-1' },+ { callerAgentVisibility: 'public', includeTrashed: true, userId: 'user-1' },agents,);const built = new PgDialect().sqlToQuery(condition);@@ -112,6 +120,77 @@ describe('workspace utils', () => {});});+ describe('recycle-bin filter', () => {+ it('adds `is_deleted IS NOT TRUE` when the cols carry the trash-aware flag', () => {+ // Every ownership-scoped read of a trash-aware table (agents, topics,+ // files, β¦) must hide rows sitting in the recycle bin β without the+ // ~250 call sites opting in one by one.+ const condition = buildWorkspaceWhere({ userId: 'user-1' }, agents);+ const built = new PgDialect().sqlToQuery(condition);++ expect(built.sql).toBe(+ '(("agents"."user_id" = $1 and "agents"."workspace_id" is null) and "agents"."is_deleted" IS NOT TRUE)',+ );+ expect(built.params).toStrictEqual(['user-1']);+ });++ it('is `IS NOT TRUE`, not `= false`, because a live row leaves the flag NULL', () => {+ // `is_deleted = false` is NULL for an unstamped row β not true β so an+ // equality filter would hide the entire table instead of its trashed rows.+ const built = new PgDialect().sqlToQuery(buildWorkspaceWhere({ userId: 'user-1' }, agents));++ expect(built.sql).not.toContain('"is_deleted" = ');+ });++ it('applies the stamp filter in workspace mode too', () => {+ const condition = buildWorkspaceWhere({ userId: 'user-1', workspaceId: 'ws-1' }, agents);+ const built = new PgDialect().sqlToQuery(condition);++ expect(built.sql).toContain('"agents"."is_deleted" IS NOT TRUE');+ expect(built.sql.startsWith('(("agents"."workspace_id" = $1')).toBe(true);+ });++ it('recognizes a trash-aware table through a Drizzle alias', () => {+ const aliasedAgents = alias(agents, 'candidate_agents');+ const condition = buildWorkspaceWhere({ userId: 'user-1' }, aliasedAgents);+ const built = new PgDialect().sqlToQuery(condition);++ expect(built.sql).toContain('"candidate_agents"."is_deleted" IS NOT TRUE');+ });++ it('skips the filter with `includeTrashed` (restore / purge internals)', () => {+ const condition = buildWorkspaceWhere({ includeTrashed: true, userId: 'user-1' }, agents);+ const built = new PgDialect().sqlToQuery(condition);++ expect(built.sql).not.toContain('is_deleted');+ });++ it('does not filter when the cols object omits isDeleted', () => {+ const condition = buildWorkspaceWhere(+ { userId: 'user-1' },+ { userId: agents.userId, workspaceId: agents.workspaceId },+ );+ expect(new PgDialect().sqlToQuery(condition).sql).not.toContain('is_deleted');+ });++ it('does not filter tables whose deleted_at has other semantics', () => {+ // agent_documents / topic_comments / workspace_members use `deleted_at`+ // as a tombstone with their own read rules and carry no `is_deleted` β+ // never auto-filtered, even if a caller wires their column in.+ const condition = buildWorkspaceWhere({ userId: 'user-1' }, agentDocuments);+ expect(new PgDialect().sqlToQuery(condition).sql).not.toContain('deleted');+ const comments = buildWorkspaceWhere(+ { userId: 'user-1', workspaceId: 'ws-1' },+ {+ isDeleted: topicComments.deletedAt,+ userId: topicComments.authorUserId,+ workspaceId: topicComments.workspaceId,+ },+ );+ expect(new PgDialect().sqlToQuery(comments).sql).not.toContain('deleted');+ });+ });+describe('buildWorkspacePayload', () => {it('writes personal payloads with a null workspace id', () => {expect(buildWorkspacePayload({ userId: 'user-1' }, { title: 'Personal agent' })).toEqual({diff --git a/packages/database/src/utils/workspace.ts b/packages/database/src/utils/workspace.tsindex 50431853610..8b3262020d6 100644--- a/packages/database/src/utils/workspace.ts+++ b/packages/database/src/utils/workspace.ts@@ -1,6 +1,50 @@import { and, eq, isNull, or, type SQL } from 'drizzle-orm';import type { AnyPgColumn } from 'drizzle-orm/pg-core';+import { notTrashed } from './softDelete';++/**+ * Tables carrying the recycle-bin columns (`softDeleteColumns()` in+ * `schemas/_helpers.ts`). For these, `buildWorkspaceWhere` transparently adds+ * `is_deleted IS NOT TRUE` whenever the caller passes the whole table (or a `cols`+ * object carrying `isDeleted`), so a trashed row is invisible to every+ * ownership-scoped read in the codebase β models, repositories and services+ * alike β without each of the ~250 call sites opting in.+ *+ * Tables that use `deleted_at` with *other* semantics (`agent_documents`,+ * `topic_comments` tombstones, `workspace_members`) never carry `is_deleted`+ * and are therefore never matched.+ *+ * Restore / purge internals pass `includeTrashed: true` to reach stamped rows.+ */+export const TRASH_AWARE_TABLES: ReadonlySet<string> = new Set([+ 'agent_cron_jobs',+ 'agent_skills',+ 'agents',+ 'chat_groups',+ 'documents',+ 'files',+ 'generation_batches',+ 'generation_topics',+ 'generations',+ 'goals',+ 'knowledge_bases',+ 'messages',+ 'metrics',+ 'projects',+ 'session_groups',+ 'tasks',+ 'threads',+ 'topics',+ 'user_memories',+ 'works',+]);++const isTrashFlag = (col: AnyPgColumn | undefined): col is AnyPgColumn =>+ !!col &&+ col.name === 'is_deleted' &&+ TRASH_AWARE_TABLES.has(Reflect.get(col.table, Symbol.for('drizzle:OriginalName')) as string);+/*** Workspace-aware ownership predicate for content tables.*@@ -53,10 +97,33 @@ export function buildWorkspaceWhere(* content.*/callerAgentVisibility?: 'private' | 'public' | null;+ /**+ * Skip the recycle-bin filter β for restore / purge / trash-listing+ * internals only. Every ordinary read must leave this unset.+ */+ includeTrashed?: boolean;+ userId: string;+ workspaceId?: string;+ },+ cols: {+ isDeleted?: AnyPgColumn;+ userId: AnyPgColumn;+ visibility?: AnyPgColumn;+ workspaceId: AnyPgColumn;+ },+): SQL {+ const base = buildScopeWhere(ctx, cols);+ if (ctx.includeTrashed || !isTrashFlag(cols.isDeleted)) return base;+ return and(base, notTrashed(cols.isDeleted)) as SQL;+}++function buildScopeWhere(+ ctx: {+ callerAgentVisibility?: 'private' | 'public' | null;userId: string;workspaceId?: string;},- cols: { userId: AnyPgColumn; workspaceId: AnyPgColumn; visibility?: AnyPgColumn },+ cols: { userId: AnyPgColumn; visibility?: AnyPgColumn; workspaceId: AnyPgColumn },): SQL {if (!ctx.workspaceId) {return and(eq(cols.userId, ctx.userId), isNull(cols.workspaceId)) as SQL;