🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
⚡️ perf(db): derive message scope from topics/sessions on transfer (#17780)
Rdmclin23402718bacc7
diff --git a/apps/server/src/routers/lambda/agent.ts b/apps/server/src/routers/lambda/agent.tsindex 9b5d96c6e18..35fec2e016b 100644--- a/apps/server/src/routers/lambda/agent.ts+++ b/apps/server/src/routers/lambda/agent.ts@@ -18,6 +18,7 @@ import { TOPIC_COMMENT_TRANSFER_HAS_FOREIGN_AUTHORS } from '@/database/models/toimport { UserModel } from '@/database/models/user';import type { ResourceAccessLevel } from '@/database/schemas';import { DEFAULT_RESOURCE_ACCESS_LEVELS, RESOURCE_ACCESS_LEVELS_BY_TYPE } from '@/database/schemas';+import { MESSAGE_TRANSFER_HAS_FOREIGN_AUTHORS } from '@/database/utils/messageScope';import { router } from '@/libs/trpc/lambda';import { serverDatabase } from '@/libs/trpc/lambda/middleware';import { AgentService } from '@/server/services/agent';@@ -855,12 +856,16 @@ export const agentRouter = router({input.targetWorkspaceId,ctx.userId,input.targetVisibility,- { rejectForeignTopicCommentAuthors: isWorkspaceNonOwner(ctx) },+ {+ rejectForeignMessageAuthors: isWorkspaceNonOwner(ctx),+ rejectForeignTopicCommentAuthors: isWorkspaceNonOwner(ctx),+ },);} catch (error) {if (error instanceof Error &&- error.message === TOPIC_COMMENT_TRANSFER_HAS_FOREIGN_AUTHORS+ (error.message === TOPIC_COMMENT_TRANSFER_HAS_FOREIGN_AUTHORS ||+ error.message === MESSAGE_TRANSFER_HAS_FOREIGN_AUTHORS)) {throw new TRPCError({cause: { data: { code: TransferErrorCode.OwnerOnly } },@@ -991,12 +996,16 @@ export const agentRouter = router({input.targetWorkspaceId,ctx.userId,input.targetVisibility,- { rejectForeignTopicCommentAuthors: isWorkspaceNonOwner(ctx) },+ {+ rejectForeignMessageAuthors: isWorkspaceNonOwner(ctx),+ rejectForeignTopicCommentAuthors: isWorkspaceNonOwner(ctx),+ },);} catch (error) {if (error instanceof Error &&- error.message === TOPIC_COMMENT_TRANSFER_HAS_FOREIGN_AUTHORS+ (error.message === TOPIC_COMMENT_TRANSFER_HAS_FOREIGN_AUTHORS ||+ error.message === MESSAGE_TRANSFER_HAS_FOREIGN_AUTHORS)) {throw new TRPCError({cause: { data: { code: TransferErrorCode.OwnerOnly } },diff --git a/apps/server/src/routers/lambda/agentEvalExternal.ts b/apps/server/src/routers/lambda/agentEvalExternal.tsindex f9fccf18c38..0484c4fe1b1 100644--- a/apps/server/src/routers/lambda/agentEvalExternal.ts+++ b/apps/server/src/routers/lambda/agentEvalExternal.ts@@ -19,7 +19,7 @@ import {} from '@/database/models/agentEval';import { ThreadModel } from '@/database/models/thread';import { messages } from '@/database/schemas';-import { buildWorkspaceWhere } from '@/database/utils/workspace';+import { buildMessageScopeWhere } from '@/database/utils/messageScope';import { router } from '@/libs/trpc/lambda';import { serverDatabase } from '@/libs/trpc/lambda/middleware';import { AgentEvalRunService, RUN_CREATE_ID_CONFLICT } from '@/server/services/agentEvalRun';@@ -466,10 +466,14 @@ export const agentEvalExternalRouter = router({.input(z.object({ threadId: z.string().optional(), topicId: z.string() })).query(async ({ ctx, input }) => {const conditions = [- buildWorkspaceWhere(- { userId: ctx.userId, workspaceId: ctx.workspaceId ?? undefined },- messages,- ),+ // Derived scope: messages.user_id/workspace_id are creation-time+ // snapshots that go stale after an agent transfer, so filtering on them+ // would return nothing for a transferred topic. The `topicId` equality+ // below keeps the correlated predicate index-bounded.+ buildMessageScopeWhere({+ userId: ctx.userId,+ workspaceId: ctx.workspaceId ?? undefined,+ }),eq(messages.topicId, input.topicId),isNull(messages.messageGroupId),];diff --git a/apps/server/src/routers/lambda/agentGroup.ts b/apps/server/src/routers/lambda/agentGroup.tsindex b36e87200d1..b080c4b11e0 100644--- a/apps/server/src/routers/lambda/agentGroup.ts+++ b/apps/server/src/routers/lambda/agentGroup.ts@@ -12,6 +12,7 @@ import { UserModel } from '@/database/models/user';import { AgentGroupRepository } from '@/database/repositories/agentGroup';import { DEFAULT_RESOURCE_ACCESS_LEVELS, RESOURCE_ACCESS_LEVELS_BY_TYPE } from '@/database/schemas';import { type ChatGroupConfig } from '@/database/types/chatGroup';+import { MESSAGE_TRANSFER_HAS_FOREIGN_AUTHORS } from '@/database/utils/messageScope';import { router } from '@/libs/trpc/lambda';import { serverDatabase } from '@/libs/trpc/lambda/middleware';import { AgentGroupService } from '@/server/services/agentGroup';@@ -690,12 +691,16 @@ export const agentGroupRouter = router({input.targetWorkspaceId,ctx.userId,input.targetVisibility,- { rejectForeignTopicCommentAuthors: isWorkspaceNonOwner(ctx) },+ {+ rejectForeignMessageAuthors: isWorkspaceNonOwner(ctx),+ rejectForeignTopicCommentAuthors: isWorkspaceNonOwner(ctx),+ },);} catch (error) {if (error instanceof Error &&- error.message === TOPIC_COMMENT_TRANSFER_HAS_FOREIGN_AUTHORS+ (error.message === TOPIC_COMMENT_TRANSFER_HAS_FOREIGN_AUTHORS ||+ error.message === MESSAGE_TRANSFER_HAS_FOREIGN_AUTHORS)) {throw new TRPCError({cause: { data: { code: TransferErrorCode.OwnerOnly } },diff --git a/apps/server/src/services/agentSignal/policies/analyzeIntent/completionSkillSynthesis.ts b/apps/server/src/services/agentSignal/policies/analyzeIntent/completionSkillSynthesis.tsindex 2d093b198cc..b69db610c8b 100644--- a/apps/server/src/services/agentSignal/policies/analyzeIntent/completionSkillSynthesis.ts+++ b/apps/server/src/services/agentSignal/policies/analyzeIntent/completionSkillSynthesis.ts@@ -5,7 +5,7 @@ import { and, asc, eq, gte, isNull } from 'drizzle-orm';import { MessageModel } from '@/database/models/message';import type { LobeChatDatabase } from '@/database/type';-import { buildWorkspaceWhere } from '@/database/utils/workspace';+import { buildMessageScopeWhere } from '@/database/utils/messageScope';import type { RuntimeProcessorContext } from '../../runtime/context';import { defineSourceHandler } from '../../runtime/middleware';@@ -148,7 +148,7 @@ const assembleTrajectoryContext = async (input: {limit: MAX_TRAJECTORY_MESSAGES,orderBy: [asc(messages.createdAt)],where: and(- buildWorkspaceWhere({ userId: input.userId, workspaceId: input.workspaceId }, messages),+ buildMessageScopeWhere({ userId: input.userId, workspaceId: input.workspaceId }),eq(messages.topicId, input.topicId),gte(messages.createdAt, input.turnStartAt),threadScopeFilter,diff --git a/apps/server/src/services/followUpAction/index.test.ts b/apps/server/src/services/followUpAction/index.test.tsindex 0bc6cabdbd0..31bac890521 100644--- a/apps/server/src/services/followUpAction/index.test.ts+++ b/apps/server/src/services/followUpAction/index.test.ts@@ -1,4 +1,5 @@// @vitest-environment node+import { PgDialect } from 'drizzle-orm/pg-core';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import * as ModelRuntimeModule from '@/server/modules/ModelRuntime';@@ -149,27 +150,11 @@ describe('FollowUpActionService.extract', () => {expect(result).toEqual({ chips: [], messageId: FOUND_MSG });});- const captureWhereOps = () => {+ // The where clause is a composed drizzle SQL object now (derived message+ // scope) — render it to SQL text + params for assertions.+ const captureWhere = () => {const arg = queryFindFirstSpy.mock.calls[0][0];- const fakeTable = {- content: { col: 'content' },- createdAt: { col: 'createdAt' },- id: { col: 'id' },- role: { col: 'role' },- threadId: { col: 'threadId' },- topicId: { col: 'topicId' },- userId: { col: 'userId' },- workspaceId: { col: 'workspaceId' },- };- const ops = {- and: (...parts: any[]) => ({ op: 'and', parts }),- eq: (col: any, value: any) => ({ col, op: 'eq', value }),- isNotNull: (col: any) => ({ col, op: 'isNotNull' }),- isNull: (col: any) => ({ col, op: 'isNull' }),- ne: (col: any, value: any) => ({ col, op: 'ne', value }),- };- const result = arg.where(fakeTable, ops);- return { parts: result.parts as any[], table: fakeTable };+ return new PgDialect().sqlToQuery(arg.where);};it('filters by threadId when provided (thread isolation)', async () => {@@ -179,28 +164,26 @@ describe('FollowUpActionService.extract', () => {threadId: 'thread-A',topicId: TEST_TOPIC,});- const { parts, table } = captureWhereOps();- expect(parts).toContainEqual({ col: table.threadId, op: 'eq', value: 'thread-A' });- expect(parts.some((p) => p.op === 'isNull' && p.col === table.threadId)).toBe(false);+ const { sql, params } = captureWhere();+ expect(params).toContain('thread-A');+ expect(sql).not.toContain('"messages"."thread_id" is null');});it('filters by isNull(threadId) when no threadId provided (main topic only)', async () => {queryFindFirstSpy.mockResolvedValue(undefined);await svc.extract({ modelConfig: MODEL_CONFIG, topicId: TEST_TOPIC });- const { parts, table } = captureWhereOps();- expect(parts).toContainEqual({ col: table.threadId, op: 'isNull' });- expect(parts.some((p) => p.op === 'eq' && p.col === table.threadId)).toBe(false);+ const { sql } = captureWhere();+ expect(sql).toContain('"messages"."thread_id" is null');});- it('filters personal mode by userId and null workspaceId', async () => {+ it('derives personal-mode scope from the owning topic/session', async () => {queryFindFirstSpy.mockResolvedValue(undefined);await svc.extract({ modelConfig: MODEL_CONFIG, topicId: TEST_TOPIC });- const { parts, table } = captureWhereOps();- const ownership = parts.find((p) => p.op === 'and' && p.parts?.length === 2);- expect(ownership.parts).toEqual([- { col: table.userId, op: 'eq', value: TEST_USER },- { col: table.workspaceId, op: 'isNull' },- ]);+ const { sql, params } = captureWhere();+ // Scope comes from the anchors, not the row snapshots alone+ expect(sql).toContain('"topics"');+ expect(sql).toContain('"sessions"');+ expect(params).toContain(TEST_USER);});it('filters workspace mode by workspaceId and forwards it to model runtime', async () => {@@ -210,8 +193,8 @@ describe('FollowUpActionService.extract', () => {await svc.extract({ modelConfig: MODEL_CONFIG, topicId: TEST_TOPIC });- const { parts, table } = captureWhereOps();- expect(parts).toContainEqual({ col: table.workspaceId, op: 'eq', value: 'workspace-1' });+ const { params } = captureWhere();+ expect(params).toContain('workspace-1');expect(ModelRuntimeModule.initModelRuntimeFromDB).toHaveBeenCalledWith(dbMock,TEST_USER,diff --git a/apps/server/src/services/followUpAction/index.ts b/apps/server/src/services/followUpAction/index.tsindex 6b09a02e6a3..1a5ad6c813e 100644--- a/apps/server/src/services/followUpAction/index.ts+++ b/apps/server/src/services/followUpAction/index.ts@@ -2,8 +2,11 @@ import { TRACING_SCENARIOS } from '@lobechat/const';import type { TracingOptions } from '@lobechat/llm-generation-tracing';import type { FollowUpChip, FollowUpExtractInput, FollowUpExtractResult } from '@lobechat/types';import debug from 'debug';+import { and, eq, isNotNull, isNull, ne } from 'drizzle-orm';+import { messages } from '@/database/schemas';import type { LobeChatDatabase } from '@/database/type';+import { buildMessageScopeWhere } from '@/database/utils/messageScope';import { AiGenerationService } from '@/server/services/aiGeneration';import { buildSuggestionPrompt, FOLLOW_UP_PROMPT_VERSION } from './prompts';@@ -35,19 +38,19 @@ export class FollowUpActionService {const row = await this.db.query.messages.findFirst({columns: { content: true, id: true },orderBy: (m, { desc }) => desc(m.createdAt),- where: (m, { and, eq, isNotNull, isNull, ne }) =>- and(- this.workspaceId- ? eq(m.workspaceId, this.workspaceId)- : and(eq(m.userId, this.userId), isNull(m.workspaceId)),- eq(m.topicId, topicId),- // Discriminate thread vs main topic: an absent threadId must NOT- // surface a thread reply that lives under the same topicId.- threadId ? eq(m.threadId, threadId) : isNull(m.threadId),- eq(m.role, 'assistant'),- isNotNull(m.content),- ne(m.content, ''),- ),+ // Scope is derived from the owning topic/session — the row's+ // user_id/workspace_id are creation-time snapshots that go stale after+ // agent transfers.+ where: and(+ buildMessageScopeWhere({ userId: this.userId, workspaceId: this.workspaceId }),+ eq(messages.topicId, topicId),+ // Discriminate thread vs main topic: an absent threadId must NOT+ // surface a thread reply that lives under the same topicId.+ threadId ? eq(messages.threadId, threadId) : isNull(messages.threadId),+ eq(messages.role, 'assistant'),+ isNotNull(messages.content),+ ne(messages.content, ''),+ ),});if (!row) return EMPTY_RESULT('');diff --git a/apps/server/src/services/memory/userMemory/extract.ts b/apps/server/src/services/memory/userMemory/extract.tsindex b95aa9710e0..0f5b0dc552d 100644--- a/apps/server/src/services/memory/userMemory/extract.ts+++ b/apps/server/src/services/memory/userMemory/extract.ts@@ -70,6 +70,7 @@ import { UserMemorySourceBenchmarkLoCoMoModel } from '@/database/models/userMemoimport { AiInfraRepos } from '@/database/repositories/aiInfra';import { asyncTasks } from '@/database/schemas';import { getServerDB } from '@/database/server';+import { buildMessageScopeWhere } from '@/database/utils/messageScope';import { buildWorkspaceWhere } from '@/database/utils/workspace';import { OtelWorkflowClient } from '@/libs/qstash';import { getServerGlobalConfig } from '@/server/globalConfig';@@ -1371,9 +1372,7 @@ export class MemoryExtractionExecutor {role: messages.role,}).from(messages)- .where(- and(buildWorkspaceWhere({ userId, workspaceId }, messages), eq(messages.topicId, topicId)),- )+ .where(and(buildMessageScopeWhere({ userId, workspaceId }), eq(messages.topicId, topicId))).orderBy(asc(messages.createdAt));const conversation = rowsdiff --git a/apps/server/src/services/usage/index.test.ts b/apps/server/src/services/usage/index.test.tsindex 2296690423a..0bb562e3e2f 100644--- a/apps/server/src/services/usage/index.test.ts+++ b/apps/server/src/services/usage/index.test.ts@@ -23,38 +23,51 @@ describe('UsageRecordService', () => {let mockDb: LobeChatDatabase;const userId = 'test-user-id';- // Helper function to setup query chain mock+ // Helper function to setup query chain mock. The service fans out over the+ // three derivation arms (topic / session / orphan); the mock returns rows+ // from the topic arm (first innerJoin chain) and empties from the rest.const setupQueryChainMock = (mockMessages: any[]) => {- const mockOrderBy = vi.fn().mockResolvedValue(mockMessages);- const mockWhere = vi.fn().mockReturnValue({ orderBy: mockOrderBy });- const mockFrom = vi.fn().mockReturnValue({ where: mockWhere });- mockDb.select = vi.fn().mockReturnValue({ from: mockFrom });+ let joinCalls = 0;+ mockDb.select = vi.fn().mockReturnValue({+ from: vi.fn().mockReturnValue({+ innerJoin: vi.fn().mockImplementation(() => {+ const isTopicArm = joinCalls++ === 0;+ return { where: vi.fn().mockResolvedValue(isTopicArm ? mockMessages : []) };+ }),+ where: vi.fn().mockResolvedValue([]),+ }),+ });};- // Variant that also captures the args passed to `.where(...)` so tests can- // assert what ended up in the composed WHERE clause.+ // Variant that also captures the args passed to `.where(...)` (topic arm+ // first) so tests can assert what ended up in the composed WHERE clause.const setupCapturingMock = (mockMessages: any[]) => {const whereArgs: unknown[] = [];- const mockOrderBy = vi.fn().mockResolvedValue(mockMessages);- const mockWhere = vi.fn().mockImplementation((arg: unknown) => {- whereArgs.push(arg);- return { orderBy: mockOrderBy };+ let joinCalls = 0;+ mockDb.select = vi.fn().mockReturnValue({+ from: vi.fn().mockReturnValue({+ innerJoin: vi.fn().mockImplementation(() => {+ const isTopicArm = joinCalls++ === 0;+ return {+ where: vi.fn().mockImplementation((arg: unknown) => {+ whereArgs.push(arg);+ return Promise.resolve(isTopicArm ? mockMessages : []);+ }),+ };+ }),+ where: vi.fn().mockImplementation((arg: unknown) => {+ whereArgs.push(arg);+ return Promise.resolve([]);+ }),+ }),});- const mockFrom = vi.fn().mockReturnValue({ where: mockWhere });- mockDb.select = vi.fn().mockReturnValue({ from: mockFrom });return { whereArgs };};beforeEach(() => {- // Create a fresh mock for each test- const mockOrderBy = vi.fn();- const mockWhere = vi.fn().mockReturnValue({ orderBy: mockOrderBy });- const mockFrom = vi.fn().mockReturnValue({ where: mockWhere });- const mockSelect = vi.fn().mockReturnValue({ from: mockFrom });-- mockDb = {- select: mockSelect,- } as unknown as LobeChatDatabase;+ mockDb = {} as unknown as LobeChatDatabase;+ // Default: every arm resolves empty+ setupQueryChainMock([]);service = new UsageRecordService(mockDb, userId);});diff --git a/apps/server/src/services/usage/index.ts b/apps/server/src/services/usage/index.tsindex 7ca9e52f40d..6b1ea3c86d9 100644--- a/apps/server/src/services/usage/index.ts+++ b/apps/server/src/services/usage/index.ts@@ -1,8 +1,8 @@import dayjs from 'dayjs';import debug from 'debug';-import { asc, desc, eq } from 'drizzle-orm';+import { and, eq, isNull, type SQL } from 'drizzle-orm';-import { messages } from '@/database/schemas';+import { messages, sessions, topics } from '@/database/schemas';import { type LobeChatDatabase } from '@/database/type';import { genRangeWhere, genWhere } from '@/database/utils/genWhere';import { buildWorkspaceWhere } from '@/database/utils/workspace';@@ -31,6 +31,25 @@ export class UsageRecordService {this.db = db;}+ /**+ * `messages.user_id`/`workspace_id` are creation-time snapshots that go+ * stale after agent transfers — usage reads derive scope from the owning+ * topic/session instead, fanned out over the three derivation arms so each+ * stays index-bounded (same strategy as `MessageModel.count`).+ */+ private scopeArms = () => {+ const ctx = { userId: this.userId, workspaceId: this.workspaceId };+ return {+ orphan: and(+ isNull(messages.topicId),+ isNull(messages.sessionId),+ buildWorkspaceWhere(ctx, messages),+ ) as SQL,+ sessionOwned: and(isNull(messages.topicId), buildWorkspaceWhere(ctx, sessions)) as SQL,+ topicOwned: buildWorkspaceWhere(ctx, topics),+ };+ };+/*** @description Find usage records by date range.* @param agentId Optional agent id to attribute usage to a single agent.@@ -40,31 +59,42 @@ export class UsageRecordService {endAt: string,agentId?: string,): Promise<UsageRecordItem[]> => {- const spends = await this.db- .select({- createdAt: messages.createdAt,- id: messages.id,- metadata: messages.metadata,- model: messages.model,- provider: messages.provider,- role: messages.role,- updatedAt: messages.createdAt,- usage: messages.usage,- userId: messages.userId,- })- .from(messages)- .where(- genWhere([- buildWorkspaceWhere(- { userId: this.userId, workspaceId: this.workspaceId },- { userId: messages.userId, workspaceId: messages.workspaceId },- ),- eq(messages.role, 'assistant'),- agentId ? eq(messages.agentId, agentId) : undefined,- genRangeWhere([startAt, endAt], messages.createdAt, (date) => date.toDate()),- ]),- )- .orderBy(desc(messages.createdAt));+ const selection = {+ createdAt: messages.createdAt,+ id: messages.id,+ metadata: messages.metadata,+ model: messages.model,+ provider: messages.provider,+ role: messages.role,+ updatedAt: messages.createdAt,+ usage: messages.usage,+ userId: messages.userId,+ };+ const conditions = [+ eq(messages.role, 'assistant'),+ agentId ? eq(messages.agentId, agentId) : undefined,+ genRangeWhere([startAt, endAt], messages.createdAt, (date) => date.toDate()),+ ];+ const { topicOwned, sessionOwned, orphan } = this.scopeArms();+ const [byTopic, bySession, orphans] = await Promise.all([+ this.db+ .select(selection)+ .from(messages)+ .innerJoin(topics, eq(topics.id, messages.topicId))+ .where(genWhere([topicOwned, ...conditions])),+ this.db+ .select(selection)+ .from(messages)+ .innerJoin(sessions, eq(sessions.id, messages.sessionId))+ .where(genWhere([sessionOwned, ...conditions])),+ this.db+ .select(selection)+ .from(messages)+ .where(genWhere([orphan, ...conditions])),+ ]);+ const spends = [...byTopic, ...bySession, ...orphans].sort(+ (a, b) => (b.createdAt?.getTime() ?? 0) - (a.createdAt?.getTime() ?? 0),+ );return spends.map((spend) => {const metadata = spend.metadata as MessageMetadata;// Prefer the dedicated `usage` column, then the canonical nested@@ -225,27 +255,38 @@ export class UsageRecordService {endAt: string,granularity: AgentUsageGranularity = 'day',): Promise<AgentUsageStats> => {- const rows = await this.db- .select({- createdAt: messages.createdAt,- metadata: messages.metadata,- model: messages.model,- provider: messages.provider,- usage: messages.usage,- })- .from(messages)- .where(- genWhere([- buildWorkspaceWhere(- { userId: this.userId, workspaceId: this.workspaceId },- { userId: messages.userId, workspaceId: messages.workspaceId },- ),- eq(messages.role, 'assistant'),- eq(messages.agentId, agentId),- genRangeWhere([startAt, endAt], messages.createdAt, (date) => date.toDate()),- ]),- )- .orderBy(asc(messages.createdAt));+ const selection = {+ createdAt: messages.createdAt,+ metadata: messages.metadata,+ model: messages.model,+ provider: messages.provider,+ usage: messages.usage,+ };+ const conditions = [+ eq(messages.role, 'assistant'),+ eq(messages.agentId, agentId),+ genRangeWhere([startAt, endAt], messages.createdAt, (date) => date.toDate()),+ ];+ const { topicOwned, sessionOwned, orphan } = this.scopeArms();+ const [byTopic, bySession, orphans] = await Promise.all([+ this.db+ .select(selection)+ .from(messages)+ .innerJoin(topics, eq(topics.id, messages.topicId))+ .where(genWhere([topicOwned, ...conditions])),+ this.db+ .select(selection)+ .from(messages)+ .innerJoin(sessions, eq(sessions.id, messages.sessionId))+ .where(genWhere([sessionOwned, ...conditions])),+ this.db+ .select(selection)+ .from(messages)+ .where(genWhere([orphan, ...conditions])),+ ]);+ const rows = [...byTopic, ...bySession, ...orphans].sort(+ (a, b) => (a.createdAt?.getTime() ?? 0) - (b.createdAt?.getTime() ?? 0),+ );const bucketStart = (date: Date) =>granularity === 'week' ? dayjs(date).startOf('week') : dayjs(date).startOf('day');diff --git a/apps/server/src/workflows/agentSignal/run.ts b/apps/server/src/workflows/agentSignal/run.tsindex a78d17d2ab4..8dc9e01d37f 100644--- a/apps/server/src/workflows/agentSignal/run.ts+++ b/apps/server/src/workflows/agentSignal/run.ts@@ -25,7 +25,7 @@ import { and, desc, eq, isNull, lte } from 'drizzle-orm';import { MessageModel } from '@/database/models/message';import { getServerDB } from '@/database/server';-import { buildWorkspaceWhere } from '@/database/utils/workspace';+import { buildMessageScopeWhere } from '@/database/utils/messageScope';import { extractTraceContext } from '@/libs/observability/traceparent';import { isAgentSignalEnabledForUser } from '@/server/services/agentSignal/featureGate';import { toAgentSignalTraceEvents } from '@/server/services/agentSignal/observability/traceEvents';@@ -312,7 +312,7 @@ const buildFeedbackSourceSerializedContext = async (limit: 10,orderBy: [desc(messages.createdAt)],where: and(- buildWorkspaceWhere({ userId: input.userId, workspaceId: input.workspaceId }, messages),+ buildMessageScopeWhere({ userId: input.userId, workspaceId: input.workspaceId }),eq(messages.topicId, sourceEvent.payload.topicId),lte(messages.createdAt, contextEndAt),threadScopeFilter,diff --git a/packages/database/src/models/__tests__/agentTransfer.test.ts b/packages/database/src/models/__tests__/agentTransfer.test.tsindex d9149b9bf00..8710587eb4e 100644--- a/packages/database/src/models/__tests__/agentTransfer.test.ts+++ b/packages/database/src/models/__tests__/agentTransfer.test.ts@@ -1,5 +1,5 @@// @vitest-environment node-import { eq } from 'drizzle-orm';+import { and, eq } from 'drizzle-orm';import { afterEach, beforeEach, describe, expect, it } from 'vitest';import { getTestDB } from '../../core/getTestDB';@@ -16,6 +16,8 @@ import {documents,files,knowledgeBases,+ messageGroups,+ messagePlugins,messages,sessionGroups,sessions,@@ -29,15 +31,23 @@ import {topicComments,topics,users,+ workspaceMembers,workspaces,} from '../../schemas';import type { LobeChatDatabase } from '../../type';+import {+ buildMessageChildScopeWhere,+ MESSAGE_TRANSFER_HAS_FOREIGN_AUTHORS,+} from '../../utils/messageScope';import { AgentModel } from '../agent';+import { MessageModel } from '../message';import {TOPIC_COMMENT_TOPIC_NOT_FOUND,TOPIC_COMMENT_TRANSFER_HAS_FOREIGN_AUTHORS,TopicCommentModel,} from '../topicComment';+import { UserModel } from '../user';+import { WorkspaceModel } from '../workspace';const serverDB: LobeChatDatabase = await getTestDB();const isServerDB = process.env.TEST_SERVER_DB === '1';@@ -171,22 +181,99 @@ describe('AgentModel.transferAgent', () => {expect(session.groupId).toBeNull();});- it('should update topics and messages', async () => {+ it('should update topics and keep messages as untouched snapshots visible via derivation', async () => {const model = new AgentModel(serverDB, userId);const agent = await model.create({ title: 'Agent' });await serverDB.insert(topics).values({ id: 'topic-1', agentId: agent.id, userId });await serverDB.insert(messages)- .values({ id: 'msg-1', agentId: agent.id, userId, role: 'assistant' });+ .values({ id: 'msg-1', agentId: agent.id, topicId: 'topic-1', userId, role: 'assistant' });await model.transferAgent(agent.id, wsId1, userId);const [topic] = await serverDB.select().from(topics).where(eq(topics.id, 'topic-1'));expect(topic.workspaceId).toBe(wsId1);+ // The message row itself is NOT rewritten: user_id/workspace_id stay as+ // creation-time snapshots (avoids the minutes-long BM25/index write+ // amplification on heavy agents)…const [msg] = await serverDB.select().from(messages).where(eq(messages.id, 'msg-1'));- expect(msg.workspaceId).toBe(wsId1);+ expect(msg.workspaceId).toBeNull();+ expect(msg.userId).toBe(userId);++ // …while scope derivation makes it immediately visible in the target+ // workspace, and no longer visible in the source personal scope.+ const wsMessages = new MessageModel(serverDB, userId, wsId1);+ expect(await wsMessages.query({ topicId: 'topic-1' })).toHaveLength(1);++ const personalMessages = new MessageModel(serverDB, userId);+ expect(await personalMessages.query({ topicId: 'topic-1' })).toHaveLength(0);+ });++ it('should keep message child tables (plugins) visible after transfer and round-trip cleanly', async () => {+ const model = new AgentModel(serverDB, userId);+ const agent = await model.create({ title: 'Agent' });++ await serverDB.insert(topics).values({ id: 'rt-topic', agentId: agent.id, userId });+ await serverDB.insert(messages).values({+ agentId: agent.id,+ id: 'rt-msg-tool',+ role: 'tool',+ topicId: 'rt-topic',+ userId,+ });+ await serverDB.insert(messagePlugins).values({+ id: 'rt-msg-tool',+ identifier: 'test-plugin',+ toolCallId: 'call-1',+ userId,+ });++ const pluginVisibleIn = async (workspaceId?: string) =>+ serverDB+ .select({ id: messagePlugins.id })+ .from(messagePlugins)+ .where(+ and(+ eq(messagePlugins.id, 'rt-msg-tool'),+ buildMessageChildScopeWhere({ userId, workspaceId }, messagePlugins.id),+ ),+ );++ // personal → workspace: message and plugin payload reachable in the+ // workspace scope even though neither row was rewritten+ await model.transferAgent(agent.id, wsId1, userId);+ const wsMessages = new MessageModel(serverDB, userId, wsId1);+ expect(await wsMessages.query({ topicId: 'rt-topic' })).toHaveLength(1);+ expect(await pluginVisibleIn(wsId1)).toHaveLength(1);+ expect(await pluginVisibleIn(undefined)).toHaveLength(0);++ // workspace → personal round-trip: everything visible again in personal scope+ const wsModel = new AgentModel(serverDB, userId, wsId1);+ await wsModel.transferAgent(agent.id, null, userId);+ const personalMessages = new MessageModel(serverDB, userId);+ expect(await personalMessages.query({ topicId: 'rt-topic' })).toHaveLength(1);+ expect(await pluginVisibleIn(undefined)).toHaveLength(1);++ // author snapshot is never rewritten+ const [msg] = await serverDB.select().from(messages).where(eq(messages.id, 'rt-msg-tool'));+ expect(msg.userId).toBe(userId);+ });++ it('should rewrite anchorless agent messages (no topic/session) on transfer', async () => {+ const model = new AgentModel(serverDB, userId);+ const agent = await model.create({ title: 'Agent' });++ // Anchorless: linked only via agentId — snapshot IS the authoritative scope+ await serverDB+ .insert(messages)+ .values({ agentId: agent.id, id: 'anchorless-msg', role: 'assistant', userId });++ await model.transferAgent(agent.id, wsId1, userId);++ const [msg] = await serverDB.select().from(messages).where(eq(messages.id, 'anchorless-msg'));+ expect(msg).toMatchObject({ userId, workspaceId: wsId1 });});it('should preserve content timestamps while transferring ownership', async () => {@@ -486,6 +573,86 @@ describe('AgentModel.transferAgent', () => {expect(await model.transferHasForeignRows(agent.id)).toBe(true);});+ it('should flag topic-only teammate messages and message groups as foreign rows', async () => {+ const model = new AgentModel(serverDB, userId, wsId1);+ const agent = await model.create({ title: 'Anchor Guarded Agent' });++ await serverDB+ .insert(topics)+ .values({ id: 'anchor-guard-topic', agentId: agent.id, userId, workspaceId: wsId1 });++ // Caller's own topic-only message — not foreign+ await serverDB.insert(messages).values({+ id: 'anchor-guard-own',+ role: 'user',+ topicId: 'anchor-guard-topic',+ userId,+ workspaceId: wsId1,+ });+ expect(await model.transferHasForeignRows(agent.id)).toBe(false);++ // A teammate's message carrying ONLY a topicId (the OpenAPI create shape:+ // agentId optional, sessionId always null) follows the transferred topic+ // under derived scope — the session/agent probes alone cannot see it+ await serverDB.insert(messages).values({+ id: 'anchor-guard-teammate',+ role: 'user',+ topicId: 'anchor-guard-topic',+ userId: targetUserId,+ workspaceId: wsId1,+ });+ expect(await model.transferHasForeignRows(agent.id)).toBe(true);++ // Same for a teammate's message group anchored to the caller's topic+ await serverDB.delete(messages).where(eq(messages.id, 'anchor-guard-teammate'));+ expect(await model.transferHasForeignRows(agent.id)).toBe(false);+ await serverDB.insert(messageGroups).values({+ id: 'anchor-guard-group',+ topicId: 'anchor-guard-topic',+ userId: targetUserId,+ workspaceId: wsId1,+ });+ expect(await model.transferHasForeignRows(agent.id)).toBe(true);+ });++ it('should recheck topic-anchored teammate rows inside the transfer transaction', async () => {+ const model = new AgentModel(serverDB, userId, wsId1);+ const agent = await model.create({ title: 'Locked Guard Agent' });++ await serverDB+ .insert(topics)+ .values({ id: 'locked-guard-topic', agentId: agent.id, userId, workspaceId: wsId1 });++ // Simulates the TOCTOU window: the teammate row already exists by the+ // time the transaction rechecks under the topic lock (the router-side+ // transferHasForeignRows precheck is deliberately skipped here).+ await serverDB.insert(messages).values({+ id: 'locked-guard-msg',+ role: 'user',+ topicId: 'locked-guard-topic',+ userId: targetUserId,+ workspaceId: wsId1,+ });++ await expect(+ model.transferAgent(agent.id, null, userId, undefined, {+ rejectForeignMessageAuthors: true,+ }),+ ).rejects.toThrow(MESSAGE_TRANSFER_HAS_FOREIGN_AUTHORS);++ // The rejection rolled the whole transfer back+ const [topic] = await serverDB.select().from(topics).where(eq(topics.id, 'locked-guard-topic'));+ expect(topic.workspaceId).toBe(wsId1);++ // Without foreign rows the same flag lets the transfer through+ await serverDB.delete(messages).where(eq(messages.id, 'locked-guard-msg'));+ await expect(+ model.transferAgent(agent.id, null, userId, undefined, {+ rejectForeignMessageAuthors: true,+ }),+ ).resolves.toBeTruthy();+ });+it.skipIf(!isServerDB)('should serialize comment creation with the authoritative transfer check',async () => {@@ -817,6 +984,131 @@ describe('AgentModel.transferAgent', () => {});});+describe('owner deletion after transfer (snapshot re-materialization)', () => {+ it('deleting the source workspace must not cascade away transferred messages', async () => {+ const wsModel = new AgentModel(serverDB, userId, wsId1);+ const agent = await wsModel.create({ title: 'WS Agent' });++ await serverDB+ .insert(topics)+ .values({ id: 'del-ws-topic', agentId: agent.id, userId, workspaceId: wsId1 });+ await serverDB.insert(messages).values([+ {+ agentId: agent.id,+ id: 'del-ws-msg',+ role: 'tool',+ topicId: 'del-ws-topic',+ userId,+ workspaceId: wsId1,+ },+ // control: stays anchored in ws1 and must die with the workspace+ { id: 'del-ws-stay', role: 'user', userId, workspaceId: wsId1 },+ ]);+ await serverDB.insert(messagePlugins).values({+ id: 'del-ws-msg',+ identifier: 'test-plugin',+ toolCallId: 'call-del',+ userId,+ workspaceId: wsId1,+ });++ await wsModel.transferAgent(agent.id, null, userId);+ await new WorkspaceModel(serverDB, userId).delete(wsId1);++ // Transferred message + child row survive, re-snapshotted to the anchor's+ // current (personal) scope…+ const [msg] = await serverDB.select().from(messages).where(eq(messages.id, 'del-ws-msg'));+ expect(msg).toMatchObject({ userId, workspaceId: null });+ const [plugin] = await serverDB+ .select()+ .from(messagePlugins)+ .where(eq(messagePlugins.id, 'del-ws-msg'));+ expect(plugin).toMatchObject({ userId, workspaceId: null });++ // …and stay readable through scope derivation.+ const personalMessages = new MessageModel(serverDB, userId);+ expect(await personalMessages.query({ topicId: 'del-ws-topic' })).toHaveLength(1);++ // The orphan row that still belonged to the workspace is gone.+ const stay = await serverDB.select().from(messages).where(eq(messages.id, 'del-ws-stay'));+ expect(stay).toHaveLength(0);+ });++ it('deleting a workspace primary owner must not cascade away histories transferred out of their workspaces', async () => {+ await serverDB+ .insert(workspaceMembers)+ .values({ role: 'member', userId: targetUserId, workspaceId: wsId1 });++ const wsModel = new AgentModel(serverDB, userId, wsId1);+ const agent = await wsModel.create({ title: 'WS Agent' });++ await serverDB+ .insert(topics)+ .values({ id: 'del-owner-topic', agentId: agent.id, userId, workspaceId: wsId1 });+ // Authored by the teammate: snapshot is (targetUserId, wsId1) — the+ // user-keyed scrub for the deleted owner would never touch this row.+ await serverDB.insert(messages).values({+ agentId: agent.id,+ id: 'del-owner-msg',+ role: 'user',+ topicId: 'del-owner-topic',+ userId: targetUserId,+ workspaceId: wsId1,+ });++ // Move the agent into the teammate's personal scope, then delete the+ // workspace primary owner — which cascades wsId1 itself.+ await wsModel.transferAgent(agent.id, null, targetUserId);+ await UserModel.deleteUser(serverDB, userId);++ const [msg] = await serverDB.select().from(messages).where(eq(messages.id, 'del-owner-msg'));+ expect(msg).toMatchObject({ userId: targetUserId, workspaceId: null });++ const teammateMessages = new MessageModel(serverDB, targetUserId);+ expect(await teammateMessages.query({ topicId: 'del-owner-topic' })).toHaveLength(1);+ });++ it('deleting the old author must not cascade away messages transferred to another scope', async () => {+ await serverDB+ .insert(workspaceMembers)+ .values({ role: 'member', userId: targetUserId, workspaceId: wsId1 });++ const wsModel = new AgentModel(serverDB, userId, wsId1);+ const agent = await wsModel.create({ title: 'WS Agent' });++ await serverDB+ .insert(topics)+ .values({ id: 'del-user-topic', agentId: agent.id, userId, workspaceId: wsId1 });+ await serverDB.insert(messages).values([+ // authored by the teammate inside the workspace+ {+ agentId: agent.id,+ id: 'del-user-msg',+ role: 'user',+ topicId: 'del-user-topic',+ userId: targetUserId,+ workspaceId: wsId1,+ },+ // control: the teammate's own personal message still cascades away+ { id: 'del-user-personal', role: 'user', userId: targetUserId },+ ]);++ // Move the agent (and its topic) into the OTHER user's personal scope,+ // then delete the teammate who authored part of the history.+ await wsModel.transferAgent(agent.id, null, userId);+ await UserModel.deleteUser(serverDB, targetUserId);++ const [msg] = await serverDB.select().from(messages).where(eq(messages.id, 'del-user-msg'));+ expect(msg).toMatchObject({ userId, workspaceId: null });++ const personalMessages = new MessageModel(serverDB, userId);+ expect(await personalMessages.query({ topicId: 'del-user-topic' })).toHaveLength(1);++ const gone = await serverDB.select().from(messages).where(eq(messages.id, 'del-user-personal'));+ expect(gone).toHaveLength(0);+ });+});+describe('AgentModel.transferAgents (batch)', () => {it('should transfer multiple agents with their topics and messages in one call', async () => {const model = new AgentModel(serverDB, userId);@@ -828,8 +1120,20 @@ describe('AgentModel.transferAgents (batch)', () => {{ id: 'batch-topic-2', agentId: agent2.id, userId },]);await serverDB.insert(messages).values([- { id: 'batch-msg-1', agentId: agent1.id, userId, role: 'assistant' },- { id: 'batch-msg-2', agentId: agent2.id, userId, role: 'assistant' },+ {+ id: 'batch-msg-1',+ agentId: agent1.id,+ topicId: 'batch-topic-1',+ userId,+ role: 'assistant',+ },+ {+ id: 'batch-msg-2',+ agentId: agent2.id,+ topicId: 'batch-topic-2',+ userId,+ role: 'assistant',+ },]);const results = await model.transferAgents([agent1.id, agent2.id], wsId1, userId);@@ -845,9 +1149,15 @@ describe('AgentModel.transferAgents (batch)', () => {const [topic] = await serverDB.select().from(topics).where(eq(topics.id, topicId));expect(topic.workspaceId).toBe(wsId1);}- for (const msgId of ['batch-msg-1', 'batch-msg-2']) {+ // Message rows stay untouched snapshots; visibility follows the topic.+ const wsMessages = new MessageModel(serverDB, userId, wsId1);+ for (const [msgId, topicId] of [+ ['batch-msg-1', 'batch-topic-1'],+ ['batch-msg-2', 'batch-topic-2'],+ ] as const) {const [msg] = await serverDB.select().from(messages).where(eq(messages.id, msgId));- expect(msg.workspaceId).toBe(wsId1);+ expect(msg.workspaceId).toBeNull();+ expect(await wsMessages.query({ topicId })).toHaveLength(1);}});diff --git a/packages/database/src/models/__tests__/messages/message.query.test.ts b/packages/database/src/models/__tests__/messages/message.query.test.tsindex 50de99f906c..8f1acd71e3c 100644--- a/packages/database/src/models/__tests__/messages/message.query.test.ts+++ b/packages/database/src/models/__tests__/messages/message.query.test.ts@@ -1413,6 +1413,56 @@ describe('MessageModel Query Tests', () => {expect(result[0].id).toBe('2');expect(result[1].id).toBe('1');});++ it('should merge all three derivation arms in descending order', async () => {+ // Topic arm: transferred-in topic — the message keeps the previous+ // owner's snapshot but derives scope from the topic's current owner+ await serverDB+ .insert(topics)+ .values([{ id: 'qa-topic', userId, createdAt: new Date('2023-01-01') }]);+ await serverDB.insert(messages).values([+ {+ id: 'qa-topic-msg',+ userId: otherUserId,+ role: 'user',+ content: 'transferred topic message',+ topicId: 'qa-topic',+ createdAt: new Date('2023-03-01'),+ },+ // Session arm: no topic, session owned by the caller+ {+ id: 'qa-session-msg',+ userId,+ role: 'user',+ content: 'session message',+ sessionId: '1',+ createdAt: new Date('2023-02-01'),+ },+ // Orphan arm: no anchors, own snapshot+ {+ id: 'qa-orphan-msg',+ userId,+ role: 'user',+ content: 'orphan message',+ createdAt: new Date('2023-01-01'),+ },+ // Foreign orphan — must not leak in+ {+ id: 'qa-foreign-msg',+ userId: otherUserId,+ role: 'user',+ content: 'foreign message',+ createdAt: new Date('2023-04-01'),+ },+ ]);++ const result = await messageModel.queryAll();+ expect(result.map((m) => m.id)).toEqual(['qa-topic-msg', 'qa-session-msg', 'qa-orphan-msg']);++ // Pagination spans arms seamlessly+ const page2 = await messageModel.queryAll({ current: 1, pageSize: 2 });+ expect(page2.map((m) => m.id)).toEqual(['qa-orphan-msg']);+ });});describe('findById', () => {diff --git a/packages/database/src/models/__tests__/messages/message.stats.test.ts b/packages/database/src/models/__tests__/messages/message.stats.test.tsindex f14005d7b22..e54527696ec 100644--- a/packages/database/src/models/__tests__/messages/message.stats.test.ts+++ b/packages/database/src/models/__tests__/messages/message.stats.test.ts@@ -801,10 +801,12 @@ describe('MessageModel Statistics Tests', () => {{ id: 's-t3', count: 3 },{ id: 's-t4', count: 4 },];- await serverDB.insert(topics).values([- ...topicRows.map((t) => ({ id: t.id, userId, agentId, title: t.id })),- { id: 's-other', userId, agentId: otherAgentId, title: 'other' },- ]);+ await serverDB+ .insert(topics)+ .values([+ ...topicRows.map((t) => ({ id: t.id, userId, agentId, title: t.id })),+ { id: 's-other', userId, agentId: otherAgentId, title: 'other' },+ ]);const msgRows = topicRows.flatMap((t) =>Array.from({ length: t.count }).map((_, i) => ({@@ -821,7 +823,14 @@ describe('MessageModel Statistics Tests', () => {// assistant messages in agentId topics — excluded by role=user{ id: 's-t1-a', userId, role: 'assistant', content: 'a', agentId, topicId: 's-t1' },// other agent's topic- { id: 's-other-u', userId, role: 'user', content: 'x', agentId: otherAgentId, topicId: 's-other' },+ {+ id: 's-other-u',+ userId,+ role: 'user',+ content: 'x',+ agentId: otherAgentId,+ topicId: 's-other',+ },// other user must not leak{ id: 's-leak', userId: otherUserId, role: 'user', content: 'leak', topicId: 's-t1' },]);@@ -868,9 +877,10 @@ 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);+ // Scope is derived from the owning topic: the message otherUser wrote+ // into s-t1 belongs to the topic owner's scope, so otherUser sees nothing.+ 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..2f2d3af3328 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@@ -131,13 +131,16 @@ describe('MessageModel.queryTopicTranscript', () => {const model = new MessageModel(serverDB, userId);const full = await model.queryTopicTranscript({ limit: 10, offset: 0, topicId });- expect(full.total).toBe(5);+ // Scope is derived from the owning topic, so the message another user+ // wrote into this topic is part of the topic owner's transcript.+ expect(full.total).toBe(6);expect(full.items.map(({ id }) => id)).toEqual(['topic-transcript-m-a','topic-transcript-m-b','topic-transcript-m-c','topic-transcript-m-d','topic-transcript-m-e',+ 'topic-transcript-other-owner-message',]);expect(full.items[1]).toMatchObject({ content: 'legacy session message' });expect(full.items[2]).toMatchObject({ content: 'group message', role: 'supervisor' });@@ -151,12 +154,14 @@ describe('MessageModel.queryTopicTranscript', () => {});const page = await model.queryTopicTranscript({ limit: 2, offset: 1, topicId });- expect(page.total).toBe(5);+ expect(page.total).toBe(6);expect(page.items.map(({ id }) => id)).toEqual(['topic-transcript-m-b','topic-transcript-m-c',]);+ // The author of the cuckoo message does NOT see the topic owner's+ // transcript — derived scope follows the topic, not the row snapshot.await expect(new MessageModel(serverDB, otherUserId).queryTopicTranscript({limit: 10,@@ -164,8 +169,8 @@ describe('MessageModel.queryTopicTranscript', () => {topicId,}),).resolves.toEqual({- items: [expect.objectContaining({ id: 'topic-transcript-other-owner-message' })],- total: 1,+ items: [],+ total: 0,});});diff --git a/packages/database/src/models/__tests__/recent.test.ts b/packages/database/src/models/__tests__/recent.test.tsindex 8a9da50f274..7b28cfeb333 100644--- a/packages/database/src/models/__tests__/recent.test.ts+++ b/packages/database/src/models/__tests__/recent.test.ts@@ -610,6 +610,39 @@ describe('RecentModel', () => {expect(result[1].lastAssistantMessage).toBe('Last assistant answer');});+ it('still previews the last message after the topic was transferred between scopes', async () => {+ // Post-transfer state: the topic was rehomed into this user's personal+ // scope, but `messages` keeps its creation-time snapshot (old workspace,+ // teammate author) because transfers deliberately don't rewrite them.+ await serverDB.insert(workspaces).values({+ id: 'recent-transfer-ws',+ name: 'Old WS',+ primaryOwnerId: otherUserId,+ slug: 'recent-transfer-ws',+ });+ await serverDB.insert(agents).values({ id: 'agent-inbox', userId, slug: 'inbox' });+ await serverDB.insert(topics).values({+ agentId: 'agent-inbox',+ id: 'topic-transferred',+ updatedAt: minutesAgo(1),+ userId,+ });+ await serverDB.insert(messages).values({+ agentId: 'agent-inbox',+ content: 'Answer written before the transfer',+ id: 'transferred-preview-message',+ role: 'assistant',+ topicId: 'topic-transferred',+ userId: otherUserId,+ workspaceId: 'recent-transfer-ws',+ });++ const result = await recentModel.queryRecent(10, ['topic'], true);++ expect(result.map((row) => row.id)).toEqual(['topic-transferred']);+ expect(result[0].lastAssistantMessage).toBe('Answer written before the transfer');+ });+it('returns Date objects for updatedAt', async () => {await serverDB.insert(agents).values({ id: 'agent-inbox', userId, slug: 'inbox' });await serverDB.insert(topics).values({diff --git a/packages/database/src/models/agent.ts b/packages/database/src/models/agent.tsindex b6d315eeb0b..36d5bf6a4bc 100644--- a/packages/database/src/models/agent.ts+++ b/packages/database/src/models/agent.ts@@ -55,6 +55,10 @@ import {import type { LobeChatDatabase } from '../type';import { genEndDateWhere, genRangeWhere, genStartDateWhere, genWhere } from '../utils/genWhere';import { normalizeInboxAgentMeta } from '../utils/inboxAgent';+import {+ hasForeignTopicAnchoredMessageRows,+ MESSAGE_TRANSFER_HAS_FOREIGN_AUTHORS,+} from '../utils/messageScope';import { buildWorkspacePayload, buildWorkspaceWhere } from '../utils/workspace';import {hasForeignTopicComments,@@ -1672,6 +1676,12 @@ export class AgentModel {// work. NULL authors (deleted accounts) count as foreign too.if (await hasForeignTopicComments(this.db, this.userId, topicWhere!)) return true;+ // Messages / message_groups anchored to a transferred topic follow it at+ // read time (derived scope) — including teammate rows carrying only a+ // topicId (e.g. OpenAPI-created: agentId optional, sessionId always+ // null), which the direct session/agent probes below cannot see.+ if (await hasForeignTopicAnchoredMessageRows(this.db, this.userId, topicWhere!)) return true;+const messageWhere =sessionIds.length > 0? or(inArray(messages.sessionId, sessionIds), inArray(messages.agentId, agentIds))@@ -1708,7 +1718,10 @@ export class AgentModel {targetWorkspaceId: string | null,targetUserId: string,targetVisibility?: 'private' | 'public',- options: { rejectForeignTopicCommentAuthors?: boolean } = {},+ options: {+ rejectForeignMessageAuthors?: boolean;+ rejectForeignTopicCommentAuthors?: boolean;+ } = {},): Promise<{ agentId: string; slug: string | null }> => {const [result] = await this.transferAgents([agentId],@@ -1722,16 +1735,23 @@ export class AgentModel {/*** Batch variant of {@link transferAgent}: moves several agents (and their- * cascaded topics / messages / threads / tasks / …) in ONE transaction, with- * every large-table UPDATE issued once via `inArray` instead of once per- * agent. All-or-nothing: a failure on any agent rolls back the whole batch.+ * cascaded topics / threads / tasks / …) in ONE transaction, with every+ * large-table UPDATE issued once via `inArray` instead of once per agent.+ * All-or-nothing: a failure on any agent rolls back the whole batch.+ *+ * `messages` rows are deliberately left untouched — their scope is derived+ * from the owning topic/session at read time (see buildMessageScopeWhere),+ * which keeps the transfer seconds-fast regardless of history size.*/transferAgents = async (agentIds: string[],targetWorkspaceId: string | null,targetUserId: string,targetVisibility?: 'private' | 'public',- options: { rejectForeignTopicCommentAuthors?: boolean } = {},+ options: {+ rejectForeignMessageAuthors?: boolean;+ rejectForeignTopicCommentAuthors?: boolean;+ } = {},): Promise<{ agentId: string; slug: string | null }[]> => {if (agentIds.length === 0) return [];@@ -1962,6 +1982,19 @@ export class AgentModel {) {throw new Error(TOPIC_COMMENT_TRANSFER_HAS_FOREIGN_AUTHORS);}++ // Re-run the topic-anchored foreign-row check UNDER the lock: the+ // pre-transaction transferHasForeignRows call races message creation.+ // Message inserts hold FOR KEY SHARE on their topic (FK enforcement),+ // which conflicts with the FOR UPDATE above — so by this point every+ // topic-anchored insert has either committed (visible here) or is+ // blocked until this transaction ends.+ if (+ options.rejectForeignMessageAuthors &&+ (await hasForeignTopicAnchoredMessageRows(trx, this.userId, topicCondition!))+ ) {+ throw new Error(MESSAGE_TRANSFER_HAS_FOREIGN_AUTHORS);+ }const movedTopics = await trx.update(topics).set({ ...ownershipUpdate, updatedAt: topics.updatedAt })@@ -1977,15 +2010,30 @@ export class AgentModel {targetWorkspaceId,);- // 7. Update messages (linked via sessionId or agentId)- const messageCondition =- sessionIds.length > 0- ? or(inArray(messages.sessionId, sessionIds), inArray(messages.agentId, agentIds))- : inArray(messages.agentId, agentIds);+ // 7. messages (and their child tables) are intentionally NOT rewritten:+ // their scope is derived from the owning topic/session (see+ // buildMessageScopeWhere), and rewriting user_id/workspace_id on the+ // shared messages table costs minutes per heavy agent — every row update+ // maintains all 17 indexes including the multi-GB BM25 full-text index.+ // The rows' user_id/workspace_id stay as creation-time author snapshots.+ //+ // 7a. EXCEPT anchorless rows (no topic AND no session, e.g. created via+ // the OpenAPI path with only an agentId): they have nothing to derive+ // scope from — their snapshot IS authoritative — so they are the one+ // message shape a transfer must still rewrite. Bounded by agent_id and+ // rare by construction, so this stays cheap.await trx.update(messages)+ // Keep the original recency — a scope transfer does not make the+ // content newer (same rationale as the agent/topic updates above)..set({ ...ownershipUpdate, updatedAt: messages.updatedAt })- .where(messageCondition!);+ .where(+ and(+ inArray(messages.agentId, agentIds),+ isNull(messages.topicId),+ isNull(messages.sessionId),+ ),+ );// 8. Update threads (linked via agentId)await trxdiff --git a/packages/database/src/models/agentSignal/nightlyReview.ts b/packages/database/src/models/agentSignal/nightlyReview.tsindex a1b13777fff..5bb5fbad89d 100644--- a/packages/database/src/models/agentSignal/nightlyReview.ts+++ b/packages/database/src/models/agentSignal/nightlyReview.ts@@ -13,8 +13,17 @@ import {or,sql,} from 'drizzle-orm';+import { unionAll } from 'drizzle-orm/pg-core';-import { agents, messagePlugins, messages, topics, users, userSettings } from '../../schemas';+import {+ agents,+ messagePlugins,+ messages,+ sessions,+ topics,+ users,+ userSettings,+} from '../../schemas';import type { LobeChatDatabase } from '../../type';import { normalizeInboxAgentTitle } from '../../utils/inboxAgent';@@ -175,9 +184,65 @@ export class AgentSignalNightlyReviewModel {userId: string,options: ListAgentSignalNightlyReviewTargetsOptions,) => {- const effectiveAgentId = sql<string>`COALESCE(${messages.agentId}, ${topics.agentId})`;const agentFilter = options.agentId ? eq(agents.id, options.agentId) : undefined;+ // `messages.user_id` / `workspace_id` are creation-time snapshots that go+ // stale after agent transfers — derive personal-scope activity from the+ // owning topic/session instead, fanned out over the three derivation arms+ // (each index-bounded: topics/sessions by user, orphans by snapshot).+ const windowConditions = [+ gte(messages.createdAt, options.windowStart),+ lte(messages.createdAt, options.windowEnd),+ ];+ const personalTopics = and(eq(topics.userId, userId), isNull(topics.workspaceId));+ const byTopic = this.db+ .select({+ agentId: sql<string>`COALESCE(${messages.agentId}, ${topics.agentId})`.as(+ 'effective_agent_id',+ ),+ createdAt: messages.createdAt,+ id: messages.id,+ topicId: messages.topicId,+ })+ .from(messages)+ .innerJoin(topics, eq(topics.id, messages.topicId))+ .where(and(personalTopics, ...windowConditions));+ const bySession = this.db+ .select({+ agentId: sql<string>`${messages.agentId}`.as('effective_agent_id'),+ createdAt: messages.createdAt,+ id: messages.id,+ topicId: messages.topicId,+ })+ .from(messages)+ .innerJoin(sessions, eq(sessions.id, messages.sessionId))+ .where(+ and(+ isNull(messages.topicId),+ eq(sessions.userId, userId),+ isNull(sessions.workspaceId),+ ...windowConditions,+ ),+ );+ const orphans = this.db+ .select({+ agentId: sql<string>`${messages.agentId}`.as('effective_agent_id'),+ createdAt: messages.createdAt,+ id: messages.id,+ topicId: messages.topicId,+ })+ .from(messages)+ .where(+ and(+ isNull(messages.topicId),+ isNull(messages.sessionId),+ eq(messages.userId, userId),+ isNull(messages.workspaceId),+ ...windowConditions,+ ),+ );+ const activity = unionAll(byTopic, bySession, orphans).as('activity');+const query = this.db.select({agentId: agents.id,@@ -185,40 +250,27 @@ export class AgentSignalNightlyReviewModel {sql<number>`COUNT(${messagePlugins.id}) FILTER (WHERE ${messagePlugins.error} IS NOT NULL)`.mapWith(Number,),- firstActivityAt: sql<Date>`MIN(${messages.createdAt})`.mapWith(parseAggregateTimestamp),- lastActivityAt: sql<Date>`MAX(${messages.createdAt})`.mapWith(parseAggregateTimestamp),- messageCount: count(messages.id),+ firstActivityAt: sql<Date>`MIN(${activity.createdAt})`.mapWith(parseAggregateTimestamp),+ lastActivityAt: sql<Date>`MAX(${activity.createdAt})`.mapWith(parseAggregateTimestamp),+ messageCount: count(activity.id),name: agents.name,slug: agents.slug,timezone: sql<string>`COALESCE(${userSettings.general}->>'timezone', 'UTC')`,title: agents.title,- topicCount: countDistinct(messages.topicId),+ topicCount: countDistinct(activity.topicId),})- .from(messages)- .leftJoin(- topics,- and(eq(topics.id, messages.topicId), eq(topics.userId, userId), isNull(topics.workspaceId)),- )+ .from(activity).innerJoin(agents,- and(eq(agents.id, effectiveAgentId), eq(agents.userId, userId), isNull(agents.workspaceId)),+ and(eq(agents.id, activity.agentId), eq(agents.userId, userId), isNull(agents.workspaceId)),).leftJoin(userSettings, eq(userSettings.id, userId))- .leftJoin(- messagePlugins,- and(- eq(messagePlugins.id, messages.id),- eq(messagePlugins.userId, userId),- isNull(messagePlugins.workspaceId),- ),- )+ // Plugin rows carry their own stale-able snapshots — the parent message+ // is already scope-derived above, so join purely by id.+ .leftJoin(messagePlugins, eq(messagePlugins.id, activity.id)).where(and(- eq(messages.userId, userId),- isNull(messages.workspaceId),agentFilter,- gte(messages.createdAt, options.windowStart),- lte(messages.createdAt, options.windowEnd),or(eq(agents.virtual, false), isNull(agents.virtual), eq(agents.slug, INBOX_SESSION_ID)),or(eq(agents.slug, INBOX_SESSION_ID),@@ -227,7 +279,7 @@ export class AgentSignalNightlyReviewModel {),).groupBy(agents.id, agents.title, agents.name, agents.slug, userSettings.general)- .orderBy(sql`MAX(${messages.createdAt}) DESC`);+ .orderBy(sql`MAX(${activity.createdAt}) DESC`);const rows = await (options.limit !== undefined ? query.limit(options.limit) : query);diff --git a/packages/database/src/models/message.ts b/packages/database/src/models/message.tsindex 5d9cb952dbf..1d14b2291ed 100644--- a/packages/database/src/models/message.ts+++ b/packages/database/src/models/message.ts@@ -42,7 +42,7 @@ import {count,desc,eq,- gt,+ getTableColumns,gte,inArray,isNotNull,@@ -52,6 +52,7 @@ import {or,sql,} from 'drizzle-orm';+import { unionAll } from 'drizzle-orm/pg-core';import { merge } from '@/utils/merge';import { sanitizeNullBytes } from '@/utils/sanitizeNullBytes';@@ -72,13 +73,21 @@ import {messagesFiles,messageTranslates,messageTTS,+ sessions,threads,+ topics,users,} from '../schemas';import type { LobeChatDatabase, Transaction } from '../type';import { sanitizeBm25Query } from '../utils/bm25';import { genEndDateWhere, genRangeWhere, genStartDateWhere, genWhere } from '../utils/genWhere';import { idGenerator } from '../utils/idGenerator';+import {+ buildMessageChildScopeWhere,+ buildMessageScopeJoinWhere,+ buildMessageScopeWhere,+ buildTopicAnchoredScopeWhere,+} from '../utils/messageScope';import { buildWorkspacePayload, buildWorkspaceWhere } from '../utils/workspace';import { recomputeTopicUsage } from './topicUsage';import { WorkModel } from './work';@@ -371,17 +380,29 @@ export class MessageModel {this.workspaceId = workspaceId;}+ // `messages.user_id` / `messages.workspace_id` are creation-time snapshots —+ // scope is derived from the owning topic/session (see buildMessageScopeWhere),+ // so transferring an agent never has to rewrite the messages table.private ownership = () =>- buildWorkspaceWhere({ userId: this.userId, workspaceId: this.workspaceId }, messages);+ buildMessageScopeWhere({ userId: this.userId, workspaceId: this.workspaceId });private pluginsOwnership = () =>- buildWorkspaceWhere({ userId: this.userId, workspaceId: this.workspaceId }, messagePlugins);+ buildMessageChildScopeWhere(+ { userId: this.userId, workspaceId: this.workspaceId },+ messagePlugins.id,+ );private translatesOwnership = () =>- buildWorkspaceWhere({ userId: this.userId, workspaceId: this.workspaceId }, messageTranslates);+ buildMessageChildScopeWhere(+ { userId: this.userId, workspaceId: this.workspaceId },+ messageTranslates.id,+ );private ttsOwnership = () =>- buildWorkspaceWhere({ userId: this.userId, workspaceId: this.workspaceId }, messageTTS);+ buildMessageChildScopeWhere(+ { userId: this.userId, workspaceId: this.workspaceId },+ messageTTS.id,+ );private agentsToSessionsOwnership = () =>buildWorkspaceWhere({ userId: this.userId, workspaceId: this.workspaceId }, agentsToSessions);@@ -1555,7 +1576,10 @@ export class MessageModel {): Promise<UIChatMessage[]> => {// 1. Query MessageGroups for this topic, optionally filtered by time rangeconst whereConditions = [- buildWorkspaceWhere({ userId: this.userId, workspaceId: this.workspaceId }, messageGroups),+ buildTopicAnchoredScopeWhere(+ { userId: this.userId, workspaceId: this.workspaceId },+ messageGroups,+ ),eq(messageGroups.topicId, topicId),];@@ -1877,11 +1901,30 @@ export class MessageModel {const { current = 0, pageSize = 100 } = params ?? {};const offset = current * pageSize;+ // Whole-scope listing: the bare derived-scope predicate would be the only+ // filter over the shared messages table (unbounded scan) — fan out over+ // the three derivation arms instead, each bounded by its own index, and+ // let the database order/page the union (same shape as count()).+ const { topicOwned, sessionOwned, orphan } = this.scopeArms();+ const columns = getTableColumns(messages);+ const scoped = unionAll(+ this.db+ .select(columns)+ .from(messages)+ .innerJoin(topics, eq(topics.id, messages.topicId))+ .where(topicOwned),+ this.db+ .select(columns)+ .from(messages)+ .innerJoin(sessions, eq(sessions.id, messages.sessionId))+ .where(sessionOwned),+ this.db.select(columns).from(messages).where(orphan),+ ).as('scoped_messages');+const result = await this.db.select()- .from(messages)- .where(and(this.ownership()))- .orderBy(desc(messages.createdAt))+ .from(scoped)+ .orderBy(desc(scoped.createdAt)).limit(pageSize).offset(offset);@@ -1901,22 +1944,53 @@ export class MessageModel {if (!keyword.trim()) return [];const bm25Query = sanitizeBm25Query(keyword);+ // Join-based scope derivation: ParadeDB can't plan the correlated-EXISTS+ // predicate together with `@@@` ("Unsupported query shape").const result = await this.db- .select()+ .select(getTableColumns(messages)).from(messages)- .where(and(this.ownership(), sql`${messages.content} @@@ ${bm25Query}`))+ .leftJoin(topics, eq(topics.id, messages.topicId))+ .leftJoin(sessions, eq(sessions.id, messages.sessionId))+ .where(+ and(+ buildMessageScopeJoinWhere({ userId: this.userId, workspaceId: this.workspaceId }),+ sql`${messages.content} @@@ ${bm25Query}`,+ ),+ ).orderBy(desc(messages.createdAt));return result as DBMessageItem[];};/**- * Ownership-scoped analytics filter conditions, shared by count /- * countGroupByTopic / topicMessageStats. The first entry is always the- * `userId × workspace` ownership predicate; later entries are optional.+ * Whole-scope aggregates can't lean on the correlated derived-scope+ * predicate alone — without another indexed filter it degenerates into a+ * full scan of the shared messages table. Instead they fan out over the+ * three derivation arms, each bounded by its own index, and merge results:+ *+ * 1. topic-owned rows → inner join `topics` under the topic scope+ * 2. session-owned rows → `topic_id IS NULL` + inner join `sessions`+ * 3. orphan legacy rows → both anchors NULL + own snapshot columns+ */+ private scopeArms = () => {+ const ctx = { userId: this.userId, workspaceId: this.workspaceId };+ return {+ orphan: and(+ isNull(messages.topicId),+ isNull(messages.sessionId),+ buildWorkspaceWhere(ctx, messages),+ ) as SQL,+ sessionOwned: and(isNull(messages.topicId), buildWorkspaceWhere(ctx, sessions)) as SQL,+ topicOwned: buildWorkspaceWhere(ctx, topics),+ };+ };++ /**+ * Analytics filter conditions shared by count / countGroupByTopic /+ * topicMessageStats. Scope is supplied by the caller via {@link scopeArms} —+ * these are only the optional user-facing filters.*/private analyticsConditions = (params?: MessageAnalyticsFilters) => [- this.ownership(),params?.agentId ? eq(messages.agentId, params.agentId) : undefined,params?.topicId ? eq(messages.topicId, params.topicId) : undefined,params?.role ? eq(messages.role, params.role) : undefined,@@ -1932,14 +2006,28 @@ export class MessageModel {];count = async (params?: MessageAnalyticsFilters): Promise<number> => {- const result = await this.db- .select({- count: count(messages.id),- })- .from(messages)- .where(genWhere(this.analyticsConditions(params)));+ const { topicOwned, sessionOwned, orphan } = this.scopeArms();+ const conditions = this.analyticsConditions(params);+ const selection = { count: count(messages.id) };++ const results = await Promise.all([+ this.db+ .select(selection)+ .from(messages)+ .innerJoin(topics, eq(topics.id, messages.topicId))+ .where(genWhere([topicOwned, ...conditions])),+ this.db+ .select(selection)+ .from(messages)+ .innerJoin(sessions, eq(sessions.id, messages.sessionId))+ .where(genWhere([sessionOwned, ...conditions])),+ this.db+ .select(selection)+ .from(messages)+ .where(genWhere([orphan, ...conditions])),+ ]);- return result[0].count;+ return results.reduce((total, rows) => total + rows[0].count, 0);};/**@@ -1950,13 +2038,15 @@ export class MessageModel {countGroupByTopic = async (params?: MessageAnalyticsFilters,): Promise<TopicMessageCountItem[]> => {+ // Rows are keyed by topicId, so only the topic-owned arm can contribute.const rows = await this.db.select({count: count(messages.id),topicId: messages.topicId,}).from(messages)- .where(genWhere([...this.analyticsConditions(params), isNotNull(messages.topicId)]))+ .innerJoin(topics, eq(topics.id, messages.topicId))+ .where(genWhere([this.scopeArms().topicOwned, ...this.analyticsConditions(params)])).groupBy(messages.topicId).orderBy(desc(sql`count`), asc(messages.topicId));@@ -1969,13 +2059,15 @@ export class MessageModel {* counts are aggregated in the DB; only the final summary is returned.*/topicMessageStats = async (params?: MessageAnalyticsFilters): Promise<TopicMessageStats> => {+ // Rows are keyed by topicId, so only the topic-owned arm can contribute.const rows = await this.db.select({count: count(messages.id),topicId: messages.topicId,}).from(messages)- .where(genWhere([...this.analyticsConditions(params), isNotNull(messages.topicId)]))+ .innerJoin(topics, eq(topics.id, messages.topicId))+ .where(genWhere([this.scopeArms().topicOwned, ...this.analyticsConditions(params)])).groupBy(messages.topicId);return computeTopicMessageStats(rows.map((r) => r.count));@@ -2007,74 +2099,116 @@ export class MessageModel {range?: [string, string];startDate?: string;}): Promise<number> => {- const result = await this.db- .select({- count: sql<string>`sum(length(${messages.content}))`.as('total_length'),- })- .from(messages)- .where(- genWhere([- this.ownership(),- params?.range- ? genRangeWhere(params.range, messages.createdAt, (date) => date.toDate())- : undefined,- params?.endDate- ? genEndDateWhere(params.endDate, messages.createdAt, (date) => date.toDate())- : undefined,- params?.startDate- ? genStartDateWhere(params.startDate, messages.createdAt, (date) => date.toDate())- : undefined,- ]),- );+ const { topicOwned, sessionOwned, orphan } = this.scopeArms();+ const conditions = [+ params?.range+ ? genRangeWhere(params.range, messages.createdAt, (date) => date.toDate())+ : undefined,+ params?.endDate+ ? genEndDateWhere(params.endDate, messages.createdAt, (date) => date.toDate())+ : undefined,+ params?.startDate+ ? genStartDateWhere(params.startDate, messages.createdAt, (date) => date.toDate())+ : undefined,+ ];+ const selection = { count: sql<string>`sum(length(${messages.content}))`.as('total_length') };- return Number(result[0].count);+ const results = await Promise.all([+ this.db+ .select(selection)+ .from(messages)+ .innerJoin(topics, eq(topics.id, messages.topicId))+ .where(genWhere([topicOwned, ...conditions])),+ this.db+ .select(selection)+ .from(messages)+ .innerJoin(sessions, eq(sessions.id, messages.sessionId))+ .where(genWhere([sessionOwned, ...conditions])),+ this.db+ .select(selection)+ .from(messages)+ .where(genWhere([orphan, ...conditions])),+ ]);++ return results.reduce((total, rows) => total + Number(rows[0].count ?? 0), 0);};rankModels = async (limit: number = 10): Promise<ModelRankItem[]> => {- return this.db- .select({- count: count(messages.id).as('count'),- id: messages.model,- })- .from(messages)- .where(and(this.ownership(), isNotNull(messages.model)))- .having(({ count }) => gt(count, 0))- .groupBy(messages.model)- .orderBy(desc(sql`count`), asc(messages.model))- .limit(limit);+ const { topicOwned, sessionOwned, orphan } = this.scopeArms();+ const selection = { count: count(messages.id).as('count'), id: messages.model };+ const hasModel = isNotNull(messages.model);++ const results = await Promise.all([+ this.db+ .select(selection)+ .from(messages)+ .innerJoin(topics, eq(topics.id, messages.topicId))+ .where(and(topicOwned, hasModel))+ .groupBy(messages.model),+ this.db+ .select(selection)+ .from(messages)+ .innerJoin(sessions, eq(sessions.id, messages.sessionId))+ .where(and(sessionOwned, hasModel))+ .groupBy(messages.model),+ this.db.select(selection).from(messages).where(and(orphan, hasModel)).groupBy(messages.model),+ ]);++ const merged = new Map<string | null, number>();+ for (const row of results.flat()) merged.set(row.id, (merged.get(row.id) ?? 0) + row.count);++ return [...merged.entries()]+ .filter(([, cnt]) => cnt > 0)+ .sort(([modelA, countA], [modelB, countB]) =>+ countA === countB ? (modelA ?? '').localeCompare(modelB ?? '') : countB - countA,+ )+ .slice(0, limit)+ .map(([id, cnt]) => ({ count: cnt, id }));};getHeatmaps = async (): Promise<HeatmapsProps['data']> => {const startDate = today().subtract(1, 'year').startOf('day');const endDate = today().endOf('day');- const result = await this.db- .select({- count: count(messages.id),- date: sql`DATE(${messages.createdAt})`.as('heatmaps_date'),- })- .from(messages)- .where(- genWhere([- this.ownership(),- genRangeWhere(- [startDate.format('YYYY-MM-DD'), endDate.add(1, 'day').format('YYYY-MM-DD')],- messages.createdAt,- (date) => date.toDate(),- ),- ]),- )- .groupBy(sql`heatmaps_date`)- .orderBy(desc(sql`heatmaps_date`));+ const { topicOwned, sessionOwned, orphan } = this.scopeArms();+ const selection = {+ count: count(messages.id),+ date: sql`DATE(${messages.createdAt})`.as('heatmaps_date'),+ };+ const inRange = genRangeWhere(+ [startDate.format('YYYY-MM-DD'), endDate.add(1, 'day').format('YYYY-MM-DD')],+ messages.createdAt,+ (date) => date.toDate(),+ );++ const results = await Promise.all([+ this.db+ .select(selection)+ .from(messages)+ .innerJoin(topics, eq(topics.id, messages.topicId))+ .where(and(topicOwned, inRange))+ .groupBy(sql`heatmaps_date`),+ this.db+ .select(selection)+ .from(messages)+ .innerJoin(sessions, eq(sessions.id, messages.sessionId))+ .where(and(sessionOwned, inRange))+ .groupBy(sql`heatmaps_date`),+ this.db+ .select(selection)+ .from(messages)+ .where(and(orphan, inRange))+ .groupBy(sql`heatmaps_date`),+ ]);const heatmapData: HeatmapsProps['data'] = [];let currentDate = startDate.clone();const dateCountMap = new Map<string, number>();- for (const item of result) {+ for (const item of results.flat()) {if (item?.date) {const dateStr = dayjs(item.date as string).format('YYYY-MM-DD');- dateCountMap.set(dateStr, item.count);+ dateCountMap.set(dateStr, (dateCountMap.get(dateStr) ?? 0) + item.count);}}@@ -2112,35 +2246,49 @@ export class MessageModel {const startDate = today().subtract(1, 'year').startOf('day');const endDate = today().endOf('day');- const result = await this.db- .select({- date: sql`DATE(${messages.createdAt})`.as('heatmaps_date'),- tokens:- sql<number>`COALESCE(SUM((COALESCE(${messages.usage}, ${messages.metadata}->'usage')->>'totalTokens')::numeric), 0)`.mapWith(- Number,- ),- })- .from(messages)- .where(- genWhere([- this.ownership(),- eq(messages.role, 'assistant'),- genRangeWhere(- [startDate.format('YYYY-MM-DD'), endDate.add(1, 'day').format('YYYY-MM-DD')],- messages.createdAt,- (date) => date.toDate(),- ),- ]),- )- .groupBy(sql`heatmaps_date`)- .orderBy(desc(sql`heatmaps_date`));+ const { topicOwned, sessionOwned, orphan } = this.scopeArms();+ const selection = {+ date: sql`DATE(${messages.createdAt})`.as('heatmaps_date'),+ tokens:+ sql<number>`COALESCE(SUM((COALESCE(${messages.usage}, ${messages.metadata}->'usage')->>'totalTokens')::numeric), 0)`.mapWith(+ Number,+ ),+ };+ const filters = and(+ eq(messages.role, 'assistant'),+ genRangeWhere(+ [startDate.format('YYYY-MM-DD'), endDate.add(1, 'day').format('YYYY-MM-DD')],+ messages.createdAt,+ (date) => date.toDate(),+ ),+ );++ const results = await Promise.all([+ this.db+ .select(selection)+ .from(messages)+ .innerJoin(topics, eq(topics.id, messages.topicId))+ .where(and(topicOwned, filters))+ .groupBy(sql`heatmaps_date`),+ this.db+ .select(selection)+ .from(messages)+ .innerJoin(sessions, eq(sessions.id, messages.sessionId))+ .where(and(sessionOwned, filters))+ .groupBy(sql`heatmaps_date`),+ this.db+ .select(selection)+ .from(messages)+ .where(and(orphan, filters))+ .groupBy(sql`heatmaps_date`),+ ]);const dateTokenMap = new Map<string, number>();let maxTokens = 0;- for (const item of result) {+ for (const item of results.flat()) {if (item?.date) {const dateStr = dayjs(item.date as string).format('YYYY-MM-DD');- const tokens = item.tokens || 0;+ const tokens = (dateTokenMap.get(dateStr) ?? 0) + (item.tokens || 0);dateTokenMap.set(dateStr, tokens);if (tokens > maxTokens) maxTokens = tokens;}@@ -2172,26 +2320,43 @@ export class MessageModel {};hasMoreThanN = async (n: number): Promise<boolean> => {- const result = await this.db- .select({ id: messages.id })- .from(messages)- .where(and(this.ownership()))- .limit(n + 1);-- return result.length > n;+ return (await this.countUpTo(n + 1)) > n;};/**- * Count messages up to a limit, useful for avoiding full table scans+ * Count messages up to a limit, useful for avoiding full table scans.+ * Walks the scope-derivation arms in order and stops as soon as `n` rows+ * are found, so each probe stays index-bounded.*/countUpTo = async (n: number): Promise<number> => {- const result = await this.db+ const { topicOwned, sessionOwned, orphan } = this.scopeArms();+ let found = 0;++ const byTopic = await this.db.select({ id: messages.id }).from(messages)- .where(and(this.ownership()))+ .innerJoin(topics, eq(topics.id, messages.topicId))+ .where(topicOwned).limit(n);+ found += byTopic.length;+ if (found >= n) return n;++ const bySession = await this.db+ .select({ id: messages.id })+ .from(messages)+ .innerJoin(sessions, eq(sessions.id, messages.sessionId))+ .where(sessionOwned)+ .limit(n - found);+ found += bySession.length;+ if (found >= n) return n;- return result.length;+ const orphans = await this.db+ .select({ id: messages.id })+ .from(messages)+ .where(orphan)+ .limit(n - found);++ return found + orphans.length;};// **************** Create *************** //@@ -2615,9 +2780,13 @@ export class MessageModel {};updatePluginState = async (id: string, state: Record<string, any>): Promise<void> => {- const item = await this.db.query.messagePlugins.findFirst({- where: and(eq(messagePlugins.id, id), this.pluginsOwnership()),- });+ // Plain select instead of RQB findFirst: RQB aliases the table, which+ // breaks the correlated EXISTS inside pluginsOwnership().+ const [item] = await this.db+ .select()+ .from(messagePlugins)+ .where(and(eq(messagePlugins.id, id), this.pluginsOwnership()))+ .limit(1);if (!item) throw new Error('Plugin not found');await this.db@@ -2627,9 +2796,11 @@ export class MessageModel {};updateMessagePlugin = async (id: string, value: Partial<MessagePluginItem>) => {- const item = await this.db.query.messagePlugins.findFirst({- where: and(eq(messagePlugins.id, id), this.pluginsOwnership()),- });+ const [item] = await this.db+ .select()+ .from(messagePlugins)+ .where(and(eq(messagePlugins.id, id), this.pluginsOwnership()))+ .limit(1);if (!item) throw new Error('Plugin not found');return this.db@@ -2650,9 +2821,11 @@ export class MessageModel {* `undefined`.*/findMessagePlugin = async (messageId: string): Promise<MessagePluginItem | undefined> => {- const row = await this.db.query.messagePlugins.findFirst({- where: and(eq(messagePlugins.id, messageId), this.pluginsOwnership()),- });+ const [row] = await this.db+ .select()+ .from(messagePlugins)+ .where(and(eq(messagePlugins.id, messageId), this.pluginsOwnership()))+ .limit(1);if (!row) return undefined;return {apiName: row.apiName ?? undefined,@@ -2890,9 +3063,11 @@ export class MessageModel {// Update messagePlugins table (pluginState, pluginError)if (pluginState !== undefined || pluginError !== undefined) {- const pluginItem = await trx.query.messagePlugins.findFirst({- where: and(eq(messagePlugins.id, id), this.pluginsOwnership()),- });+ const [pluginItem] = await trx+ .select()+ .from(messagePlugins)+ .where(and(eq(messagePlugins.id, id), this.pluginsOwnership()))+ .limit(1);// A plugin-only patch never touches `messages`, so the plugin row is// the only evidence the tool message exists.@@ -3133,9 +3308,11 @@ export class MessageModel {};updateTranslate = async (id: string, translate: Partial<ChatTranslate>) => {- const result = await this.db.query.messageTranslates.findFirst({- where: and(eq(messageTranslates.id, id), this.translatesOwnership()),- });+ const [result] = await this.db+ .select()+ .from(messageTranslates)+ .where(and(eq(messageTranslates.id, id), this.translatesOwnership()))+ .limit(1);// If the message does not exist in the translate table, insert itif (!result) {@@ -3159,9 +3336,11 @@ export class MessageModel {// Older clients sent an empty payload when starting TTS, so keep this backward-compatible.if ([contentMd5, file, voice].every((value) => value === undefined)) return;- const result = await this.db.query.messageTTS.findFirst({- where: and(eq(messageTTS.id, id), this.ttsOwnership()),- });+ const [result] = await this.db+ .select()+ .from(messageTTS)+ .where(and(eq(messageTTS.id, id), this.ttsOwnership()))+ .limit(1);// If the message does not exist in the TTS table, insert itif (!result) {@@ -3483,9 +3662,9 @@ export class MessageModel {.where(and(eq(messageQueries.id, id),- buildWorkspaceWhere(+ buildMessageChildScopeWhere({ userId: this.userId, workspaceId: this.workspaceId },- messageQueries,+ messageQueries.messageId,),),);@@ -3507,7 +3686,43 @@ export class MessageModel {);deleteAllMessages = async () => {- return this.db.delete(messages).where(and(this.ownership()));+ // Whole-scope delete: drive each derivation arm from its own index instead+ // of filtering the shared messages table with the correlated predicate.+ const ctx = { userId: this.userId, workspaceId: this.workspaceId };++ return this.db.transaction(async (tx) => {+ await tx+ .delete(messages)+ .where(+ inArray(+ messages.topicId,+ tx.select({ id: topics.id }).from(topics).where(buildWorkspaceWhere(ctx, topics)),+ ),+ );+ await tx+ .delete(messages)+ .where(+ and(+ isNull(messages.topicId),+ inArray(+ messages.sessionId,+ tx+ .select({ id: sessions.id })+ .from(sessions)+ .where(buildWorkspaceWhere(ctx, sessions)),+ ),+ ),+ );+ await tx+ .delete(messages)+ .where(+ and(+ isNull(messages.topicId),+ isNull(messages.sessionId),+ buildWorkspaceWhere(ctx, messages),+ ),+ );+ });};/**diff --git a/packages/database/src/models/recent.ts b/packages/database/src/models/recent.tsindex a7a7db1f6e6..aca14f654b6 100644--- a/packages/database/src/models/recent.ts+++ b/packages/database/src/models/recent.ts@@ -73,11 +73,14 @@ export class RecentModel {value: sql<string>`left(${messages.content}, ${LAST_MESSAGE_PREVIEW_LENGTH + 1})`,}).from(messages)+ // No scope predicate on `messages`: its user_id/workspace_id are+ // creation-time snapshots that go stale after an agent transfer, and the+ // correlation to `topics.id` already inherits the topic arm's scope check+ // below — which is the message's authoritative scope (see messageScope.ts)..where(and(eq(messages.topicId, topics.id),eq(messages.role, 'assistant'),- buildWorkspaceWhere(scope, messages),ne(messages.content, ''),),)diff --git a/packages/database/src/models/topic.ts b/packages/database/src/models/topic.tsindex ade3d1b1007..92b9f069417 100644--- a/packages/database/src/models/topic.ts+++ b/packages/database/src/models/topic.ts@@ -46,6 +46,7 @@ import type { LobeChatDatabase } from '../type';import { sanitizeBm25Query } from '../utils/bm25';import { genEndDateWhere, genRangeWhere, genStartDateWhere, genWhere } from '../utils/genWhere';import { idGenerator } from '../utils/idGenerator';+import { buildMessageScopeWhere } from '../utils/messageScope';import { buildWorkspacePayload, buildWorkspaceWhere } from '../utils/workspace';import { recomputeTopicUsage } from './topicUsage';@@ -249,7 +250,7 @@ export class TopicModel {private mine = () => and(this.ownership(), eq(topics.userId, this.userId));private messageOwnership = () =>- buildWorkspaceWhere({ userId: this.userId, workspaceId: this.workspaceId }, messages);+ buildMessageScopeWhere({ userId: this.userId, workspaceId: this.workspaceId });// **************** Query *************** //query = async ({@@ -384,7 +385,7 @@ export class TopicModel {// display `updatedAt` above matches the client-side sort key to the server// order (otherwise the two disagree and the list visibly jumps) while a// rename/favorite edit still shows its real edit time. See rankTopics for- // the same activity-time pattern.+ // the same activity-time pattern.sortUpdatedAt: topicActivityAt,// Workspace sidebars filter maintenance actions client-side by// ownership (own vs workspace scope) — the filter needs the row@@ -460,7 +461,7 @@ export class TopicModel {// display `updatedAt` above matches the client-side sort key to the server// order (otherwise the two disagree and the list visibly jumps) while a// rename/favorite edit still shows its real edit time. See rankTopics for- // the same activity-time pattern.+ // the same activity-time pattern.sortUpdatedAt: topicActivityAt,// Workspace sidebars filter maintenance actions client-side by// ownership (own vs workspace scope) — the filter needs the row@@ -532,7 +533,7 @@ export class TopicModel {// display `updatedAt` above matches the client-side sort key to the server// order (otherwise the two disagree and the list visibly jumps) while a// rename/favorite edit still shows its real edit time. See rankTopics for- // the same activity-time pattern.+ // the same activity-time pattern.sortUpdatedAt: topicActivityAt,// Workspace sidebars filter maintenance actions client-side by// ownership (own vs workspace scope) — the filter needs the row@@ -748,19 +749,15 @@ export class TopicModel {.from(topics).where(and(this.ownership(), scopeCondition, sql`${topics.title} @@@ ${bm25Query}`)).orderBy(desc(topics.updatedAt)),- // Query topic IDs matching by message content (BM25)+ // Query topic IDs matching by message content (BM25). Scope comes from+ // the joined, ownership-filtered topics — message rows carry only+ // creation-time snapshots, and ParadeDB can't plan the derived EXISTS+ // predicate together with `@@@` anyway.this.db.select({ topicId: messages.topicId }).from(messages).innerJoin(topics, eq(messages.topicId, topics.id))- .where(- and(- this.messageOwnership(),- sql`${messages.content} @@@ ${bm25Query}`,- this.ownership(),- scopeCondition,- ),- )+ .where(and(sql`${messages.content} @@@ ${bm25Query}`, this.ownership(), scopeCondition)).groupBy(messages.topicId),]);// If no topics found by message content, return topics matching by titlediff --git a/packages/database/src/models/user.ts b/packages/database/src/models/user.tsindex 3504eb1c449..5c9a4b719b1 100644--- a/packages/database/src/models/user.ts+++ b/packages/database/src/models/user.ts@@ -15,8 +15,9 @@ import { merge } from '@/utils/merge';import { today } from '@/utils/time';import type { NewUser, UserItem, UserSettingsItem } from '../schemas';-import { messages, nextauthAccounts, topics, users, userSettings } from '../schemas';+import { messages, nextauthAccounts, topics, users, userSettings, workspaces } from '../schemas';import type { LobeChatDatabase } from '../type';+import { resnapshotTransferredMessagesBeforeOwnerDelete } from '../utils/messageScope';type DecryptUserKeyVaults = (encryptKeyVaultsStr: string | null,@@ -343,7 +344,25 @@ export class UserModel {};static deleteUser = async (db: LobeChatDatabase, id: string) => {- return db.delete(users).where(eq(users.id, id));+ return db.transaction(async (tx) => {+ // Deleting a user also cascades every workspace they primary-own, and+ // those cascade further through messages.workspace_id — so each owned+ // workspace needs its own scrub (rows transferred away can carry the+ // old workspace snapshot under a DIFFERENT author user_id).+ const ownedWorkspaces = await tx+ .select({ id: workspaces.id })+ .from(workspaces)+ .where(eq(workspaces.primaryOwnerId, id));+ for (const workspace of ownedWorkspaces) {+ await resnapshotTransferredMessagesBeforeOwnerDelete(tx, { workspaceId: workspace.id });+ }++ // Messages transferred out of this user's scope still carry the user in+ // their snapshot user_id (cascade FK) — re-snapshot them from their+ // anchor first, or the delete below would destroy transferred history.+ await resnapshotTransferredMessagesBeforeOwnerDelete(tx, { userId: id });+ return tx.delete(users).where(eq(users.id, id));+ });};static findById = async (db: LobeChatDatabase, id: string) => {diff --git a/packages/database/src/models/workspace.ts b/packages/database/src/models/workspace.tsindex 7ec9a38ea65..498c884e809 100644--- a/packages/database/src/models/workspace.ts+++ b/packages/database/src/models/workspace.ts@@ -7,6 +7,7 @@ import {workspaces,} from '../schemas/workspace';import type { LobeChatDatabase } from '../type';+import { resnapshotTransferredMessagesBeforeOwnerDelete } from '../utils/messageScope';const getActiveMembershipRole = async (db: LobeChatDatabase,@@ -96,9 +97,24 @@ export class WorkspaceModel {};delete = async (id: string) => {- return this.db- .delete(workspaces)- .where(and(eq(workspaces.id, id), eq(workspaces.primaryOwnerId, this.userId)));+ return this.db.transaction(async (tx) => {+ // Only the primary owner may delete — verify BEFORE the resnapshot+ // below, so an unauthorized caller cannot trigger the scrub's writes.+ const [owned] = await tx+ .select({ id: workspaces.id })+ .from(workspaces)+ .where(and(eq(workspaces.id, id), eq(workspaces.primaryOwnerId, this.userId)))+ .limit(1);+ if (!owned) return;++ // Messages transferred OUT of this workspace still carry it in their+ // snapshot workspace_id (cascade FK) — re-snapshot them from their+ // anchor first, or the delete below would destroy transferred history.+ await resnapshotTransferredMessagesBeforeOwnerDelete(tx, { workspaceId: id });+ return tx+ .delete(workspaces)+ .where(and(eq(workspaces.id, id), eq(workspaces.primaryOwnerId, this.userId)));+ });};findById = async (id: string) => {diff --git a/packages/database/src/repositories/agentGroup/index.test.ts b/packages/database/src/repositories/agentGroup/index.test.tsindex de4c009dc67..425887c20c0 100644--- a/packages/database/src/repositories/agentGroup/index.test.ts+++ b/packages/database/src/repositories/agentGroup/index.test.ts@@ -12,12 +12,13 @@ import {} from '../../models/topicComment';import { agents } from '../../schemas/agent';import { chatGroups, chatGroupsAgents } from '../../schemas/chatGroup';-import { messagePlugins, messages } from '../../schemas/message';+import { messageGroups, messagePlugins, messages } from '../../schemas/message';import { threads, topics } from '../../schemas/topic';import { topicCommentMentions, topicComments } from '../../schemas/topicComment';import { users } from '../../schemas/user';import { workspaces } from '../../schemas/workspace';import type { LobeChatDatabase } from '../../type';+import { MESSAGE_TRANSFER_HAS_FOREIGN_AUTHORS } from '../../utils/messageScope';import { AgentGroupRepository } from './index';const userId = 'agent-group-test-user';@@ -1662,6 +1663,96 @@ describe('AgentGroupRepository', () => {expect(await wsRepo.transferHasForeignRows('guard-group')).toBe(true);});+ it('flags topic-only teammate messages and message groups as foreign transfer rows', async () => {+ await serverDB.insert(chatGroups).values({+ id: 'anchor-guard-group',+ title: 'Anchor Guard Group',+ userId,+ workspaceId,+ });+ await serverDB.insert(topics).values({+ groupId: 'anchor-guard-group',+ id: 'anchor-guard-group-topic',+ title: 'Own Topic',+ userId,+ workspaceId,+ });++ const wsRepo = new AgentGroupRepository(serverDB, userId, workspaceId);++ // Caller's own topic-only message — not foreign+ await serverDB.insert(messages).values({+ id: 'anchor-guard-group-own',+ role: 'user',+ topicId: 'anchor-guard-group-topic',+ userId,+ workspaceId,+ });+ expect(await wsRepo.transferHasForeignRows('anchor-guard-group')).toBe(false);++ // A teammate's message carrying ONLY a topicId (no groupId/sessionId)+ // follows the transferred topic under derived scope — the direct+ // groupId probe alone cannot see it+ await serverDB.insert(messages).values({+ id: 'anchor-guard-group-teammate',+ role: 'user',+ topicId: 'anchor-guard-group-topic',+ userId: otherUserId,+ workspaceId,+ });+ expect(await wsRepo.transferHasForeignRows('anchor-guard-group')).toBe(true);++ // Same for a teammate's message group anchored to the caller's topic+ await serverDB.delete(messages).where(eq(messages.id, 'anchor-guard-group-teammate'));+ expect(await wsRepo.transferHasForeignRows('anchor-guard-group')).toBe(false);+ await serverDB.insert(messageGroups).values({+ id: 'anchor-guard-group-mg',+ topicId: 'anchor-guard-group-topic',+ userId: otherUserId,+ workspaceId,+ });+ expect(await wsRepo.transferHasForeignRows('anchor-guard-group')).toBe(true);+ });++ it('rechecks topic-anchored teammate rows inside the group transfer transaction', async () => {+ await serverDB.insert(chatGroups).values({+ id: 'locked-guard-group',+ title: 'Locked Guard Group',+ userId,+ workspaceId,+ });+ await serverDB.insert(topics).values({+ groupId: 'locked-guard-group',+ id: 'locked-guard-group-topic',+ title: 'Own Topic',+ userId,+ workspaceId,+ });+ // Teammate topic-only row present when the transaction rechecks under+ // the topic lock (the precheck is deliberately skipped here).+ await serverDB.insert(messages).values({+ id: 'locked-guard-group-msg',+ role: 'user',+ topicId: 'locked-guard-group-topic',+ userId: otherUserId,+ workspaceId,+ });++ const wsRepo = new AgentGroupRepository(serverDB, userId, workspaceId);+ await expect(+ wsRepo.transferToWorkspace('locked-guard-group', null, userId, undefined, {+ rejectForeignMessageAuthors: true,+ }),+ ).rejects.toThrow(MESSAGE_TRANSFER_HAS_FOREIGN_AUTHORS);++ // The rejection rolled the whole transfer back+ const [topic] = await serverDB+ .select()+ .from(topics)+ .where(eq(topics.id, 'locked-guard-group-topic'));+ expect(topic.workspaceId).toBe(workspaceId);+ });+it.skipIf(!isServerDB)('serializes comment creation with the authoritative group transfer check',async () => {diff --git a/packages/database/src/repositories/agentGroup/index.ts b/packages/database/src/repositories/agentGroup/index.tsindex 71293eb16f4..884981b4ea2 100644--- a/packages/database/src/repositories/agentGroup/index.ts+++ b/packages/database/src/repositories/agentGroup/index.ts@@ -29,6 +29,12 @@ import {import type { LobeChatDatabase } from '../../type';import { idGenerator } from '../../utils/idGenerator';import { normalizeInboxAgentMeta } from '../../utils/inboxAgent';+import {+ buildMessageChildScopeWhere,+ buildMessageScopeWhere,+ hasForeignTopicAnchoredMessageRows,+ MESSAGE_TRANSFER_HAS_FOREIGN_AUTHORS,+} from '../../utils/messageScope';import { buildWorkspaceWhere } from '../../utils/workspace';interface CopyAgentGroupToWorkspaceOptions {@@ -111,9 +117,14 @@ export class AgentGroupRepository {private threadOwnership = () =>buildWorkspaceWhere({ userId: this.userId, workspaceId: this.workspaceId }, threads);private messageOwnership = () =>- buildWorkspaceWhere({ userId: this.userId, workspaceId: this.workspaceId }, messages);+ buildMessageScopeWhere({ userId: this.userId, workspaceId: this.workspaceId });+ // Child snapshots drift after agent transfer — derive from the parent+ // message instead of trusting the row's own user_id/workspace_id.private messagePluginOwnership = () =>- buildWorkspaceWhere({ userId: this.userId, workspaceId: this.workspaceId }, messagePlugins);+ buildMessageChildScopeWhere(+ { userId: this.userId, workspaceId: this.workspaceId },+ messagePlugins.id,+ );private buildCopiedAgent = (source: AgentItem | undefined,@@ -265,9 +276,12 @@ export class AgentGroupRepository {if (sourceMessages.length === 0) return;const sourceMessageIds = sourceMessages.map((message) => message.id);- const sourcePlugins = await executor.query.messagePlugins.findMany({- where: and(this.messagePluginOwnership(), inArray(messagePlugins.id, sourceMessageIds)),- });+ // Plain select instead of RQB findMany: RQB aliases the table, which+ // breaks the correlated EXISTS inside messagePluginOwnership().+ const sourcePlugins = await executor+ .select()+ .from(messagePlugins)+ .where(and(this.messagePluginOwnership(), inArray(messagePlugins.id, sourceMessageIds)));const messageRows = sourceMessages.map((message) => {const newMessageId = messageIdMap.get(message.id)!;@@ -877,6 +891,12 @@ export class AgentGroupRepository {if (await hasForeignTopicComments(this.db, this.userId, eq(topics.groupId, groupId)))return true;+ // Messages / message_groups anchored to a transferred topic follow it at+ // read time (derived scope) — including teammate rows carrying only a+ // topicId, which the direct groupId probe below cannot see.+ if (await hasForeignTopicAnchoredMessageRows(this.db, this.userId, eq(topics.groupId, groupId)))+ return true;+const [foreignThread] = await this.db.select({ id: threads.id }).from(threads)@@ -897,7 +917,10 @@ export class AgentGroupRepository {targetWorkspaceId: string | null,targetUserId: string,targetVisibility?: 'private' | 'public',- options: { rejectForeignTopicCommentAuthors?: boolean } = {},+ options: {+ rejectForeignMessageAuthors?: boolean;+ rejectForeignTopicCommentAuthors?: boolean;+ } = {},): Promise<{ groupId: string } | null> {const sourceGroup = await this.db.query.chatGroups.findFirst({where: and(eq(chatGroups.id, groupId), this.groupOwnership()),@@ -991,6 +1014,16 @@ export class AgentGroupRepository {throw new Error(TOPIC_COMMENT_TRANSFER_HAS_FOREIGN_AUTHORS);}+ // Re-run the topic-anchored foreign-row check UNDER the lock — the+ // precheck races message creation; see AgentModel.transferAgents for+ // the FOR KEY SHARE / FOR UPDATE serialization argument.+ if (+ options.rejectForeignMessageAuthors &&+ (await hasForeignTopicAnchoredMessageRows(trx, this.userId, eq(topics.groupId, groupId)))+ ) {+ throw new Error(MESSAGE_TRANSFER_HAS_FOREIGN_AUTHORS);+ }+const movedTopics = await trx.update(topics).set(ownershipUpdate)diff --git a/packages/database/src/repositories/agentMigration/index.ts b/packages/database/src/repositories/agentMigration/index.tsindex fe2882a33d2..ffd71e2b93e 100644--- a/packages/database/src/repositories/agentMigration/index.ts+++ b/packages/database/src/repositories/agentMigration/index.ts@@ -3,6 +3,7 @@ import type { AnyPgColumn } from 'drizzle-orm/pg-core';import { agents, agentsToSessions, messages, sessions, topics } from '../../schemas';import type { LobeChatDatabase } from '../../type';+import { buildMessageScopeWhere } from '../../utils/messageScope';import { buildWorkspaceWhere } from '../../utils/workspace';type MigrateBySessionParams = { agentId: string; sessionId: string };@@ -29,6 +30,12 @@ export class AgentMigrationRepo {private ws = (cols: { userId: AnyPgColumn; workspaceId: AnyPgColumn }) =>buildWorkspaceWhere({ userId: this.userId, workspaceId: this.workspaceId }, cols);+ // messages.user_id/workspace_id are creation-time snapshots — the ownership+ // guard on message writes derives from the owning topic/session instead, so+ // legacy rows stay reachable after their agent was transferred across scopes.+ private messagesWs = (db: LobeChatDatabase) =>+ buildMessageScopeWhere({ userId: this.userId, workspaceId: this.workspaceId });+/*** Runtime migration: backfill agentId for all legacy topics and messages* Used for progressive migration so future queries don't need agentsToSessions lookup@@ -92,7 +99,9 @@ export class AgentMigrationRepo {await tx.update(messages).set({ agentId, updatedAt: messages.updatedAt })- .where(and(this.ws(messages), inArray(messages.topicId, topicIds), isNull(messages.agentId)));+ .where(+ and(this.messagesWs(tx), inArray(messages.topicId, topicIds), isNull(messages.agentId)),+ );// 4. Also update messages without topicId but in inbox (sessionId IS NULL) - preserve original updatedAtawait tx@@ -100,7 +109,7 @@ export class AgentMigrationRepo {.set({ agentId, updatedAt: messages.updatedAt }).where(and(- this.ws(messages),+ this.messagesWs(tx),isNull(messages.sessionId),isNull(messages.topicId),isNull(messages.agentId),@@ -135,7 +144,7 @@ export class AgentMigrationRepo {.update(messages).set({ agentId, updatedAt: messages.updatedAt }).where(- and(this.ws(messages), inArray(messages.topicId, topicIds), isNull(messages.agentId)),+ and(this.messagesWs(tx), inArray(messages.topicId, topicIds), isNull(messages.agentId)),);}@@ -145,7 +154,7 @@ export class AgentMigrationRepo {.set({ agentId, updatedAt: messages.updatedAt }).where(and(- this.ws(messages),+ this.messagesWs(tx),eq(messages.sessionId, sessionId),isNull(messages.topicId),isNull(messages.agentId),diff --git a/packages/database/src/repositories/compression/index.ts b/packages/database/src/repositories/compression/index.tsindex 7a0fa7d3c0d..d4a96712ded 100644--- a/packages/database/src/repositories/compression/index.ts+++ b/packages/database/src/repositories/compression/index.ts@@ -5,7 +5,7 @@ import { and, eq, inArray, isNull } from 'drizzle-orm';import type { MessageGroupItem } from '../../schemas';import { messageGroups, messages } from '../../schemas';import type { LobeChatDatabase } from '../../type';-import { buildWorkspaceWhere } from '../../utils/workspace';+import { buildMessageScopeWhere, buildTopicAnchoredScopeWhere } from '../../utils/messageScope';export interface CreateCompressionGroupParams {content: string;@@ -47,11 +47,16 @@ export class CompressionRepository {this.workspaceId = workspaceId;}+ // messages / message_groups carry only creation-time scope snapshots — the+ // authoritative scope is derived from the owning topic (see messageScope.ts).private groupsOwnership = () =>- buildWorkspaceWhere({ userId: this.userId, workspaceId: this.workspaceId }, messageGroups);+ buildTopicAnchoredScopeWhere(+ { userId: this.userId, workspaceId: this.workspaceId },+ messageGroups,+ );private messagesOwnership = () =>- buildWorkspaceWhere({ userId: this.userId, workspaceId: this.workspaceId }, messages);+ buildMessageScopeWhere({ userId: this.userId, workspaceId: this.workspaceId });/*** Create a compression group and mark messages as compresseddiff --git a/packages/database/src/repositories/dataExporter/index.ts b/packages/database/src/repositories/dataExporter/index.tsindex 3db81b32586..9f61ac6c44d 100644--- a/packages/database/src/repositories/dataExporter/index.ts+++ b/packages/database/src/repositories/dataExporter/index.ts@@ -1,10 +1,26 @@-import { and, eq, inArray } from 'drizzle-orm';+import type { SQL } from 'drizzle-orm';+import { and, eq, getTableColumns, inArray, isNull } from 'drizzle-orm';+import type { PgTable } from 'drizzle-orm/pg-core';import pMap from 'p-map';import * as EXPORT_TABLES from '../../schemas';import type { LobeChatDatabase } from '../../type';+import { buildMessageChildScopeWhere } from '../../utils/messageScope';import { buildWorkspaceWhere } from '../../utils/workspace';+/**+ * Message-family tables carry only creation-time scope snapshots; their+ * authoritative scope is derived from the owning topic/session, so exports+ * must use the derived predicates instead of the snapshot columns.+ */+const DERIVED_SCOPE_TABLES: Partial<+ Record<keyof typeof EXPORT_TABLES, (ctx: { userId: string; workspaceId?: string }) => SQL>+> = {+ messageChunks: (ctx) => buildMessageChildScopeWhere(ctx, EXPORT_TABLES.messageChunks.messageId),+ messagePlugins: (ctx) => buildMessageChildScopeWhere(ctx, EXPORT_TABLES.messagePlugins.id),+ messageTranslates: (ctx) => buildMessageChildScopeWhere(ctx, EXPORT_TABLES.messageTranslates.id),+};+interface BaseTableConfig {table: keyof typeof EXPORT_TABLES;type: 'base';@@ -99,6 +115,42 @@ export class DataExporterRepos {});}+ /**+ * Export `messages` across the three scope-derivation arms (topic-owned /+ * session-owned / orphan), each bounded by its own index — the snapshot+ * `user_id`/`workspace_id` columns must not be used as scope filters.+ */+ private async queryMessages() {+ const ctx = { userId: this.userId, workspaceId: this.workspaceId };+ const { messages, sessions, topics } = EXPORT_TABLES;+ const columns = getTableColumns(messages);++ const [byTopic, bySession, orphans] = await Promise.all([+ this.db+ .select(columns)+ .from(messages)+ .innerJoin(topics, eq(topics.id, messages.topicId))+ .where(buildWorkspaceWhere(ctx, topics)),+ this.db+ .select(columns)+ .from(messages)+ .innerJoin(sessions, eq(sessions.id, messages.sessionId))+ .where(and(isNull(messages.topicId), buildWorkspaceWhere(ctx, sessions))),+ this.db+ .select(columns)+ .from(messages)+ .where(+ and(+ isNull(messages.topicId),+ isNull(messages.sessionId),+ buildWorkspaceWhere(ctx, messages),+ ),+ ),+ ]);++ return [...byTopic, ...bySession, ...orphans];+ }+private async queryTable(config: RelationTableConfig, existingData: Record<string, any[]>) {const { table } = config;const tableObj = EXPORT_TABLES[table];@@ -160,15 +212,32 @@ export class DataExporterRepos {// If there's relation config, use relation query+ // messages needs the three-arm derived-scope export (see queryMessages) —+ // a plain where over the shared table would have no index to bound it.+ if (table === 'messages') {+ const result = await this.queryMessages();+ console.info(`Successfully exported table: ${table}, count: ${result.length}`);+ return this.removeUserId(result);+ }+// Default to querying with userId, use userField for special casesconst userField = config.userField || 'userId';- const where =- 'workspaceId' in tableObj+ const derivedScope = DERIVED_SCOPE_TABLES[table];+ const where = derivedScope+ ? derivedScope({ userId: this.userId, workspaceId: this.workspaceId })+ : 'workspaceId' in tableObj? buildWorkspaceWhere({ userId: this.userId, workspaceId: this.workspaceId }, tableObj): eq(tableObj[userField], this.userId);- // @ts-expect-error query- const result = await this.db.query[table].findMany({ where });+ // Derived-scope tables must NOT go through RQB: it aliases the table,+ // which breaks the correlated EXISTS inside the derived predicate.+ const result = derivedScope+ ? await this.db+ .select()+ .from(tableObj as PgTable)+ .where(where)+ : // @ts-expect-error query+ await this.db.query[table].findMany({ where });// Only remove userId field for tables queried with userIdconsole.info(`Successfully exported table: ${table}, count: ${result.length}`);diff --git a/packages/database/src/repositories/search/index.ts b/packages/database/src/repositories/search/index.tsindex 02d7137e1be..f3ba5544e08 100644--- a/packages/database/src/repositories/search/index.ts+++ b/packages/database/src/repositories/search/index.ts@@ -1,4 +1,15 @@-import { and, desc, eq, inArray, isNull, ne, type SQL, sql, type SQLWrapper } from 'drizzle-orm';+import {+ and,+ desc,+ eq,+ inArray,+ isNull,+ ne,+ or,+ type SQL,+ sql,+ type SQLWrapper,+} from 'drizzle-orm';import type { AnyPgColumn } from 'drizzle-orm/pg-core';import {@@ -10,12 +21,15 @@ import {knowledgeBaseFiles,knowledgeBases,messages,+ sessions,topics,userMemories,+ workspaceMembers,} from '../../schemas';import type { LobeChatDatabase } from '../../type';import { sanitizeBm25Query } from '../../utils/bm25';import { normalizeInboxAgentMeta, normalizeInboxAgentTitle } from '../../utils/inboxAgent';+import { buildMessageScopeJoinWhere } from '../../utils/messageScope';import { buildWorkspaceWhere } from '../../utils/workspace';export type SearchResultType =@@ -729,6 +743,40 @@ export class SearchRepo {const candidateLimit = limit * RECENCY_CANDIDATE_MULTIPLIER;+ // messages.user_id/workspace_id are creation-time snapshots — a message's+ // authoritative scope is derived from its owning topic/session+ // (buildMessageScopeJoinWhere), and that check MUST live above the scan:+ // joins inside the scan break TopN, and ParadeDB rejects the EXISTS form+ // outright ("Unsupported query shape"). The scan keeps only a fast-field+ // author/tenant BOUND that over-covers the derived scope:+ // - personal mode: `user_id = me` (pushdown-able → TopN + real scores).+ // Approximation: teammate-authored rows inside topics transferred INTO+ // a personal scope fall outside the bound (rare by construction).+ // - workspace mode: workspace snapshot rows OR rows authored by any+ // member (covers content transferred in by a member; the member list+ // is inlined as literals — a subquery here would degrade the scan the+ // same way EXISTS does). Plan quality matches upstream workspace mode+ // (already non-TopN until LOBE-12381).+ let scanBound: SQL;+ if (this.workspaceId) {+ const memberRows = await this.db+ .select({ userId: workspaceMembers.userId })+ .from(workspaceMembers)+ .where(+ and(+ eq(workspaceMembers.workspaceId, this.workspaceId),+ isNull(workspaceMembers.deletedAt),+ ),+ );+ const memberIds = memberRows.map((row) => row.userId);+ scanBound = or(+ buildWorkspaceWhere(this.scope, messages),+ memberIds.length > 0 ? inArray(messages.userId, memberIds) : undefined,+ ) as SQL;+ } else {+ scanBound = eq(messages.userId, this.userId) as SQL;+ }+const hits = this.db.select({agentId: messages.agentId,@@ -739,14 +787,16 @@ export class SearchRepo {model: messages.model,role: messages.role,score: sql<number>`paradedb.score(${messages.id})`.as('score'),+ sessionId: messages.sessionId,topicId: messages.topicId,updatedAt: messages.updatedAt,+ userId: messages.userId,workspaceId: messages.workspaceId,}).from(messages).where(and(- this.scanScopeWhere(messages),+ scanBound,ne(messages.role, 'tool'),agentId && !this.liftsAgentFilter ? eq(messages.agentId, agentId) : undefined,sql`${messages.content} @@@ ${bm25Query}`,@@ -755,11 +805,16 @@ export class SearchRepo {.orderBy(sql`paradedb.score(${messages.id}) DESC`)// `agent_id` is not a BM25 field, so where the scan's score order is real// its filter lives above the scan and the pool deepens to compensate. See- // the scan-shape invariant and `liftsAgentFilter` above.+ // the scan-shape invariant and `liftsAgentFilter` above. The derived+ // scope check above the scan drops rows in every mode now, so the pool+ // over-fetches in workspace mode too..limit(agentId && this.liftsAgentFilter? AGENT_SCOPE_CANDIDATE_POOL- : this.scanCandidateLimit(candidateLimit),+ : Math.max(+ candidateLimit * WORKSPACE_FILTER_CANDIDATE_MULTIPLIER,+ WORKSPACE_FILTER_MIN_CANDIDATES,+ ),).as('message_hits');@@ -781,9 +836,13 @@ export class SearchRepo {}).from(hits).leftJoin(agents, eq(hits.agentId, agents.id))+ .leftJoin(topics, eq(topics.id, hits.topicId))+ .leftJoin(sessions, eq(sessions.id, hits.sessionId)).where(and(- this.liftedScopeWhere(hits.workspaceId),+ // Authoritative derived scope — topic first, then session, then the+ // orphan rows' own snapshot columns.+ buildMessageScopeJoinWhere(this.scope, hits),agentId ? eq(hits.agentId, agentId) : undefined,),)diff --git a/packages/database/src/repositories/topicDoctor/index.ts b/packages/database/src/repositories/topicDoctor/index.tsindex d316da6d955..493e5dd9593 100644--- a/packages/database/src/repositories/topicDoctor/index.ts+++ b/packages/database/src/repositories/topicDoctor/index.ts@@ -1,11 +1,10 @@import { diagnoseTopic, type TopicDiagnosis } from '@lobechat/conversation-flow';import { and, eq, inArray } from 'drizzle-orm';-import type { AnyPgColumn } from 'drizzle-orm/pg-core';import { MessageModel } from '../../models/message';import { messages } from '../../schemas';import type { LobeChatDatabase } from '../../type';-import { buildWorkspaceWhere } from '../../utils/workspace';+import { buildMessageScopeWhere } from '../../utils/messageScope';interface TopicScope {agentId?: string | null;@@ -40,8 +39,10 @@ export class TopicDoctorRepo {this.messageModel = new MessageModel(db, userId, workspaceId);}- private ws = (cols: { userId: AnyPgColumn; workspaceId: AnyPgColumn }) =>- buildWorkspaceWhere({ userId: this.userId, workspaceId: this.workspaceId }, cols);+ // messages.user_id/workspace_id are creation-time snapshots — derive scope+ // from the owning topic/session instead (see messageScope.ts).+ private messagesWs = () =>+ buildMessageScopeWhere({ userId: this.userId, workspaceId: this.workspaceId });diagnose = async ({ agentId, topicId }: TopicScope): Promise<TopicDiagnosis> => {// The same list the client renders from, so the `parse()` inside the diagnosis sees@@ -64,7 +65,7 @@ export class TopicDoctorRepo {.where(and(eq(messages.topicId, scope.topicId),- this.ws(messages),+ this.messagesWs(),inArray(messages.id,patch.map((op) => op.messageId),@@ -98,7 +99,7 @@ export class TopicDoctorRepo {// A repair changes how history is threaded, not when it was written.updatedAt: messages.updatedAt,})- .where(and(eq(messages.id, op.messageId), this.ws(messages)));+ .where(and(eq(messages.id, op.messageId), this.messagesWs()));}});diff --git a/packages/database/src/repositories/userMemory/UserMemoryTopicRepository.ts b/packages/database/src/repositories/userMemory/UserMemoryTopicRepository.tsindex be5b251bd12..594585d771f 100644--- a/packages/database/src/repositories/userMemory/UserMemoryTopicRepository.ts+++ b/packages/database/src/repositories/userMemory/UserMemoryTopicRepository.ts@@ -2,7 +2,7 @@ import { and, asc, eq } from 'drizzle-orm';import { messages } from '../../schemas';import type { LobeChatDatabase } from '../../type';-import { buildWorkspaceWhere } from '../../utils/workspace';+import { buildMessageScopeWhere } from '../../utils/messageScope';/*** Maximum character length for the query string used in memory search@@ -39,7 +39,11 @@ export class UserMemoryTopicRepository {.from(messages).where(and(- buildWorkspaceWhere({ userId: this.userId, workspaceId: this.workspaceId }, messages),+ // Memory extraction only reads what THIS user wrote — user_id is the+ // author snapshot, which stays valid across agent transfers; the+ // derived predicate keeps the topic-scope check transfer-safe.+ buildMessageScopeWhere({ userId: this.userId, workspaceId: this.workspaceId }),+ eq(messages.userId, this.userId),eq(messages.topicId, topicId),eq(messages.role, 'user'),),diff --git a/packages/database/src/schemas/message.ts b/packages/database/src/schemas/message.tsindex b62c728c5bc..a41d78eaafc 100644--- a/packages/database/src/schemas/message.ts+++ b/packages/database/src/schemas/message.ts@@ -127,6 +127,11 @@ export const messages = pgTable(clientId: text('client_id'),// foreign keys+ /**+ * Creation-time snapshot of the author. NOT a scope filter: a message's+ * authoritative scope is derived from its topic/session (see+ * `buildMessageScopeWhere`), so agent transfers never rewrite this column.+ */userId: text('user_id').references(() => users.id, { onDelete: 'cascade' }).notNull(),@@ -149,6 +154,10 @@ export const messages = pgTable(messageGroupId: varchar255('message_group_id').references(() => messageGroups.id, {onDelete: 'cascade',}),+ /**+ * Creation-time snapshot of the workspace. NOT a scope filter — see+ * `userId` above; derive scope via `buildMessageScopeWhere` instead.+ */workspaceId: text('workspace_id').references(() => workspaces.id, { onDelete: 'cascade' }),...timestamps,},diff --git a/packages/database/src/utils/messageScope.ts b/packages/database/src/utils/messageScope.tsnew file mode 100644index 00000000000..eedfa8e57b5--- /dev/null+++ b/packages/database/src/utils/messageScope.ts@@ -0,0 +1,270 @@+import { and, eq, exists, isNull, ne, or, type SQL, sql, type SQLWrapper } from 'drizzle-orm';+import { type AnyPgColumn, QueryBuilder } from 'drizzle-orm/pg-core';++import {+ messageChunks,+ messageGroups,+ messagePlugins,+ messageQueries,+ messageQueryChunks,+ messages,+ messagesFiles,+ messageTranslates,+ messageTTS,+ sessions,+ topics,+} from '../schemas';+import type { LobeChatDatabase } from '../type';+import { buildWorkspaceWhere } from './workspace';++/**+ * Standalone builder so the predicates below can be constructed WITHOUT a+ * live database handle — they only ever produce SQL. This keeps them usable+ * from code whose `db` is a partial test stub, and makes the dependency+ * explicit: nothing here executes queries.+ */+const qb = new QueryBuilder();++/**+ * Derived ownership predicate for the `messages` table.+ *+ * `messages.user_id` / `messages.workspace_id` are creation-time snapshots and+ * MUST NOT be used for scope filtering: transferring an agent between scopes+ * rehomes topics/sessions but intentionally leaves the `messages` rows+ * untouched (rewriting them is minutes-long due to index/BM25 write+ * amplification). A message's authoritative scope is therefore derived from+ * its stable anchors:+ *+ * 1. `topic_id` set → the owning topic's scope+ * 2. else `session_id` set → the owning session's scope+ * 3. else (legacy orphan rows, never part of a transfer) → the row's own+ * snapshot columns+ *+ * The predicate is self-contained (correlated EXISTS on the anchors' primary+ * keys), so callers don't need to pre-authorize the topic/session — queries+ * keyed by id/topicId/sessionId/agentId pay one PK probe per candidate row.+ * Do NOT use it as the only filter of a whole-table scan (counts, exports):+ * those call sites must drive from `topics`/`sessions` joins instead so an+ * index bounds the scan.+ */+export const buildMessageScopeWhere = (ctx: { userId: string; workspaceId?: string }): SQL =>+ or(+ // 1. Message belongs to a topic → derive from the topic's current scope+ exists(+ qb+ .select({ id: topics.id })+ .from(topics)+ .where(and(eq(topics.id, messages.topicId), buildWorkspaceWhere(ctx, topics))),+ ),+ // 2. No topic, but a session → derive from the session's current scope+ and(+ isNull(messages.topicId),+ exists(+ qb+ .select({ id: sessions.id })+ .from(sessions)+ .where(and(eq(sessions.id, messages.sessionId), buildWorkspaceWhere(ctx, sessions))),+ ),+ ),+ // 3. Orphan legacy rows (no topic, no session): the snapshot is authoritative+ and(isNull(messages.topicId), isNull(messages.sessionId), buildWorkspaceWhere(ctx, messages)),+ ) as SQL;++/**+ * Join-based variant of {@link buildMessageScopeWhere} for queries planned by+ * the pg_search custom scan (`content @@@ …` + `paradedb.score` ordering):+ * ParadeDB rejects correlated EXISTS predicates in that shape+ * ("Unsupported query shape"), while plain joins plan fine.+ *+ * Callers MUST add both anchors to the query:+ * `.leftJoin(topics, eq(topics.id, messages.topicId))`+ * `.leftJoin(sessions, eq(sessions.id, messages.sessionId))`+ */+export const buildMessageScopeJoinWhere = (+ ctx: { userId: string; workspaceId?: string },+ cols: {+ sessionId: AnyPgColumn | SQLWrapper;+ topicId: AnyPgColumn | SQLWrapper;+ userId: AnyPgColumn;+ workspaceId: AnyPgColumn;+ } = messages,+): SQL =>+ or(+ // topic joined and in scope (left-joined NULL rows fail the predicate)+ buildWorkspaceWhere(ctx, topics),+ and(isNull(cols.topicId), buildWorkspaceWhere(ctx, sessions)),+ and(isNull(cols.topicId), isNull(cols.sessionId), buildWorkspaceWhere(ctx, cols)),+ ) as SQL;++/**+ * Derived ownership predicate for topic-anchored tables whose only stable+ * anchor is `topic_id` (e.g. `message_groups`): rows with a topic follow the+ * topic's current scope; rows without one fall back to their own snapshot+ * columns.+ */+export const buildTopicAnchoredScopeWhere = (+ ctx: { userId: string; workspaceId?: string },+ cols: { topicId: AnyPgColumn; userId: AnyPgColumn; workspaceId: AnyPgColumn },+): SQL =>+ or(+ exists(+ qb+ .select({ id: topics.id })+ .from(topics)+ .where(and(eq(topics.id, cols.topicId), buildWorkspaceWhere(ctx, topics))),+ ),+ and(isNull(cols.topicId), buildWorkspaceWhere(ctx, cols)),+ ) as SQL;++/**+ * Derived ownership predicate for message child tables+ * (`message_plugins` / `message_translates` / `message_tts` /+ * `messages_files` / `message_queries` …).+ *+ * Child rows carry their own `user_id`/`workspace_id` snapshots, but those+ * drift exactly like the parent message's (and historically were not even+ * rewritten on transfer). Their authoritative scope is simply "my parent+ * message's scope", expressed via the given FK column onto `messages.id`.+ *+ * Skip this predicate entirely when the query already inner-joins `messages`+ * under {@link buildMessageScopeWhere} — the join makes it redundant.+ */+export const buildMessageChildScopeWhere = (+ ctx: { userId: string; workspaceId?: string },+ messageIdColumn: AnyPgColumn,+): SQL =>+ exists(+ qb+ .select({ id: messages.id })+ .from(messages)+ .where(and(eq(messages.id, messageIdColumn), buildMessageScopeWhere(ctx))),+ ) as SQL;++/**+ * Re-materialize stale scope snapshots BEFORE deleting a snapshot FK target+ * (a workspace, or a user).+ *+ * Because transfers leave `messages` (and message child tables /+ * `message_groups`) with their creation-time `user_id` / `workspace_id`, those+ * columns can keep pointing at an owner the rows no longer belong to — and+ * they carry `ON DELETE cascade` FKs, so deleting that old owner would+ * silently destroy history that was transferred away.+ *+ * This scrub restores the pre-derivation invariant for exactly the rows a+ * transfer used to rewrite: rows whose snapshot `workspace_id` disagrees with+ * their anchor's current `workspace_id` (the workspace axis only ever changes+ * via a transfer, so this is a precise stale marker; author snapshots inside+ * an untouched scope are intentionally left alone to preserve the existing+ * "deleting a user removes what they authored" cascade semantics).+ *+ * Owner deletion is rare and already heavyweight, so paying the targeted+ * UPDATEs here — instead of on every transfer — is the whole point of the+ * derived-scope design. Call it inside the same transaction as the owner+ * DELETE.+ */+export const resnapshotTransferredMessagesBeforeOwnerDelete = async (+ // `Pick` so both the base database and a transaction executor are accepted+ db: Pick<LobeChatDatabase, 'execute'>,+ owner: { userId: string } | { workspaceId: string },+): Promise<void> => {+ const ownedBy = (table: { userId: AnyPgColumn; workspaceId: AnyPgColumn }) =>+ 'userId' in owner ? eq(table.userId, owner.userId) : eq(table.workspaceId, owner.workspaceId);++ // 1. Messages anchored to a topic follow the topic's current scope.+ await db.execute(sql`+ UPDATE ${messages} SET user_id = ${topics.userId}, workspace_id = ${topics.workspaceId}+ FROM ${topics}+ WHERE ${and(+ eq(messages.topicId, topics.id),+ ownedBy(messages),+ sql`${messages.workspaceId} IS DISTINCT FROM ${topics.workspaceId}`,+ )}+ `);++ // 2. Messages without a topic follow their session's current scope.+ await db.execute(sql`+ UPDATE ${messages} SET user_id = ${sessions.userId}, workspace_id = ${sessions.workspaceId}+ FROM ${sessions}+ WHERE ${and(+ isNull(messages.topicId),+ eq(messages.sessionId, sessions.id),+ ownedBy(messages),+ sql`${messages.workspaceId} IS DISTINCT FROM ${sessions.workspaceId}`,+ )}+ `);++ // 3. message_groups are topic-anchored.+ await db.execute(sql`+ UPDATE ${messageGroups} SET user_id = ${topics.userId}, workspace_id = ${topics.workspaceId}+ FROM ${topics}+ WHERE ${and(+ eq(messageGroups.topicId, topics.id),+ ownedBy(messageGroups),+ sql`${messageGroups.workspaceId} IS DISTINCT FROM ${topics.workspaceId}`,+ )}+ `);++ // 4. Message child tables inherit the (now re-snapshotted) parent message.+ const childAnchors = [+ [messagePlugins, messagePlugins.id],+ [messageTranslates, messageTranslates.id],+ [messageTTS, messageTTS.id],+ [messagesFiles, messagesFiles.messageId],+ [messageQueries, messageQueries.messageId],+ [messageQueryChunks, messageQueryChunks.messageId],+ [messageChunks, messageChunks.messageId],+ ] as const;+ for (const [child, messageIdColumn] of childAnchors) {+ await db.execute(sql`+ UPDATE ${child} SET user_id = ${messages.userId}, workspace_id = ${messages.workspaceId}+ FROM ${messages}+ WHERE ${and(+ eq(messageIdColumn, messages.id),+ ownedBy(child),+ sql`${child.workspaceId} IS DISTINCT FROM ${messages.workspaceId}`,+ )}+ `);+ }+};++/** Transfer aborted: a teammate's topic-anchored message/message_group appeared. */+export const MESSAGE_TRANSFER_HAS_FOREIGN_AUTHORS = 'MESSAGE_TRANSFER_HAS_FOREIGN_AUTHORS';++/**+ * Whether any message rows anchored to the given topics were authored by+ * someone other than `userId`.+ *+ * Transfer guards need this because `messages` and `message_groups` derive+ * their scope from the owning topic at read time (see buildMessageScopeWhere /+ * buildTopicAnchoredScopeWhere): every row anchored to a transferred topic+ * moves with it — including rows the direct session/agent linkage probes+ * cannot see, e.g. OpenAPI-created messages that carry only a `topicId`+ * (`agentId` is optional there and `sessionId` is always null). A teammate's+ * topic-only rows are still their work, so a non-owner transfer must not+ * rehome them.+ *+ * `topicWhere` must bound the probed topics (by session/agent/group linkage)+ * so both probes stay index-driven; each stops at the first foreign row.+ */+export const hasForeignTopicAnchoredMessageRows = async (+ // `Pick` so both the base database and a transaction executor are accepted+ db: Pick<LobeChatDatabase, 'select'>,+ userId: string,+ topicWhere: SQL,+): Promise<boolean> => {+ const [foreignMessage] = await db+ .select({ id: messages.id })+ .from(messages)+ .innerJoin(topics, eq(messages.topicId, topics.id))+ .where(and(topicWhere, ne(messages.userId, userId)))+ .limit(1);+ if (foreignMessage) return true;++ const [foreignGroup] = await db+ .select({ id: messageGroups.id })+ .from(messageGroups)+ .innerJoin(topics, eq(messageGroups.topicId, topics.id))+ .where(and(topicWhere, ne(messageGroups.userId, userId)))+ .limit(1);+ return !!foreignGroup;+};diff --git a/packages/openapi/src/common/base.service.ts b/packages/openapi/src/common/base.service.tsindex d58c1126f3e..11779c23790 100644--- a/packages/openapi/src/common/base.service.ts+++ b/packages/openapi/src/common/base.service.ts@@ -306,13 +306,32 @@ export abstract class BaseService implements IBaseService {return targetFile?.userId;}- // Query messages table+ // Query messages table. `messages.user_id` is a creation-time+ // snapshot that goes stale after agent transfers — derive the owner+ // from the message's anchor (topic first, then session) so+ // permission checks agree with the derived read scope.case !!target?.targetMessageId: {const targetMessage = await this.db.query.messages.findFirst({- columns: { userId: true },+ columns: { sessionId: true, topicId: true, userId: true },where: eq(messages.id, target.targetMessageId),});- return targetMessage?.userId;+ if (!targetMessage) return undefined;++ if (targetMessage.topicId) {+ const anchorTopic = await this.db.query.topics.findFirst({+ columns: { userId: true },+ where: eq(topics.id, targetMessage.topicId),+ });+ return anchorTopic?.userId ?? targetMessage.userId;+ }+ if (targetMessage.sessionId) {+ const anchorSession = await this.db.query.sessions.findFirst({+ columns: { userId: true },+ where: eq(sessions.id, targetMessage.sessionId),+ });+ return anchorSession?.userId ?? targetMessage.userId;+ }+ return targetMessage.userId;}// Query aiModels tablediff --git a/packages/openapi/src/services/message-translations.service.ts b/packages/openapi/src/services/message-translations.service.tsindex d53073fea61..e151234370d 100644--- a/packages/openapi/src/services/message-translations.service.ts+++ b/packages/openapi/src/services/message-translations.service.ts@@ -1,7 +1,8 @@-import { and, eq } from 'drizzle-orm';+import { and, eq, type SQL } from 'drizzle-orm';import { messages, messageTranslates } from '@/database/schemas';import type { LobeChatDatabase } from '@/database/type';+import { buildMessageChildScopeWhere, buildMessageScopeWhere } from '@/database/utils/messageScope';import { BaseService } from '../common/base.service';import { removeSystemContext } from '../helpers/translate';@@ -20,6 +21,22 @@ export class MessageTranslateService extends BaseService {super(db, userId, workspaceId);}+ /**+ * Message scope is derived from the owning topic/session — the snapshot+ * `user_id`/`workspace_id` columns go stale after agent transfers, on both+ * `messages` and `message_translates`.+ */+ private messageScopeWhere(): SQL {+ return buildMessageScopeWhere({ userId: this.userId, workspaceId: this.workspaceId });+ }++ private translateScopeWhere(): SQL {+ return buildMessageChildScopeWhere(+ { userId: this.userId, workspaceId: this.workspaceId },+ messageTranslates.id,+ );+ }+/*** Get translation info by message ID* @param messageId Message ID@@ -31,12 +48,13 @@ export class MessageTranslateService extends BaseService {this.log('info', '根据消息ID获取翻译信息', { messageId, userId: this.userId });try {- const result = await this.db.query.messageTranslates.findFirst({- where: and(- eq(messageTranslates.id, messageId),- this.buildWorkspaceWhere(messageTranslates),- ),- });+ // Plain select instead of RQB findFirst: RQB aliases the table, which+ // breaks the correlated EXISTS inside translateScopeWhere().+ const [result] = await this.db+ .select()+ .from(messageTranslates)+ .where(and(eq(messageTranslates.id, messageId), this.translateScopeWhere()))+ .limit(1);if (!result) {this.log('info', '未找到翻译信息', { messageId });@@ -77,7 +95,7 @@ export class MessageTranslateService extends BaseService {try {// First fetch the original message content and sessionIdconst messageInfo = await this.db.query.messages.findFirst({- where: and(eq(messages.id, translateData.messageId), this.buildWorkspaceWhere(messages)),+ where: and(eq(messages.id, translateData.messageId), this.messageScopeWhere()),});if (!messageInfo) {@@ -119,7 +137,7 @@ export class MessageTranslateService extends BaseService {try {// Check if message existsconst messageInfo = await this.db.query.messages.findFirst({- where: and(eq(messages.id, data.messageId), this.buildWorkspaceWhere(messages)),+ where: and(eq(messages.id, data.messageId), this.messageScopeWhere()),});if (!messageInfo) {throw this.createCommonError('未找到要更新翻译信息的消息');@@ -170,12 +188,11 @@ export class MessageTranslateService extends BaseService {try {// Check if the translation message exists- const originalTranslation = await this.db.query.messageTranslates.findFirst({- where: and(- eq(messageTranslates.id, messageId),- this.buildWorkspaceWhere(messageTranslates),- ),- });+ const [originalTranslation] = await this.db+ .select()+ .from(messageTranslates)+ .where(and(eq(messageTranslates.id, messageId), this.translateScopeWhere()))+ .limit(1);if (!originalTranslation) {throw this.createNotFoundError('翻译消息不存在');@@ -183,9 +200,7 @@ export class MessageTranslateService extends BaseService {await this.db.delete(messageTranslates)- .where(- and(eq(messageTranslates.id, messageId), this.buildWorkspaceWhere(messageTranslates)),- );+ .where(and(eq(messageTranslates.id, messageId), this.translateScopeWhere()));return { deleted: true, messageId };} catch (error) {diff --git a/packages/openapi/src/services/message.service.ts b/packages/openapi/src/services/message.service.tsindex 18495d30439..5b559b51723 100644--- a/packages/openapi/src/services/message.service.ts+++ b/packages/openapi/src/services/message.service.ts@@ -1,8 +1,10 @@-import { and, asc, count, desc, eq, ilike, inArray, isNull } from 'drizzle-orm';+import { and, asc, count, desc, eq, ilike, inArray, isNull, type SQL } from 'drizzle-orm';-import { messages, messagesFiles } from '@/database/schemas';+import { MessageModel } from '@/database/models/message';+import { messages, messagesFiles, topics } from '@/database/schemas';import type { LobeChatDatabase } from '@/database/type';import { idGenerator } from '@/database/utils/idGenerator';+import { buildMessageScopeWhere } from '@/database/utils/messageScope';import { FileService as CoreFileService } from '@/server/services/file';import { BaseService } from '../common/base.service';@@ -39,6 +41,23 @@ export class MessageService extends BaseService {this.coreFileService = new CoreFileService(db, userId!, workspaceId);}+ /**+ * Derived-scope replacement for `buildWorkspaceWhere(messages)`:+ * `messages.user_id` / `messages.workspace_id` are creation-time snapshots,+ * so scope must be derived from the owning topic/session or transferred+ * conversations disappear from (or wrongly stay in) OpenAPI reads.+ */+ private messageScopeWhere(): SQL {+ return buildMessageScopeWhere({ userId: this.userId, workspaceId: this.workspaceId });+ }++ /** Derived-scope counterpart of {@link BaseService.buildPermissionWhere}. */+ private messagePermissionScopeWhere(condition?: { userId?: string }): SQL | undefined {+ if (this.workspaceId) return this.messageScopeWhere();+ if (condition?.userId) return buildMessageScopeWhere({ userId: condition.userId });+ return;+ }+/*** Format message content, currently mainly formatting the file list* @param fileId File ID@@ -93,12 +112,11 @@ export class MessageService extends BaseService {throw this.createAuthorizationError(permissionResult.message || '无权访问此用户的消息');}- const result = await this.db- .select({ count: count() })- .from(messages)- .where(this.buildPermissionWhere(messages, { userId: targetUserId }));-- const messageCount = result[0]?.count || 0;+ // Whole-scope count: MessageModel.count fans out over the derivation+ // arms so each is index-bounded (a bare derived EXISTS would full-scan).+ const messageCount = this.workspaceId+ ? await new MessageModel(this.db, this.userId, this.workspaceId).count()+ : await new MessageModel(this.db, targetUserId).count();this.log('info', '用户消息统计完成', { count: messageCount });return { count: messageCount };@@ -128,7 +146,7 @@ export class MessageService extends BaseService {const result = await this.db.select({ count: count() }).from(messages)- .where(and(inArray(messages.topicId, topicIds), this.buildWorkspaceWhere(messages)));+ .where(and(inArray(messages.topicId, topicIds), this.messageScopeWhere()));const messageCount = result[0]?.count || 0;this.log('info', '话题消息统计完成', { count: messageCount });@@ -158,13 +176,9 @@ export class MessageService extends BaseService {return await this.countMessagesByTopicIds(query.topicIds);}- // Count all messages for the current user- const result = await this.db- .select({ count: count() })- .from(messages)- .where(this.buildWorkspaceWhere(messages));-- const messageCount = result[0]?.count || 0;+ // Count all messages for the current user — see countMessagesByUserId+ // for why this goes through MessageModel.count (index-bounded arms).+ const messageCount = await new MessageModel(this.db, this.userId, this.workspaceId).count();this.log('info', '当前用户消息统计完成', { count: messageCount });return { count: messageCount };@@ -197,7 +211,7 @@ export class MessageService extends BaseService {const { keyword, limit = 20, offset = 0 } = searchRequest;// Build query conditions- const conditions = [this.buildWorkspaceWhere(messages)];+ const conditions = [this.messageScopeWhere()];const contentMatchedMessages = await this.db.select({ id: messages.id })@@ -267,7 +281,7 @@ export class MessageService extends BaseService {throw this.createAuthorizationError(permissionResult.message || '无权访问消息列表');}- conditions.push(this.buildPermissionWhere(messages, { userId: request.userId })!);+ conditions.push(this.messagePermissionScopeWhere({ userId: request.userId })!);}// Verify topic ownership and whether the user has message read permission@@ -281,7 +295,7 @@ export class MessageService extends BaseService {}conditions.push(eq(messages.topicId, request.topicId));- conditions.push(this.buildWorkspaceWhere(messages));+ conditions.push(this.messageScopeWhere());}if (request.role) {@@ -354,7 +368,7 @@ export class MessageService extends BaseService {// Build query conditionsconst conditions = [eq(messages.id, messageId)];- const permissionWhere = this.buildPermissionWhere(messages, permissionResult.condition);+ const permissionWhere = this.messagePermissionScopeWhere(permissionResult.condition);if (permissionWhere) conditions.push(permissionWhere);const message = (await this.db.query.messages.findFirst({@@ -409,33 +423,56 @@ export class MessageService extends BaseService {throw this.createAuthorizationError(permissionResult.message || '无权创建消息');}- const [newMessage] = await this.db- .insert(messages)- .values({- agentId: messageData.agentId,- clientId: messageData.clientId,- content: messageData.content,- favorite: messageData.favorite ?? false,- id: idGenerator('messages'),- metadata: messageData.metadata,- model: messageData.model,- observationId: messageData.observationId,- parentId: messageData.parentId,- provider: messageData.provider,- quotaId: messageData.quotaId,- reasoning: messageData.reasoning,- role: messageData.role,- search: messageData.search,- sessionId: null,- threadId: messageData.threadId,- tools: messageData.tools,- topicId: messageData.topicId,- traceId: messageData.traceId,- ...this.buildWorkspacePayload({}),- })- .returning({- id: messages.id,- });+ const [newMessage] = await this.db.transaction(async (tx) => {+ if (messageData.topicId) {+ // Serialize with agent/group transfers, mirroring the topic-comment+ // create protocol: the transfer locks its topics FOR UPDATE and+ // rechecks for teammate-authored rows, so this create must block on+ // an in-flight transfer and revalidate the topic's scope once the+ // lock clears — the permission check above ran without a lock and+ // could have approved a topic that has since moved to another scope.+ const [topic] = await tx+ .select({ userId: topics.userId, workspaceId: topics.workspaceId })+ .from(topics)+ .where(eq(topics.id, messageData.topicId))+ .limit(1)+ .for('share');+ const inScope = this.workspaceId+ ? topic?.workspaceId === this.workspaceId+ : !!topic && topic.userId === this.userId && !topic.workspaceId;+ if (!inScope) {+ throw this.createAuthorizationError('话题已不在当前范围内,无法创建消息');+ }+ }++ return tx+ .insert(messages)+ .values({+ agentId: messageData.agentId,+ clientId: messageData.clientId,+ content: messageData.content,+ favorite: messageData.favorite ?? false,+ id: idGenerator('messages'),+ metadata: messageData.metadata,+ model: messageData.model,+ observationId: messageData.observationId,+ parentId: messageData.parentId,+ provider: messageData.provider,+ quotaId: messageData.quotaId,+ reasoning: messageData.reasoning,+ role: messageData.role,+ search: messageData.search,+ sessionId: null,+ threadId: messageData.threadId,+ tools: messageData.tools,+ topicId: messageData.topicId,+ traceId: messageData.traceId,+ ...this.buildWorkspacePayload({}),+ })+ .returning({+ id: messages.id,+ });+ });// Handle file attachmentsif (messageData.files && messageData.files.length > 0) {@@ -456,7 +493,7 @@ export class MessageService extends BaseService {// Re-query the complete message including session and topic informationconst completeMessage = (await this.db.query.messages.findFirst({- where: and(eq(messages.id, newMessage.id), this.buildWorkspaceWhere(messages)),+ where: and(eq(messages.id, newMessage.id), this.messageScopeWhere()),with: {filesToMessages: {with: {@@ -591,7 +628,7 @@ export class MessageService extends BaseService {orderBy: desc(messages.createdAt),where: and(topicId === null ? isNull(messages.topicId) : eq(messages.topicId, topicId),- this.buildWorkspaceWhere(messages),+ this.messageScopeWhere(),),});@@ -632,7 +669,7 @@ export class MessageService extends BaseService {const whereConditions = [eq(messages.id, messageId)];// Apply permission conditions- const permissionWhere = this.buildPermissionWhere(messages, permissionResult.condition);+ const permissionWhere = this.messagePermissionScopeWhere(permissionResult.condition);if (permissionWhere) whereConditions.push(permissionWhere);// Use a transaction to delete messages and their associations with filesdiff --git a/packages/openapi/src/services/user.service.ts b/packages/openapi/src/services/user.service.tsindex 2a6e4eb6ab6..ba621b9394e 100644--- a/packages/openapi/src/services/user.service.ts+++ b/packages/openapi/src/services/user.service.ts@@ -2,6 +2,7 @@ import { and, count, desc, eq, ilike, inArray, isNull, ne, or } from 'drizzle-orimport { ALL_SCOPE } from '@/const/rbac';import { RbacModel } from '@/database/models/rbac';+import { UserModel } from '@/database/models/user';import { messages, roles, userRoles, users } from '@/database/schemas';import type { LobeChatDatabase } from '@/database/type';import { idGenerator } from '@/database/utils/idGenerator';@@ -332,8 +333,10 @@ export class UserService extends BaseService {throw this.createAuthorizationError(permissionResult.message || '没有权限删除该用户');}- // Check if the user exists- const result = await this.db.delete(users).where(eq(users.id, userId));+ // Check if the user exists. Route through UserModel.deleteUser so+ // transferred-away message snapshots are re-materialized before the+ // cascade (see resnapshotTransferredMessagesBeforeOwnerDelete).+ const result = await UserModel.deleteUser(this.db, userId);if (!result.rowCount) {throw this.createNotFoundError('用户不存在');