🤯 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
⏪️ revert(db): restore snapshot-based message scope on transfer (revert #17780) (#17927)
Rdmclin2d7eaa44051a6
diff --git a/apps/server/src/routers/lambda/agent.ts b/apps/server/src/routers/lambda/agent.tsindex 35fec2e016b..9b5d96c6e18 100644--- a/apps/server/src/routers/lambda/agent.ts+++ b/apps/server/src/routers/lambda/agent.ts@@ -18,7 +18,6 @@ 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';@@ -856,16 +855,12 @@ export const agentRouter = router({input.targetWorkspaceId,ctx.userId,input.targetVisibility,- {- rejectForeignMessageAuthors: isWorkspaceNonOwner(ctx),- rejectForeignTopicCommentAuthors: isWorkspaceNonOwner(ctx),- },+ { rejectForeignTopicCommentAuthors: isWorkspaceNonOwner(ctx) },);} catch (error) {if (error instanceof Error &&- (error.message === TOPIC_COMMENT_TRANSFER_HAS_FOREIGN_AUTHORS ||- error.message === MESSAGE_TRANSFER_HAS_FOREIGN_AUTHORS)+ error.message === TOPIC_COMMENT_TRANSFER_HAS_FOREIGN_AUTHORS) {throw new TRPCError({cause: { data: { code: TransferErrorCode.OwnerOnly } },@@ -996,16 +991,12 @@ export const agentRouter = router({input.targetWorkspaceId,ctx.userId,input.targetVisibility,- {- rejectForeignMessageAuthors: isWorkspaceNonOwner(ctx),- rejectForeignTopicCommentAuthors: isWorkspaceNonOwner(ctx),- },+ { rejectForeignTopicCommentAuthors: isWorkspaceNonOwner(ctx) },);} catch (error) {if (error instanceof Error &&- (error.message === TOPIC_COMMENT_TRANSFER_HAS_FOREIGN_AUTHORS ||- error.message === MESSAGE_TRANSFER_HAS_FOREIGN_AUTHORS)+ error.message === TOPIC_COMMENT_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 0484c4fe1b1..f9fccf18c38 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 { buildMessageScopeWhere } from '@/database/utils/messageScope';+import { buildWorkspaceWhere } from '@/database/utils/workspace';import { router } from '@/libs/trpc/lambda';import { serverDatabase } from '@/libs/trpc/lambda/middleware';import { AgentEvalRunService, RUN_CREATE_ID_CONFLICT } from '@/server/services/agentEvalRun';@@ -466,14 +466,10 @@ export const agentEvalExternalRouter = router({.input(z.object({ threadId: z.string().optional(), topicId: z.string() })).query(async ({ ctx, input }) => {const conditions = [- // 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,- }),+ buildWorkspaceWhere(+ { userId: ctx.userId, workspaceId: ctx.workspaceId ?? undefined },+ messages,+ ),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 b080c4b11e0..b36e87200d1 100644--- a/apps/server/src/routers/lambda/agentGroup.ts+++ b/apps/server/src/routers/lambda/agentGroup.ts@@ -12,7 +12,6 @@ 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';@@ -691,16 +690,12 @@ export const agentGroupRouter = router({input.targetWorkspaceId,ctx.userId,input.targetVisibility,- {- rejectForeignMessageAuthors: isWorkspaceNonOwner(ctx),- rejectForeignTopicCommentAuthors: isWorkspaceNonOwner(ctx),- },+ { rejectForeignTopicCommentAuthors: isWorkspaceNonOwner(ctx) },);} catch (error) {if (error instanceof Error &&- (error.message === TOPIC_COMMENT_TRANSFER_HAS_FOREIGN_AUTHORS ||- error.message === MESSAGE_TRANSFER_HAS_FOREIGN_AUTHORS)+ error.message === TOPIC_COMMENT_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 b69db610c8b..2d093b198cc 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 { buildMessageScopeWhere } from '@/database/utils/messageScope';+import { buildWorkspaceWhere } from '@/database/utils/workspace';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(- buildMessageScopeWhere({ userId: input.userId, workspaceId: input.workspaceId }),+ buildWorkspaceWhere({ userId: input.userId, workspaceId: input.workspaceId }, messages),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 31bac890521..0bc6cabdbd0 100644--- a/apps/server/src/services/followUpAction/index.test.ts+++ b/apps/server/src/services/followUpAction/index.test.ts@@ -1,5 +1,4 @@// @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';@@ -150,11 +149,27 @@ describe('FollowUpActionService.extract', () => {expect(result).toEqual({ chips: [], messageId: FOUND_MSG });});- // The where clause is a composed drizzle SQL object now (derived message- // scope) — render it to SQL text + params for assertions.- const captureWhere = () => {+ const captureWhereOps = () => {const arg = queryFindFirstSpy.mock.calls[0][0];- return new PgDialect().sqlToQuery(arg.where);+ 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 };};it('filters by threadId when provided (thread isolation)', async () => {@@ -164,26 +179,28 @@ describe('FollowUpActionService.extract', () => {threadId: 'thread-A',topicId: TEST_TOPIC,});- const { sql, params } = captureWhere();- expect(params).toContain('thread-A');- expect(sql).not.toContain('"messages"."thread_id" is null');+ 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);});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 { sql } = captureWhere();- expect(sql).toContain('"messages"."thread_id" is null');+ 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);});- it('derives personal-mode scope from the owning topic/session', async () => {+ it('filters personal mode by userId and null workspaceId', async () => {queryFindFirstSpy.mockResolvedValue(undefined);await svc.extract({ modelConfig: MODEL_CONFIG, topicId: TEST_TOPIC });- 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);+ 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' },+ ]);});it('filters workspace mode by workspaceId and forwards it to model runtime', async () => {@@ -193,8 +210,8 @@ describe('FollowUpActionService.extract', () => {await svc.extract({ modelConfig: MODEL_CONFIG, topicId: TEST_TOPIC });- const { params } = captureWhere();- expect(params).toContain('workspace-1');+ const { parts, table } = captureWhereOps();+ expect(parts).toContainEqual({ col: table.workspaceId, op: 'eq', value: '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 1a5ad6c813e..6b09a02e6a3 100644--- a/apps/server/src/services/followUpAction/index.ts+++ b/apps/server/src/services/followUpAction/index.ts@@ -2,11 +2,8 @@ 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';@@ -38,19 +35,19 @@ export class FollowUpActionService {const row = await this.db.query.messages.findFirst({columns: { content: true, id: true },orderBy: (m, { desc }) => desc(m.createdAt),- // 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, ''),- ),+ 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, ''),+ ),});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 0f5b0dc552d..b95aa9710e0 100644--- a/apps/server/src/services/memory/userMemory/extract.ts+++ b/apps/server/src/services/memory/userMemory/extract.ts@@ -70,7 +70,6 @@ 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';@@ -1372,7 +1371,9 @@ export class MemoryExtractionExecutor {role: messages.role,}).from(messages)- .where(and(buildMessageScopeWhere({ userId, workspaceId }), eq(messages.topicId, topicId)))+ .where(+ and(buildWorkspaceWhere({ userId, workspaceId }, messages), 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 0bb562e3e2f..2296690423a 100644--- a/apps/server/src/services/usage/index.test.ts+++ b/apps/server/src/services/usage/index.test.ts@@ -23,51 +23,38 @@ describe('UsageRecordService', () => {let mockDb: LobeChatDatabase;const userId = 'test-user-id';- // 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.+ // Helper function to setup query chain mockconst setupQueryChainMock = (mockMessages: any[]) => {- 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([]),- }),- });+ 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 });};- // Variant that also captures the args passed to `.where(...)` (topic arm- // first) so tests can assert what ended up in the composed WHERE clause.+ // Variant that also captures the args passed to `.where(...)` so tests can+ // assert what ended up in the composed WHERE clause.const setupCapturingMock = (mockMessages: any[]) => {const whereArgs: unknown[] = [];- 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 mockOrderBy = vi.fn().mockResolvedValue(mockMessages);+ const mockWhere = vi.fn().mockImplementation((arg: unknown) => {+ whereArgs.push(arg);+ return { orderBy: mockOrderBy };});+ const mockFrom = vi.fn().mockReturnValue({ where: mockWhere });+ mockDb.select = vi.fn().mockReturnValue({ from: mockFrom });return { whereArgs };};beforeEach(() => {- mockDb = {} as unknown as LobeChatDatabase;- // Default: every arm resolves empty- setupQueryChainMock([]);+ // 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;service = new UsageRecordService(mockDb, userId);});diff --git a/apps/server/src/services/usage/index.ts b/apps/server/src/services/usage/index.tsindex 6b1ea3c86d9..7ca9e52f40d 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 { and, eq, isNull, type SQL } from 'drizzle-orm';+import { asc, desc, eq } from 'drizzle-orm';-import { messages, sessions, topics } from '@/database/schemas';+import { messages } from '@/database/schemas';import { type LobeChatDatabase } from '@/database/type';import { genRangeWhere, genWhere } from '@/database/utils/genWhere';import { buildWorkspaceWhere } from '@/database/utils/workspace';@@ -31,25 +31,6 @@ 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.@@ -59,42 +40,31 @@ export class UsageRecordService {endAt: string,agentId?: string,): Promise<UsageRecordItem[]> => {- 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),- );+ 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));return spends.map((spend) => {const metadata = spend.metadata as MessageMetadata;// Prefer the dedicated `usage` column, then the canonical nested@@ -255,38 +225,27 @@ export class UsageRecordService {endAt: string,granularity: AgentUsageGranularity = 'day',): Promise<AgentUsageStats> => {- 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 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 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 8dc9e01d37f..a78d17d2ab4 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 { buildMessageScopeWhere } from '@/database/utils/messageScope';+import { buildWorkspaceWhere } from '@/database/utils/workspace';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(- buildMessageScopeWhere({ userId: input.userId, workspaceId: input.workspaceId }),+ buildWorkspaceWhere({ userId: input.userId, workspaceId: input.workspaceId }, messages),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 8710587eb4e..d9149b9bf00 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 { and, eq } from 'drizzle-orm';+import { eq } from 'drizzle-orm';import { afterEach, beforeEach, describe, expect, it } from 'vitest';import { getTestDB } from '../../core/getTestDB';@@ -16,8 +16,6 @@ import {documents,files,knowledgeBases,- messageGroups,- messagePlugins,messages,sessionGroups,sessions,@@ -31,23 +29,15 @@ 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';@@ -181,99 +171,22 @@ describe('AgentModel.transferAgent', () => {expect(session.groupId).toBeNull();});- it('should update topics and keep messages as untouched snapshots visible via derivation', async () => {+ it('should update topics and messages', 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, topicId: 'topic-1', userId, role: 'assistant' });+ .values({ id: 'msg-1', agentId: agent.id, 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).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 });+ expect(msg.workspaceId).toBe(wsId1);});it('should preserve content timestamps while transferring ownership', async () => {@@ -573,86 +486,6 @@ 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 () => {@@ -984,131 +817,6 @@ 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);@@ -1120,20 +828,8 @@ describe('AgentModel.transferAgents (batch)', () => {{ id: 'batch-topic-2', agentId: agent2.id, userId },]);await serverDB.insert(messages).values([- {- 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',- },+ { id: 'batch-msg-1', agentId: agent1.id, userId, role: 'assistant' },+ { id: 'batch-msg-2', agentId: agent2.id, userId, role: 'assistant' },]);const results = await model.transferAgents([agent1.id, agent2.id], wsId1, userId);@@ -1149,15 +845,9 @@ describe('AgentModel.transferAgents (batch)', () => {const [topic] = await serverDB.select().from(topics).where(eq(topics.id, topicId));expect(topic.workspaceId).toBe(wsId1);}- // 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) {+ for (const msgId of ['batch-msg-1', 'batch-msg-2']) {const [msg] = await serverDB.select().from(messages).where(eq(messages.id, msgId));- expect(msg.workspaceId).toBeNull();- expect(await wsMessages.query({ topicId })).toHaveLength(1);+ expect(msg.workspaceId).toBe(wsId1);}});diff --git a/packages/database/src/models/__tests__/messages/message.query.test.ts b/packages/database/src/models/__tests__/messages/message.query.test.tsindex 8f1acd71e3c..50de99f906c 100644--- a/packages/database/src/models/__tests__/messages/message.query.test.ts+++ b/packages/database/src/models/__tests__/messages/message.query.test.ts@@ -1413,56 +1413,6 @@ 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 e54527696ec..d5e22f6ac3f 100644--- a/packages/database/src/models/__tests__/messages/message.stats.test.ts+++ b/packages/database/src/models/__tests__/messages/message.stats.test.ts@@ -877,10 +877,9 @@ describe('MessageModel Statistics Tests', () => {it('does not leak other users’ topics', async () => {const otherModel = new MessageModel(serverDB, otherUserId);const stats = await otherModel.topicMessageStats({ role: 'user' });- // 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);+ // otherUser only has the single leaked message in s-t1+ expect(stats.topics).toBe(1);+ expect(stats.totalMessages).toBe(1);});});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 2f2d3af3328..f56b3a5a4aa 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,16 +131,13 @@ describe('MessageModel.queryTopicTranscript', () => {const model = new MessageModel(serverDB, userId);const full = await model.queryTopicTranscript({ limit: 10, offset: 0, topicId });- // 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.total).toBe(5);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' });@@ -154,14 +151,12 @@ describe('MessageModel.queryTopicTranscript', () => {});const page = await model.queryTopicTranscript({ limit: 2, offset: 1, topicId });- expect(page.total).toBe(6);+ expect(page.total).toBe(5);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,@@ -169,8 +164,8 @@ describe('MessageModel.queryTopicTranscript', () => {topicId,}),).resolves.toEqual({- items: [],- total: 0,+ items: [expect.objectContaining({ id: 'topic-transcript-other-owner-message' })],+ total: 1,});});diff --git a/packages/database/src/models/__tests__/recent.test.ts b/packages/database/src/models/__tests__/recent.test.tsindex 7b28cfeb333..8a9da50f274 100644--- a/packages/database/src/models/__tests__/recent.test.ts+++ b/packages/database/src/models/__tests__/recent.test.ts@@ -610,39 +610,6 @@ 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 36d5bf6a4bc..b6d315eeb0b 100644--- a/packages/database/src/models/agent.ts+++ b/packages/database/src/models/agent.ts@@ -55,10 +55,6 @@ 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,@@ -1676,12 +1672,6 @@ 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))@@ -1718,10 +1708,7 @@ export class AgentModel {targetWorkspaceId: string | null,targetUserId: string,targetVisibility?: 'private' | 'public',- options: {- rejectForeignMessageAuthors?: boolean;- rejectForeignTopicCommentAuthors?: boolean;- } = {},+ options: { rejectForeignTopicCommentAuthors?: boolean } = {},): Promise<{ agentId: string; slug: string | null }> => {const [result] = await this.transferAgents([agentId],@@ -1735,23 +1722,16 @@ export class AgentModel {/*** Batch variant of {@link transferAgent}: moves several agents (and their- * 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.+ * 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.*/transferAgents = async (agentIds: string[],targetWorkspaceId: string | null,targetUserId: string,targetVisibility?: 'private' | 'public',- options: {- rejectForeignMessageAuthors?: boolean;- rejectForeignTopicCommentAuthors?: boolean;- } = {},+ options: { rejectForeignTopicCommentAuthors?: boolean } = {},): Promise<{ agentId: string; slug: string | null }[]> => {if (agentIds.length === 0) return [];@@ -1982,19 +1962,6 @@ 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 })@@ -2010,30 +1977,15 @@ export class AgentModel {targetWorkspaceId,);- // 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.+ // 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);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(- and(- inArray(messages.agentId, agentIds),- isNull(messages.topicId),- isNull(messages.sessionId),- ),- );+ .where(messageCondition!);// 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 5bb5fbad89d..a1b13777fff 100644--- a/packages/database/src/models/agentSignal/nightlyReview.ts+++ b/packages/database/src/models/agentSignal/nightlyReview.ts@@ -13,17 +13,8 @@ import {or,sql,} from 'drizzle-orm';-import { unionAll } from 'drizzle-orm/pg-core';-import {- agents,- messagePlugins,- messages,- sessions,- topics,- users,- userSettings,-} from '../../schemas';+import { agents, messagePlugins, messages, topics, users, userSettings } from '../../schemas';import type { LobeChatDatabase } from '../../type';import { normalizeInboxAgentTitle } from '../../utils/inboxAgent';@@ -184,65 +175,9 @@ 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,@@ -250,27 +185,40 @@ export class AgentSignalNightlyReviewModel {sql<number>`COUNT(${messagePlugins.id}) FILTER (WHERE ${messagePlugins.error} IS NOT NULL)`.mapWith(Number,),- firstActivityAt: sql<Date>`MIN(${activity.createdAt})`.mapWith(parseAggregateTimestamp),- lastActivityAt: sql<Date>`MAX(${activity.createdAt})`.mapWith(parseAggregateTimestamp),- messageCount: count(activity.id),+ firstActivityAt: sql<Date>`MIN(${messages.createdAt})`.mapWith(parseAggregateTimestamp),+ lastActivityAt: sql<Date>`MAX(${messages.createdAt})`.mapWith(parseAggregateTimestamp),+ messageCount: count(messages.id),name: agents.name,slug: agents.slug,timezone: sql<string>`COALESCE(${userSettings.general}->>'timezone', 'UTC')`,title: agents.title,- topicCount: countDistinct(activity.topicId),+ topicCount: countDistinct(messages.topicId),})- .from(activity)+ .from(messages)+ .leftJoin(+ topics,+ and(eq(topics.id, messages.topicId), eq(topics.userId, userId), isNull(topics.workspaceId)),+ ).innerJoin(agents,- and(eq(agents.id, activity.agentId), eq(agents.userId, userId), isNull(agents.workspaceId)),+ and(eq(agents.id, effectiveAgentId), eq(agents.userId, userId), isNull(agents.workspaceId)),).leftJoin(userSettings, eq(userSettings.id, userId))- // 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))+ .leftJoin(+ messagePlugins,+ and(+ eq(messagePlugins.id, messages.id),+ eq(messagePlugins.userId, userId),+ isNull(messagePlugins.workspaceId),+ ),+ ).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),@@ -279,7 +227,7 @@ export class AgentSignalNightlyReviewModel {),).groupBy(agents.id, agents.title, agents.name, agents.slug, userSettings.general)- .orderBy(sql`MAX(${activity.createdAt}) DESC`);+ .orderBy(sql`MAX(${messages.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 1d14b2291ed..5d9cb952dbf 100644--- a/packages/database/src/models/message.ts+++ b/packages/database/src/models/message.ts@@ -42,7 +42,7 @@ import {count,desc,eq,- getTableColumns,+ gt,gte,inArray,isNotNull,@@ -52,7 +52,6 @@ import {or,sql,} from 'drizzle-orm';-import { unionAll } from 'drizzle-orm/pg-core';import { merge } from '@/utils/merge';import { sanitizeNullBytes } from '@/utils/sanitizeNullBytes';@@ -73,21 +72,13 @@ 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';@@ -380,29 +371,17 @@ 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 = () =>- buildMessageScopeWhere({ userId: this.userId, workspaceId: this.workspaceId });+ buildWorkspaceWhere({ userId: this.userId, workspaceId: this.workspaceId }, messages);private pluginsOwnership = () =>- buildMessageChildScopeWhere(- { userId: this.userId, workspaceId: this.workspaceId },- messagePlugins.id,- );+ buildWorkspaceWhere({ userId: this.userId, workspaceId: this.workspaceId }, messagePlugins);private translatesOwnership = () =>- buildMessageChildScopeWhere(- { userId: this.userId, workspaceId: this.workspaceId },- messageTranslates.id,- );+ buildWorkspaceWhere({ userId: this.userId, workspaceId: this.workspaceId }, messageTranslates);private ttsOwnership = () =>- buildMessageChildScopeWhere(- { userId: this.userId, workspaceId: this.workspaceId },- messageTTS.id,- );+ buildWorkspaceWhere({ userId: this.userId, workspaceId: this.workspaceId }, messageTTS);private agentsToSessionsOwnership = () =>buildWorkspaceWhere({ userId: this.userId, workspaceId: this.workspaceId }, agentsToSessions);@@ -1576,10 +1555,7 @@ export class MessageModel {): Promise<UIChatMessage[]> => {// 1. Query MessageGroups for this topic, optionally filtered by time rangeconst whereConditions = [- buildTopicAnchoredScopeWhere(- { userId: this.userId, workspaceId: this.workspaceId },- messageGroups,- ),+ buildWorkspaceWhere({ userId: this.userId, workspaceId: this.workspaceId }, messageGroups),eq(messageGroups.topicId, topicId),];@@ -1901,30 +1877,11 @@ 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(scoped)- .orderBy(desc(scoped.createdAt))+ .from(messages)+ .where(and(this.ownership()))+ .orderBy(desc(messages.createdAt)).limit(pageSize).offset(offset);@@ -1944,53 +1901,22 @@ 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(getTableColumns(messages))+ .select().from(messages)- .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}`,- ),- )+ .where(and(this.ownership(), sql`${messages.content} @@@ ${bm25Query}`)).orderBy(desc(messages.createdAt));return result as DBMessageItem[];};/**- * 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.+ * Ownership-scoped analytics filter conditions, shared by count /+ * countGroupByTopic / topicMessageStats. The first entry is always the+ * `userId × workspace` ownership predicate; later entries are optional.*/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,@@ -2006,28 +1932,14 @@ export class MessageModel {];count = async (params?: MessageAnalyticsFilters): Promise<number> => {- 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])),- ]);+ const result = await this.db+ .select({+ count: count(messages.id),+ })+ .from(messages)+ .where(genWhere(this.analyticsConditions(params)));- return results.reduce((total, rows) => total + rows[0].count, 0);+ return result[0].count;};/**@@ -2038,15 +1950,13 @@ 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)- .innerJoin(topics, eq(topics.id, messages.topicId))- .where(genWhere([this.scopeArms().topicOwned, ...this.analyticsConditions(params)]))+ .where(genWhere([...this.analyticsConditions(params), isNotNull(messages.topicId)])).groupBy(messages.topicId).orderBy(desc(sql`count`), asc(messages.topicId));@@ -2059,15 +1969,13 @@ 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)- .innerJoin(topics, eq(topics.id, messages.topicId))- .where(genWhere([this.scopeArms().topicOwned, ...this.analyticsConditions(params)]))+ .where(genWhere([...this.analyticsConditions(params), isNotNull(messages.topicId)])).groupBy(messages.topicId);return computeTopicMessageStats(rows.map((r) => r.count));@@ -2099,116 +2007,74 @@ export class MessageModel {range?: [string, string];startDate?: string;}): Promise<number> => {- 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') };-- 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])),- ]);+ 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,+ ]),+ );- return results.reduce((total, rows) => total + Number(rows[0].count ?? 0), 0);+ return Number(result[0].count);};rankModels = async (limit: number = 10): Promise<ModelRankItem[]> => {- 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 }));+ 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);};getHeatmaps = async (): Promise<HeatmapsProps['data']> => {const startDate = today().subtract(1, 'year').startOf('day');const endDate = today().endOf('day');- 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 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 heatmapData: HeatmapsProps['data'] = [];let currentDate = startDate.clone();const dateCountMap = new Map<string, number>();- for (const item of results.flat()) {+ for (const item of result) {if (item?.date) {const dateStr = dayjs(item.date as string).format('YYYY-MM-DD');- dateCountMap.set(dateStr, (dateCountMap.get(dateStr) ?? 0) + item.count);+ dateCountMap.set(dateStr, item.count);}}@@ -2246,49 +2112,35 @@ export class MessageModel {const startDate = today().subtract(1, 'year').startOf('day');const endDate = today().endOf('day');- 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 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 dateTokenMap = new Map<string, number>();let maxTokens = 0;- for (const item of results.flat()) {+ for (const item of result) {if (item?.date) {const dateStr = dayjs(item.date as string).format('YYYY-MM-DD');- const tokens = (dateTokenMap.get(dateStr) ?? 0) + (item.tokens || 0);+ const tokens = item.tokens || 0;dateTokenMap.set(dateStr, tokens);if (tokens > maxTokens) maxTokens = tokens;}@@ -2320,43 +2172,26 @@ export class MessageModel {};hasMoreThanN = async (n: number): Promise<boolean> => {- return (await this.countUpTo(n + 1)) > n;+ const result = await this.db+ .select({ id: messages.id })+ .from(messages)+ .where(and(this.ownership()))+ .limit(n + 1);++ return result.length > n;};/**- * 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.+ * Count messages up to a limit, useful for avoiding full table scans*/countUpTo = async (n: number): Promise<number> => {- const { topicOwned, sessionOwned, orphan } = this.scopeArms();- let found = 0;-- const byTopic = await this.db+ const result = await this.db.select({ id: messages.id }).from(messages)- .innerJoin(topics, eq(topics.id, messages.topicId))- .where(topicOwned)+ .where(and(this.ownership())).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;- const orphans = await this.db- .select({ id: messages.id })- .from(messages)- .where(orphan)- .limit(n - found);-- return found + orphans.length;+ return result.length;};// **************** Create *************** //@@ -2780,13 +2615,9 @@ export class MessageModel {};updatePluginState = async (id: string, state: Record<string, any>): Promise<void> => {- // 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);+ const item = await this.db.query.messagePlugins.findFirst({+ where: and(eq(messagePlugins.id, id), this.pluginsOwnership()),+ });if (!item) throw new Error('Plugin not found');await this.db@@ -2796,11 +2627,9 @@ export class MessageModel {};updateMessagePlugin = async (id: string, value: Partial<MessagePluginItem>) => {- const [item] = await this.db- .select()- .from(messagePlugins)- .where(and(eq(messagePlugins.id, id), this.pluginsOwnership()))- .limit(1);+ const item = await this.db.query.messagePlugins.findFirst({+ where: and(eq(messagePlugins.id, id), this.pluginsOwnership()),+ });if (!item) throw new Error('Plugin not found');return this.db@@ -2821,11 +2650,9 @@ export class MessageModel {* `undefined`.*/findMessagePlugin = async (messageId: string): Promise<MessagePluginItem | undefined> => {- const [row] = await this.db- .select()- .from(messagePlugins)- .where(and(eq(messagePlugins.id, messageId), this.pluginsOwnership()))- .limit(1);+ const row = await this.db.query.messagePlugins.findFirst({+ where: and(eq(messagePlugins.id, messageId), this.pluginsOwnership()),+ });if (!row) return undefined;return {apiName: row.apiName ?? undefined,@@ -3063,11 +2890,9 @@ export class MessageModel {// Update messagePlugins table (pluginState, pluginError)if (pluginState !== undefined || pluginError !== undefined) {- const [pluginItem] = await trx- .select()- .from(messagePlugins)- .where(and(eq(messagePlugins.id, id), this.pluginsOwnership()))- .limit(1);+ const pluginItem = await trx.query.messagePlugins.findFirst({+ where: and(eq(messagePlugins.id, id), this.pluginsOwnership()),+ });// A plugin-only patch never touches `messages`, so the plugin row is// the only evidence the tool message exists.@@ -3308,11 +3133,9 @@ export class MessageModel {};updateTranslate = async (id: string, translate: Partial<ChatTranslate>) => {- const [result] = await this.db- .select()- .from(messageTranslates)- .where(and(eq(messageTranslates.id, id), this.translatesOwnership()))- .limit(1);+ const result = await this.db.query.messageTranslates.findFirst({+ where: and(eq(messageTranslates.id, id), this.translatesOwnership()),+ });// If the message does not exist in the translate table, insert itif (!result) {@@ -3336,11 +3159,9 @@ 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- .select()- .from(messageTTS)- .where(and(eq(messageTTS.id, id), this.ttsOwnership()))- .limit(1);+ const result = await this.db.query.messageTTS.findFirst({+ where: and(eq(messageTTS.id, id), this.ttsOwnership()),+ });// If the message does not exist in the TTS table, insert itif (!result) {@@ -3662,9 +3483,9 @@ export class MessageModel {.where(and(eq(messageQueries.id, id),- buildMessageChildScopeWhere(+ buildWorkspaceWhere({ userId: this.userId, workspaceId: this.workspaceId },- messageQueries.messageId,+ messageQueries,),),);@@ -3686,43 +3507,7 @@ export class MessageModel {);deleteAllMessages = async () => {- // 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),- ),- );- });+ return this.db.delete(messages).where(and(this.ownership()));};/**diff --git a/packages/database/src/models/recent.ts b/packages/database/src/models/recent.tsindex aca14f654b6..a7a7db1f6e6 100644--- a/packages/database/src/models/recent.ts+++ b/packages/database/src/models/recent.ts@@ -73,14 +73,11 @@ 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 92b9f069417..8052898074d 100644--- a/packages/database/src/models/topic.ts+++ b/packages/database/src/models/topic.ts@@ -46,7 +46,6 @@ 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';@@ -250,7 +249,7 @@ export class TopicModel {private mine = () => and(this.ownership(), eq(topics.userId, this.userId));private messageOwnership = () =>- buildMessageScopeWhere({ userId: this.userId, workspaceId: this.workspaceId });+ buildWorkspaceWhere({ userId: this.userId, workspaceId: this.workspaceId }, messages);// **************** Query *************** //query = async ({@@ -749,15 +748,19 @@ 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). 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.+ // Query topic IDs matching by message content (BM25)this.db.select({ topicId: messages.topicId }).from(messages).innerJoin(topics, eq(messages.topicId, topics.id))- .where(and(sql`${messages.content} @@@ ${bm25Query}`, this.ownership(), scopeCondition))+ .where(+ and(+ this.messageOwnership(),+ 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 5c9a4b719b1..3504eb1c449 100644--- a/packages/database/src/models/user.ts+++ b/packages/database/src/models/user.ts@@ -15,9 +15,8 @@ import { merge } from '@/utils/merge';import { today } from '@/utils/time';import type { NewUser, UserItem, UserSettingsItem } from '../schemas';-import { messages, nextauthAccounts, topics, users, userSettings, workspaces } from '../schemas';+import { messages, nextauthAccounts, topics, users, userSettings } from '../schemas';import type { LobeChatDatabase } from '../type';-import { resnapshotTransferredMessagesBeforeOwnerDelete } from '../utils/messageScope';type DecryptUserKeyVaults = (encryptKeyVaultsStr: string | null,@@ -344,25 +343,7 @@ export class UserModel {};static deleteUser = async (db: LobeChatDatabase, id: string) => {- 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));- });+ return db.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 498c884e809..7ec9a38ea65 100644--- a/packages/database/src/models/workspace.ts+++ b/packages/database/src/models/workspace.ts@@ -7,7 +7,6 @@ import {workspaces,} from '../schemas/workspace';import type { LobeChatDatabase } from '../type';-import { resnapshotTransferredMessagesBeforeOwnerDelete } from '../utils/messageScope';const getActiveMembershipRole = async (db: LobeChatDatabase,@@ -97,24 +96,9 @@ export class WorkspaceModel {};delete = async (id: string) => {- 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)));- });+ return this.db+ .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 425887c20c0..de4c009dc67 100644--- a/packages/database/src/repositories/agentGroup/index.test.ts+++ b/packages/database/src/repositories/agentGroup/index.test.ts@@ -12,13 +12,12 @@ import {} from '../../models/topicComment';import { agents } from '../../schemas/agent';import { chatGroups, chatGroupsAgents } from '../../schemas/chatGroup';-import { messageGroups, messagePlugins, messages } from '../../schemas/message';+import { 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';@@ -1663,96 +1662,6 @@ 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 884981b4ea2..71293eb16f4 100644--- a/packages/database/src/repositories/agentGroup/index.ts+++ b/packages/database/src/repositories/agentGroup/index.ts@@ -29,12 +29,6 @@ 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 {@@ -117,14 +111,9 @@ export class AgentGroupRepository {private threadOwnership = () =>buildWorkspaceWhere({ userId: this.userId, workspaceId: this.workspaceId }, threads);private messageOwnership = () =>- 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.+ buildWorkspaceWhere({ userId: this.userId, workspaceId: this.workspaceId }, messages);private messagePluginOwnership = () =>- buildMessageChildScopeWhere(- { userId: this.userId, workspaceId: this.workspaceId },- messagePlugins.id,- );+ buildWorkspaceWhere({ userId: this.userId, workspaceId: this.workspaceId }, messagePlugins);private buildCopiedAgent = (source: AgentItem | undefined,@@ -276,12 +265,9 @@ export class AgentGroupRepository {if (sourceMessages.length === 0) return;const sourceMessageIds = sourceMessages.map((message) => message.id);- // 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 sourcePlugins = await executor.query.messagePlugins.findMany({+ where: and(this.messagePluginOwnership(), inArray(messagePlugins.id, sourceMessageIds)),+ });const messageRows = sourceMessages.map((message) => {const newMessageId = messageIdMap.get(message.id)!;@@ -891,12 +877,6 @@ 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)@@ -917,10 +897,7 @@ export class AgentGroupRepository {targetWorkspaceId: string | null,targetUserId: string,targetVisibility?: 'private' | 'public',- options: {- rejectForeignMessageAuthors?: boolean;- rejectForeignTopicCommentAuthors?: boolean;- } = {},+ options: { rejectForeignTopicCommentAuthors?: boolean } = {},): Promise<{ groupId: string } | null> {const sourceGroup = await this.db.query.chatGroups.findFirst({where: and(eq(chatGroups.id, groupId), this.groupOwnership()),@@ -1014,16 +991,6 @@ 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 ffd71e2b93e..fe2882a33d2 100644--- a/packages/database/src/repositories/agentMigration/index.ts+++ b/packages/database/src/repositories/agentMigration/index.ts@@ -3,7 +3,6 @@ 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 };@@ -30,12 +29,6 @@ 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@@ -99,9 +92,7 @@ export class AgentMigrationRepo {await tx.update(messages).set({ agentId, updatedAt: messages.updatedAt })- .where(- and(this.messagesWs(tx), inArray(messages.topicId, topicIds), isNull(messages.agentId)),- );+ .where(and(this.ws(messages), inArray(messages.topicId, topicIds), isNull(messages.agentId)));// 4. Also update messages without topicId but in inbox (sessionId IS NULL) - preserve original updatedAtawait tx@@ -109,7 +100,7 @@ export class AgentMigrationRepo {.set({ agentId, updatedAt: messages.updatedAt }).where(and(- this.messagesWs(tx),+ this.ws(messages),isNull(messages.sessionId),isNull(messages.topicId),isNull(messages.agentId),@@ -144,7 +135,7 @@ export class AgentMigrationRepo {.update(messages).set({ agentId, updatedAt: messages.updatedAt }).where(- and(this.messagesWs(tx), inArray(messages.topicId, topicIds), isNull(messages.agentId)),+ and(this.ws(messages), inArray(messages.topicId, topicIds), isNull(messages.agentId)),);}@@ -154,7 +145,7 @@ export class AgentMigrationRepo {.set({ agentId, updatedAt: messages.updatedAt }).where(and(- this.messagesWs(tx),+ this.ws(messages),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 d4a96712ded..7a0fa7d3c0d 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 { buildMessageScopeWhere, buildTopicAnchoredScopeWhere } from '../../utils/messageScope';+import { buildWorkspaceWhere } from '../../utils/workspace';export interface CreateCompressionGroupParams {content: string;@@ -47,16 +47,11 @@ 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 = () =>- buildTopicAnchoredScopeWhere(- { userId: this.userId, workspaceId: this.workspaceId },- messageGroups,- );+ buildWorkspaceWhere({ userId: this.userId, workspaceId: this.workspaceId }, messageGroups);private messagesOwnership = () =>- buildMessageScopeWhere({ userId: this.userId, workspaceId: this.workspaceId });+ buildWorkspaceWhere({ userId: this.userId, workspaceId: this.workspaceId }, messages);/*** 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 9f61ac6c44d..3db81b32586 100644--- a/packages/database/src/repositories/dataExporter/index.ts+++ b/packages/database/src/repositories/dataExporter/index.ts@@ -1,26 +1,10 @@-import type { SQL } from 'drizzle-orm';-import { and, eq, getTableColumns, inArray, isNull } from 'drizzle-orm';-import type { PgTable } from 'drizzle-orm/pg-core';+import { and, eq, inArray } from 'drizzle-orm';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';@@ -115,42 +99,6 @@ 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];@@ -212,32 +160,15 @@ 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 derivedScope = DERIVED_SCOPE_TABLES[table];- const where = derivedScope- ? derivedScope({ userId: this.userId, workspaceId: this.workspaceId })- : 'workspaceId' in tableObj+ const where =+ 'workspaceId' in tableObj? buildWorkspaceWhere({ userId: this.userId, workspaceId: this.workspaceId }, tableObj): eq(tableObj[userField], this.userId);- // 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 });+ // @ts-expect-error query+ const result = 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 f3ba5544e08..02d7137e1be 100644--- a/packages/database/src/repositories/search/index.ts+++ b/packages/database/src/repositories/search/index.ts@@ -1,15 +1,4 @@-import {- and,- desc,- eq,- inArray,- isNull,- ne,- or,- type SQL,- sql,- type SQLWrapper,-} from 'drizzle-orm';+import { and, desc, eq, inArray, isNull, ne, type SQL, sql, type SQLWrapper } from 'drizzle-orm';import type { AnyPgColumn } from 'drizzle-orm/pg-core';import {@@ -21,15 +10,12 @@ 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 =@@ -743,40 +729,6 @@ 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,@@ -787,16 +739,14 @@ 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(- scanBound,+ this.scanScopeWhere(messages),ne(messages.role, 'tool'),agentId && !this.liftsAgentFilter ? eq(messages.agentId, agentId) : undefined,sql`${messages.content} @@@ ${bm25Query}`,@@ -805,16 +755,11 @@ 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 derived- // scope check above the scan drops rows in every mode now, so the pool- // over-fetches in workspace mode too.+ // the scan-shape invariant and `liftsAgentFilter` above..limit(agentId && this.liftsAgentFilter? AGENT_SCOPE_CANDIDATE_POOL- : Math.max(- candidateLimit * WORKSPACE_FILTER_CANDIDATE_MULTIPLIER,- WORKSPACE_FILTER_MIN_CANDIDATES,- ),+ : this.scanCandidateLimit(candidateLimit),).as('message_hits');@@ -836,13 +781,9 @@ 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(- // Authoritative derived scope — topic first, then session, then the- // orphan rows' own snapshot columns.- buildMessageScopeJoinWhere(this.scope, hits),+ this.liftedScopeWhere(hits.workspaceId),agentId ? eq(hits.agentId, agentId) : undefined,),)diff --git a/packages/database/src/repositories/topicDoctor/index.ts b/packages/database/src/repositories/topicDoctor/index.tsindex 493e5dd9593..d316da6d955 100644--- a/packages/database/src/repositories/topicDoctor/index.ts+++ b/packages/database/src/repositories/topicDoctor/index.ts@@ -1,10 +1,11 @@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 { buildMessageScopeWhere } from '../../utils/messageScope';+import { buildWorkspaceWhere } from '../../utils/workspace';interface TopicScope {agentId?: string | null;@@ -39,10 +40,8 @@ export class TopicDoctorRepo {this.messageModel = new MessageModel(db, userId, workspaceId);}- // 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 });+ private ws = (cols: { userId: AnyPgColumn; workspaceId: AnyPgColumn }) =>+ buildWorkspaceWhere({ userId: this.userId, workspaceId: this.workspaceId }, cols);diagnose = async ({ agentId, topicId }: TopicScope): Promise<TopicDiagnosis> => {// The same list the client renders from, so the `parse()` inside the diagnosis sees@@ -65,7 +64,7 @@ export class TopicDoctorRepo {.where(and(eq(messages.topicId, scope.topicId),- this.messagesWs(),+ this.ws(messages),inArray(messages.id,patch.map((op) => op.messageId),@@ -99,7 +98,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.messagesWs()));+ .where(and(eq(messages.id, op.messageId), this.ws(messages)));}});diff --git a/packages/database/src/repositories/userMemory/UserMemoryTopicRepository.ts b/packages/database/src/repositories/userMemory/UserMemoryTopicRepository.tsindex 594585d771f..be5b251bd12 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 { buildMessageScopeWhere } from '../../utils/messageScope';+import { buildWorkspaceWhere } from '../../utils/workspace';/*** Maximum character length for the query string used in memory search@@ -39,11 +39,7 @@ export class UserMemoryTopicRepository {.from(messages).where(and(- // 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),+ buildWorkspaceWhere({ userId: this.userId, workspaceId: this.workspaceId }, messages),eq(messages.topicId, topicId),eq(messages.role, 'user'),),diff --git a/packages/database/src/schemas/message.ts b/packages/database/src/schemas/message.tsindex a41d78eaafc..b62c728c5bc 100644--- a/packages/database/src/schemas/message.ts+++ b/packages/database/src/schemas/message.ts@@ -127,11 +127,6 @@ 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(),@@ -154,10 +149,6 @@ 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.tsdeleted file mode 100644index eedfa8e57b5..00000000000--- a/packages/database/src/utils/messageScope.ts+++ /dev/null@@ -1,270 +0,0 @@-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 11779c23790..d58c1126f3e 100644--- a/packages/openapi/src/common/base.service.ts+++ b/packages/openapi/src/common/base.service.ts@@ -306,32 +306,13 @@ export abstract class BaseService implements IBaseService {return targetFile?.userId;}- // 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.+ // Query messages tablecase !!target?.targetMessageId: {const targetMessage = await this.db.query.messages.findFirst({- columns: { sessionId: true, topicId: true, userId: true },+ columns: { userId: true },where: eq(messages.id, target.targetMessageId),});- 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;+ 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 e151234370d..d53073fea61 100644--- a/packages/openapi/src/services/message-translations.service.ts+++ b/packages/openapi/src/services/message-translations.service.ts@@ -1,8 +1,7 @@-import { and, eq, type SQL } from 'drizzle-orm';+import { and, eq } 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';@@ -21,22 +20,6 @@ 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@@ -48,13 +31,12 @@ export class MessageTranslateService extends BaseService {this.log('info', '根据消息ID获取翻译信息', { messageId, userId: this.userId });try {- // 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);+ const result = await this.db.query.messageTranslates.findFirst({+ where: and(+ eq(messageTranslates.id, messageId),+ this.buildWorkspaceWhere(messageTranslates),+ ),+ });if (!result) {this.log('info', '未找到翻译信息', { messageId });@@ -95,7 +77,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.messageScopeWhere()),+ where: and(eq(messages.id, translateData.messageId), this.buildWorkspaceWhere(messages)),});if (!messageInfo) {@@ -137,7 +119,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.messageScopeWhere()),+ where: and(eq(messages.id, data.messageId), this.buildWorkspaceWhere(messages)),});if (!messageInfo) {throw this.createCommonError('未找到要更新翻译信息的消息');@@ -188,11 +170,12 @@ export class MessageTranslateService extends BaseService {try {// Check if the translation message exists- const [originalTranslation] = await this.db- .select()- .from(messageTranslates)- .where(and(eq(messageTranslates.id, messageId), this.translateScopeWhere()))- .limit(1);+ const originalTranslation = await this.db.query.messageTranslates.findFirst({+ where: and(+ eq(messageTranslates.id, messageId),+ this.buildWorkspaceWhere(messageTranslates),+ ),+ });if (!originalTranslation) {throw this.createNotFoundError('翻译消息不存在');@@ -200,7 +183,9 @@ export class MessageTranslateService extends BaseService {await this.db.delete(messageTranslates)- .where(and(eq(messageTranslates.id, messageId), this.translateScopeWhere()));+ .where(+ and(eq(messageTranslates.id, messageId), this.buildWorkspaceWhere(messageTranslates)),+ );return { deleted: true, messageId };} catch (error) {diff --git a/packages/openapi/src/services/message.service.ts b/packages/openapi/src/services/message.service.tsindex 5b559b51723..18495d30439 100644--- a/packages/openapi/src/services/message.service.ts+++ b/packages/openapi/src/services/message.service.ts@@ -1,10 +1,8 @@-import { and, asc, count, desc, eq, ilike, inArray, isNull, type SQL } from 'drizzle-orm';+import { and, asc, count, desc, eq, ilike, inArray, isNull } from 'drizzle-orm';-import { MessageModel } from '@/database/models/message';-import { messages, messagesFiles, topics } from '@/database/schemas';+import { messages, messagesFiles } 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';@@ -41,23 +39,6 @@ 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@@ -112,11 +93,12 @@ export class MessageService extends BaseService {throw this.createAuthorizationError(permissionResult.message || '无权访问此用户的消息');}- // 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();+ const result = await this.db+ .select({ count: count() })+ .from(messages)+ .where(this.buildPermissionWhere(messages, { userId: targetUserId }));++ const messageCount = result[0]?.count || 0;this.log('info', '用户消息统计完成', { count: messageCount });return { count: messageCount };@@ -146,7 +128,7 @@ export class MessageService extends BaseService {const result = await this.db.select({ count: count() }).from(messages)- .where(and(inArray(messages.topicId, topicIds), this.messageScopeWhere()));+ .where(and(inArray(messages.topicId, topicIds), this.buildWorkspaceWhere(messages)));const messageCount = result[0]?.count || 0;this.log('info', '话题消息统计完成', { count: messageCount });@@ -176,9 +158,13 @@ export class MessageService extends BaseService {return await this.countMessagesByTopicIds(query.topicIds);}- // 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();+ // 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;this.log('info', '当前用户消息统计完成', { count: messageCount });return { count: messageCount };@@ -211,7 +197,7 @@ export class MessageService extends BaseService {const { keyword, limit = 20, offset = 0 } = searchRequest;// Build query conditions- const conditions = [this.messageScopeWhere()];+ const conditions = [this.buildWorkspaceWhere(messages)];const contentMatchedMessages = await this.db.select({ id: messages.id })@@ -281,7 +267,7 @@ export class MessageService extends BaseService {throw this.createAuthorizationError(permissionResult.message || '无权访问消息列表');}- conditions.push(this.messagePermissionScopeWhere({ userId: request.userId })!);+ conditions.push(this.buildPermissionWhere(messages, { userId: request.userId })!);}// Verify topic ownership and whether the user has message read permission@@ -295,7 +281,7 @@ export class MessageService extends BaseService {}conditions.push(eq(messages.topicId, request.topicId));- conditions.push(this.messageScopeWhere());+ conditions.push(this.buildWorkspaceWhere(messages));}if (request.role) {@@ -368,7 +354,7 @@ export class MessageService extends BaseService {// Build query conditionsconst conditions = [eq(messages.id, messageId)];- const permissionWhere = this.messagePermissionScopeWhere(permissionResult.condition);+ const permissionWhere = this.buildPermissionWhere(messages, permissionResult.condition);if (permissionWhere) conditions.push(permissionWhere);const message = (await this.db.query.messages.findFirst({@@ -423,56 +409,33 @@ export class MessageService extends BaseService {throw this.createAuthorizationError(permissionResult.message || '无权创建消息');}- 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,- });- });+ 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,+ });// Handle file attachmentsif (messageData.files && messageData.files.length > 0) {@@ -493,7 +456,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.messageScopeWhere()),+ where: and(eq(messages.id, newMessage.id), this.buildWorkspaceWhere(messages)),with: {filesToMessages: {with: {@@ -628,7 +591,7 @@ export class MessageService extends BaseService {orderBy: desc(messages.createdAt),where: and(topicId === null ? isNull(messages.topicId) : eq(messages.topicId, topicId),- this.messageScopeWhere(),+ this.buildWorkspaceWhere(messages),),});@@ -669,7 +632,7 @@ export class MessageService extends BaseService {const whereConditions = [eq(messages.id, messageId)];// Apply permission conditions- const permissionWhere = this.messagePermissionScopeWhere(permissionResult.condition);+ const permissionWhere = this.buildPermissionWhere(messages, 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 ba621b9394e..2a6e4eb6ab6 100644--- a/packages/openapi/src/services/user.service.ts+++ b/packages/openapi/src/services/user.service.ts@@ -2,7 +2,6 @@ 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';@@ -333,10 +332,8 @@ export class UserService extends BaseService {throw this.createAuthorizationError(permissionResult.message || '没有权限删除该用户');}- // 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);+ // Check if the user exists+ const result = await this.db.delete(users).where(eq(users.id, userId));if (!result.rowCount) {throw this.createNotFoundError('用户不存在');