π€― 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
β»οΈ refactor(database): split the 3310-line topic model into cohesive modules (#21129)
Arvin Xu7f6896815947
diff --git a/apps/server/src/routers/lambda/__tests__/aiChat.test.ts b/apps/server/src/routers/lambda/__tests__/aiChat.test.tsindex 4206c288c22..a3c657be151 100644--- a/apps/server/src/routers/lambda/__tests__/aiChat.test.ts+++ b/apps/server/src/routers/lambda/__tests__/aiChat.test.ts@@ -9,7 +9,7 @@ import { describe, expect, it, vi } from 'vitest';import { AgentModel } from '@/database/models/agent';import { MessageModel } from '@/database/models/message';import { ThreadModel } from '@/database/models/thread';-import { TopicModel } from '@/database/models/topic';+import { TopicRepository } from '@/database/repositories/topic';import { AiChatService } from '@/server/services/aiChat';import { aiChatRouter } from '../aiChat';@@ -19,7 +19,7 @@ const flushAsyncTasks = () => new Promise<void>((resolve) => setTimeout(resolve,vi.mock('@/database/models/agent');vi.mock('@/database/models/message');vi.mock('@/database/models/thread');-vi.mock('@/database/models/topic');+vi.mock('@/database/repositories/topic');vi.mock('@/server/services/aiChat');vi.mock('@/server/services/file', () => ({FileService: vi.fn(),@@ -82,7 +82,7 @@ describe('aiChatRouter', () => {topics: { items: [{}], total: 1 },});- vi.mocked(TopicModel).mockImplementation(function () {+ vi.mocked(TopicRepository).mockImplementation(function () {return { create: mockCreateTopic } as any;});const mockCreateUserAndAssistantMessages = mockMessageModel(mockCreateMessage);@@ -167,7 +167,7 @@ describe('aiChatRouter', () => {topics: { items: [{}], total: 1 },});- vi.mocked(TopicModel).mockImplementation(function () {+ vi.mocked(TopicRepository).mockImplementation(function () {return { create: mockCreateTopic } as any;});const mockCreateUserAndAssistantMessages = mockMessageModel(mockCreateMessage);@@ -199,7 +199,7 @@ describe('aiChatRouter', () => {const mockCreateTopic = vi.fn().mockResolvedValue({ id: 't1' });const mockCreateMessage = vi.fn().mockResolvedValue({ id: 'm-user' });- vi.mocked(TopicModel).mockImplementation(function () {+ vi.mocked(TopicRepository).mockImplementation(function () {return { create: mockCreateTopic } as any;});mockMessageModel(mockCreateMessage);@@ -584,7 +584,7 @@ describe('aiChatRouter', () => {.mockResolvedValueOnce({ id: 'm-assistant' });const mockGet = vi.fn().mockResolvedValue({ messages: [], topics: [{ id: 't-new' }] });- vi.mocked(TopicModel).mockImplementation(function () {+ vi.mocked(TopicRepository).mockImplementation(function () {return { create: mockCreateTopic } as any;});vi.mocked(ThreadModel).mockImplementation(function () {@@ -677,7 +677,7 @@ describe('aiChatRouter', () => {.mockResolvedValueOnce({ id: 'm-assistant' });const mockGet = vi.fn().mockResolvedValue({ messages: [], topics: [{}] });- vi.mocked(TopicModel).mockImplementation(function () {+ vi.mocked(TopicRepository).mockImplementation(function () {return { create: mockCreateTopic } as any;});mockMessageModel(mockCreateMessage);@@ -714,7 +714,7 @@ describe('aiChatRouter', () => {.mockResolvedValueOnce({ id: 'm-assistant' });const mockGet = vi.fn().mockResolvedValue({ messages: [], topics: [{}] });- vi.mocked(TopicModel).mockImplementation(function () {+ vi.mocked(TopicRepository).mockImplementation(function () {return { create: mockCreateTopic } as any;});mockMessageModel(mockCreateMessage);@@ -945,7 +945,7 @@ describe('aiChatRouter', () => {const mockGet = vi.fn().mockResolvedValue({ messages: [], topics: [{}] });const mockTouchUpdatedAt = vi.fn().mockResolvedValue(undefined);- vi.mocked(TopicModel).mockImplementation(function () {+ vi.mocked(TopicRepository).mockImplementation(function () {return { create: mockCreateTopic } as any;});mockMessageModel(mockCreateMessage);@@ -986,7 +986,7 @@ describe('aiChatRouter', () => {const mockGet = vi.fn().mockResolvedValue({ messages: [], topics: [{}] });const mockTouchUpdatedAt = vi.fn().mockResolvedValue(undefined);- vi.mocked(TopicModel).mockImplementation(function () {+ vi.mocked(TopicRepository).mockImplementation(function () {return { create: mockCreateTopic } as any;});mockMessageModel(mockCreateMessage);@@ -1028,7 +1028,7 @@ describe('aiChatRouter', () => {const mockTouchUpdatedAt = vi.fn().mockRejectedValue(touchError);try {- vi.mocked(TopicModel).mockImplementation(function () {+ vi.mocked(TopicRepository).mockImplementation(function () {return { create: mockCreateTopic } as any;});mockMessageModel(mockCreateMessage);@@ -1076,7 +1076,7 @@ describe('aiChatRouter', () => {return touchUpdatedAtPromise;});- vi.mocked(TopicModel).mockImplementation(function () {+ vi.mocked(TopicRepository).mockImplementation(function () {return { create: mockCreateTopic } as any;});const mockCreateUserAndAssistantMessages = mockMessageModel(mockCreateMessage);@@ -1118,7 +1118,7 @@ describe('aiChatRouter', () => {const mockGet = vi.fn().mockResolvedValue({ messages: [], topics: [{}] });const mockTouchUpdatedAt = vi.fn().mockResolvedValue(undefined);- vi.mocked(TopicModel).mockImplementation(function () {+ vi.mocked(TopicRepository).mockImplementation(function () {return { create: mockCreateTopic } as any;});mockMessageModel(mockCreateMessage);diff --git a/apps/server/src/routers/lambda/__tests__/shareVisitorEntryGuard.router.test.ts b/apps/server/src/routers/lambda/__tests__/shareVisitorEntryGuard.router.test.tsindex 3179649d255..c1326089f4a 100644--- a/apps/server/src/routers/lambda/__tests__/shareVisitorEntryGuard.router.test.ts+++ b/apps/server/src/routers/lambda/__tests__/shareVisitorEntryGuard.router.test.ts@@ -22,11 +22,8 @@ const mockTopicUpdate = vi.fn();vi.mock('@/database/models/topic', () => ({TopicModel: vi.fn(function () {return {- batchCreate: mockTopicBatchCreate,- batchMoveToAgent: mockTopicBatchMoveToAgent,create: mockTopicCreate,delete: mockTopicDelete,- duplicate: mockTopicDuplicate,findOwnersByIds: mockTopicFindOwnersByIds,findOwnTopicById: mockTopicFindOwnTopicById,findShareVisitorTopicIds: mockTopicFindShareVisitorTopicIds,@@ -36,6 +33,20 @@ vi.mock('@/database/models/topic', () => ({}),}));+// Cross-aggregate topic writes (create with messages, batch create, clone/fork,+// move) go through TopicRepository; share the spies so guard tests still prove+// the write never ran.+vi.mock('@/database/repositories/topic', () => ({+ TopicRepository: vi.fn(function () {+ return {+ batchCreate: mockTopicBatchCreate,+ batchMoveToAgent: mockTopicBatchMoveToAgent,+ create: mockTopicCreate,+ duplicate: mockTopicDuplicate,+ };+ }),+}));+const mockMessageFindShareVisitorMessageIds = vi.fn();const mockMessageDeleteMessagesBySession = vi.fn();const mockMessageUpdateTTS = vi.fn();diff --git a/apps/server/src/routers/lambda/__tests__/topic.test.ts b/apps/server/src/routers/lambda/__tests__/topic.test.tsindex f9af7bde8c3..3215400ad00 100644--- a/apps/server/src/routers/lambda/__tests__/topic.test.ts+++ b/apps/server/src/routers/lambda/__tests__/topic.test.ts@@ -2,11 +2,16 @@ import { describe, expect, it, vi } from 'vitest';import { TopicModel } from '@/database/models/topic';import { TopicShareModel } from '@/database/models/topicShare';+import { TopicRepository } from '@/database/repositories/topic';vi.mock('@/database/models/topic', () => ({TopicModel: vi.fn(),}));+vi.mock('@/database/repositories/topic', () => ({+ TopicRepository: vi.fn(),+}));+vi.mock('@/database/models/topicShare', () => ({TopicShareModel: vi.fn(),}));@@ -214,7 +219,7 @@ describe('topicRouter', () => {it('should handle batchCreateTopics with agentId', async () => {const mockBatchCreate = vi.fn().mockResolvedValue([{ id: 'topic1' }, { id: 'topic2' }]);- vi.mocked(TopicModel).mockImplementation(function () {+ vi.mocked(TopicRepository).mockImplementation(function () {return {batchCreate: mockBatchCreate,} as any;@@ -226,10 +231,10 @@ describe('topicRouter', () => {];const ctx = {- topicModel: new TopicModel({} as any, 'user1'),+ topicRepo: new TopicRepository({} as any, 'user1'),};- const result = await ctx.topicModel.batchCreate(input as any);+ const result = await ctx.topicRepo.batchCreate(input as any);expect(mockBatchCreate).toHaveBeenCalledWith(input);expect(result).toHaveLength(2);diff --git a/apps/server/src/routers/lambda/aiChat.ts b/apps/server/src/routers/lambda/aiChat.tsindex 76fea6f9e0a..c943e0a1667 100644--- a/apps/server/src/routers/lambda/aiChat.ts+++ b/apps/server/src/routers/lambda/aiChat.ts@@ -17,7 +17,7 @@ import { LOADING_FLAT } from '@/const/message';import { AgentModel } from '@/database/models/agent';import { MessageModel } from '@/database/models/message';import { ThreadModel } from '@/database/models/thread';-import { TopicModel } from '@/database/models/topic';+import { TopicRepository } from '@/database/repositories/topic';import { router } from '@/libs/trpc/lambda';import { serverDatabase } from '@/libs/trpc/lambda/middleware';import { markSilentTRPCErrorLog } from '@/libs/trpc/utils/errorLogger';@@ -137,7 +137,7 @@ const aiChatProcedure = wsCompatProcedure.use(serverDatabase).use(async (opts) =fileService: new FileService(ctx.serverDB, ctx.userId, wsId),messageModel: new MessageModel(ctx.serverDB, ctx.userId, wsId),threadModel: new ThreadModel(ctx.serverDB, ctx.userId, wsId),- topicModel: new TopicModel(ctx.serverDB, ctx.userId, wsId),+ topicRepo: new TopicRepository(ctx.serverDB, ctx.userId, wsId),},});});@@ -267,8 +267,8 @@ export const aiChatRouter = router({// conversation under; honour it so the topic never changes id// mid-flight. Absent (older client) β the model mints one.return modelTiming- ? ctx.topicModel.create(payload, input.newTopic!.id, modelTiming)- : ctx.topicModel.create(payload, input.newTopic!.id);+ ? ctx.topicRepo.create(payload, input.newTopic!.id, modelTiming)+ : ctx.topicRepo.create(payload, input.newTopic!.id);},{messageCount: input.newTopic.topicMessageIds?.length ?? 0,diff --git a/apps/server/src/routers/lambda/topic/create.test.ts b/apps/server/src/routers/lambda/topic/create.test.tsindex b691a76ce8d..62bb31a61ad 100644--- a/apps/server/src/routers/lambda/topic/create.test.ts+++ b/apps/server/src/routers/lambda/topic/create.test.ts@@ -8,8 +8,8 @@ vi.mock('@/database/core/db-adaptor', () => ({}));const mockTopicBatchCreate = vi.fn();-vi.mock('@/database/models/topic', () => ({- TopicModel: vi.fn(function () {+vi.mock('@/database/repositories/topic', () => ({+ TopicRepository: vi.fn(function () {return { batchCreate: mockTopicBatchCreate };}),}));diff --git a/apps/server/src/routers/lambda/topic/create.ts b/apps/server/src/routers/lambda/topic/create.tsindex 2c5f4d18f4e..c86bb438986 100644--- a/apps/server/src/routers/lambda/topic/create.ts+++ b/apps/server/src/routers/lambda/topic/create.ts@@ -73,7 +73,7 @@ export const createRouter = router({resolvedTopics.flatMap((item) => item.messages ?? []),);- const data = await ctx.topicModel.batchCreate(resolvedTopics as any);+ const data = await ctx.topicRepo.batchCreate(resolvedTopics as any);return { added: data.length, ids: [], skips: [], success: true };}),@@ -85,7 +85,7 @@ export const createRouter = router({// Duplicating a visitor topic would copy its content into creator scope// (see `assertCreatorTopicTargets` on `batchMoveTopics` above).await assertCreatorTopicTargets(guardCtx(ctx), [input.id]);- const data = await ctx.topicModel.duplicate(input.id, input.newTitle);+ const data = await ctx.topicRepo.duplicate(input.id, input.newTitle);return data.topic.id;}),@@ -109,7 +109,7 @@ export const createRouter = router({.mutation(async ({ input, ctx }) => {await assertCanUseTopicTargets(guardCtx(ctx), [input.id]);await assertCreatorTopicTargets(guardCtx(ctx), [input.id]);- const data = await ctx.topicModel.duplicate(input.id, input.newTitle, {+ const data = await ctx.topicRepo.duplicate(input.id, input.newTitle, {upToMessageId: input.messageId,});@@ -200,7 +200,7 @@ export const createRouter = router({}): undefined;- const data = await ctx.topicModel.create({+ const data = await ctx.topicRepo.create({...rest,agentId: resolved.agentId,sessionId: resolved.sessionId,diff --git a/apps/server/src/routers/lambda/topic/update.ts b/apps/server/src/routers/lambda/topic/update.tsindex 007e58e69e3..616c4a25d36 100644--- a/apps/server/src/routers/lambda/topic/update.ts+++ b/apps/server/src/routers/lambda/topic/update.ts@@ -126,7 +126,7 @@ export const updateRouter = router({// boundary rather than in the model defaults.await assertCreatorTopicTargets(guardCtx(ctx), input.topicIds);- return ctx.topicModel.batchMoveToAgent(input.topicIds, input.targetAgentId);+ return ctx.topicRepo.batchMoveToAgent(input.topicIds, input.targetAgentId);}),cancelRateLimitContinuation: topicProcedure.use(withScopedPermission('topic:update'))diff --git a/apps/server/src/services/aiAgent/__tests__/precreatedTopic.test.ts b/apps/server/src/services/aiAgent/__tests__/precreatedTopic.test.tsindex b9f0fbbcd11..3dadd9ec26d 100644--- a/apps/server/src/services/aiAgent/__tests__/precreatedTopic.test.ts+++ b/apps/server/src/services/aiAgent/__tests__/precreatedTopic.test.ts@@ -1,6 +1,6 @@import { beforeEach, describe, expect, it, vi } from 'vitest';-import { resolvePrecreatedTopicSnapshot } from '../pipeline/precreatedTopic';+import { createGroupAgentTopic, resolvePrecreatedTopicSnapshot } from '../pipeline/precreatedTopic';const { getInfoForAIGeneration, getPreference, isResourceAuthorOrAdmin } = vi.hoisted(() => ({getInfoForAIGeneration: vi.fn(),@@ -61,3 +61,38 @@ describe('resolvePrecreatedTopicSnapshot', () => {expect(snapshot).toMatchObject({ model: 'gpt-4o', provider: 'openai' });});});++describe('createGroupAgentTopic', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ getPreference.mockResolvedValue({});+ isResourceAuthorOrAdmin.mockResolvedValue(false);+ getInfoForAIGeneration.mockResolvedValue({ responseLanguage: 'en-US' });+ });++ // Re-parenting `topicMessageIds` is a cross-aggregate write: it must go+ // through the repository, since TopicModel.create refuses a messages list.+ it('creates the topic through the repository with the adopted messages', async () => {+ const create = vi.fn().mockResolvedValue({ id: 'topic-new' });++ const topicId = await createGroupAgentTopic(+ { ...deps(), topicRepo: { create } as never },+ {+ agentId: 'agent-a',+ groupId: 'group-1',+ message: 'hello group',+ newTopic: { title: 'Group topic', topicMessageIds: ['msg-1', 'msg-2'] },+ },+ );++ expect(topicId).toBe('topic-new');+ expect(create).toHaveBeenCalledWith(+ expect.objectContaining({+ agentId: 'agent-a',+ groupId: 'group-1',+ messages: ['msg-1', 'msg-2'],+ title: 'Group topic',+ }),+ );+ });+});diff --git a/apps/server/src/services/aiAgent/index.ts b/apps/server/src/services/aiAgent/index.tsindex e692e3982e6..de515af2067 100644--- a/apps/server/src/services/aiAgent/index.ts+++ b/apps/server/src/services/aiAgent/index.ts@@ -30,6 +30,7 @@ import { TaskModel } from '@/database/models/task';import { ThreadModel } from '@/database/models/thread';import { TopicModel } from '@/database/models/topic';import { UserModel } from '@/database/models/user';+import { TopicRepository } from '@/database/repositories/topic';import { createStreamEventManager } from '@/server/modules/AgentRuntime/factory';import { AgentService } from '@/server/services/agent';import { AgentDocumentsService } from '@/server/services/agentDocuments';@@ -540,7 +541,10 @@ export class AiAgentService {// - no topicId is provided (default behavior for group chat)if (newTopic || !inputTopicId) {topicId = await createGroupAgentTopic(- { ...this.precreatedTopicDeps(), topicModel: this.topicModel },+ {+ ...this.precreatedTopicDeps(),+ topicRepo: new TopicRepository(this.db, this.userId, this.workspaceId),+ },{ agentId, groupId, message, newTopic },);isCreateNewTopic = true;diff --git a/apps/server/src/services/aiAgent/pipeline/precreatedTopic.ts b/apps/server/src/services/aiAgent/pipeline/precreatedTopic.tsindex 7efd4a818fa..4a4d08a3f51 100644--- a/apps/server/src/services/aiAgent/pipeline/precreatedTopic.ts+++ b/apps/server/src/services/aiAgent/pipeline/precreatedTopic.ts@@ -2,7 +2,7 @@ import type { LobeChatDatabase } from '@lobechat/database';import type { ExecGroupAgentParams } from '@lobechat/types';import { TRPCError } from '@trpc/server';-import type { TopicModel } from '@/database/models/topic';+import type { TopicRepository } from '@/database/repositories/topic';import type { AgentConfigWithId } from '@/server/services/agent';import { AgentService } from '@/server/services/agent';import { markdownToTxt } from '@/utils/markdownToTxt';@@ -60,7 +60,8 @@ export const resolvePrecreatedTopicSnapshot = async (};export interface GroupAgentTopicDeps extends PrecreatedTopicDeps {- topicModel: TopicModel;+ /** Repository-owned create: `newTopic.topicMessageIds` re-parents messages atomically. */+ topicRepo: TopicRepository;}/**@@ -85,7 +86,7 @@ export const createGroupAgentTopic = async ({ db: deps.db, userId: deps.userId, workspaceId: deps.workspaceId },agentConfig,);- const topicItem = await deps.topicModel.create({+ const topicItem = await deps.topicRepo.create({...snapshot,agentId,groupId,diff --git a/packages/database/package.json b/packages/database/package.jsonindex 962c4759c17..1b9834bc076 100644--- a/packages/database/package.json+++ b/packages/database/package.json@@ -22,6 +22,7 @@"@lobechat/conversation-flow": "workspace:*","@lobechat/types": "workspace:*","@lobechat/utils": "workspace:*",+ "p-map": "^7.0.6","random-words": "^2.0.1","remove-markdown": "^0.6.4","ts-md5": "^2.0.1",diff --git a/packages/database/src/models/__tests__/topic.test.ts b/packages/database/src/models/__tests__/topic.test.tsindex ec1eba4eae1..5ab8a3186a2 100644--- a/packages/database/src/models/__tests__/topic.test.ts+++ b/packages/database/src/models/__tests__/topic.test.ts@@ -9,7 +9,6 @@ import {chatGroups,messages,projects,- sessions,topics,users,workspaces,@@ -152,60 +151,6 @@ describe('TopicModel', () => {expect(topic.groupId).toBeNull();expect(topic.sessionId).toBeNull();});-- it('attaches given messages to the new topic in a transaction', async () => {- await serverDB.insert(messages).values([- { content: 'm1', id: 'msg-1', role: 'user', userId },- { content: 'm2', id: 'msg-2', role: 'assistant', userId },- ]);-- const topic = await topicModel.create({ messages: ['msg-1', 'msg-2'], title: 'with msgs' });-- const linked = await serverDB- .select({ id: messages.id, topicId: messages.topicId })- .from(messages)- .where(eq(messages.topicId, topic.id));-- expect(linked.map((m) => m.id).sort()).toEqual(['msg-1', 'msg-2']);- });- });-- describe('batchCreate', () => {- it('keeps a session topic session-scoped and a group topic group-scoped', async () => {- await serverDB.insert(agents).values({ id: 'agent-b', userId });- await serverDB.insert(sessions).values({ id: 'session-x', userId });- await serverDB.insert(chatGroups).values({ id: 'group-b', userId });-- const created = await topicModel.batchCreate([- { agentId: 'agent-b', sessionId: 'session-x', title: 'session topic' },- { groupId: 'group-b', title: 'group topic' },- ]);-- const bySession = created.find((t) => t.title === 'session topic')!;- const byGroup = created.find((t) => t.title === 'group topic')!;-- // sessionId given (no groupId) β sessionId kept, groupId stays null- expect(bySession.sessionId).toBe('session-x');- expect(bySession.groupId).toBeNull();-- // groupId given (no sessionId) β groupId kept, sessionId stays null- expect(byGroup.groupId).toBe('group-b');- expect(byGroup.sessionId).toBeNull();- });-- it('drops both owner ids when sessionId and groupId are passed together', async () => {- await serverDB.insert(sessions).values({ id: 'session-both', userId });- await serverDB.insert(chatGroups).values({ id: 'group-both', userId });-- // Each field is nulled based on the *other* being present, so passing both- // detaches the topic from both β callers must pick exactly one.- const [created] = await topicModel.batchCreate([- { groupId: 'group-both', sessionId: 'session-both', title: 'ambiguous' },- ]);-- expect(created.sessionId).toBeNull();- expect(created.groupId).toBeNull();- });});describe('findById', () => {@@ -1719,251 +1664,6 @@ describe('TopicModel', () => {});});- describe('duplicate', () => {- it('copies the topic and its messages under a new id', async () => {- const topic = await topicModel.create({ title: 'original' });- await serverDB.insert(messages).values([- { content: 'hi', id: 'dup-m1', role: 'user', topicId: topic.id, userId },- { content: 'yo', id: 'dup-m2', role: 'assistant', topicId: topic.id, userId },- ]);-- const { topic: cloned, messages: clonedMessages } = await topicModel.duplicate(- topic.id,- 'copy',- );-- expect(cloned.id).not.toBe(topic.id);- expect(cloned.title).toBe('copy');- expect(clonedMessages).toHaveLength(2);- expect(clonedMessages.every((m) => m.topicId === cloned.id)).toBe(true);- expect(clonedMessages.map((m) => m.id)).not.toContain('dup-m1');- });-- it('marks duplicated messages and resets the topic-level rollups', async () => {- const usage = { cost: 0.05, totalInputTokens: 100, totalOutputTokens: 50 };- const topic = await topicModel.create({ title: 'billed' });- await serverDB- .update(topics)- .set({ totalCost: '0.05' as any, totalTokens: 150 })- .where(eq(topics.id, topic.id));- await serverDB.insert(messages).values([- {- content: 'answer',- id: 'dup-billed',- metadata: { performance: { tps: 42 }, usage },- role: 'assistant',- topicId: topic.id,- usage,- userId,- },- ]);-- const { topic: cloned, messages: clonedMessages } = await topicModel.duplicate(topic.id);-- // per-message figures are transcript facts and survive the copy...- const clone = clonedMessages[0];- expect(clone.usage).toEqual(usage);- const metadata = clone.metadata as Record<string, unknown>;- expect(metadata.usage).toEqual(usage);- expect(metadata.performance).toEqual({ tps: 42 });- // ...but the row is marked, so usage reports skip it- expect(metadata.copied).toBe(true);-- // the topic rollup answers "what did this topic cost this scope", and a- // fresh duplicate has spent nothing yet- const clonedTopic = await serverDB.query.topics.findFirst({- where: (t, { eq: is }) => is(t.id, cloned.id),- });- expect(clonedTopic?.totalCost).toBeNull();- expect(clonedTopic?.totalTokens).toBeNull();- });-- it('throws when the source topic does not exist', async () => {- await expect(topicModel.duplicate('nope')).rejects.toThrow('not found');- });-- it('copies only the ancestor chain when forking up to a message', async () => {- const topic = await topicModel.create({ title: 'fork source' });- await serverDB.insert(messages).values([- { content: 'q1', id: 'fork-m1', role: 'user', topicId: topic.id, userId },- {- content: 'a1',- id: 'fork-m2',- parentId: 'fork-m1',- role: 'assistant',- topicId: topic.id,- userId,- },- {- content: 'q2',- id: 'fork-m3',- parentId: 'fork-m2',- role: 'user',- topicId: topic.id,- userId,- },- ]);-- const { topic: forked, messages: forkedMessages } = await topicModel.duplicate(- topic.id,- 'forked',- { upToMessageId: 'fork-m2' },- );-- // only the selected prefix is copied, in root β selected order- expect(forkedMessages.map((m) => m.content)).toEqual(['q1', 'a1']);- expect(forkedMessages.every((m) => m.topicId === forked.id)).toBe(true);-- // the chain is re-parented inside the fork: root stays root, child points at the copy- const [root, child] = forkedMessages;- expect(root.parentId).toBeNull();- expect(child.parentId).toBe(root.id);-- // the unselected tail stays behind in the source topic- const sourceMessages = await serverDB- .select()- .from(messages)- .where(eq(messages.topicId, topic.id));- expect(sourceMessages.map((m) => m.id).sort()).toEqual(['fork-m1', 'fork-m2', 'fork-m3']);- });-- it('leaves sibling branches out of the fork', async () => {- const topic = await topicModel.create({ title: 'branched source' });- await serverDB.insert(messages).values([- { content: 'q1', id: 'br-m1', role: 'user', topicId: topic.id, userId },- {- content: 'draft',- id: 'br-m2a',- parentId: 'br-m1',- role: 'assistant',- topicId: topic.id,- userId,- },- {- content: 'regenerated',- id: 'br-m2b',- parentId: 'br-m1',- role: 'assistant',- topicId: topic.id,- userId,- },- ]);-- const { messages: forkedMessages } = await topicModel.duplicate(topic.id, 'forked', {- upToMessageId: 'br-m2b',- });-- expect(forkedMessages.map((m) => m.content)).toEqual(['q1', 'regenerated']);- });-- it('throws when the fork anchor message is not in the topic', async () => {- const topic = await topicModel.create({ title: 'no anchor' });-- await expect(- topicModel.duplicate(topic.id, 'forked', { upToMessageId: 'missing' }),- ).rejects.toThrow('not found in topic');- });-- it('stamps the copy with fresh activity time instead of inheriting the source date', async () => {- const sourceDate = new Date('2020-01-02T03:04:05Z');- const topic = await topicModel.create({ title: 'stale source' });- await serverDB.insert(messages).values([- {- content: 'old q',- createdAt: sourceDate,- id: 'stale-m1',- role: 'user',- topicId: topic.id,- updatedAt: sourceDate,- userId,- },- {- content: 'old a',- createdAt: new Date(sourceDate.getTime() + 1000),- id: 'stale-m2',- parentId: 'stale-m1',- role: 'assistant',- topicId: topic.id,- updatedAt: new Date(sourceDate.getTime() + 1000),- userId,- },- ]);-- const before = Date.now();- const { topic: cloned, messages: clonedMessages } = await topicModel.duplicate(- topic.id,- 'fresh copy',- { upToMessageId: 'stale-m2' },- );-- // A copy is new activity: its own row and every copied message carry the- // copy moment. The sidebar keys topics by the newest message activity, so- // inheriting the source's 2020 timestamps would re-file the copy under the- // source's date group instead of today.- expect(new Date(cloned.createdAt).getTime()).toBeGreaterThanOrEqual(before - 1000);- for (const message of clonedMessages) {- expect(new Date(message.updatedAt).getTime()).toBeGreaterThanOrEqual(before - 1000);- }-- // The retained order survives retiming: rows still increase root β leaf.- const [root, child] = clonedMessages;- expect(new Date(root.createdAt).getTime()).toBeLessThan(new Date(child.createdAt).getTime());-- // The source keeps its own timestamps untouched.- const sourceMessages = await serverDB- .select()- .from(messages)- .where(eq(messages.topicId, topic.id));- expect(sourceMessages.every((m) => new Date(m.updatedAt).getTime() < before)).toBe(true);- });- });-- describe('batchMoveToAgent', () => {- it('reassigns agentId, clears sessionId, and moves child messages', async () => {- await serverDB.insert(agents).values([- { id: 'agent-src', userId },- { id: 'agent-dst', userId },- ]);- await serverDB.insert(topics).values({- agentId: 'agent-src',- id: 'move-1',- sessionId: null,- title: 'movable',- userId,- });- await serverDB.insert(messages).values({- agentId: 'agent-src',- content: 'm',- id: 'move-msg',- role: 'user',- topicId: 'move-1',- userId,- });-- await topicModel.batchMoveToAgent(['move-1'], 'agent-dst');-- const [topic] = await serverDB.select().from(topics).where(eq(topics.id, 'move-1'));- expect(topic.agentId).toBe('agent-dst');- expect(topic.sessionId).toBeNull();-- const [msg] = await serverDB.select().from(messages).where(eq(messages.id, 'move-msg'));- expect(msg.agentId).toBe('agent-dst');- });-- it('throws when the target agent is not accessible', async () => {- await serverDB.insert(agents).values({ id: 'agent-foreign', userId: otherUserId });- await serverDB.insert(topics).values({ id: 'move-x', title: 'x', userId });-- await expect(topicModel.batchMoveToAgent(['move-x'], 'agent-foreign')).rejects.toThrow(- 'not found or not accessible',- );- });-- it('is a no-op for an empty id list', async () => {- await expect(topicModel.batchMoveToAgent([], 'whatever')).resolves.toBeUndefined();- });- });-describe('getCronTopicsGroupedByCronJob', () => {it('groups cron-triggered topics by their cronJobId and skips topics without one', async () => {await serverDB.insert(agents).values({ id: 'agent-cron', userId });diff --git a/packages/database/src/models/__tests__/topics/topic.characterization.test.ts b/packages/database/src/models/__tests__/topics/topic.characterization.test.tsnew file mode 100644index 00000000000..6176b85cd98--- /dev/null+++ b/packages/database/src/models/__tests__/topics/topic.characterization.test.ts@@ -0,0 +1,368 @@+import { eq } from 'drizzle-orm';+import { afterEach, beforeEach, describe, expect, it } from 'vitest';++import { getTestDB } from '../../../core/getTestDB';+import { agentOperations, agents, chatGroups, sessions, topics, users } from '../../../schemas';+import type { LobeChatDatabase } from '../../../type';+import * as topicModule from '../../topic';+import { TopicModel } from '../../topic';++const userId = 'topic-char-user';+const otherUserId = 'topic-char-other';+const agentId = 'topic-char-agent';+const groupId = 'topic-char-group';+const sessionId = 'topic-char-session';++const serverDB: LobeChatDatabase = await getTestDB();+const topicModel = new TopicModel(serverDB, userId);++/** Former private helpers; excluded so the pin only covers the public surface. */+const PRIVATE_MEMBERS = new Set([+ 'genId',+ 'matchContainer',+ 'matchGroup',+ 'matchKeywordScope',+ 'matchSession',+ 'messageOwnership',+ 'mine',+ 'notShareVisitor',+ 'ownership',+ 'trashScope',+ 'workspaceScope',+]);++const PUBLIC_METHODS = [+ 'appendRunningOperationChild',+ 'armScheduledRun',+ 'batchDelete',+ 'batchDeleteByAgentId',+ 'batchDeleteByGroupId',+ 'batchDeleteBySessionId',+ 'batchDeleteIncludingTrashed',+ 'batchInsert',+ 'cancelRateLimitContinuation',+ 'count',+ 'countBySender',+ 'countShareVisitors',+ 'countTopicsForMemoryExtractor',+ 'create',+ 'delete',+ 'deleteAll',+ 'findByAgentAndDocumentTrigger',+ 'findById',+ 'findByIds',+ 'findOwnTopicById',+ 'findOwnTopicsByIds',+ 'findOwnersByIds',+ 'findRecentByBotThread',+ 'findRunInitiators',+ 'findShareVisitorTopicIds',+ 'findTrashedByIds',+ 'getCronTopicsGroupedByCronJob',+ 'isRunningOperationAlive',+ 'listTopicsForMemoryExtractor',+ 'patchRunningOperation',+ 'purge',+ 'query',+ 'queryByKeyword',+ 'queryBySender',+ 'queryRecent',+ 'queryTopics',+ 'rank',+ 'recomputeUsage',+ 'releaseTaskCallbackReservation',+ 'removeRunningOperationChild',+ 'repairAgentInterventionContinuation',+ 'resetMemoryExtractStatus',+ 'restore',+ 'settleRunningOperation',+ 'settleRunningStatus',+ 'softDelete',+ 'softDeleteAll',+ 'softDeleteByAgentId',+ 'softDeleteByGroupId',+ 'softDeleteByParents',+ 'softDeleteBySessionId',+ 'takeRunningOperation',+ 'tryReserveTaskCallback',+ 'update',+ 'updateMetadata',+ 'updateModelPin',+ 'updateRunningOperationAssistantMessage',+];++describe('TopicModel - public surface', () => {+ it('exposes the same instance methods', () => {+ const model = new TopicModel({} as LobeChatDatabase, userId);+ const methods = Object.keys(model)+ .filter((key) => typeof (model as any)[key] === 'function' && !PRIVATE_MEMBERS.has(key))+ .sort();++ expect(methods).toEqual(PUBLIC_METHODS);+ });++ it('exposes the same static methods', () => {+ expect(+ [+ 'claimScheduledTopic',+ 'clearScheduledRun',+ 'getDueScheduledTopics',+ 'repointScheduledRunFailedMessage',+ ].filter((key) => typeof (TopicModel as any)[key] === 'function'),+ ).toHaveLength(4);+ });++ it('keeps the runtime exports of the module', () => {+ expect(Object.keys(topicModule).sort()).toEqual([+ 'TopicModel',+ 'getTopicDeviceId',+ 'hasLiveTaskCallbackReservation',+ ]);+ });+});++describe('TopicModel - characterization', () => {+ const deletedAt = new Date('2024-06-01T00:00:00.000Z');++ beforeEach(async () => {+ await serverDB.delete(agentOperations);+ await serverDB.delete(users);+ await serverDB.insert(users).values([{ id: userId }, { id: otherUserId }]);+ await serverDB.insert(sessions).values({ id: sessionId, userId });+ await serverDB.insert(agents).values({ id: agentId, userId });+ await serverDB.insert(chatGroups).values({ id: groupId, userId });+ await serverDB.insert(topics).values([+ { agentId, id: 'agent-topic', title: 'agent', userId },+ { groupId, id: 'group-topic', title: 'group', userId },+ { id: 'session-topic', sessionId, title: 'session', userId },+ { id: 'inbox-topic', title: 'inbox', userId },+ { agentId, id: 'visitor-topic', senderId: 'visitor-1', title: 'visitor', userId },+ { agentId, id: 'visitor-topic-2', senderId: 'visitor-1', title: 'visitor 2', userId },+ { id: 'foreign-topic', title: 'foreign', userId: otherUserId },+ ]);+ });++ afterEach(async () => {+ await serverDB.delete(agentOperations);+ await serverDB.delete(users);+ });++ const liveIds = async () =>+ (+ await serverDB+ .select({ id: topics.id, isDeleted: topics.isDeleted })+ .from(topics)+ .where(eq(topics.userId, userId))+ )+ .filter((row) => !row.isDeleted)+ .map((row) => row.id)+ .sort();++ describe('recycle bin', () => {+ it('softDelete trashes owned ids, skipping visitor and foreign rows', async () => {+ const result = await topicModel.softDelete(+ ['agent-topic', 'visitor-topic', 'foreign-topic'],+ { deletedAt },+ );++ expect(result.map((row) => row.id)).toEqual(['agent-topic']);+ expect(result[0]).toMatchObject({ deletedAt, isDeleted: true });+ expect(await topicModel.findById('agent-topic')).toBeUndefined();+ });++ it('softDelete returns [] for empty ids', async () => {+ expect(await topicModel.softDelete([], { deletedAt })).toEqual([]);+ });++ it.each([+ [+ 'softDeleteBySessionId',+ () => topicModel.softDeleteBySessionId(sessionId, { deletedAt }),+ ['session-topic'],+ ],+ [+ 'softDeleteBySessionId(null)',+ () => topicModel.softDeleteBySessionId(null, { deletedAt }),+ ['agent-topic', 'group-topic', 'inbox-topic'],+ ],+ [+ 'softDeleteByGroupId',+ () => topicModel.softDeleteByGroupId(groupId, { deletedAt }),+ ['group-topic'],+ ],+ [+ 'softDeleteByAgentId',+ () => topicModel.softDeleteByAgentId(agentId, { deletedAt, restrictToCreator: true }),+ ['agent-topic'],+ ],+ [+ 'softDeleteByParents',+ () =>+ topicModel.softDeleteByParents(+ { groupIds: [groupId], sessionIds: [sessionId] },+ { deletedAt },+ ),+ ['group-topic', 'session-topic'],+ ],+ ['softDeleteByParents({})', () => topicModel.softDeleteByParents({}, { deletedAt }), []],+ [+ 'softDeleteAll',+ () => topicModel.softDeleteAll({ deletedAt }),+ ['agent-topic', 'group-topic', 'inbox-topic', 'session-topic'],+ ],+ ] as const)('%s trashes exactly the matching creator rows', async (_name, run, expected) => {+ const result = await run();++ expect(result.map((row) => row.id).sort()).toEqual([...expected]);+ });++ it('restore / findTrashedByIds / purge only touch trashed owned rows', async () => {+ await topicModel.softDelete(['agent-topic', 'group-topic'], { deletedAt });++ expect(+ (await topicModel.findTrashedByIds(['agent-topic', 'inbox-topic'])).map((r) => r.id),+ ).toEqual(['agent-topic']);+ expect((await topicModel.restore(['agent-topic', 'inbox-topic'])).map((r) => r.id)).toEqual([+ 'agent-topic',+ ]);+ expect(await topicModel.purge(['agent-topic', 'group-topic', 'inbox-topic'])).toEqual([+ 'group-topic',+ ]);+ expect(await liveIds()).toEqual([+ 'agent-topic',+ 'inbox-topic',+ 'session-topic',+ 'visitor-topic',+ 'visitor-topic-2',+ ]);+ expect(await topicModel.restore([])).toEqual([]);+ expect(await topicModel.findTrashedByIds([])).toEqual([]);+ expect(await topicModel.purge([])).toEqual([]);+ });++ it('batchDeleteIncludingTrashed removes trashed rows too', async () => {+ await topicModel.softDelete(['agent-topic'], { deletedAt });+ await topicModel.batchDeleteIncludingTrashed(['agent-topic', 'visitor-topic']);++ const remaining = await serverDB.select({ id: topics.id }).from(topics);+ expect(remaining.map((row) => row.id)).not.toContain('agent-topic');+ expect(remaining.map((row) => row.id)).toContain('visitor-topic');+ });+ });++ describe('reads', () => {+ it('findOwnersByIds returns owned, non-visitor rows', async () => {+ expect(await topicModel.findOwnersByIds([])).toEqual([]);+ expect(+ await topicModel.findOwnersByIds(['agent-topic', 'visitor-topic', 'foreign-topic']),+ ).toEqual([{ id: 'agent-topic', userId }]);+ });++ it('share visitor scoping depends on includeShareVisitor', async () => {+ const visitorModel = new TopicModel(serverDB, userId, undefined, undefined, {+ includeShareVisitor: true,+ });++ expect(await topicModel.findById('visitor-topic')).toBeUndefined();+ expect((await visitorModel.findById('visitor-topic'))?.id).toBe('visitor-topic');+ expect(await topicModel.findShareVisitorTopicIds(['visitor-topic', 'agent-topic'])).toEqual([+ 'visitor-topic',+ ]);+ expect(await topicModel.countBySender({ agentId, senderId: 'visitor-1' })).toBe(2);+ expect(await topicModel.countBySender({ agentId, senderId: 'visitor-2' })).toBe(0);+ expect(await topicModel.countShareVisitors({ agentId })).toEqual({+ topicCount: 2,+ visitorCount: 1,+ });+ });++ it('findRecentByBotThread matches the bot thread id, newest first, limited', async () => {+ await serverDB.insert(topics).values([+ {+ id: 'bot-1',+ metadata: { bot: { platformThreadId: 'thread-1' } } as any,+ updatedAt: new Date('2024-01-01'),+ userId,+ },+ {+ id: 'bot-2',+ metadata: { bot: { platformThreadId: 'thread-1' } } as any,+ updatedAt: new Date('2024-01-02'),+ userId,+ },+ {+ id: 'bot-other',+ metadata: { bot: { platformThreadId: 'thread-2' } } as any,+ userId,+ },+ ]);++ expect(await topicModel.findRecentByBotThread('')).toEqual([]);+ expect((await topicModel.findRecentByBotThread('thread-1')).map((t) => t.id)).toEqual([+ 'bot-2',+ 'bot-1',+ ]);+ expect(+ (await topicModel.findRecentByBotThread('thread-1', { limit: 1 })).map((t) => t.id),+ ).toEqual(['bot-2']);+ });+ });++ describe('running operation markers', () => {+ const setRunning = (metadata: Record<string, unknown>) =>+ serverDB+ .update(topics)+ .set({ metadata: metadata as any })+ .where(eq(topics.id, 'agent-topic'));++ it('removeRunningOperationChild drops only the named child', async () => {+ expect(await topicModel.removeRunningOperationChild('agent-topic', 'child-1')).toBe(false);++ await setRunning({+ runningOperation: {+ assistantMessageId: 'msg',+ childOperations: [+ { assistantMessageId: 'c1', operationId: 'child-1' },+ { assistantMessageId: 'c2', operationId: 'child-2' },+ ],+ operationId: 'root',+ },+ });++ expect(await topicModel.removeRunningOperationChild('agent-topic', 'child-1')).toBe(true);+ const topic = await topicModel.findById('agent-topic');+ expect(topic?.metadata?.runningOperation?.childOperations).toEqual([+ { assistantMessageId: 'c2', operationId: 'child-2' },+ ]);+ });++ it.each([+ ['no row, fresh marker stamp', undefined, new Date().toISOString(), true],+ ['no row, stale marker stamp', undefined, '2000-01-01T00:00:00.000Z', false],+ ['no row, no stamp', undefined, undefined, false],+ ['parked on a human', 'waiting_for_human', undefined, true],+ ['terminal status', 'done', undefined, false],+ ['fresh running row', 'running', undefined, true],+ ] as const)(+ 'isRunningOperationAlive: %s',+ async (_name, operationStatus, startedAt, expected) => {+ if (operationStatus) {+ await serverDB.insert(agentOperations).values({+ id: 'op-alive',+ status: operationStatus,+ topicId: 'agent-topic',+ userId,+ } as any);+ }++ expect(+ await topicModel.isRunningOperationAlive(serverDB, {+ assistantMessageId: 'msg',+ operationId: 'op-alive',+ startedAt,+ } as any),+ ).toBe(expected);+ },+ );+ });+});diff --git a/packages/database/src/models/topic.ts b/packages/database/src/models/topic.tsdeleted file mode 100644index 78079264a4a..00000000000--- a/packages/database/src/models/topic.ts+++ /dev/null@@ -1,3310 +0,0 @@-import { AGENT_SHARE_VISITOR_TOPIC_LIST_LIMIT } from '@lobechat/const';-import type {- AgentOperationStatus,- ChatTopicMetadata,- ChatTopicStatus,- DBMessageItem,- TopicQuerySortBy,- TopicRankItem,- TopicScheduledRun,-} from '@lobechat/types';-import { parseTopicScheduledRun } from '@lobechat/types';-import type { TimingSink } from '@lobechat/utils';-import {- getDurationMs,- logTimingSink as logTiming,- runTimedSinkStage as runTimedStage,-} from '@lobechat/utils';-import type { SQL } from 'drizzle-orm';-import {- and,- asc,- count,- countDistinct,- desc,- eq,- getTableColumns,- gt,- gte,- inArray,- isNotNull,- isNull,- lte,- ne,- not,- or,- sql,-} from 'drizzle-orm';--import { clampToolIdentifier } from '@/utils/clampToolIdentifier';--import type { FtsSearchCandidateSource } from '../repositories/ftsSearch';-import type { TopicItem } from '../schemas';-import {- agentOperations,- agents,- chatGroups,- messagePlugins,- messages,- threads,- topicDocuments,- topics,-} from '../schemas';-import type { LobeChatDatabase } from '../type';-import { sanitizeBm25Query } from '../utils/bm25';-import { COPIED_TOPIC_USAGE_RESET } from '../utils/copiedTranscript';-import { markCopiedMessageMetadata } from '../utils/copyMessagesInDatabase';-import { genEndDateWhere, genRangeWhere, genStartDateWhere, genWhere } from '../utils/genWhere';-import { idGenerator } from '../utils/idGenerator';-import { inJsonStringArray } from '../utils/inJsonStringArray';-import { searchableMessage } from '../utils/searchableMessage';-import { notShareVisitorTopic } from '../utils/shareVisitor';-import {- isTrashed,- notTrashed,- restoreStamp,- type SoftDeleteOptions,- trashStamp,-} from '../utils/softDelete';-import { buildWorkspacePayload, buildWorkspaceWhere } from '../utils/workspace';-import { topicMetadataWithCreator } from './topicCreator';-import { recomputeTopicUsage } from './topicUsage';--type OnboardingSessionMetadataPatch = Partial<NonNullable<ChatTopicMetadata['onboardingSession']>>;-type RunningOperation = NonNullable<ChatTopicMetadata['runningOperation']>;-type RunningOperationPatch = Omit<Partial<RunningOperation>, 'childOperations' | 'operationId'>;-type TopicMetadataPatch = Omit<Partial<ChatTopicMetadata>, 'onboardingSession'> & {- onboardingSession?: OnboardingSessionMetadataPatch;-};--/**- * How much of the last assistant reply `queryTopics` ships to a list view. Long- * enough that a run summary arrives whole, short enough that 200 rows of raw- * markdown never do β anything past it is marked with an ellipsis, and the full- * text is one click away in the topic itself.- */-const LAST_MESSAGE_PREVIEW_LENGTH = 2000;-const TASK_CALLBACK_RESERVATION_TTL_MS = 5 * 60 * 1000;--/**- * The device a topic runs on: the one its in-flight run was dispatched to,- * else the one its turns are pinned to. The live dispatch wins because a run- * does not always follow the pin β an `auto` target, an explicit request- * device or a fixed workspace target can send it elsewhere. The `deviceId`- * filter of `TopicModel.queryTopics` applies the same precedence in SQL.- */-export const getTopicDeviceId = (- metadata: Pick<ChatTopicMetadata, 'boundDeviceId' | 'runningOperation'> | null | undefined,-): string | undefined => metadata?.runningOperation?.deviceId ?? metadata?.boundDeviceId;--/**- * Whether a turn start currently holds the topic's short start reservation.- * A writer that changes where the topic runs must respect it as it would a- * `runningOperation`: the reserving turn may already have resolved its target.- */-export const hasLiveTaskCallbackReservation = (- metadata: Pick<ChatTopicMetadata, 'taskCallbackReservation'> | null | undefined,- now = Date.now(),-): boolean => {- const reservation = metadata?.taskCallbackReservation;- if (!reservation) return false;- const reservedAt = Date.parse(reservation.reservedAt);- return Number.isFinite(reservedAt) && now - reservedAt < TASK_CALLBACK_RESERVATION_TTL_MS;-};-/**- * How long an operation that still claims `running` / `idle` may hold the topic- * against a background start before it is treated as abandoned.- *- * Only a backstop for the case the operation row cannot describe: a process- * killed mid-run leaves its row at `running` forever, and every marker clear- * site is best-effort (`ServerOperationStore.clearRunningMark` swallows- * failures; the gateway client clears it from `onSessionComplete`, which never- * runs if the tab closed). Runs parked on a human or an async tool are exempt β- * those legitimately last days β so this only has to be longer than a plausible- * uninterrupted generation. The real reaper remains the gateway watchdog's- * `finalize-abandoned` call.- */-const ABANDONED_OPERATION_TTL_MS = 6 * 60 * 60 * 1000;-/**- * Operation statuses that mean "this run is still the topic's owner". Parked- * states are included on purpose: a run waiting for approval is not stuck.- */-const LIVE_OPERATION_STATUSES = new Set([- 'idle',- 'running',- 'waiting_for_human',- 'waiting_for_async_tool',- 'waiting_for_client',-]);-/** Parked states are exempt from the abandoned-age backstop β see above. */-const UNBOUNDED_OPERATION_STATUSES = new Set(['waiting_for_human', 'waiting_for_async_tool']);--/**- * Operation statuses in which the server is still driving the run, so a- * client-reported end must not clear its topic marker. `waiting_for_human` is- * excluded on purpose: a run parked for approval is stream-terminal for the- * client, which settles it to stop the spinner.- */-const CLIENT_UNSETTLEABLE_OPERATION_STATUSES = new Set<AgentOperationStatus>([- 'running',- 'waiting_for_async_tool',- 'waiting_for_client',-]);--export interface SettleRunningOperationOptions {- /**- * Refuse to clear a marker whose operation row is still `running` /- * `waiting_for_async_tool`. Set for client-reported settles, which can be- * triggered by an early or mirrored terminal event.- */- rejectInFlightOperation?: boolean;-}--export interface TopicListItem extends TopicItem {- /** The topic's last non-empty assistant reply, truncated with a trailing `β¦`. Only set when `queryTopics` is called with `withLastMessage`. */- lastAssistantMessage?: string | null;- /**- * Visibility of the agent/group this topic belongs to β `'private'` marks a- * conversation that must stay out of shared/team listings even though the- * viewer may own it. Null for legacy rows with no resolvable parent.- */- parentVisibility?: 'private' | 'public' | null;- /**- * When the topic's current run started (`agent_operations.startedAt` of its- * latest top-level running operation). Only computed for `running` topics;- * null for everything else, and for runs that never wrote an operation row- * (e.g. client-mode runs) β callers must keep a fallback.- */- runStartedAt?: Date | null;-}--/**- * Sanitized projection of `topics.metadata.runningOperation` for a visitor DTO- * β only the fields `useGatewayReconnect`'s `RunningOperation` needs to resume- * a streaming session on reload. Never the full `runningOperation` object: it- * also carries device/hetero fields (`deviceId`, `deviceUserId`, `hooks`, β¦)- * that describe creator-side dispatch and must not reach a visitor.- */-export interface VisitorRunningOperation {- assistantMessageId: string;- heteroType?: string | null;- operationId: string;- scope?: string;- /** Liveness/elapsed-time stamp β see `useGatewayReconnect`'s `startedAt`. */- startedAt?: string;- threadId?: string | null;-}--/**- * Visitor-facing topic DTO for the agent-share surface. Deliberately narrow:- * the underlying row is CREATOR-owned and also carries the creator's userId,- * model/provider snapshot, cost/usage and internal metadata.- */-export interface VisitorTopicItem {- createdAt: Date;- id: string;- /**- * Sanitized `runningOperation` marker, present only while a run is active on- * this topic. Lets the share surface reconnect a Gateway stream after a page- * reload β see {@link VisitorRunningOperation} for why it's projected- * instead of forwarding `topics.metadata.runningOperation` as-is.- */- runningOperation?: VisitorRunningOperation | null;- title: string | null;- updatedAt: Date;-}--/**- * Fallback page size for {@link TopicModel.queryBySender} when a caller- * doesn't pass one. Pinned to the package default per-visitor topic cap.- *- * Callers with a live share config (e.g. `shareChat.getTopics`) MUST pass the- * share's actual resolved `maxTopicsPerVisitor` as `pageSize` instead of- * relying on this default β a creator who raises the cap above the default- * would otherwise have a visitor's list silently truncated below what that- * visitor is actually allowed to create.- */-const VISITOR_TOPIC_PAGE_SIZE = AGENT_SHARE_VISITOR_TOPIC_LIST_LIMIT;--/**- * Projects `topics.metadata.runningOperation` down to the visitor-safe subset- * β see {@link VisitorRunningOperation}. Used by {@link TopicModel.queryBySender}- * so a share visitor's topic list can drive `useGatewayReconnect` without ever- * receiving the rest of `metadata` (creator-only fields β see the module doc).- */-const pickVisitorRunningOperation = (- metadata: ChatTopicMetadata | null | undefined,-): VisitorRunningOperation | null => {- const runningOperation = metadata?.runningOperation;- if (!runningOperation) return null;-- const { assistantMessageId, heteroType, operationId, scope, startedAt, threadId } =- runningOperation;- return { assistantMessageId, heteroType, operationId, scope, startedAt, threadId };-};--export interface CreateTopicParams {- agentId?: string | null;- favorite?: boolean;- groupId?: string | null;- messages?: string[];- metadata?: ChatTopicMetadata;- /** Pinned model snapshot, persisted to the top-level `topics.model` column. */- model?: string | null;- /** Owning business project, independent of the execution directory. */- projectId?: string | null;- /** Project directory this conversation is pinned to as its execution context. */- projectWorkingDirectoryId?: string | null;- provider?: string | null;- /**- * Agent-share visitor topics carry the CREATOR's `userId` (billing/data- * attribution) plus the visitor's id here, so creator-facing listings- * exclude them (`notShareVisitorTopic`, applied by `query`, `count`,- * `queryTopics`, `queryRecent` and `rank`) while the share surface scopes- * reads per visitor (`queryBySender` / `countBySender`).- *- * A future opt-in surface (`allowCreatorViewSessions`) may let a creator- * explicitly browse visitor sessions; that is not wired up yet β every- * creator-facing read today unconditionally excludes senderId rows.- */- senderId?: string | null;- sessionId?: string | null;- /**- * Initial status. Defaults to the column default (`active`). A topic created- * with `metadata.scheduledRun` must set `scheduled` here so the status and the- * payload land in the same insert β the dispatcher treats the pair as one fact.- */- status?: ChatTopicStatus;- title?: string;- trigger?: string | null;-}--interface QueryTopicParams {- agentId?: string | null;- /**- * @deprecated Use agentId or groupId instead. Kept for backward compatibility.- * Container ID (sessionId or groupId) to filter topics by- */- containerId?: string | null;- current?: number;- /**- * Restrict an `agentId` query to the builder conversations that configured- * one specific target (`metadata.editingAgentId` / `metadata.editingGroupId`).- *- * Builder panels run on a single builtin agent shared by every target, whose- * topics deliberately carry no `groupId` / `sessionId` β those columns mark a- * topic as part of the target's own chat read path. The builder panel itself- * shows the unfiltered history on purpose; these exist so a caller that wants- * one target's builds can ask for them. Only meaningful alongside `agentId`;- * ignored by the group / container branches.- */- editingAgentId?: string | null;- editingGroupId?: string | null;- /**- * Exclude topics by status (e.g. ['completed'])- */- excludeStatuses?: string[];- /**- * Exclude topics by trigger types (e.g. ['cron'])- * Ignored when includeTriggers is provided.- */- excludeTriggers?: string[];- /**- * Group ID to filter topics by- */- groupId?: string | null;- /**- * Include only topics whose trigger matches one of these values.- * Takes precedence over excludeTriggers when provided.- */- includeTriggers?: string[];- /**- * Whether this is an inbox agent query.- * When true, also includes legacy inbox topics (sessionId IS NULL AND groupId IS NULL AND agentId IS NULL)- */- isInbox?: boolean;- pageSize?: number;- /**- * Server-side ordering. Defaults to `updatedAt`. `status` orders by status- * priority (see `STATUS_SORT_RANK`) so the sidebar "group by status" mode- * keeps high-priority topics on the first page.- */- sortBy?: TopicQuerySortBy;- timing?: ModelTimingContext;- /**- * Include only topics matching the given trigger types (positive filter)- */- triggers?: string[];- /**- * When true, the SELECT also returns the heavier card-detail columns used- * by the per-agent Topics management page: `firstUserMessage` (subquery),- * `messageCount` (subquery), `description`, `trigger`. `cost` and- * `tokenUsage` are intentionally omitted until a dedicated schema migration- * adds real columns to back them. Defaults to false so sidebar paths stay- * cheap.- */- withDetails?: boolean;-}--export interface ModelTimingContext extends TimingSink {}--/**- * Scope used to constrain a keyword search to a single conversation owner.- * Mirrors the precedence of {@link TopicModel.query}: groupId > agentId >- * containerId (legacy sessionId / groupId).- */-export interface TopicKeywordScope {- agentId?: string | null;- /**- * @deprecated Use agentId or groupId instead. Only consulted when neither- * agentId nor groupId is provided (legacy / mobile string-arg callers).- * Container ID (sessionId or groupId) to filter topics by.- */- containerId?: string | null;- groupId?: string | null;-}--export interface ListTopicsForMemoryExtractorCursor {- createdAt: Date;- id: string;-}--// Status priority for the sidebar "group by status" ordering. Lower rank =-// higher in the list. A NULL / unknown status falls through to `active` (3),-// matching the client which treats a missing status as active. Keep this in-// sync with `STATUS_GROUP_ORDER` / `resolveStatusBucket` in `@lobechat/utils`-// (client-side bucketing): `waitingForHuman`, `failed` and `unread` all collapse-// into the top `pending` bucket, so they must float to the top here too β-// otherwise such a topic could fall off the first page and vanish from the-// pending group.-const STATUS_SORT_RANK = sql`CASE ${topics.status}- WHEN 'waitingForHuman' THEN 0- WHEN 'failed' THEN 1- WHEN 'unread' THEN 2- WHEN 'running' THEN 3- WHEN 'scheduled' THEN 4- WHEN 'active' THEN 5- WHEN 'completed' THEN 6- WHEN 'archived' THEN 7- ELSE 5 END`;--// Favorites always float to the top; the rest are ordered by the requested-// strategy. `status` adds the priority bucket before the recency tiebreaker.-const buildTopicOrderBy = (topicActivityAt: SQL, sortBy?: TopicQuerySortBy): SQL[] =>- sortBy === 'status'- ? [desc(topics.favorite), asc(STATUS_SORT_RANK), desc(topicActivityAt)]- : [desc(topics.favorite), desc(topicActivityAt)];--/**- * NEVER null-test a jsonb arrow / path expression inside a WHERE clause:- *- * ```sql- * (metadata ->> 'cronJobId') IS NULL -- π₯- * (metadata #>> '{a,b}') IS NOT NULL -- π₯- * ```- *- * The crash is `pg_search`'s (ParadeDB BM25) planner hook, and it fires on any- * table carrying a `bm25` index: `rt_fetch used out-of-bounds`, SQLSTATE XX000.- * Drizzle reports it as a bare `Failed query:`, with the real cause only in the- * driver's `[cause]`. Four properties make it uniquely nasty:- *- * - It fires at PLAN time. `EXPLAIN` alone crashes, so a table with zero- * matching rows crashes exactly like a full one.- * - Stock Postgres, PGlite, and any table *without* a bm25 index run these- * predicates happily β no test we can write will ever catch it.- * - It has nothing to do with jsonb. `upper(col) IS NULL` and `(id + 1) IS NULL`- * crash identically; the trigger is a null test over a *computed expression*- * in a qual. A null test over a bare column is fine.- * - Only quals crash β WHERE, JOIN ON, HAVING, and the WHERE of a subquery, CTE,- * UPDATE or DELETE. SELECT lists, ORDER BY and `UPDATE β¦ SET` targets are safe.- *- * `topics` and `messages` carry bm25 indexes today, but so do `agents`, `files`,- * `documents`, `chat_groups`, `knowledge_bases` and every `user_memories*`- * table β and that list is one migration away from growing. A predicate written- * today outlives the index list, so the rule is table-independent: never write- * the shape.- *- * COALESCE the extracted value to a sentinel instead β same semantics, a shape- * the planner survives:- *- * ```sql- * COALESCE(metadata ->> 'cronJobId', '') = '' -- "is null"- * COALESCE((metadata #>> '{a,b}')::numeric, 0) <= $1 -- numeric gate- * COALESCE(metadata ->> 'status', '') <> 'done' -- IS DISTINCT FROM- * ```- *- * (`IS DISTINCT FROM` measured safe on pg_search 0.15.26, but the guard bans it- * anyway β it sits one planner-hook change from the crashing family and the- * COALESCE form costs nothing.)- *- * This has now bitten three times: #13040, `getLatestSpineMessageId` (#16693)- * and `getDueScheduledTopics` (#17077 β the scheduled-run cron crashed on every- * tick from the day it shipped, so rate-limit continuations never once resumed).- * `jsonbNullTest.test.ts` is the source-shape guard that holds the line.- */-export interface TopicModelOptions {- /**- * Opt IN to agent-share visitor topics. Visitor conversations persist under- * the CREATOR's `userId` (only `topics.senderId` marks them), so every- * creator-facing read/write is default-scoped to exclude them. Only the- * share-runtime surfaces (share-scoped tRPC routers, share abuse guards,- * and the agent runtime paths that persist or clean up a visitor turn- * under the creator's identity) should set this to `true`.- */- includeShareVisitor?: boolean;-}--export class TopicModel {- private userId: string;- private db: LobeChatDatabase;- private ftsSearchCandidateSource?: FtsSearchCandidateSource;- private workspaceId?: string;- /**- * When true, {@link ownership} (and by extension every creator-scoped read- * path below) stops ANDing {@link notShareVisitorTopic}. Reserved for- * surfaces that are share-runtime by design (agent-share visitor router,- * share-scoped abuse guards) and for the agent runtime paths that persist- * or clean up a visitor turn under the CREATOR's identity. Defaults to- * false so every ordinary creator-facing caller fails closed instead of- * relying on a per-callsite `notShareVisitorTopic()` AND.- */- private includeShareVisitor: boolean;-- constructor(- db: LobeChatDatabase,- userId: string,- workspaceId?: string,- ftsSearchCandidateSource?: FtsSearchCandidateSource,- options: TopicModelOptions = {},- ) {- this.userId = userId;- this.db = db;- this.workspaceId = workspaceId;- this.ftsSearchCandidateSource = ftsSearchCandidateSource;- this.includeShareVisitor = options.includeShareVisitor ?? false;- }-- /**- * Raw workspace/user scope, WITHOUT the visitor exclusion. Backing store for- * both {@link ownership} and {@link mine}, and the escape hatch for methods- * that must see visitor rows independent of the instance flag- * ({@link queryBySender} / {@link countBySender} / {@link countShareVisitors}).- */- private workspaceScope = () =>- buildWorkspaceWhere({ userId: this.userId, workspaceId: this.workspaceId }, topics);-- /**- * {@link workspaceScope} without the recycle-bin filter, still excluding- * share-visitor topics β restore / trash lookups / purge internals only.- */- private trashScope = () =>- and(- buildWorkspaceWhere(- { includeTrashed: true, userId: this.userId, workspaceId: this.workspaceId },- topics,- ),- this.notShareVisitor(),- );-- private ownership = () => and(this.workspaceScope(), this.notShareVisitor());-- /**- * In workspace mode `ownership()` matches every member's topics, so a bulk- * "clear all" would wipe teammates' conversations. Destructive sweeps must- * additionally pin `user_id` to the caller (personal mode is unchanged β- * ownership already scopes to the user there).- *- * `mine()` deliberately does NOT AND {@link notShareVisitor} β it is the- * per-user variant of {@link workspaceScope} and the share-scoped methods- * ({@link queryBySender} / {@link countBySender} / {@link countShareVisitors})- * layer their own `senderId` predicate on top of it. Creator-facing- * destructive sweeps that reach for `mine()` still get the visitor- * exclusion by AND-ing {@link notShareVisitor} themselves.- */- private mine = () => and(this.workspaceScope(), eq(topics.userId, this.userId));-- private messageOwnership = () =>- buildWorkspaceWhere({ userId: this.userId, workspaceId: this.workspaceId }, messages);-- /**- * The default visitor exclusion applied by {@link ownership}: `topics.senderId IS NULL`,- * shared with the repositories/models that query `topics` outside this- * class (see `notShareVisitorTopic` in `../utils/shareVisitor`). Returns- * `undefined` when the instance was constructed with `includeShareVisitor:- * true`, so the share runtime opts in explicitly and every other caller- * gets the visitor guard for free.- *- * The visitor-scoped counterparts ({@link queryBySender}, {@link countBySender})- * intentionally do the opposite β they match on `senderId`, not exclude- * it β and use {@link mine} (which skips this helper).- */- private notShareVisitor = () => (this.includeShareVisitor ? undefined : notShareVisitorTopic());-- query = async ({- agentId,- containerId,- current = 0,- editingAgentId,- editingGroupId,- excludeStatuses,- excludeTriggers,- includeTriggers,- pageSize = 9999,- groupId,- isInbox,- sortBy,- timing,- triggers,- withDetails = false,- }: QueryTopicParams = {}) => {- const queryStartedAt = Date.now();- logTiming(timing, 'db.topic.query:start', {- current,- hasAgentId: !!agentId,- hasContainerId: !!containerId,- hasGroupId: !!groupId,- isInbox: !!isInbox,- pageSize,- withDetails,- });- const offset = current * pageSize;-- // Heavier columns gated behind `withDetails` and used by the per-agent- // Topics management page: real aggregates from the `messages` table- // (firstUserMessage + messageCount), plus the `description` / `trigger`- // columns that sidebar paths don't consume. `cost` and `tokenUsage`- // intentionally stay undefined here β they need their own schema- // migration before they can be backed by real numbers.- //- // The two correlated subqueries are built with Drizzle's query builder- // (not a raw `sql` template) so the inner `eq(messages.topicId,- // topics.id)` renders as `"messages"."topic_id" = "topics"."id"` β both- // sides fully qualified. A bare `sql\`... ${topics.id} ...\`` template- // renders `topics.id` as an unqualified `"id"`, which PostgreSQL then- // resolves against the inner FROM (messages.id) and the WHERE silently- // matches nothing.- const firstUserMessageSubquery = this.db- .select({ value: messages.content })- .from(messages)- .where(- and(eq(messages.topicId, topics.id), eq(messages.role, 'user'), this.messageOwnership()),- )- .orderBy(asc(messages.createdAt))- .limit(1);- const messageCountSubquery = this.db- .select({ value: sql<number>`count(*)::int` })- .from(messages)- .where(and(eq(messages.topicId, topics.id), this.messageOwnership()));- const latestMessageAtSubquery = this.db- .select({ value: messages.updatedAt })- .from(messages)- .where(and(eq(messages.topicId, topics.id), this.messageOwnership()))- .orderBy(desc(messages.updatedAt))- .limit(1);- const topicActivityAt =- sql<Date>`COALESCE((${latestMessageAtSubquery}), ${topics.updatedAt})`.mapWith(- topics.updatedAt,- );-- // When the topic's current run started, so a sidebar can show live elapsed- // time instead of `updatedAt` (which moves on every message write). The- // latest *top-level* running operation is the current run: sub-operations- // (callAgent) would restart the clock at their own spawn time, and an- // abandoned `running` row from a crashed earlier run sorts below the live- // one. Not scoped by `ownership()` β in a workspace the run may have been- // started by another member, and the topic join is already ownership-gated.- const runStartedAtSubquery = this.db- .select({ value: agentOperations.startedAt })- .from(agentOperations)- .where(- and(- eq(agentOperations.topicId, topics.id),- eq(agentOperations.status, 'running'),- isNull(agentOperations.parentOperationId),- isNotNull(agentOperations.startedAt),- ),- )- .orderBy(desc(agentOperations.startedAt))- .limit(1);-- // CASE-gated so only rows that are actually running pay for the lookup β- // and a stale running op under a finished topic can't resurrect a timer.- const runStartedAtColumn =- sql<Date | null>`CASE WHEN ${topics.status} = 'running' THEN (${runStartedAtSubquery}) ELSE NULL END`- .mapWith(agentOperations.startedAt)- .as('run_started_at');-- const orderBy = buildTopicOrderBy(topicActivityAt, sortBy);-- const detailColumns = withDetails- ? {- description: topics.description,- firstUserMessage: sql<string | null>`(${firstUserMessageSubquery})`.as(- 'first_user_message',- ),- messageCount: sql<number>`(${messageCountSubquery})`.as('message_count'),- trigger: topics.trigger,- }- : {};-- const includeTriggerCondition =- includeTriggers && includeTriggers.length > 0- ? inArray(topics.trigger, includeTriggers)- : undefined;- const excludeTriggerCondition = includeTriggerCondition- ? undefined- : excludeTriggers && excludeTriggers.length > 0- ? or(isNull(topics.trigger), not(inArray(topics.trigger, excludeTriggers)))- : undefined;- const triggerCondition =- triggers && triggers.length > 0 ? inArray(topics.trigger, triggers) : undefined;- const excludeStatusCondition =- excludeStatuses && excludeStatuses.length > 0- ? or(- isNull(topics.status),- not(inArray(topics.status, excludeStatuses as ChatTopicStatus[])),- )- : undefined;- // Topics created before the marker existed carry neither key and therefore- // match no target β they cannot: what they configured was never recorded- // anywhere in the row. `topics_agent_id_idx` still drives the scan, so the- // unindexed JSONB comparison only runs over one agent's rows.- const editingTargetCondition = and(- editingAgentId ? sql`${topics.metadata}->>'editingAgentId' = ${editingAgentId}` : undefined,- editingGroupId ? sql`${topics.metadata}->>'editingGroupId' = ${editingGroupId}` : undefined,- );-- if (groupId) {- const whereCondition = and(- this.ownership(),- this.notShareVisitor(),- eq(topics.groupId, groupId),- includeTriggerCondition,- excludeTriggerCondition,- triggerCondition,- excludeStatusCondition,- );-- const [items, totalResult] = await Promise.all([- runTimedStage(- timing,- 'db.topic.query.group.items.select',- () =>- this.db- // Cast to `any` because Drizzle's `.select` infers a strict- // SelectedFields shape and the conditional `detailColumns` widens- // to a union; the runtime shape is correct and the client casts- // back to `ChatTopic[]` after TRPC serialization.- .select({- completedAt: topics.completedAt,- createdAt: topics.createdAt,- favorite: topics.favorite,- historySummary: topics.historySummary,- id: topics.id,- metadata: topicMetadataWithCreator(this.db, this.messageOwnership()),- projectId: topics.projectId,- projectWorkingDirectoryId: topics.projectWorkingDirectoryId,- model: topics.model,- provider: topics.provider,- runStartedAt: runStartedAtColumn,- status: topics.status,- title: topics.title,- updatedAt: topics.updatedAt,- // Sidebar sorts/groups topics client-side by this `sortUpdatedAt` β the- // same `topicActivityAt` the ORDER BY uses (latest message time, COALESCE- // fallback to the row's own updatedAt). Keeping it separate from the- // display `updatedAt` above matches the client-side sort key to the server- // order (otherwise the two disagree and the list visibly jumps) while a- // rename/favorite edit still shows its real edit time. See rankTopics for- // the same activity-time pattern.- sortUpdatedAt: topicActivityAt,- // Workspace sidebars filter maintenance actions client-side by- // ownership (own vs workspace scope) β the filter needs the row- // owner even in the slim projection.- userId: topics.userId,- ...detailColumns,- } as any)- .from(topics)- .where(whereCondition)- .orderBy(...orderBy)- .limit(pageSize)- .offset(offset),- { current, pageSize },- ),- runTimedStage(timing, 'db.topic.query.group.count.select', () =>- this.db- .select({ count: count(topics.id) })- .from(topics)- .where(whereCondition),- ),- ]);-- logTiming(timing, 'db.topic.query:done', {- itemCount: items.length,- stageMs: getDurationMs(queryStartedAt),- total: totalResult[0].count,- });- return { items, total: totalResult[0].count };- }-- // If agentId is provided, match topics by `topics.agentId` directly. The- // inbox agent additionally adopts very old orphan rows where every owner- // column (session / group / agent) is null.- if (agentId) {- const agentCondition = isInbox- ? or(- eq(topics.agentId, agentId),- and(isNull(topics.sessionId), isNull(topics.groupId), isNull(topics.agentId)),- )- : eq(topics.agentId, agentId);-- const agentWhere = and(- this.ownership(),- this.notShareVisitor(),- agentCondition,- editingTargetCondition,- includeTriggerCondition,- excludeTriggerCondition,- triggerCondition,- excludeStatusCondition,- );-- const [items, totalResult] = await Promise.all([- runTimedStage(- timing,- 'db.topic.query.agent.items.select',- () =>- this.db- // See note on the group-branch select above re: `as any` cast.- .select({- completedAt: topics.completedAt,- createdAt: topics.createdAt,- favorite: topics.favorite,- historySummary: topics.historySummary,- id: topics.id,- metadata: topicMetadataWithCreator(this.db, this.messageOwnership()),- projectId: topics.projectId,- projectWorkingDirectoryId: topics.projectWorkingDirectoryId,- model: topics.model,- provider: topics.provider,- runStartedAt: runStartedAtColumn,- status: topics.status,- title: topics.title,- updatedAt: topics.updatedAt,- // Sidebar sorts/groups topics client-side by this `sortUpdatedAt` β the- // same `topicActivityAt` the ORDER BY uses (latest message time, COALESCE- // fallback to the row's own updatedAt). Keeping it separate from the- // display `updatedAt` above matches the client-side sort key to the server- // order (otherwise the two disagree and the list visibly jumps) while a- // rename/favorite edit still shows its real edit time. See rankTopics for- // the same activity-time pattern.- sortUpdatedAt: topicActivityAt,- // Workspace sidebars filter maintenance actions client-side by- // ownership (own vs workspace scope) β the filter needs the row- // owner even in the slim projection.- userId: topics.userId,- ...detailColumns,- } as any)- .from(topics)- .where(agentWhere)- .orderBy(...orderBy)- .limit(pageSize)- .offset(offset),- { current, isInbox: !!isInbox, pageSize },- ),- runTimedStage(- timing,- 'db.topic.query.agent.count.select',- () =>- this.db- .select({ count: count(topics.id) })- .from(topics)- .where(agentWhere),- { isInbox: !!isInbox },- ),- ]);-- logTiming(timing, 'db.topic.query:done', {- itemCount: items.length,- stageMs: getDurationMs(queryStartedAt),- total: totalResult[0].count,- });- return { items, total: totalResult[0].count };- }-- // Fallback to containerId-based query (backward compatibility)- const whereCondition = and(- this.ownership(),- this.notShareVisitor(),- this.matchContainer(containerId),- includeTriggerCondition,- excludeTriggerCondition,- triggerCondition,- excludeStatusCondition,- );-- const [items, totalResult] = await Promise.all([- runTimedStage(- timing,- 'db.topic.query.container.items.select',- () =>- this.db- // See note on the group-branch select above re: `as any` cast.- .select({- agentId: topics.agentId,- completedAt: topics.completedAt,- createdAt: topics.createdAt,- favorite: topics.favorite,- historySummary: topics.historySummary,- id: topics.id,- metadata: topicMetadataWithCreator(this.db, this.messageOwnership()),- projectId: topics.projectId,- projectWorkingDirectoryId: topics.projectWorkingDirectoryId,- model: topics.model,- provider: topics.provider,- runStartedAt: runStartedAtColumn,- sessionId: topics.sessionId,- status: topics.status,- title: topics.title,- updatedAt: topics.updatedAt,- // Sidebar sorts/groups topics client-side by this `sortUpdatedAt` β the- // same `topicActivityAt` the ORDER BY uses (latest message time, COALESCE- // fallback to the row's own updatedAt). Keeping it separate from the- // display `updatedAt` above matches the client-side sort key to the server- // order (otherwise the two disagree and the list visibly jumps) while a- // rename/favorite edit still shows its real edit time. See rankTopics for- // the same activity-time pattern.- sortUpdatedAt: topicActivityAt,- // Workspace sidebars filter maintenance actions client-side by- // ownership (own vs workspace scope) β the filter needs the row- // owner even in the slim projection.- userId: topics.userId,- ...detailColumns,- } as any)- .from(topics)- .where(whereCondition)- .orderBy(...orderBy)- .limit(pageSize)- .offset(offset),- { current, pageSize },- ),- runTimedStage(timing, 'db.topic.query.container.count.select', () =>- this.db- .select({ count: count(topics.id) })- .from(topics)- .where(whereCondition),- ),- ]);-- // Remove internal fields before returning-- const cleanItems = items.map(({ agentId: _agentId, sessionId: _sessionId, ...rest }) => rest);-- logTiming(timing, 'db.topic.query:done', {- itemCount: cleanItems.length,- stageMs: getDurationMs(queryStartedAt),- total: totalResult[0].count,- });-- return { items: cleanItems, total: totalResult[0].count };- };-- /**- * Ownership-scoped lookup. Agent-share visitor topics carry the CREATOR's- * `userId` and are excluded by default; the share runtime opts in by- * constructing the model with `{ includeShareVisitor: true }`.- * `findVisitorTopicOrThrow` in `apps/server/src/routers/lambda/shareChat.ts`- * relies on that opt-in and then verifies `senderId` itself.- */- findById = async (id: string) => {- return this.db.query.topics.findFirst({- where: and(eq(topics.id, id), this.ownership()),- });- };-- /**- * Kept for readability at creator-facing router call sites; the default- * scope already excludes agent-share visitor topics, so this is a thin- * alias of {@link TopicModel.findById}.- */- findOwnTopicById = async (id: string) => {- return this.findById(id);- };-- /**- * Ids among `ids` that resolve to an agent-share VISITOR topic under this- * owner β the inverse of {@link notShareVisitorTopic}, the predicate every- * creator-facing read applies.- *- * Creator-facing write entry points use this to reject visitor targets- * (see `assertCreatorTopicTargets` in the server router helpers). Ids that- * match no row at all are NOT reported, so callers keep their existing no-op- * behaviour for stale/foreign ids.- */- findShareVisitorTopicIds = async (ids: string[]): Promise<string[]> => {- if (ids.length === 0) return [];-- const rows = await this.db- .select({ id: topics.id })- .from(topics)- // Explicitly scoped visitor-inclusive: this method's whole job is to- // return visitor ids so the router-level `assertCreatorTopicTargets`- // can reject them, so it must bypass the instance's visitor exclusion.- .where(and(inArray(topics.id, ids), this.workspaceScope(), isNotNull(topics.senderId)));-- return rows.map((row) => row.id);- };-- findByIds = async (ids: string[]): Promise<TopicItem[]> => {- if (ids.length === 0) return [];- return this.db.query.topics.findMany({- where: and(inArray(topics.id, ids), this.ownership()),- });- };-- /**- * Kept for readability at creator-facing router call sites; the default- * scope already excludes agent-share visitor topics, so this is a thin- * alias of {@link TopicModel.findByIds}.- */- findOwnTopicsByIds = async (ids: string[]): Promise<TopicItem[]> => {- return this.findByIds(ids);- };-- /**- * Minimal creator projection for router-level workspace row checks on- * batch-by-ids operations (batch delete / move).- */- findOwnersByIds = async (ids: string[]): Promise<{ id: string; userId: string }[]> => {- if (ids.length === 0) return [];-- return this.db- .select({ id: topics.id, userId: topics.userId })- .from(topics)- .where(and(inArray(topics.id, ids), this.ownership()));- };-- /**- * Find the unique topic an agent shares with a document for a given trigger- * (e.g. the doc-anchored chat topic provisioned by- * `agentDocument.getOrCreateChatTopic`). Joins through `topic_documents`.- */- findByAgentAndDocumentTrigger = async (params: {- agentId: string;- documentId: string;- trigger: string;- }): Promise<TopicItem | undefined> => {- const result = await this.db- .select({ topic: topics })- .from(topics)- .innerJoin(topicDocuments, eq(topicDocuments.topicId, topics.id))- .where(- and(- this.ownership(),- eq(topics.agentId, params.agentId),- eq(topics.trigger, params.trigger),- eq(topicDocuments.documentId, params.documentId),- ),- )- .limit(1);-- return result[0]?.topic;- };-- /**- * Query the current user's topics, optionally filtered by status β e.g. to- * list actively-running topics across all agents without pulling the full- * topic set to the client.- *- * `withLastMessage` additionally pulls each topic's last assistant reply, so a- * list can show what the agent actually said instead of just a title. The- * preview is truncated server-side β raw assistant output is unbounded- * markdown, and a list only ever renders the head of it.- */- queryTopics = async ({- deviceId,- statuses,- pageSize = 200,- withLastMessage,- }: {- /**- * Only topics on this device β the one its in-flight run was dispatched to- * (`metadata.runningOperation.deviceId`), else the one its turns are- * pinned to (`metadata.boundDeviceId`). See {@link getTopicDeviceId},- * which applies the same precedence in memory.- */- deviceId?: string;- pageSize?: number;- statuses?: string[];- withLastMessage?: boolean;- } = {}): Promise<TopicListItem[]> => {- const scope = { userId: this.userId, workspaceId: this.workspaceId };-- // Unlike the per-agent topic list, this feed is not scoped by agent at all:- // in a workspace `ownership()` matches every member's rows, so a topic- // whose owning agent/group is someone else's PRIVATE conversation would- // surface here β title and last assistant reply included. Gate on the- // parent the same way the Recent feed does. Rows with no resolvable parent- // (legacy session-only topics) have nothing to check and keep the previous- // behaviour.- const visibleParentWhere = or(- and(isNull(topics.agentId), isNull(topics.groupId)),- and(isNotNull(topics.groupId), buildWorkspaceWhere(scope, chatGroups)),- and(isNull(topics.groupId), isNotNull(topics.agentId), buildWorkspaceWhere(scope, agents)),- );-- const where = and(- this.ownership(),- this.notShareVisitor(),- visibleParentWhere,- statuses && statuses.length > 0- ? inArray(topics.status, statuses as ChatTopicStatus[])- : undefined,- deviceId- ? sql`COALESCE(${topics.metadata} -> 'runningOperation' ->> 'deviceId', ${topics.metadata} ->> 'boundDeviceId') = ${deviceId}`- : undefined,- );-- // `buildWorkspaceWhere` keeps a member's OWN private rows visible, which is- // right for a "mine" list and wrong for a shared one. Ship the parent's- // visibility so the caller's team view can drop private conversations- // without a second round trip.- const parentVisibilityColumn = sql<- 'private' | 'public' | null- >`COALESCE(${chatGroups.visibility}, ${agents.visibility})`.as('parent_visibility');-- // When the topic's current run started, so a list can show live elapsed- // time instead of `updatedAt` (which moves on every message write). The- // latest *top-level* running operation is the current run: sub-operations- // (callAgent) would restart the clock at their own spawn time, and an- // abandoned `running` row from a crashed earlier run sorts below the live- // one. Not scoped by `ownership()` β in a workspace the run may have been- // started by another member, and the topic join is already ownership-gated.- const runStartedAtSubquery = this.db- .select({ value: agentOperations.startedAt })- .from(agentOperations)- .where(- and(- eq(agentOperations.topicId, topics.id),- eq(agentOperations.status, 'running'),- isNull(agentOperations.parentOperationId),- isNotNull(agentOperations.startedAt),- ),- )- .orderBy(desc(agentOperations.startedAt))- .limit(1);-- // Client-executed runs (desktop heterogeneous CLI, in-browser runtime) never- // reach `agent_operations` β nothing server-side creates the operation β so- // their start is stamped onto the topic by the status write that claims it- // (see {@link TopicModel.update}). The operation row still wins when both- // exist: it is the server's own record of the run, while the stamp is a- // client-reported time.- const localRunStartedAt = sql`(${topics.metadata} ->> 'runStartedAt')::timestamptz`;-- // CASE-gated so only rows that are actually running pay for the lookup β- // and a stale running op (or stamp) under a finished topic can't resurrect- // a timer.- const runStartedAtColumn =- sql<Date | null>`CASE WHEN ${topics.status} = 'running' THEN COALESCE((${runStartedAtSubquery}), ${localRunStartedAt}) ELSE NULL END`- .mapWith(agentOperations.startedAt)- .as('run_started_at');-- if (!withLastMessage) {- return this.db- .select({- ...getTableColumns(topics),- metadata: topicMetadataWithCreator(this.db, this.messageOwnership()),- parentVisibility: parentVisibilityColumn,- runStartedAt: runStartedAtColumn,- })- .from(topics)- .leftJoin(agents, eq(topics.agentId, agents.id))- .leftJoin(chatGroups, eq(topics.groupId, chatGroups.id))- .where(where)- .orderBy(desc(topics.updatedAt))- .limit(pageSize);- }-- // Built with the query builder rather than a raw `sql` template so the inner- // `eq(messages.topicId, topics.id)` renders both sides fully qualified β- // see the note on `firstUserMessageSubquery` in `query()`.- //- // Assistant turns that only carried tool calls persist an empty `content`;- // skipping them lands on the last thing the agent actually *said*.- // One char past the limit, so the caller can tell "exactly this long" from- // "cut short" and mark the cut instead of ending mid-sentence.- const lastAssistantMessageSubquery = this.db- .select({- value: sql<string>`left(${messages.content}, ${LAST_MESSAGE_PREVIEW_LENGTH + 1})`,- })- .from(messages)- .where(- and(- eq(messages.topicId, topics.id),- eq(messages.role, 'assistant'),- this.messageOwnership(),- ne(messages.content, ''),- ),- )- .orderBy(desc(messages.createdAt))- .limit(1);-- const rows = await this.db- .select({- ...getTableColumns(topics),- metadata: topicMetadataWithCreator(this.db, this.messageOwnership()),- lastAssistantMessage: sql<string | null>`(${lastAssistantMessageSubquery})`.as(- 'last_assistant_message',- ),- parentVisibility: parentVisibilityColumn,- runStartedAt: runStartedAtColumn,- })- .from(topics)- .leftJoin(agents, eq(topics.agentId, agents.id))- .leftJoin(chatGroups, eq(topics.groupId, chatGroups.id))- .where(where)- .orderBy(desc(topics.updatedAt))- .limit(pageSize);-- return rows.map((row) => ({- ...row,- lastAssistantMessage:- row.lastAssistantMessage && row.lastAssistantMessage.length > LAST_MESSAGE_PREVIEW_LENGTH- ? `${row.lastAssistantMessage.slice(0, LAST_MESSAGE_PREVIEW_LENGTH)}β¦`- : row.lastAssistantMessage,- }));- };-- /**- * Who started each topic's current run. Workspace topics are co-editable, so- * the member running a topic now can differ from its creator (`topics.userId`);- * the latest top-level running operation records the actual initiator β the- * same row `runStartedAt` reads. Topics whose run never wrote an operation- * row (client-executed runs) are absent; callers fall back to the creator.- *- * Not scoped by {@link ownership}: in a workspace the run may belong to- * another member, and callers pass ids from an ownership-gated topic read.- */- findRunInitiators = async (topicIds: string[]): Promise<Map<string, string>> => {- if (topicIds.length === 0) return new Map();-- const rows = await this.db- .selectDistinctOn([agentOperations.topicId], {- topicId: agentOperations.topicId,- userId: agentOperations.userId,- })- .from(agentOperations)- .where(- and(- inArray(agentOperations.topicId, topicIds),- eq(agentOperations.status, 'running'),- isNull(agentOperations.parentOperationId),- isNotNull(agentOperations.startedAt),- ),- )- .orderBy(agentOperations.topicId, desc(agentOperations.startedAt));-- return new Map(rows.flatMap((row) => (row.topicId ? [[row.topicId, row.userId]] : [])));- };-- /**- * Recent topics from the same IM channel, most-recent first. Matches the- * channel via the `metadata.bot.platformThreadId` path written at topic- * creation (see `ChatTopicBotContext`). Used to pre-inject cross-session- * history on platforms that can't read chat history at runtime (e.g. WeChat,- * whose `readMessages` throws), so a fresh topic still knows what the channel- * was just talking about.- */- findRecentByBotThread = async (- platformThreadId: string,- { limit = 3 }: { limit?: number } = {},- ): Promise<TopicItem[]> => {- if (!platformThreadId) return [];-- return this.db- .select()- .from(topics)- .where(- and(- this.ownership(),- sql`${topics.metadata} -> 'bot' ->> 'platformThreadId' = ${platformThreadId}`,- ),- )- .orderBy(desc(topics.updatedAt))- .limit(limit);- };-- queryByKeyword = async (- keyword: string,- scope?: string | null | TopicKeywordScope,- ): Promise<TopicItem[]> => {- if (!keyword.trim()) return [];-- // Backward compatibility: a bare string / null second argument is treated- // as the legacy `containerId` (sessionId or groupId).- const scopeOptions: TopicKeywordScope =- scope && typeof scope === 'object' ? scope : { containerId: scope ?? null };- const scopeCondition = this.matchKeywordScope(scopeOptions);-- const bm25Query = sanitizeBm25Query(keyword);- const candidateResults = this.ftsSearchCandidateSource?.ftsSearchCandidateEnabled- ? await Promise.all([- this.ftsSearchCandidateSource.ftsSearchCandidates({- entity: 'topics',- filters: { topicScope: scopeOptions },- pagination: {},- query: { fields: ['title'], text: keyword },- }),- this.ftsSearchCandidateSource.ftsSearchCandidates({- entity: 'messages',- filters: { topicScope: scopeOptions },- pagination: {},- query: { fields: ['content'], text: keyword },- }),- ])- : undefined;- const topicCandidateIds = candidateResults?.[0].candidates.map(({ id }) => id);- const messageCandidateIds = candidateResults?.[1].candidates.map(({ id }) => id);-- // Run title and message content searches in parallel- const [topicsByTitle, topicIdsByMessages] = await Promise.all([- // Query topics matching by title (BM25)- this.db- .select()- .from(topics)- .where(- and(- this.ownership(),- this.notShareVisitor(),- scopeCondition,- topicCandidateIds- ? inJsonStringArray(topics.id, topicCandidateIds)- : sql`${topics.title} @@@ ${bm25Query}`,- ),- )- .orderBy(desc(topics.updatedAt)),- // 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(- this.messageOwnership(),- searchableMessage(),- messageCandidateIds- ? inJsonStringArray(messages.id, messageCandidateIds)- : sql`${messages.content} @@@ ${bm25Query}`,- this.ownership(),- this.notShareVisitor(),- scopeCondition,- ),- )- .groupBy(messages.topicId),- ]);- // If no topics found by message content, return topics matching by title- if (topicIdsByMessages.length === 0) {- return topicsByTitle;- }-- // Query topics found by message content- const topicIds = topicIdsByMessages- .map((t) => t.topicId)- .filter((id): id is string => id !== null);-- const topicsByMessages = await this.db.query.topics.findMany({- orderBy: [desc(topics.updatedAt)],- where: and(this.ownership(), inArray(topics.id, topicIds)),- });-- // Merge results and deduplicate- const allTopics = [...topicsByTitle];- const existingIds = new Set(topicsByTitle.map((t) => t.id));-- for (const topic of topicsByMessages) {- if (!existingIds.has(topic.id)) {- allTopics.push(topic);- }- }-- // Sort by update time- return allTopics.sort(- (a, b) => new Date(b.updatedAt).getTime() - new Date(a.updatedAt).getTime(),- );- };- count = async (params?: {- agentId?: string;- containerId?: string | null;- endDate?: string;- range?: [string, string];- startDate?: string;- }): Promise<number> => {- // Build agent-specific condition if agentId is provided- const agentCondition: SQL | undefined = params?.agentId- ? eq(topics.agentId, params.agentId)- : undefined;-- const result = await this.db- .select({- count: count(topics.id),- })- .from(topics)- .where(- genWhere([- this.ownership(),- this.notShareVisitor(),- agentCondition,- params?.containerId ? this.matchContainer(params.containerId) : undefined,- params?.range- ? genRangeWhere(params.range, topics.createdAt, (date) => date.toDate())- : undefined,- params?.endDate- ? genEndDateWhere(params.endDate, topics.createdAt, (date) => date.toDate())- : undefined,- params?.startDate- ? genStartDateWhere(params.startDate, topics.createdAt, (date) => date.toDate())- : undefined,- ]),- );-- return result[0].count;- };-- rank = async (limit: number = 10): Promise<TopicRankItem[]> => {- return this.db- .select({- agentId: topics.agentId,- count: count(messages.id).as('count'),- id: topics.id,- title: topics.title,- })- .from(topics)- .where(and(this.ownership(), this.notShareVisitor()))- .leftJoin(messages, eq(topics.id, messages.topicId))- .groupBy(topics.id)- .orderBy(desc(sql`count`))- .having(({ count }) => gt(count, 0))- .limit(limit);- };-- /**- * Query recent topics for homepage display.- * Returns basic topic info with agentId/groupId for later resolution.- * - For agent topics: excludes virtual agents (except inbox)- * - For group topics: includes topics with groupId- * - For inbox: includes topics with slug='inbox'- */- queryRecent = async (limit: number = 12) => {- const latestMessageAtSubquery = this.db- .select({ value: messages.updatedAt })- .from(messages)- .where(and(eq(messages.topicId, topics.id), this.messageOwnership()))- .orderBy(desc(messages.updatedAt))- .limit(1);- const topicActivityAt =- sql<Date>`COALESCE((${latestMessageAtSubquery}), ${topics.updatedAt})`.mapWith(- topics.updatedAt,- );-- const result = await this.db- .select({- agentId: topics.agentId,- groupId: topics.groupId,- id: topics.id,- sessionId: topics.sessionId,- title: topics.title,- updatedAt: topicActivityAt,- })- .from(topics)- .leftJoin(agents, eq(topics.agentId, agents.id))- .where(- and(- this.ownership(),- this.notShareVisitor(),- or(- // Group topics: has groupId- not(isNull(topics.groupId)),- // Inbox agent topics- eq(agents.slug, 'inbox'),- // Agent topics: exclude virtual agents- and(isNull(topics.groupId), ne(agents.virtual, true)),- ),- ),- )- .orderBy(desc(topicActivityAt))- .limit(limit);-- return result.map((item) => ({- ...item,- type: item.groupId ? ('group' as const) : ('agent' as const),- updatedAt: item.updatedAt instanceof Date ? item.updatedAt : new Date(item.updatedAt),- }));- };-- // **************** Agent Share (visitor-scoped) *************** //-- /**- * Share-visitor topic list for one visitor on one shared agent. The model is- * constructed with the CREATOR's userId (visitor topics carry it), so the- * caller β the shareChat router β must have already authorized the visitor- * via the share access check; `agentId` + `senderId` together are the- * per-visitor boundary.- *- * `agent_shares` is 1:1 per agent (`agent_shares_agent_id_unique`), so- * `agentId` alone identifies which share a visitor topic belongs to β there- * is no `topics.share_id` column to scope by. Turning sharing off and back- * on keeps the same row and the same `agentId`, so a returning visitor's- * older conversations DO resurface under the republished share. That is the- * accepted trade-off of not carrying a share id on the row.- *- * Selects a visitor-facing DTO instead of the full row: the visitor surface- * only renders id/title/runningOperation, and the row also carries- * creator-only fields (owning userId, model/provider snapshot, cost/usage,- * internal status and the rest of `metadata`) that must never reach a share- * visitor. `metadata` itself IS selected (needed to project- * `runningOperation`), but only the sanitized projection β never the raw- * column β leaves this method; see {@link VisitorRunningOperation}.- */- queryBySender = async (- { agentId, senderId }: { agentId: string; senderId: string },- { pageSize = VISITOR_TOPIC_PAGE_SIZE }: { pageSize?: number } = {},- ): Promise<VisitorTopicItem[]> => {- const rows = await this.db- .select({- createdAt: topics.createdAt,- id: topics.id,- metadata: topics.metadata,- title: topics.title,- updatedAt: topics.updatedAt,- })- .from(topics)- .where(and(this.mine(), eq(topics.agentId, agentId), eq(topics.senderId, senderId)))- .orderBy(desc(topics.updatedAt))- .limit(pageSize);-- return rows.map(({ metadata, ...rest }) => ({- ...rest,- runningOperation: pickVisitorRunningOperation(metadata),- }));- };-- /**- * Per-visitor topic count on a shared agent β drives `maxTopicsPerVisitor`.- * Same `(agentId, senderId)` scoping as {@link queryBySender}; see that- * method's JSDoc for why there is no share-id dimension.- */- countBySender = async ({- agentId,- senderId,- }: {- agentId: string;- senderId: string;- }): Promise<number> => {- const result = await this.db- .select({ count: count(topics.id) })- .from(topics)- .where(and(this.mine(), eq(topics.agentId, agentId), eq(topics.senderId, senderId)));-- return result[0].count;- };-- /**- * Creator-facing roll-up for one shared agent: how many conversations- * visitors started, and how many distinct visitors started them.- *- * Counterpart to {@link countBySender}, which counts ONE visitor. Both rely- * on `senderId` being non-null only for share-originated topics, so the- * creator's own conversations with the same agent are excluded. Scoped by- * `this.mine()` like every other read here, so the numbers can only ever- * describe rows the caller owns.- *- * `agentShares` is 1:1 per agent, so `agentId` alone is the share dimension- * β see {@link queryBySender} for why a disable β re-enable cycle keeps- * counting the earlier conversations.- */- countShareVisitors = async ({- agentId,- }: {- agentId: string;- }): Promise<{ topicCount: number; visitorCount: number }> => {- const [result] = await this.db- .select({- topicCount: count(topics.id),- visitorCount: countDistinct(topics.senderId),- })- .from(topics)- .where(and(this.mine(), eq(topics.agentId, agentId), isNotNull(topics.senderId)));-- return {- topicCount: Number(result?.topicCount ?? 0),- visitorCount: Number(result?.visitorCount ?? 0),- };- };-- // **************** Create *************** //-- create = async (- { messages: messageIds, ...params }: CreateTopicParams,- id: string = this.genId(),- timing?: ModelTimingContext,- ): Promise<TopicItem> => {- const insertData = buildWorkspacePayload(- { userId: this.userId, workspaceId: this.workspaceId },- {- ...params,- agentId: params.agentId || null,- groupId: params.groupId || null,- id,- sessionId: params.sessionId || null,- },- );- const insertMeta = {- hasAgentId: !!params.agentId,- hasGroupId: !!params.groupId,- hasSessionId: !!params.sessionId,- };-- if (!messageIds || messageIds.length === 0) {- const [topic] = await runTimedStage(- timing,- 'db.topic.create.topics.insert',- () => this.db.insert(topics).values(insertData).returning(),- insertMeta,- );-- return topic;- }-- return runTimedStage(- timing,- 'db.topic.create.transaction',- () =>- this.db.transaction(async (tx) => {- // Insert new topic- const [topic] = await runTimedStage(- timing,- 'db.topic.create.topics.insert',- () => tx.insert(topics).values(insertData).returning(),- insertMeta,- );-- // Update associated messages' topicId- await runTimedStage(- timing,- 'db.topic.create.messages.updateTopic',- () =>- tx- .update(messages)- .set({ topicId: topic.id })- .where(and(this.messageOwnership(), inArray(messages.id, messageIds))),- { messageCount: messageIds.length },- );-- return topic;- }),- {- hasAgentId: !!params.agentId,- hasGroupId: !!params.groupId,- hasSessionId: !!params.sessionId,- messageCount: messageIds?.length ?? 0,- },- );- };-- batchCreate = async (topicParams: (CreateTopicParams & { id?: string })[]) => {- // Start a transaction- return this.db.transaction(async (tx) => {- // Batch insert new topics into the topics table- const createdTopics = await tx- .insert(topics)- .values(- topicParams.map((params) =>- buildWorkspacePayload(- { userId: this.userId, workspaceId: this.workspaceId },- {- agentId: params.agentId || null,- favorite: params.favorite,- groupId: params.sessionId ? null : params.groupId,- id: params.id || this.genId(),- sessionId: params.groupId ? null : params.sessionId,- title: params.title,- trigger: params.trigger,- },- ),- ),- )- .returning();-- // For each newly created topic, update the topicId of associated messages- await Promise.all(- createdTopics.map(async (topic, index) => {- const messageIds = topicParams[index].messages;- if (messageIds && messageIds.length > 0) {- await tx- .update(messages)- .set({ topicId: topic.id })- .where(and(this.messageOwnership(), inArray(messages.id, messageIds)));- }- }),- );-- return createdTopics;- });- };-- /**- * Copy a topic into a new one.- *- * `options.upToMessageId` narrows the copy to the ancestor chain ending at- * that message (first message β that message) β the "fork from here" path.- * Without it the whole topic is copied, matching the duplicate action.- */- duplicate = async (topicId: string, newTitle?: string, options?: { upToMessageId?: string }) => {- return this.db.transaction(async (tx) => {- // find original topic- const originalTopic = await tx.query.topics.findFirst({- where: and(eq(topics.id, topicId), this.ownership()),- });-- if (!originalTopic) {- throw new Error(`Topic with id ${topicId} not found`);- }-- // A copy is a brand-new topic: stamp its own timestamps instead of- // inheriting the source's. The sidebar sorts and groups by the latest- // activity time (`topicActivityAt`, i.e. the newest message), so a copy- // that kept the source's date would re-file itself under the source's- // original day instead of showing up as what it is β activity now.- const copiedAt = new Date();-- // copy topic- const [duplicatedTopic] = await tx- .insert(topics)- .values(- buildWorkspacePayload(- { userId: this.userId, workspaceId: this.workspaceId },- {- ...originalTopic,- ...COPIED_TOPIC_USAGE_RESET,- clientId: null,- createdAt: copiedAt,- id: this.genId(),- title: newTitle || originalTopic?.title,- updatedAt: copiedAt,- },- ),- )- .returning();-- // Find messages associated with the original topic, ordered by createdAt- const topicMessages = await tx- .select()- .from(messages)- .where(and(eq(messages.topicId, topicId), this.messageOwnership()))- .orderBy(messages.createdAt);-- // A fork copies only the selected prefix of the conversation (first- // message β `upToMessageId`), so sibling branches left behind by- // regenerate stay in the source topic; a duplicate copies the whole topic.- let originalMessages = topicMessages;- if (options?.upToMessageId) {- const byId = new Map(topicMessages.map((message) => [message.id, message]));- const selected = byId.get(options.upToMessageId);- if (!selected) {- throw new Error(`Message with id ${options.upToMessageId} not found in topic ${topicId}`);- }-- // Walk up to the root, then reverse back to root β selected so parents- // are inserted before their children.- const chain: typeof topicMessages = [];- const visited = new Set<string>();- let cursor: (typeof topicMessages)[number] | undefined = selected;- while (cursor && !visited.has(cursor.id)) {- visited.add(cursor.id);- chain.push(cursor);- cursor = cursor.parentId ? byId.get(cursor.parentId) : undefined;- }-- originalMessages = chain.reverse();- }-- // Find all messagePlugins for this topic- const messageIds = originalMessages.map((m) => m.id);- const originalPlugins =- messageIds.length > 0- ? await tx.select().from(messagePlugins).where(inArray(messagePlugins.id, messageIds))- : [];-- // Build oldId -> newId mapping for messages- const idMap = new Map<string, string>();- originalMessages.forEach((message) => {- idMap.set(message.id, idGenerator('messages'));- });-- // Build oldToolId -> newToolId mapping for tools- const toolIdMap = new Map<string, string>();- originalMessages.forEach((message) => {- if (message.tools && Array.isArray(message.tools)) {- (message.tools as any[]).forEach((tool: any) => {- if (tool.id) {- toolIdMap.set(tool.id, `toolu_${idGenerator('messages')}`);- }- });- }- });-- // copy messages sequentially to respect foreign key constraints- const duplicatedMessages: DBMessageItem[] = [];- for (const [index, message] of originalMessages.entries()) {- const newId = idMap.get(message.id)!;- const newParentId = message.parentId ? idMap.get(message.parentId) || null : null;-- // Retime the copy to the copy moment while preserving its internal- // order (monotonic, 1ms apart, ending at `copiedAt`). The sidebar's- // activity key is the newest message time, so carrying the source's- // timestamps would keep the new topic in the source's date group.- const messageAt = new Date(copiedAt.getTime() - (originalMessages.length - 1 - index));-- // Update tool IDs in tools array- let newTools = message.tools;- if (newTools && Array.isArray(newTools)) {- newTools = (newTools as any[]).map((tool: any) => ({- ...tool,- id: tool.id ? toolIdMap.get(tool.id) || tool.id : tool.id,- }));- }-- const result = (await tx- .insert(messages)- .values({- ...message,- clientId: null,- createdAt: messageAt,- id: newId,- // A duplicate consumed no tokens: mark it so usage reports do not- // count the source's generation twice (the figures themselves stay- // β they are what the transcript records).- metadata: markCopiedMessageMetadata(message.metadata),- parentId: newParentId,- tools: newTools,- topicId: duplicatedTopic.id,- updatedAt: messageAt,- })- .returning()) as DBMessageItem[];-- duplicatedMessages.push(result[0]);-- // Copy messagePlugins if exists for this message- const plugin = originalPlugins.find((p) => p.id === message.id);- if (plugin) {- const newToolCallId = plugin.toolCallId ? toolIdMap.get(plugin.toolCallId) || null : null;-- await tx.insert(messagePlugins).values({- ...plugin,- apiName: clampToolIdentifier(plugin.apiName),- clientId: null,- id: newId,- identifier: clampToolIdentifier(plugin.identifier),- toolCallId: newToolCallId,- });- }- }-- return {- messages: duplicatedMessages,- topic: duplicatedTopic,- };- });- };-- // **************** Delete *************** //-- /**- * Delete one topic, cascading to the messages associated with it.- *- * Agent-share visitor topics carry the creator's `userId`, so ownership alone- * would let the creator-facing `topic.removeTopic` destroy a visitor- * conversation from a raw topic id (obtainable out of band, e.g. through data- * export). Excluded here for the same reason the bulk sweeps exclude them β- * see {@link deleteAll}.- */- delete = async (id: string) => {- return this.db- .delete(topics)- .where(and(eq(topics.id, id), this.ownership(), this.notShareVisitor()));- };-- /**- * Deletes multiple topics based on the sessionId.- * `restrictToCreator` limits the sweep to the caller's own rows (workspace- * non-owner members must not clear teammates' topics).- *- * Visitor topics have no sessionId, so the null-session (inbox) branch would- * otherwise sweep them in β see {@link deleteAll} for why bulk sweeps exclude- * them.- */- batchDeleteBySessionId = async (- sessionId?: string | null,- options?: { restrictToCreator?: boolean },- ) => {- return this.db- .delete(topics)- .where(- and(- this.matchSession(sessionId),- options?.restrictToCreator ? this.mine() : this.ownership(),- this.notShareVisitor(),- ),- );- };-- /**- * Deletes multiple topics based on the groupId.- * `restrictToCreator` limits the sweep to the caller's own rows in workspace mode.- *- * Visitor topics have no groupId, so the null-group branch would otherwise- * sweep them in β see {@link deleteAll}.- */- batchDeleteByGroupId = async (- groupId?: string | null,- options?: { restrictToCreator?: boolean },- ) => {- return this.db- .delete(topics)- .where(- and(- this.matchGroup(groupId),- options?.restrictToCreator ? this.mine() : this.ownership(),- this.notShareVisitor(),- ),- );- };-- /**- * Deletes all topics matching the given agentId (`topics.agentId`).- * `restrictToCreator` limits the sweep to the caller's own rows (workspace- * non-owner members must not clear teammates' topics).- *- * This is the creator's "clear this agent's topics" action, so agent-share- * visitor topics are excluded (see {@link deleteAll}). Deleting the agent- * itself is a different path: `topics.agent_id` cascades at the DB level, so- * visitor topics do go away with the agent without any call to this method.- */- batchDeleteByAgentId = async (agentId: string, options?: { restrictToCreator?: boolean }) => {- return this.db- .delete(topics)- .where(- and(- options?.restrictToCreator ? this.mine() : this.ownership(),- eq(topics.agentId, agentId),- this.notShareVisitor(),- ),- );- };-- /**- * Deletes multiple topics and all messages associated with them in a transaction.- *- * Agent-share visitor topics are excluded β see {@link TopicModel.delete}.- */- batchDelete = async (ids: string[]) => {- return this.db- .delete(topics)- .where(and(inArray(topics.id, ids), this.ownership(), this.notShareVisitor()));- };-- /**- * Hard delete by id that also reaches rows already in the recycle bin β- * same ownership + share-visitor guards as {@link batchDelete}, scoped with- * {@link trashScope} (`includeTrashed`) instead of {@link ownership}. For- * cascade paths that own their id list: a linked topic sitting in the- * recycle bin must not survive its parent's deletion and resurrect as a- * sidebar orphan when the user later restores it.- */- batchDeleteIncludingTrashed = async (ids: string[]) => {- return this.db.delete(topics).where(and(inArray(topics.id, ids), this.trashScope()));- };-- /**- * Creator-facing "clear all my topics".- *- * Agent-share visitor topics live under the creator's `userId` but are hidden- * from every creator-facing listing (see `notShareVisitorTopic` in- * `../utils/shareVisitor`), so a sweep the creator cannot see the contents of- * must not destroy them β "clear all" can only mean the rows the creator sees.- * The same rule applies to the other id-less sweeps here.- *- * Id-targeted deletes ({@link TopicModel.delete}, {@link TopicModel.batchDelete})- * apply the same guard: a creator can obtain a visitor topic id out of band- * (data export), so naming the id is not proof the row is theirs to delete.- */- deleteAll = async () => {- return this.db.delete(topics).where(and(this.mine(), this.notShareVisitor()));- };-- // **************** Recycle bin *************** //-- /**- * Move topics to the recycle bin: stamp `deleted_at` and return the rows so- * the caller can register them. Rows already trashed are left untouched (their- * own registry row keeps their original stamp). Messages / threads are not- * stamped β they are hidden by their parent and hard-cascade at purge time.- */- softDelete = async (ids: string[], options: SoftDeleteOptions): Promise<TopicItem[]> => {- if (ids.length === 0) return [];- return this.db- .update(topics)- .set(trashStamp(options.deletedAt))- .where(- and(- inArray(topics.id, ids),- options.restrictToCreator ? this.mine() : this.ownership(),- this.notShareVisitor(),- ),- )- .returning();- };-- /** Soft-delete counterpart of `batchDeleteBySessionId` (`sessionId` null = the agent's default session). */- softDeleteBySessionId = async (- sessionId: string | null | undefined,- options: SoftDeleteOptions,- ): Promise<TopicItem[]> => {- return this.db- .update(topics)- .set(trashStamp(options.deletedAt))- .where(- and(- this.matchSession(sessionId),- options.restrictToCreator ? this.mine() : this.ownership(),- this.notShareVisitor(),- ),- )- .returning();- };-- softDeleteByGroupId = async (- groupId: string | null | undefined,- options: SoftDeleteOptions,- ): Promise<TopicItem[]> => {- return this.db- .update(topics)- .set(trashStamp(options.deletedAt))- .where(- and(- this.matchGroup(groupId),- options.restrictToCreator ? this.mine() : this.ownership(),- this.notShareVisitor(),- ),- )- .returning();- };-- softDeleteByAgentId = async (- agentId: string,- options: SoftDeleteOptions,- ): Promise<TopicItem[]> => {- return this.db- .update(topics)- .set(trashStamp(options.deletedAt))- .where(- and(- eq(topics.agentId, agentId),- options.restrictToCreator ? this.mine() : this.ownership(),- this.notShareVisitor(),- ),- )- .returning();- };-- /**- * Cascade helper for trashing an agent / group / session: stamps every live- * topic that hangs off any of the given parents (by `agent_id`, `session_id`- * or `group_id`) in one statement.- */- softDeleteByParents = async (- parents: { agentIds?: string[]; groupIds?: string[]; sessionIds?: string[] },- options: SoftDeleteOptions,- ): Promise<TopicItem[]> => {- const conditions: SQL[] = [];- if (parents.agentIds?.length) conditions.push(inArray(topics.agentId, parents.agentIds));- if (parents.sessionIds?.length) conditions.push(inArray(topics.sessionId, parents.sessionIds));- if (parents.groupIds?.length) conditions.push(inArray(topics.groupId, parents.groupIds));- if (conditions.length === 0) return [];-- return this.db- .update(topics)- .set(trashStamp(options.deletedAt))- .where(- and(- or(...conditions),- options.restrictToCreator ? this.mine() : this.ownership(),- this.notShareVisitor(),- ),- )- .returning();- };-- softDeleteAll = async (options: SoftDeleteOptions): Promise<TopicItem[]> => {- return this.db- .update(topics)- .set(trashStamp(options.deletedAt))- .where(and(this.mine(), this.notShareVisitor()))- .returning();- };-- /** Bring trashed topics back. Only rows currently stamped are touched. */- restore = async (ids: string[]): Promise<TopicItem[]> => {- if (ids.length === 0) return [];- return this.db- .update(topics)- .set(restoreStamp())- .where(and(inArray(topics.id, ids), this.trashScope(), isTrashed(topics.isDeleted)))- .returning();- };-- /** Trashed rows by id, bypassing the recycle-bin filter (restore / purge internals). */- findTrashedByIds = async (ids: string[]): Promise<TopicItem[]> => {- if (ids.length === 0) return [];- return this.db- .select()- .from(topics)- .where(and(inArray(topics.id, ids), this.trashScope(), isTrashed(topics.isDeleted)));- };-- /**- * Hard delete for the purge sweep: bypasses the recycle-bin filter so a- * trashed row (invisible to `delete`) can actually be removed. FK cascades- * take messages, threads and the rest with it.- */- purge = async (ids: string[]): Promise<string[]> => {- if (ids.length === 0) return [];- // Only rows still stamped: a restore that commits between the registry- // read and this delete must win, not be hard-deleted as a stale purge.- const rows = await this.db- .delete(topics)- .where(and(inArray(topics.id, ids), this.trashScope(), isTrashed(topics.isDeleted)))- .returning({ id: topics.id });- return rows.map((row) => row.id);- };-- // **************** Update *************** //-- update = async (id: string, data: Partial<TopicItem>) => {- /**- * Older clients switch models through the general update endpoint. Clear- * the old model's reasoning pin in the same statement, comparing against- * the persisted row so partial writes and concurrent switches stay safe.- * Explicit metadata remains the caller's replacement snapshot.- */- const modelChanged = or(- data.model !== undefined ? sql`${topics.model} is distinct from ${data.model}` : undefined,- data.provider !== undefined- ? sql`${topics.provider} is distinct from ${data.provider}`- : undefined,- );- const persistedMetadata = modelChanged- ? sql`case when ${modelChanged} then coalesce(${topics.metadata}, '{}'::jsonb) - 'reasoningConfig' else coalesce(${topics.metadata}, '{}'::jsonb) end`- : sql`coalesce(${topics.metadata}, '{}'::jsonb)`;-- /**- * A locally executed run β desktop heterogeneous CLI, in-browser runtime β- * has no `agent_operations` row: its runtime lives in the client, and the- * only thing it tells the server is this status write. Stamp when the run- * claimed the topic in the same statement, so a list can show a live- * elapsed clock for those runs the same way it does for server-side ones- * (see `runStartedAtColumn` in {@link TopicModel.queryTopics}).- *- * Compared against the PERSISTED status so a resume out of- * `waitingForHuman` β the same run, continuing after an approval β keeps- * its original start instead of restarting the clock. The stamp is left- * behind on terminal statuses: every reader gates on `status = 'running'`,- * and the next run overwrites it.- */- const metadata =- data.metadata !== undefined- ? data.metadata- : data.status === 'running'- ? sql`case when ${topics.status} in ('running', 'waitingForHuman') then ${persistedMetadata} else jsonb_set(${persistedMetadata}, '{runStartedAt}', to_jsonb(now())) end`- : modelChanged- ? persistedMetadata- : undefined;-- return this.db- .update(topics)- .set({ ...data, metadata, updatedAt: new Date() })- .where(and(eq(topics.id, id), this.ownership()))- .returning();- };-- /**- * Settle a topic out of `running` once its run has terminated server-side.- *- * Guarded on `status = 'running'` so it is race-tolerant with clients: an- * attached renderer writes 'active' (focused) or 'unread' (backgrounded) on- * the terminal stream event, and whichever write lands first wins β this one- * degrades to a no-op instead of clobbering it. Without a server-side settle,- * a run with no client attached (cron-dispatched scheduled resume, app closed- * mid-run) leaves the topic at `running` forever.- *- * Returns the settled row, or nothing when the guard didn't match.- */- settleRunningStatus = async (id: string, status: TopicItem['status'] = 'unread') => {- return this.db- .update(topics)- .set({ status, updatedAt: new Date() })- .where(and(eq(topics.id, id), eq(topics.status, 'running'), this.ownership()))- .returning({ id: topics.id, status: topics.status });- };-- /**- * Atomically clear and settle the operation that still owns a topic.- * A row lock keeps a stale terminal callback from clearing a newer operation- * between the ownership check and update. Missing markers are intentionally- * not settled because a client-side run can set `status = 'running'` without- * an operation marker, so there is no proof that the terminal callback owns it.- *- * The result distinguishes a missing marker from a conflicting operation:- * some legitimate hetero callbacks arrive after another terminal path has- * already cleared their marker, while a callback that observes a newer- * operation must stop before dispatching lifecycle hooks for the wrong run.- */- settleRunningOperation = async (- id: string,- operationId: string,- status: TopicItem['status'] = 'unread',- options: SettleRunningOperationOptions = {},- ) => {- return this.db.transaction(async (tx) => {- const [existing] = await tx- .select({- metadata: topics.metadata,- projectId: topics.projectId,- projectWorkingDirectoryId: topics.projectWorkingDirectoryId,- status: topics.status,- })- .from(topics)- .where(and(eq(topics.id, id), this.ownership()))- .for('update');-- const runningOperation = existing?.metadata?.runningOperation;- if (!runningOperation) {- const currentMessage = existing?.metadata?.heteroCurrentMsgId;- if (- existing?.metadata?.lastSettledOperationId === operationId &&- existing.status === 'unread' &&- status === 'active'- ) {- await tx- .update(topics)- .set({ status: 'active', updatedAt: new Date() })- .where(and(eq(topics.id, id), this.ownership()));-- return {- assistantMessageId:- currentMessage?.operationId === operationId ? currentMessage.msgId : undefined,- status: 'corrected' as const,- };- }-- return {- assistantMessageId:- currentMessage?.operationId === operationId ? currentMessage.msgId : undefined,- status: 'missing' as const,- };- }- const isRoot = runningOperation.operationId === operationId;- const operation = isRoot- ? runningOperation- : runningOperation.childOperations?.find((child) => child.operationId === operationId);- if (!operation) {- return { activeOperationId: runningOperation.operationId, status: 'conflict' as const };- }-- // A client only learns a run ended from a stream event, and a mirrored or- // early event can arrive while the server is still driving the run (e.g. a- // supervisor parked on `waiting_for_async_tool` for its group members).- // Clearing the marker then drops the run's topic reservation, so the next- // member start fails as "Topic β¦ remained busy". The server's own- // `finish` clears the marker before it publishes the terminal event, so a- // genuine end never reaches this check with the marker still in place.- if (options.rejectInFlightOperation) {- const [operationRow] = await tx- .select({ status: agentOperations.status })- .from(agentOperations)- .where(eq(agentOperations.id, operationId))- .limit(1);- if (- operationRow &&- CLIENT_UNSETTLEABLE_OPERATION_STATUSES.has(operationRow.status as AgentOperationStatus)- ) {- return {- activeOperationId: runningOperation.operationId,- operationStatus: operationRow.status as AgentOperationStatus,- status: 'in_flight' as const,- };- }- }-- const metadata = {- ...existing.metadata,- ...(isRoot ? { lastSettledOperationId: operationId } : {}),- runningOperation: isRoot- ? null- : {- ...runningOperation,- childOperations: runningOperation.childOperations?.filter(- (child) => child.operationId !== operationId,- ),- },- } as ChatTopicMetadata;-- await tx- .update(topics)- .set({- metadata,- ...(isRoot && existing.status === 'running' ? { status } : {}),- updatedAt: new Date(),- })- .where(and(eq(topics.id, id), this.ownership()));-- const currentMessage = existing.metadata?.heteroCurrentMsgId;- return {- assistantMessageId:- currentMessage?.operationId === operationId- ? currentMessage.msgId- : operation.assistantMessageId,- hooks: operation.hooks,- orchestrationRole: operation.orchestrationRole,- status: 'settled' as const,- threadId: operation.threadId ?? undefined,- };- });- };-- /**- * Move multiple topics (and all their messages) to another agent.- *- * Reassigns ownership purely through the `agentId` foreign key (the new data- * model). Every child entity of the topic that carries its own `agentId` FK- * MUST be updated together β `topics`, `messages`, and `threads`. Topic lists- * query by `topics.agentId` and message queries filter by `messages.agentId`,- * so updating only the topic would leave the moved conversation showing up- * empty under the target agent; and `threads.agentId` is itself a- * cascade-on-delete FK, so a thread left pointing at the source agent would- * be destroyed if that agent is later deleted.- *- * `sessionId` is cleared on `topics` and `messages` so the rows fully detach- * from the source agent's legacy session and can't leak back through the- * sessionId-based legacy query fallback (`threads` has no `sessionId`).- *- * Topics can only be moved to an agent owned by the same user/workspace. The- * target agent is verified with the same ownership predicate before applying- * the move β `topics.agentId` / `messages.agentId` are plain FKs to- * `agents.id` with cascade-on-delete, so attaching rows to a foreign agent- * would both leak them across tenants and risk losing them if that agent is- * later deleted.- */- batchMoveToAgent = async (topicIds: string[], targetAgentId: string) => {- if (topicIds.length === 0) return;-- return this.db.transaction(async (tx) => {- const [targetAgent] = await tx- .select({ id: agents.id })- .from(agents)- .where(- and(- eq(agents.id, targetAgentId),- buildWorkspaceWhere({ userId: this.userId, workspaceId: this.workspaceId }, agents),- ),- )- .limit(1);-- if (!targetAgent) {- throw new Error(`Target agent ${targetAgentId} not found or not accessible`);- }-- await tx- .update(topics)- .set({ agentId: targetAgentId, sessionId: null, updatedAt: new Date() })- .where(and(inArray(topics.id, topicIds), this.ownership()));-- await tx- .update(messages)- .set({ agentId: targetAgentId, sessionId: null })- .where(and(inArray(messages.topicId, topicIds), this.messageOwnership()));-- await tx- .update(threads)- .set({ agentId: targetAgentId })- .where(- and(- inArray(threads.topicId, topicIds),- buildWorkspaceWhere({ userId: this.userId, workspaceId: this.workspaceId }, threads),- ),- );- });- };-- /**- * Recompute this topic's denormalized usage/cost rollup from its assistant- * messages. The canonical aggregation lives in `recomputeTopicUsage`; the- * live path (MessageModel) calls it inline within its own transaction, while- * external callers use this wrapper. Runs in a transaction for consistency.- */- recomputeUsage = async (id: string) =>- this.db.transaction((trx) => recomputeTopicUsage(trx, this.userId, id, this.workspaceId));-- /**- * Update topic metadata with merge logic- * This method merges new metadata with existing metadata instead of replacing it- */- updateMetadata = async (id: string, metadata: TopicMetadataPatch) => {- // Merge into the existing metadata under a row lock so concurrent writers- // can't lose each other's keys. The old read-then-write was a non-atomic- // read-modify-write: a hetero run seeds `metadata.runningOperation` while- // heteroIngest concurrently writes `metadata.heteroCurrentMsgId`, and a write- // built on a stale snapshot (interleaved read, or a read-replica that hadn't- // caught up) silently dropped `runningOperation` β stranding the finished- // task at `task_topics.status = 'running'` because heteroFinish then had no- // hooks to deliver. `SELECT β¦ FOR UPDATE` forces a primary read + serializes- // writers on the row, killing both the interleave and replica-lag variants- // while preserving the exact (shallow + nested onboardingSession) merge.- return this.db.transaction(async (tx) => {- const [existing] = await tx- .select({ metadata: topics.metadata })- .from(topics)- .where(and(eq(topics.id, id), this.ownership()))- .for('update');-- // No row (missing or not owned) β nothing to update, mirror the old no-op.- if (!existing) return [];-- const mergedOnboardingSession =- existing.metadata?.onboardingSession && metadata.onboardingSession- ? {- ...existing.metadata.onboardingSession,- ...metadata.onboardingSession,- }- : metadata.onboardingSession;-- const mergedMetadata = {- ...existing.metadata,- ...metadata,- ...(mergedOnboardingSession && { onboardingSession: mergedOnboardingSession }),- } as ChatTopicMetadata;-- return tx- .update(topics)- .set({ metadata: mergedMetadata })- .where(and(eq(topics.id, id), this.ownership()))- .returning();- });- };-- /**- * Switch a topic's pinned model together with its model-scoped effort pin- * (`metadata.reasoningConfig` / `metadata.heteroEffort`) in one row-locked- * statement, so neither a concurrent switch nor an in-flight run can observe- * the new model paired with the previous model's pin. `reasoningConfig` is- * model-keyed and therefore always replaced (dropped when not provided);- * `heteroEffort` and `heteroSpeed` are only touched when given.- */- updateModelPin = async (- id: string,- {- metadata,- model,- provider,- }: {- metadata?: Pick<ChatTopicMetadata, 'heteroEffort' | 'heteroSpeed' | 'reasoningConfig'>;- model: string;- provider: string;- },- ) =>- this.db.transaction(async (tx) => {- const [existing] = await tx- .select({ metadata: topics.metadata })- .from(topics)- .where(and(eq(topics.id, id), this.ownership()))- .for('update');-- if (!existing) return [];-- const { reasoningConfig: _stale, ...rest } = existing.metadata ?? {};- const mergedMetadata: ChatTopicMetadata = {- ...rest,- ...(metadata?.heteroEffort !== undefined && { heteroEffort: metadata.heteroEffort }),- ...(metadata?.heteroSpeed !== undefined && { heteroSpeed: metadata.heteroSpeed }),- ...(metadata?.reasoningConfig !== undefined && {- reasoningConfig: metadata.reasoningConfig,- }),- };-- return tx- .update(topics)- .set({ metadata: mergedMetadata, model, provider, updatedAt: new Date() })- .where(and(eq(topics.id, id), this.ownership()))- .returning();- });-- appendRunningOperationChild = async (- id: string,- parentOperationId: string,- child: RunningOperation,- ): Promise<boolean> =>- this.db.transaction(async (tx) => {- const [existing] = await tx- .select({ metadata: topics.metadata })- .from(topics)- .where(and(eq(topics.id, id), this.ownership()))- .for('update');- const runningOperation = existing?.metadata?.runningOperation;- if (!existing || runningOperation?.operationId !== parentOperationId) return false;-- await tx- .update(topics)- .set({- metadata: {- ...existing.metadata,- runningOperation: {- ...runningOperation,- childOperations: [- ...(runningOperation.childOperations ?? []).filter(- (operation) => operation.operationId !== child.operationId,- ),- child,- ],- },- },- })- .where(and(eq(topics.id, id), this.ownership()));- return true;- });-- patchRunningOperation = async (- id: string,- operationId: string,- patch: RunningOperationPatch,- ): Promise<boolean> =>- this.db.transaction(async (tx) => {- const [existing] = await tx- .select({ metadata: topics.metadata })- .from(topics)- .where(and(eq(topics.id, id), this.ownership()))- .for('update');- const runningOperation = existing?.metadata?.runningOperation;- if (!existing || !runningOperation) return false;-- let nextRunningOperation: RunningOperation;- if (runningOperation.operationId === operationId) {- nextRunningOperation = { ...runningOperation, ...patch };- } else {- let matched = false;- const childOperations = runningOperation.childOperations?.map((child) => {- if (child.operationId !== operationId) return child;- matched = true;- return { ...child, ...patch };- });- if (!matched) return false;- nextRunningOperation = { ...runningOperation, childOperations };- }-- await tx- .update(topics)- .set({- metadata: { ...existing.metadata, runningOperation: nextRunningOperation },- })- .where(and(eq(topics.id, id), this.ownership()));- return true;- });-- removeRunningOperationChild = async (id: string, operationId: string): Promise<boolean> =>- this.db.transaction(async (tx) => {- const [existing] = await tx- .select({ metadata: topics.metadata })- .from(topics)- .where(and(eq(topics.id, id), this.ownership()))- .for('update');- const runningOperation = existing?.metadata?.runningOperation;- if (!existing || !runningOperation?.childOperations) return false;- await tx- .update(topics)- .set({- metadata: {- ...existing.metadata,- runningOperation: {- ...runningOperation,- childOperations: runningOperation.childOperations.filter(- (child) => child.operationId !== operationId,- ),- },- },- })- .where(and(eq(topics.id, id), this.ownership()));- return true;- });-- updateRunningOperationAssistantMessage = async (- id: string,- operationId: string,- assistantMessageId: string,- ): Promise<boolean> =>- this.db.transaction(async (tx) => {- const [existing] = await tx- .select({ metadata: topics.metadata })- .from(topics)- .where(and(eq(topics.id, id), this.ownership()))- .for('update');- const runningOperation = existing?.metadata?.runningOperation;- if (!existing || !runningOperation) return false;-- if (runningOperation.operationId === operationId) {- await tx- .update(topics)- .set({- metadata: {- ...existing.metadata,- heteroCurrentMsgId: { msgId: assistantMessageId, operationId },- runningOperation: { ...runningOperation, assistantMessageId },- },- })- .where(and(eq(topics.id, id), this.ownership()));- return true;- }-- const childOperations = runningOperation.childOperations?.map((child) =>- child.operationId === operationId ? { ...child, assistantMessageId } : child,- );- if (!childOperations?.some((child) => child.operationId === operationId)) return false;-- await tx- .update(topics)- .set({- metadata: {- ...existing.metadata,- heteroCurrentMsgId: { msgId: assistantMessageId, operationId },- runningOperation: { ...runningOperation, childOperations },- },- })- .where(and(eq(topics.id, id), this.ownership()));- return true;- });-- takeRunningOperation = async (- id: string,- operationId: string,- ): Promise<- | {- isRoot: boolean;- operation: NonNullable<ChatTopicMetadata['runningOperation']>;- }- | undefined- > =>- this.db.transaction(async (tx) => {- const [existing] = await tx- .select({ metadata: topics.metadata })- .from(topics)- .where(and(eq(topics.id, id), this.ownership()))- .for('update');- const runningOperation = existing?.metadata?.runningOperation;- if (!existing || !runningOperation) return undefined;-- if (runningOperation.operationId === operationId) {- await tx- .update(topics)- .set({- metadata: { ...existing.metadata, runningOperation: null },- })- .where(and(eq(topics.id, id), this.ownership()));- return { isRoot: true, operation: runningOperation };- }-- const child = runningOperation.childOperations?.find(- (candidate) => candidate.operationId === operationId,- );- if (!child) return undefined;-- await tx- .update(topics)- .set({- metadata: {- ...existing.metadata,- runningOperation: {- ...runningOperation,- childOperations: runningOperation.childOperations?.filter(- (candidate) => candidate.operationId !== operationId,- ),- },- },- })- .where(and(eq(topics.id, id), this.ownership()));- return { isRoot: false, operation: child };- });-- /**- * Whether the run a `runningOperation` marker points at is still the topic's- * legitimate owner.- *- * Public so the gateway-token refresh routers can refuse to reconnect a- * client to a marker whose run has already ended (the marker is cleared- * best-effort, so a stale one must not be taken at face value).- *- * The marker itself cannot answer this β it carries no heartbeat and is- * cleared best-effort β so the authority is the operation row, which both the- * in-process runtime (`createOperation`) and the heterogeneous path- * (`CompletionLifecycle.recordStart`) write before publishing the marker.- *- * Falls back to the marker's own `startedAt` only when no row exists: hetero's- * `recordStart` is deliberately non-fatal, so a DB hiccup can leave a live run- * with a marker and no row. A marker with neither a row nor a stamp cannot be- * proven live and must not keep an already-stuck topic stuck.- */- isRunningOperationAlive = async (- tx: Pick<LobeChatDatabase, 'select'>,- runningOperation: NonNullable<ChatTopicMetadata['runningOperation']>,- ): Promise<boolean> => {- const [operation] = await tx- .select({ createdAt: agentOperations.createdAt, status: agentOperations.status })- .from(agentOperations)- .where(eq(agentOperations.id, runningOperation.operationId))- .limit(1);-- if (!operation) {- const markerStartedAt = runningOperation.startedAt- ? Date.parse(runningOperation.startedAt)- : Number.NaN;- return (- Number.isFinite(markerStartedAt) &&- Date.now() - markerStartedAt < ABANDONED_OPERATION_TTL_MS- );- }-- if (!LIVE_OPERATION_STATUSES.has(operation.status)) return false;- if (UNBOUNDED_OPERATION_STATUSES.has(operation.status)) return true;-- // Claims `running`/`idle`, but a killed process never writes a terminal- // status β age it out so the topic is not held forever.- const startedAt = operation.createdAt ? new Date(operation.createdAt).getTime() : Number.NaN;- return !Number.isFinite(startedAt) || Date.now() - startedAt < ABANDONED_OPERATION_TTL_MS;- };-- /**- * Atomically reserve an idle topic for one task-callback delivery.- *- * The topic row lock closes the check/set race between callback workers:- * only one callback can observe both `runningOperation` and the reservation- * as empty. Foreground/tool continuations clear `runningOperation` before a- * callback can claim the topic, so the callback always re-anchors on the- * completed turn's latest spine.- */- tryReserveTaskCallback = async (- id: string,- messageId: string,- options?: {- /**- * Permit a start that runs *under* this marker (a group member starting- * beneath its supervisor). A pure permission check β it never takes the- * reservation.- */- allowRunningOperationId?: string;- /**- * A deterministic intervention reservation is an initializer fence, not- * a reentrant mutex. Its concurrent same-id caller must wait until the- * owner releases (or the lease expires) instead of entering preparation- * and overwriting an already-running continuation state.- */- allowSameReservationReentry?: boolean;- /**- * Skip the `runningOperation` check entirely and serialize only on the- * short reservation. Set by interactive sends: "don't run two foreground- * turns at once" is a UX policy the client already owns end to end (queue- * tray, "Send now", FIFO drain), and it is the only layer that can show- * the user anything. A second, blind copy of that policy here can only- * fail worse β it used to destroy the message before it was ever- * persisted. Background starts (task callbacks, cron, bots) have no such- * queue and keep the check.- */- ignoreRunningOperation?: boolean;- replacesOperationId?: string;- },- ): Promise<boolean | null> =>- this.db.transaction(async (tx) => {- const [existing] = await tx- .select({ metadata: topics.metadata })- .from(topics)- .where(and(eq(topics.id, id), this.ownership()))- .for('update');-- if (!existing) return null;-- const reservation = existing.metadata?.taskCallbackReservation;- const hasLiveReservation = hasLiveTaskCallbackReservation(existing.metadata);-- if (- reservation?.messageId === messageId &&- hasLiveReservation &&- options?.allowSameReservationReentry !== false- ) {- return true;- }-- const runningOperation = existing.metadata?.runningOperation;- const ownedRunningOperation =- !!options?.allowRunningOperationId &&- runningOperation?.operationId === options.allowRunningOperationId;- if (options?.allowRunningOperationId) return ownedRunningOperation;-- const canReplaceRunningOperation =- !!options?.replacesOperationId &&- runningOperation?.operationId === options.replacesOperationId;-- // Only a run that can prove it is still alive may hold the topic. Ask the- // operation row rather than the marker's age: the marker is never- // refreshed, so age alone declares a legitimately long run (an approval- // wait can last days) dead and lets a competing continuation start.- const hasLiveRunningOperation =- !!runningOperation &&- !canReplaceRunningOperation &&- !options?.ignoreRunningOperation &&- (await this.isRunningOperationAlive(tx, runningOperation));-- if (hasLiveRunningOperation || hasLiveReservation) return false;-- await tx- .update(topics)- .set({- metadata: {- ...existing.metadata,- ...(canReplaceRunningOperation && { runningOperation: null }),- taskCallbackReservation: {- messageId,- reservedAt: new Date().toISOString(),- },- },- })- .where(and(eq(topics.id, id), this.ownership()));-- return true;- });-- /**- * Repair the reconnect anchor after an intervention queue ACK. The same row- * lock also releases only this continuation's reservation, closing the crash- * window between provider ACK and execAgent's ordinary running-marker write.- */- repairAgentInterventionContinuation = async (params: {- active: boolean;- assistantMessageId: string;- continuationOperationId: string;- reservationId: string;- scope?: string | null;- sourceOperationId: string;- startedAt: string;- threadId?: string | null;- topicId: string;- }): Promise<'conflict' | 'repaired' | 'terminal'> =>- this.db.transaction(async (tx) => {- const [existing] = await tx- .select({ metadata: topics.metadata })- .from(topics)- .where(and(eq(topics.id, params.topicId), this.ownership()))- .for('update');- if (!existing) return 'conflict';-- const current = existing.metadata?.runningOperation;- const reservation = existing.metadata?.taskCallbackReservation;- const hasLiveReservation = hasLiveTaskCallbackReservation(existing.metadata);- const ownsCurrent =- !current ||- current.operationId === params.sourceOperationId ||- current.operationId === params.continuationOperationId;- const ownsReservation = reservation?.messageId === params.reservationId;- if (hasLiveReservation && !ownsReservation) return 'conflict';- if (!ownsCurrent) {- if (ownsReservation) {- await tx- .update(topics)- .set({- metadata: { ...existing.metadata, taskCallbackReservation: null },- updatedAt: new Date(),- })- .where(and(eq(topics.id, params.topicId), this.ownership()));- }- return 'conflict';- }-- const runningOperation = params.active- ? {- ...(current?.operationId === params.continuationOperationId ? current : {}),- assistantMessageId: params.assistantMessageId,- heteroType: null,- operationId: params.continuationOperationId,- scope: params.scope ?? undefined,- startedAt: params.startedAt,- threadId: params.threadId ?? undefined,- }- : null;- await tx- .update(topics)- .set({- metadata: {- ...existing.metadata,- runningOperation,- ...(ownsReservation || !hasLiveReservation ? { taskCallbackReservation: null } : {}),- },- updatedAt: new Date(),- })- .where(and(eq(topics.id, params.topicId), this.ownership()));-- return params.active ? 'repaired' : 'terminal';- });-- /**- * Release only the caller's reservation. The ownership check prevents a- * delayed finally block from clearing a newer callback's claim.- */- releaseTaskCallbackReservation = async (- id: string,- messageId: string,- ): Promise<'absent' | 'foreign' | 'released'> =>- this.db.transaction(async (tx) => {- const [existing] = await tx- .select({ metadata: topics.metadata })- .from(topics)- .where(and(eq(topics.id, id), this.ownership()))- .for('update');-- const reservation = existing?.metadata?.taskCallbackReservation;- if (!reservation) return 'absent';- if (reservation.messageId !== messageId) return 'foreign';-- await tx- .update(topics)- .set({- metadata: {- ...existing.metadata,- taskCallbackReservation: null,- },- })- .where(and(eq(topics.id, id), this.ownership()));- return 'released';- });-- /** Atomically cancel an unclaimed rate-limit run, serialized with the dispatcher. */- cancelRateLimitContinuation = async (id: string) =>- this.db.transaction(async (tx) => {- const [row] = await tx- .select({ metadata: topics.metadata, status: topics.status })- .from(topics)- .where(and(eq(topics.id, id), this.ownership()))- .for('update');- if (!row) return { status: 'unchanged' as const };- if (row.status === 'running') return { status: 'busy' as const };- const scheduledRun = parseTopicScheduledRun(row.metadata?.scheduledRun);- if (row.status !== 'scheduled' || scheduledRun?.kind !== 'resume_after_rate_limit')- return { status: 'unchanged' as const };- // A lease expiring does not stop its dispatcher. Once claimed, a handoff- // must not race that worker, even if its five-minute lease has elapsed.- if (scheduledRun.claim) return { status: 'busy' as const };-- const metadata = { ...row.metadata, scheduledRun: null };- await tx- .update(topics)- .set({ metadata, status: 'failed' })- .where(and(eq(topics.id, id), this.ownership()));- return { metadata, status: 'cancelled' as const };- });-- /**- * Arm a scheduled run on an owned topic: writes `metadata.scheduledRun` and- * flips the status to `scheduled` in a single update.- *- * The pair is one fact β a topic that is `scheduled` with no payload spins in- * the dispatcher forever, and a payload on a non-`scheduled` topic never fires- * β so they must never be written separately. The inverse is- * {@link TopicModel.clearScheduledRun}.- */- armScheduledRun = async (id: string, scheduledRun: TopicScheduledRun): Promise<void> => {- await this.db.transaction(async (tx) => {- const [existing] = await tx- .select({ metadata: topics.metadata })- .from(topics)- .where(and(eq(topics.id, id), this.ownership()))- .for('update');-- if (!existing) return;-- await tx- .update(topics)- .set({- metadata: { ...existing.metadata, scheduledRun } as ChatTopicMetadata,- status: 'scheduled',- })- .where(and(eq(topics.id, id), this.ownership()));- });- };-- getCronTopicsGroupedByCronJob = async (- agentId: string,- ): Promise<{ cronJobId: string; topics: TopicItem[] }[]> => {- const rows = await this.db- .select()- .from(topics)- .where(- and(- this.ownership(),- eq(topics.agentId, agentId),- eq(topics.trigger, 'cron'),- sql`COALESCE(${topics.metadata}->>'cronJobId', '') <> ''`,- ),- )- .orderBy(desc(topics.createdAt));-- const grouped = new Map<string, TopicItem[]>();- for (const topic of rows) {- const cronJobId = (topic.metadata as { cronJobId?: string } | null)?.cronJobId;- if (!cronJobId) continue;- const group = grouped.get(cronJobId) ?? [];- group.push(topic);- grouped.set(cronJobId, group);- }-- return [...grouped.entries()].map(([cronJobId, topicList]) => ({- cronJobId,- topics: topicList,- }));- };-- // **************** Helper *************** //-- private genId = () => idGenerator('topics');-- private matchSession = (sessionId?: string | null) =>- sessionId ? eq(topics.sessionId, sessionId) : isNull(topics.sessionId);-- private matchGroup = (groupId?: string | null) =>- groupId ? eq(topics.groupId, groupId) : isNull(topics.groupId);-- private matchContainer = (containerId?: string | null) => {- if (containerId) return or(eq(topics.sessionId, containerId), eq(topics.groupId, containerId));- // If neither is provided, match topics with no session or group- return and(isNull(topics.sessionId), isNull(topics.groupId));- };-- /**- * Build the WHERE condition that scopes a keyword search to a single- * conversation owner. Mirrors {@link TopicModel.query}'s precedence and- * conditions exactly (groupId > agentId > containerId), so search returns the- * same set the topics list shows.- *- * The agent branch matches `topics.agentId` directly β the new agent system- * stamps every topic with an agentId, and the old `matchContainer` path- * (sessionId / groupId only) would miss those rows entirely. It deliberately- * does NOT fall back to the resolved sessionId: the list has no such fallback- * either, so adding one would (a) surface un-migrated rows the list hides and- * (b) leak topics owned by another agent that shares the same session mapping.- * Legacy rows are backfilled with an agentId by the migration the list query- * triggers, after which the agentId match finds them.- */- private matchKeywordScope = ({- agentId,- containerId,- groupId,- }: TopicKeywordScope): SQL | undefined => {- if (groupId) return eq(topics.groupId, groupId);- if (agentId) return eq(topics.agentId, agentId);- return this.matchContainer(containerId);- };-- listTopicsForMemoryExtractor = async (- options: {- cursor?: ListTopicsForMemoryExtractorCursor;- endDate?: Date;- ignoreExtracted?: boolean;- limit?: number;- startDate?: Date;- } = {},- ) => {- const cursorCondition = options.cursor- ? and(- ne(topics.id, options.cursor.id),- or(- gt(topics.createdAt, options.cursor.createdAt),- and(eq(topics.createdAt, options.cursor.createdAt), gt(topics.id, options.cursor.id)),- ),- )- : undefined;-- return this.db.query.topics.findMany({- columns: {- createdAt: true,- id: true,- metadata: true,- userId: true,- },- limit: options.limit,- orderBy: (fields, { asc }) => [asc(fields.createdAt), asc(fields.id)],- where: and(- this.ownership(),- // Share-visitor conversations are not the creator's own speech β never- // feed them into the creator's memory extraction.- this.notShareVisitor(),- options.startDate ? gte(topics.createdAt, options.startDate) : undefined,- options.endDate ? lte(topics.createdAt, options.endDate) : undefined,- options.ignoreExtracted- ? undefined- : // COALESCE, not `IS DISTINCT FROM`: a null test on a jsonb arrow- // expression crashes the production engine (see the note on the class).- // A null `metadata` extracts to '' here too, so this covers it.- sql`COALESCE(${topics.metadata}->>'userMemoryExtractStatus', '') <> 'completed'`,- cursorCondition,- ),- });- };-- countTopicsForMemoryExtractor = async (- options: {- endDate?: Date;- ignoreExtracted?: boolean;- startDate?: Date;- } = {},- ) => {- const result = await this.db- .select({ total: count(topics.id) })- .from(topics)- .where(- and(- this.ownership(),- this.notShareVisitor(),- options.startDate ? gte(topics.createdAt, options.startDate) : undefined,- options.endDate ? lte(topics.createdAt, options.endDate) : undefined,- options.ignoreExtracted- ? undefined- : sql`COALESCE(${topics.metadata}->>'userMemoryExtractStatus', '') <> 'completed'`,- ),- );-- return result[0]?.total ?? 0;- };-- /**- * Resets the memory-extraction state of all the caller's topics back to- * `pending`, clearing any previous run summary. Used by "purge all- * memories": after memories are deleted, topics keep `userMemoryExtractStatus =- * 'completed'`, so `isTopicExtracted()` skips them forever and nothing can- * ever be re-extracted. Resetting to `pending` makes the next memory- * analysis re-process them. Fixes #18498.- *- * Scoped by `userId` only (not `mine()`): `deleteAll` removes every memory- * belonging to the caller regardless of workspace scope, so the reset must- * cover topics across personal and all workspace scopes alike, otherwise- * topics in the other scope keep `completed` and stay stuck behind the- * extraction skip gate.- */- resetMemoryExtractStatus = async () => {- return this.db- .update(topics)- .set({- metadata: sql`jsonb_set(- jsonb_set(${topics.metadata}, '{userMemoryExtractStatus}', to_jsonb('pending'::text), true),- '{userMemoryExtractRunState}', '{}'::jsonb, true- )`,- })- .where(eq(topics.userId, this.userId));- };-- // **************** Scheduled run (backend cron) *************** //-- /**- * Topics with a scheduled run that has come due.- * System-level sweep (no ownership filter) used by the cron dispatcher.- *- * Due = `status = 'scheduled'` AND the run's gate has passed AND there is no- * live claim (`scheduledRun.claim.expiresAt` is absent, or already expired) β- * so a topic another replica is mid-dispatch on is skipped.- *- * `runAt` is the gate for every {@link TopicScheduledRunKind}: a row carrying a- * `kind` but no `runAt` is never due, which is what keeps a half-written- * scheduled topic from being dispatched immediately.- *- * The one exception is a row parked by the pre-`kind` version, which has no- * `runAt` and gated on the rate-limit reset instead. Those are still in the DB- * on deploy, so this reproduces their old gate rather than stranding them at- * `scheduled` forever β matching `parseTopicScheduledRun`, which upgrades the- * payload the dispatcher then reads.- */- static async getDueScheduledTopics(- db: LobeChatDatabase,- now: Date = new Date(),- ): Promise<TopicItem[]> {- const nowIso = now.toISOString();- const nowEpochSeconds = Math.floor(now.getTime() / 1000);-- // Every jsonb path below is COALESCE'd to a sentinel rather than null-tested:- // `#>> β¦ IS NULL` in a WHERE clause takes the production engine down. See the- // note on the class.- const runAt = sql`COALESCE(${topics.metadata}#>>'{scheduledRun,runAt}', '')`;-- return db- .select()- .from(topics)- .where(- and(- eq(topics.status, 'scheduled'),- notTrashed(topics.isDeleted),- or(- // `''` is the absent-runAt sentinel, and it never satisfies this pair β- // an absent gate must not read as "due now", which is what keeps a- // half-written schedule parked.- and(sql`${runAt} <> ''`, sql`${runAt} <= ${nowIso}`),- // Legacy (pre-`kind`) payload: no `runAt`, gated on the rate-limit- // reset, and an absent reset read as "due now" (hence the 0 default).- and(- sql`${runAt} = ''`,- sql`COALESCE(${topics.metadata}#>>'{scheduledRun,reason}', '') = 'rate_limit'`,- sql`COALESCE((${topics.metadata}#>>'{scheduledRun,rateLimit,resetsAt}')::numeric, 0) <= ${nowEpochSeconds}`,- ),- ),- // No claim, or the lease has expired. `''` (no claim) sorts before every- // ISO timestamp, so the same comparison covers both.- sql`COALESCE(${topics.metadata}#>>'{scheduledRun,claim,expiresAt}', '') <= ${nowIso}`,- ),- );- }-- /**- * Atomically claim a scheduled topic before dispatch, so two concurrent cron- * ticks can't trigger the same continuation twice. Serializes on the row with- * `SELECT β¦ FOR UPDATE` (mirrors {@link updateMetadata}) and only writes the- * lease if the topic is still `scheduled` and not already claimed by a live- * lease. Returns `true` when this caller won the claim.- */- static async claimScheduledTopic(- db: LobeChatDatabase,- id: string,- claim: { claimedAt: string; expiresAt: string; id: string },- now: Date = new Date(),- ): Promise<boolean> {- return db.transaction(async (tx) => {- const [row] = await tx- .select({- metadata: topics.metadata,- projectId: topics.projectId,- projectWorkingDirectoryId: topics.projectWorkingDirectoryId,- status: topics.status,- })- .from(topics)- .where(eq(topics.id, id))- .for('update');-- if (!row || row.status !== 'scheduled') return false;-- const scheduledRun = row.metadata?.scheduledRun;- if (!scheduledRun) return false;-- const existingClaim = scheduledRun.claim;- const claimLive = existingClaim && new Date(existingClaim.expiresAt) > now;- if (claimLive) return false;-- await tx- .update(topics)- .set({- metadata: {- ...row.metadata,- scheduledRun: { ...scheduledRun, claim },- } as ChatTopicMetadata,- })- .where(eq(topics.id, id));-- return true;- });- }-- /**- * Clear the scheduled continuation and restore a normal status. Used both when- * a continuation is successfully dispatched/executed and when it is cancelled.- */- static async clearScheduledRun(- db: LobeChatDatabase,- id: string,- nextStatus: ChatTopicStatus = 'active',- expectedClaimId?: string,- ): Promise<void> {- await db.transaction(async (tx) => {- const [row] = await tx- .select({- metadata: topics.metadata,- projectId: topics.projectId,- projectWorkingDirectoryId: topics.projectWorkingDirectoryId,- status: topics.status,- })- .from(topics)- .where(eq(topics.id, id))- .for('update');- if (!row || row.status !== 'scheduled') return;- if (expectedClaimId && row.metadata?.scheduledRun?.claim?.id !== expectedClaimId) return;-- const nextMetadata = { ...row.metadata, scheduledRun: null } as ChatTopicMetadata;- await tx- .update(topics)- .set({ metadata: nextMetadata, status: nextStatus })- .where(eq(topics.id, id));- });- }-- /**- * Re-point a still-pending scheduled run at a new failed-attempt message. A- * dispatch that fails inside execAgent leaves its own error bubble on the- * placeholder it created; tracking that bubble as the run's- * `failedAssistantMessageId` lets the next tick's pre-dispatch cleanup clear- * it the same way it clears the original card, so retries don't strand one- * stale error bubble per failed attempt.- *- * `expectedClaimId` fences stale writers the same way it does in- * {@link TopicModel.clearScheduledRun}: a dispatch attempt that outlived its- * claim lease β or one whose schedule the user cancelled and re-armed β must- * not overwrite the pointer of a NEWER scheduled run, or the next cleanup- * would delete / anchor against an unrelated message. No-ops when the- * schedule was cleared or the claim no longer matches.- */- static async repointScheduledRunFailedMessage(- db: LobeChatDatabase,- id: string,- failedAssistantMessageId: string,- expectedClaimId: string,- ): Promise<void> {- await db.transaction(async (tx) => {- const [row] = await tx- .select({- metadata: topics.metadata,- projectId: topics.projectId,- projectWorkingDirectoryId: topics.projectWorkingDirectoryId,- status: topics.status,- })- .from(topics)- .where(eq(topics.id, id))- .for('update');- if (!row || row.status !== 'scheduled') return;-- const scheduledRun = row.metadata?.scheduledRun;- if (!scheduledRun) return;- if (scheduledRun.claim?.id !== expectedClaimId) return;-- await tx- .update(topics)- .set({- metadata: {- ...row.metadata,- scheduledRun: {- ...scheduledRun,- failedAssistantMessageId,- updatedAt: new Date().toISOString(),- },- } as ChatTopicMetadata,- })- .where(eq(topics.id, id));- });- }-}diff --git a/packages/database/src/models/topic/context.ts b/packages/database/src/models/topic/context.tsnew file mode 100644index 00000000000..b912e807fb2--- /dev/null+++ b/packages/database/src/models/topic/context.ts@@ -0,0 +1,155 @@+import type { SQL } from 'drizzle-orm';+import { and, eq, isNull, or } from 'drizzle-orm';++import type { FtsSearchCandidateSource } from '../../repositories/ftsSearch';+import { messages, topics } from '../../schemas';+import type { LobeChatDatabase } from '../../type';+import { idGenerator } from '../../utils/idGenerator';+import { notShareVisitorTopic } from '../../utils/shareVisitor';+import { buildWorkspaceWhere } from '../../utils/workspace';+import type { TopicKeywordScope } from './types';++/**+ * The state and scope predicates every `TopicModel` operation shares. Built once+ * per model instance; the operation modules receive it as their first argument.+ */+export interface TopicModelContext {+ db: LobeChatDatabase;+ ftsSearchCandidateSource?: FtsSearchCandidateSource;+ genId: () => string;+ /**+ * When true, {@link TopicModelContext.ownership} (and by extension every+ * creator-scoped read path) stops ANDing {@link notShareVisitorTopic}.+ * Reserved for surfaces that are share-runtime by design (agent-share visitor+ * router, share-scoped abuse guards) and for the agent runtime paths that+ * persist or clean up a visitor turn under the CREATOR's identity. Defaults+ * to false so every ordinary creator-facing caller fails closed instead of+ * relying on a per-callsite `notShareVisitorTopic()` AND.+ */+ includeShareVisitor: boolean;+ matchContainer: (containerId?: string | null) => SQL | undefined;+ matchGroup: (groupId?: string | null) => SQL;+ matchKeywordScope: (scope: TopicKeywordScope) => SQL | undefined;+ matchSession: (sessionId?: string | null) => SQL;+ messageOwnership: () => SQL | undefined;+ mine: () => SQL | undefined;+ notShareVisitor: () => SQL | undefined;+ ownership: () => SQL | undefined;+ trashScope: () => SQL | undefined;+ userId: string;+ workspaceId?: string;+ workspaceScope: () => SQL | undefined;+}++export const createTopicModelContext = ({+ db,+ ftsSearchCandidateSource,+ includeShareVisitor,+ userId,+ workspaceId,+}: Pick<+ TopicModelContext,+ 'db' | 'ftsSearchCandidateSource' | 'includeShareVisitor' | 'userId' | 'workspaceId'+>): TopicModelContext => {+ const ctx: TopicModelContext = {+ db,+ ftsSearchCandidateSource,+ includeShareVisitor,+ userId,+ workspaceId,++ /**+ * Raw workspace/user scope, WITHOUT the visitor exclusion. Backing store for+ * both {@link ownership} and {@link mine}, and the escape hatch for methods+ * that must see visitor rows independent of the instance flag+ * ({@link queryBySender} / {@link countBySender} / {@link countShareVisitors}).+ */+ workspaceScope: () =>+ buildWorkspaceWhere({ userId: ctx.userId, workspaceId: ctx.workspaceId }, topics),++ /**+ * {@link workspaceScope} without the recycle-bin filter, still excluding+ * share-visitor topics β restore / trash lookups / purge internals only.+ */+ trashScope: () =>+ and(+ buildWorkspaceWhere(+ { includeTrashed: true, userId: ctx.userId, workspaceId: ctx.workspaceId },+ topics,+ ),+ ctx.notShareVisitor(),+ ),++ ownership: () => and(ctx.workspaceScope(), ctx.notShareVisitor()),++ /**+ * In workspace mode `ownership()` matches every member's topics, so a bulk+ * "clear all" would wipe teammates' conversations. Destructive sweeps must+ * additionally pin `user_id` to the caller (personal mode is unchanged β+ * ownership already scopes to the user there).+ *+ * `mine()` deliberately does NOT AND {@link notShareVisitor} β it is the+ * per-user variant of {@link workspaceScope} and the share-scoped methods+ * ({@link queryBySender} / {@link countBySender} / {@link countShareVisitors})+ * layer their own `senderId` predicate on top of it. Creator-facing+ * destructive sweeps that reach for `mine()` still get the visitor+ * exclusion by AND-ing {@link notShareVisitor} themselves.+ */+ mine: () => and(ctx.workspaceScope(), eq(topics.userId, ctx.userId)),++ messageOwnership: () =>+ buildWorkspaceWhere({ userId: ctx.userId, workspaceId: ctx.workspaceId }, messages),++ /**+ * The default visitor exclusion applied by {@link ownership}: `topics.senderId IS NULL`,+ * shared with the repositories/models that query `topics` outside this+ * class (see `notShareVisitorTopic` in `../utils/shareVisitor`). Returns+ * `undefined` when the instance was constructed with `includeShareVisitor:+ * true`, so the share runtime opts in explicitly and every other caller+ * gets the visitor guard for free.+ *+ * The visitor-scoped counterparts ({@link queryBySender}, {@link countBySender})+ * intentionally do the opposite β they match on `senderId`, not exclude+ * it β and use {@link mine} (which skips this helper).+ */+ notShareVisitor: () => (ctx.includeShareVisitor ? undefined : notShareVisitorTopic()),++ genId: () => idGenerator('topics'),++ matchSession: (sessionId?: string | null) =>+ sessionId ? eq(topics.sessionId, sessionId) : isNull(topics.sessionId),++ matchGroup: (groupId?: string | null) =>+ groupId ? eq(topics.groupId, groupId) : isNull(topics.groupId),++ matchContainer: (containerId?: string | null) => {+ if (containerId)+ return or(eq(topics.sessionId, containerId), eq(topics.groupId, containerId));+ // If neither is provided, match topics with no session or group+ return and(isNull(topics.sessionId), isNull(topics.groupId));+ },++ /**+ * Build the WHERE condition that scopes a keyword search to a single+ * conversation owner. Mirrors {@link TopicModel.query}'s precedence and+ * conditions exactly (groupId > agentId > containerId), so search returns the+ * same set the topics list shows.+ *+ * The agent branch matches `topics.agentId` directly β the new agent system+ * stamps every topic with an agentId, and the old `matchContainer` path+ * (sessionId / groupId only) would miss those rows entirely. It deliberately+ * does NOT fall back to the resolved sessionId: the list has no such fallback+ * either, so adding one would (a) surface un-migrated rows the list hides and+ * (b) leak topics owned by another agent that shares the same session mapping.+ * Legacy rows are backfilled with an agentId by the migration the list query+ * triggers, after which the agentId match finds them.+ */+ matchKeywordScope: ({ agentId, containerId, groupId }: TopicKeywordScope): SQL | undefined => {+ if (groupId) return eq(topics.groupId, groupId);+ if (agentId) return eq(topics.agentId, agentId);+ return ctx.matchContainer(containerId);+ },+ };++ return ctx;+};diff --git a/packages/database/src/models/topic/create.ts b/packages/database/src/models/topic/create.tsnew file mode 100644index 00000000000..57c175eeafc--- /dev/null+++ b/packages/database/src/models/topic/create.ts@@ -0,0 +1,80 @@+import { runTimedSinkStage as runTimedStage } from '@lobechat/utils';++import { type TopicItem, topics } from '../../schemas';+import { buildWorkspacePayload } from '../../utils/workspace';+import type { TopicModelContext } from './context';+import type { CreateTopicParams, ModelTimingContext } from './types';++/**+ * Inserts one topic row. Re-parenting existing messages onto the new topic is+ * a cross-aggregate write owned by `TopicRepository.create`, which composes+ * this insert inside its transaction.+ */+export const create = async (+ ctx: TopicModelContext,+ topicParams: Omit<CreateTopicParams, 'messages'>,+ id: string = ctx.genId(),+ timing?: ModelTimingContext,+): Promise<TopicItem> => {+ // The type rejects a literal `messages` key; this also catches a widened+ // `CreateTopicParams` value so a missed caller fails instead of silently+ // dropping the re-parenting.+ const { messages: messageIds, ...params } = topicParams as CreateTopicParams;+ if (messageIds && messageIds.length > 0) {+ throw new Error(+ 'TopicModel.create does not re-parent messages; use TopicRepository.create instead',+ );+ }++ const insertData = buildWorkspacePayload(+ { userId: ctx.userId, workspaceId: ctx.workspaceId },+ {+ ...params,+ agentId: params.agentId || null,+ groupId: params.groupId || null,+ id,+ sessionId: params.sessionId || null,+ },+ );++ const [topic] = await runTimedStage(+ timing,+ 'db.topic.create.topics.insert',+ () => ctx.db.insert(topics).values(insertData).returning(),+ {+ hasAgentId: !!params.agentId,+ hasGroupId: !!params.groupId,+ hasSessionId: !!params.sessionId,+ },+ );++ return topic;+};++/**+ * Batch-inserts topic rows, preserving input order in the returned rows.+ * Re-parenting messages onto them is owned by `TopicRepository.batchCreate`.+ */+export const batchInsert = async (+ ctx: TopicModelContext,+ topicParams: (Omit<CreateTopicParams, 'messages'> & { id?: string })[],+) =>+ ctx.db+ .insert(topics)+ .values(+ topicParams.map((params) =>+ buildWorkspacePayload(+ { userId: ctx.userId, workspaceId: ctx.workspaceId },+ {+ agentId: params.agentId || null,+ favorite: params.favorite,+ groupId: params.sessionId ? null : params.groupId,+ id: params.id || ctx.genId(),+ sessionId: params.groupId ? null : params.sessionId,+ title: params.title,+ trigger: params.trigger,+ },+ ),+ ),+ )+ .returning();diff --git a/packages/database/src/models/topic/delete.ts b/packages/database/src/models/topic/delete.tsnew file mode 100644index 00000000000..1dea8e8ff18--- /dev/null+++ b/packages/database/src/models/topic/delete.ts@@ -0,0 +1,133 @@+import { and, eq, inArray } from 'drizzle-orm';++import { topics } from '../../schemas';+import type { TopicModelContext } from './context';++/**+ * Delete one topic, cascading to the messages associated with it.+ *+ * Agent-share visitor topics carry the creator's `userId`, so ownership alone+ * would let the creator-facing `topic.removeTopic` destroy a visitor+ * conversation from a raw topic id (obtainable out of band, e.g. through data+ * export). Excluded here for the same reason the bulk sweeps exclude them β+ * see {@link deleteAll}.+ */+export const deleteTopic = async (ctx: TopicModelContext, id: string) => {+ return ctx.db+ .delete(topics)+ .where(and(eq(topics.id, id), ctx.ownership(), ctx.notShareVisitor()));+};++/**+ * Deletes multiple topics based on the sessionId.+ * `restrictToCreator` limits the sweep to the caller's own rows (workspace+ * non-owner members must not clear teammates' topics).+ *+ * Visitor topics have no sessionId, so the null-session (inbox) branch would+ * otherwise sweep them in β see {@link deleteAll} for why bulk sweeps exclude+ * them.+ */+export const batchDeleteBySessionId = async (+ ctx: TopicModelContext,+ sessionId?: string | null,+ options?: { restrictToCreator?: boolean },+) => {+ return ctx.db+ .delete(topics)+ .where(+ and(+ ctx.matchSession(sessionId),+ options?.restrictToCreator ? ctx.mine() : ctx.ownership(),+ ctx.notShareVisitor(),+ ),+ );+};++/**+ * Deletes multiple topics based on the groupId.+ * `restrictToCreator` limits the sweep to the caller's own rows in workspace mode.+ *+ * Visitor topics have no groupId, so the null-group branch would otherwise+ * sweep them in β see {@link deleteAll}.+ */+export const batchDeleteByGroupId = async (+ ctx: TopicModelContext,+ groupId?: string | null,+ options?: { restrictToCreator?: boolean },+) => {+ return ctx.db+ .delete(topics)+ .where(+ and(+ ctx.matchGroup(groupId),+ options?.restrictToCreator ? ctx.mine() : ctx.ownership(),+ ctx.notShareVisitor(),+ ),+ );+};++/**+ * Deletes all topics matching the given agentId (`topics.agentId`).+ * `restrictToCreator` limits the sweep to the caller's own rows (workspace+ * non-owner members must not clear teammates' topics).+ *+ * This is the creator's "clear this agent's topics" action, so agent-share+ * visitor topics are excluded (see {@link deleteAll}). Deleting the agent+ * itself is a different path: `topics.agent_id` cascades at the DB level, so+ * visitor topics do go away with the agent without any call to this method.+ */+export const batchDeleteByAgentId = async (+ ctx: TopicModelContext,+ agentId: string,+ options?: { restrictToCreator?: boolean },+) => {+ return ctx.db+ .delete(topics)+ .where(+ and(+ options?.restrictToCreator ? ctx.mine() : ctx.ownership(),+ eq(topics.agentId, agentId),+ ctx.notShareVisitor(),+ ),+ );+};++/**+ * Deletes multiple topics and all messages associated with them in a transaction.+ *+ * Agent-share visitor topics are excluded β see {@link TopicModel.delete}.+ */+export const batchDelete = async (ctx: TopicModelContext, ids: string[]) => {+ return ctx.db+ .delete(topics)+ .where(and(inArray(topics.id, ids), ctx.ownership(), ctx.notShareVisitor()));+};++/**+ * Hard delete by id that also reaches rows already in the recycle bin β+ * same ownership + share-visitor guards as {@link batchDelete}, scoped with+ * {@link trashScope} (`includeTrashed`) instead of {@link ownership}. For+ * cascade paths that own their id list: a linked topic sitting in the+ * recycle bin must not survive its parent's deletion and resurrect as a+ * sidebar orphan when the user later restores it.+ */+export const batchDeleteIncludingTrashed = async (ctx: TopicModelContext, ids: string[]) => {+ return ctx.db.delete(topics).where(and(inArray(topics.id, ids), ctx.trashScope()));+};++/**+ * Creator-facing "clear all my topics".+ *+ * Agent-share visitor topics live under the creator's `userId` but are hidden+ * from every creator-facing listing (see `notShareVisitorTopic` in+ * `../utils/shareVisitor`), so a sweep the creator cannot see the contents of+ * must not destroy them β "clear all" can only mean the rows the creator sees.+ * The same rule applies to the other id-less sweeps here.+ *+ * Id-targeted deletes ({@link TopicModel.delete}, {@link TopicModel.batchDelete})+ * apply the same guard: a creator can obtain a visitor topic id out of band+ * (data export), so naming the id is not proof the row is theirs to delete.+ */+export const deleteAll = async (ctx: TopicModelContext) => {+ return ctx.db.delete(topics).where(and(ctx.mine(), ctx.notShareVisitor()));+};diff --git a/packages/database/src/models/topic/find.ts b/packages/database/src/models/topic/find.tsnew file mode 100644index 00000000000..86b8d4abd2b--- /dev/null+++ b/packages/database/src/models/topic/find.ts@@ -0,0 +1,455 @@+import type { TopicRankItem } from '@lobechat/types';+import {+ and,+ count,+ desc,+ eq,+ gt,+ inArray,+ isNotNull,+ isNull,+ ne,+ not,+ or,+ type SQL,+ sql,+} from 'drizzle-orm';++import {+ agentOperations,+ agents,+ messages,+ topicDocuments,+ type TopicItem,+ topics,+} from '../../schemas';+import { sanitizeBm25Query } from '../../utils/bm25';+import { genEndDateWhere, genRangeWhere, genStartDateWhere, genWhere } from '../../utils/genWhere';+import { inJsonStringArray } from '../../utils/inJsonStringArray';+import { searchableMessage } from '../../utils/searchableMessage';+import type { TopicModelContext } from './context';+import type { TopicKeywordScope } from './types';++/**+ * Ownership-scoped lookup. Agent-share visitor topics carry the CREATOR's+ * `userId` and are excluded by default; the share runtime opts in by+ * constructing the model with `{ includeShareVisitor: true }`.+ * `findVisitorTopicOrThrow` in `apps/server/src/routers/lambda/shareChat.ts`+ * relies on that opt-in and then verifies `senderId` itself.+ */+export const findById = async (ctx: TopicModelContext, id: string) => {+ return ctx.db.query.topics.findFirst({+ where: and(eq(topics.id, id), ctx.ownership()),+ });+};++/**+ * Kept for readability at creator-facing router call sites; the default+ * scope already excludes agent-share visitor topics, so this is a thin+ * alias of {@link TopicModel.findById}.+ */+export const findOwnTopicById = async (ctx: TopicModelContext, id: string) => {+ return findById(ctx, id);+};++/**+ * Ids among `ids` that resolve to an agent-share VISITOR topic under this+ * owner β the inverse of {@link notShareVisitorTopic}, the predicate every+ * creator-facing read applies.+ *+ * Creator-facing write entry points use this to reject visitor targets+ * (see `assertCreatorTopicTargets` in the server router helpers). Ids that+ * match no row at all are NOT reported, so callers keep their existing no-op+ * behaviour for stale/foreign ids.+ */+export const findShareVisitorTopicIds = async (+ ctx: TopicModelContext,+ ids: string[],+): Promise<string[]> => {+ if (ids.length === 0) return [];++ const rows = await ctx.db+ .select({ id: topics.id })+ .from(topics)+ // Explicitly scoped visitor-inclusive: this method's whole job is to+ // return visitor ids so the router-level `assertCreatorTopicTargets`+ // can reject them, so it must bypass the instance's visitor exclusion.+ .where(and(inArray(topics.id, ids), ctx.workspaceScope(), isNotNull(topics.senderId)));++ return rows.map((row) => row.id);+};++export const findByIds = async (ctx: TopicModelContext, ids: string[]): Promise<TopicItem[]> => {+ if (ids.length === 0) return [];+ return ctx.db.query.topics.findMany({+ where: and(inArray(topics.id, ids), ctx.ownership()),+ });+};++/**+ * Kept for readability at creator-facing router call sites; the default+ * scope already excludes agent-share visitor topics, so this is a thin+ * alias of {@link TopicModel.findByIds}.+ */+export const findOwnTopicsByIds = async (+ ctx: TopicModelContext,+ ids: string[],+): Promise<TopicItem[]> => {+ return findByIds(ctx, ids);+};++/**+ * Minimal creator projection for router-level workspace row checks on+ * batch-by-ids operations (batch delete / move).+ */+export const findOwnersByIds = async (+ ctx: TopicModelContext,+ ids: string[],+): Promise<{ id: string; userId: string }[]> => {+ if (ids.length === 0) return [];++ return ctx.db+ .select({ id: topics.id, userId: topics.userId })+ .from(topics)+ .where(and(inArray(topics.id, ids), ctx.ownership()));+};++/**+ * Find the unique topic an agent shares with a document for a given trigger+ * (e.g. the doc-anchored chat topic provisioned by+ * `agentDocument.getOrCreateChatTopic`). Joins through `topic_documents`.+ */+export const findByAgentAndDocumentTrigger = async (+ ctx: TopicModelContext,+ params: {+ agentId: string;+ documentId: string;+ trigger: string;+ },+): Promise<TopicItem | undefined> => {+ const result = await ctx.db+ .select({ topic: topics })+ .from(topics)+ .innerJoin(topicDocuments, eq(topicDocuments.topicId, topics.id))+ .where(+ and(+ ctx.ownership(),+ eq(topics.agentId, params.agentId),+ eq(topics.trigger, params.trigger),+ eq(topicDocuments.documentId, params.documentId),+ ),+ )+ .limit(1);++ return result[0]?.topic;+};++/**+ * Who started each topic's current run. Workspace topics are co-editable, so+ * the member running a topic now can differ from its creator (`topics.userId`);+ * the latest top-level running operation records the actual initiator β the+ * same row `runStartedAt` reads. Topics whose run never wrote an operation+ * row (client-executed runs) are absent; callers fall back to the creator.+ *+ * Not scoped by {@link ownership}: in a workspace the run may belong to+ * another member, and callers pass ids from an ownership-gated topic read.+ */+export const findRunInitiators = async (+ ctx: TopicModelContext,+ topicIds: string[],+): Promise<Map<string, string>> => {+ if (topicIds.length === 0) return new Map();++ const rows = await ctx.db+ .selectDistinctOn([agentOperations.topicId], {+ topicId: agentOperations.topicId,+ userId: agentOperations.userId,+ })+ .from(agentOperations)+ .where(+ and(+ inArray(agentOperations.topicId, topicIds),+ eq(agentOperations.status, 'running'),+ isNull(agentOperations.parentOperationId),+ isNotNull(agentOperations.startedAt),+ ),+ )+ .orderBy(agentOperations.topicId, desc(agentOperations.startedAt));++ return new Map(rows.flatMap((row) => (row.topicId ? [[row.topicId, row.userId]] : [])));+};++/**+ * Recent topics from the same IM channel, most-recent first. Matches the+ * channel via the `metadata.bot.platformThreadId` path written at topic+ * creation (see `ChatTopicBotContext`). Used to pre-inject cross-session+ * history on platforms that can't read chat history at runtime (e.g. WeChat,+ * whose `readMessages` throws), so a fresh topic still knows what the channel+ * was just talking about.+ */+export const findRecentByBotThread = async (+ ctx: TopicModelContext,+ platformThreadId: string,+ { limit = 3 }: { limit?: number } = {},+): Promise<TopicItem[]> => {+ if (!platformThreadId) return [];++ return ctx.db+ .select()+ .from(topics)+ .where(+ and(+ ctx.ownership(),+ sql`${topics.metadata} -> 'bot' ->> 'platformThreadId' = ${platformThreadId}`,+ ),+ )+ .orderBy(desc(topics.updatedAt))+ .limit(limit);+};++export const queryByKeyword = async (+ ctx: TopicModelContext,+ keyword: string,+ scope?: string | null | TopicKeywordScope,+): Promise<TopicItem[]> => {+ if (!keyword.trim()) return [];++ // Backward compatibility: a bare string / null second argument is treated+ // as the legacy `containerId` (sessionId or groupId).+ const scopeOptions: TopicKeywordScope =+ scope && typeof scope === 'object' ? scope : { containerId: scope ?? null };+ const scopeCondition = ctx.matchKeywordScope(scopeOptions);++ const bm25Query = sanitizeBm25Query(keyword);+ const candidateResults = ctx.ftsSearchCandidateSource?.ftsSearchCandidateEnabled+ ? await Promise.all([+ ctx.ftsSearchCandidateSource.ftsSearchCandidates({+ entity: 'topics',+ filters: { topicScope: scopeOptions },+ pagination: {},+ query: { fields: ['title'], text: keyword },+ }),+ ctx.ftsSearchCandidateSource.ftsSearchCandidates({+ entity: 'messages',+ filters: { topicScope: scopeOptions },+ pagination: {},+ query: { fields: ['content'], text: keyword },+ }),+ ])+ : undefined;+ const topicCandidateIds = candidateResults?.[0].candidates.map(({ id }) => id);+ const messageCandidateIds = candidateResults?.[1].candidates.map(({ id }) => id);++ // Run title and message content searches in parallel+ const [topicsByTitle, topicIdsByMessages] = await Promise.all([+ // Query topics matching by title (BM25)+ ctx.db+ .select()+ .from(topics)+ .where(+ and(+ ctx.ownership(),+ ctx.notShareVisitor(),+ scopeCondition,+ topicCandidateIds+ ? inJsonStringArray(topics.id, topicCandidateIds)+ : sql`${topics.title} @@@ ${bm25Query}`,+ ),+ )+ .orderBy(desc(topics.updatedAt)),+ // Query topic IDs matching by message content (BM25)+ ctx.db+ .select({ topicId: messages.topicId })+ .from(messages)+ .innerJoin(topics, eq(messages.topicId, topics.id))+ .where(+ and(+ ctx.messageOwnership(),+ searchableMessage(),+ messageCandidateIds+ ? inJsonStringArray(messages.id, messageCandidateIds)+ : sql`${messages.content} @@@ ${bm25Query}`,+ ctx.ownership(),+ ctx.notShareVisitor(),+ scopeCondition,+ ),+ )+ .groupBy(messages.topicId),+ ]);+ // If no topics found by message content, return topics matching by title+ if (topicIdsByMessages.length === 0) {+ return topicsByTitle;+ }++ // Query topics found by message content+ const topicIds = topicIdsByMessages+ .map((t) => t.topicId)+ .filter((id): id is string => id !== null);++ const topicsByMessages = await ctx.db.query.topics.findMany({+ orderBy: [desc(topics.updatedAt)],+ where: and(ctx.ownership(), inArray(topics.id, topicIds)),+ });++ // Merge results and deduplicate+ const allTopics = [...topicsByTitle];+ const existingIds = new Set(topicsByTitle.map((t) => t.id));++ for (const topic of topicsByMessages) {+ if (!existingIds.has(topic.id)) {+ allTopics.push(topic);+ }+ }++ // Sort by update time+ return allTopics.sort(+ (a, b) => new Date(b.updatedAt).getTime() - new Date(a.updatedAt).getTime(),+ );+};++export const countTopics = async (+ ctx: TopicModelContext,+ params?: {+ agentId?: string;+ containerId?: string | null;+ endDate?: string;+ range?: [string, string];+ startDate?: string;+ },+): Promise<number> => {+ // Build agent-specific condition if agentId is provided+ const agentCondition: SQL | undefined = params?.agentId+ ? eq(topics.agentId, params.agentId)+ : undefined;++ const result = await ctx.db+ .select({+ count: count(topics.id),+ })+ .from(topics)+ .where(+ genWhere([+ ctx.ownership(),+ ctx.notShareVisitor(),+ agentCondition,+ params?.containerId ? ctx.matchContainer(params.containerId) : undefined,+ params?.range+ ? genRangeWhere(params.range, topics.createdAt, (date) => date.toDate())+ : undefined,+ params?.endDate+ ? genEndDateWhere(params.endDate, topics.createdAt, (date) => date.toDate())+ : undefined,+ params?.startDate+ ? genStartDateWhere(params.startDate, topics.createdAt, (date) => date.toDate())+ : undefined,+ ]),+ );++ return result[0].count;+};++export const rank = async (+ ctx: TopicModelContext,+ limit: number = 10,+): Promise<TopicRankItem[]> => {+ return ctx.db+ .select({+ agentId: topics.agentId,+ count: count(messages.id).as('count'),+ id: topics.id,+ title: topics.title,+ })+ .from(topics)+ .where(and(ctx.ownership(), ctx.notShareVisitor()))+ .leftJoin(messages, eq(topics.id, messages.topicId))+ .groupBy(topics.id)+ .orderBy(desc(sql`count`))+ .having(({ count }) => gt(count, 0))+ .limit(limit);+};++/**+ * Query recent topics for homepage display.+ * Returns basic topic info with agentId/groupId for later resolution.+ * - For agent topics: excludes virtual agents (except inbox)+ * - For group topics: includes topics with groupId+ * - For inbox: includes topics with slug='inbox'+ */+export const queryRecent = async (ctx: TopicModelContext, limit: number = 12) => {+ const latestMessageAtSubquery = ctx.db+ .select({ value: messages.updatedAt })+ .from(messages)+ .where(and(eq(messages.topicId, topics.id), ctx.messageOwnership()))+ .orderBy(desc(messages.updatedAt))+ .limit(1);+ const topicActivityAt =+ sql<Date>`COALESCE((${latestMessageAtSubquery}), ${topics.updatedAt})`.mapWith(+ topics.updatedAt,+ );++ const result = await ctx.db+ .select({+ agentId: topics.agentId,+ groupId: topics.groupId,+ id: topics.id,+ sessionId: topics.sessionId,+ title: topics.title,+ updatedAt: topicActivityAt,+ })+ .from(topics)+ .leftJoin(agents, eq(topics.agentId, agents.id))+ .where(+ and(+ ctx.ownership(),+ ctx.notShareVisitor(),+ or(+ // Group topics: has groupId+ not(isNull(topics.groupId)),+ // Inbox agent topics+ eq(agents.slug, 'inbox'),+ // Agent topics: exclude virtual agents+ and(isNull(topics.groupId), ne(agents.virtual, true)),+ ),+ ),+ )+ .orderBy(desc(topicActivityAt))+ .limit(limit);++ return result.map((item) => ({+ ...item,+ type: item.groupId ? ('group' as const) : ('agent' as const),+ updatedAt: item.updatedAt instanceof Date ? item.updatedAt : new Date(item.updatedAt),+ }));+};++export const getCronTopicsGroupedByCronJob = async (+ ctx: TopicModelContext,+ agentId: string,+): Promise<{ cronJobId: string; topics: TopicItem[] }[]> => {+ const rows = await ctx.db+ .select()+ .from(topics)+ .where(+ and(+ ctx.ownership(),+ eq(topics.agentId, agentId),+ eq(topics.trigger, 'cron'),+ sql`COALESCE(${topics.metadata}->>'cronJobId', '') <> ''`,+ ),+ )+ .orderBy(desc(topics.createdAt));++ const grouped = new Map<string, TopicItem[]>();+ for (const topic of rows) {+ const cronJobId = (topic.metadata as { cronJobId?: string } | null)?.cronJobId;+ if (!cronJobId) continue;+ const group = grouped.get(cronJobId) ?? [];+ group.push(topic);+ grouped.set(cronJobId, group);+ }++ return [...grouped.entries()].map(([cronJobId, topicList]) => ({+ cronJobId,+ topics: topicList,+ }));+};diff --git a/packages/database/src/models/topic/index.ts b/packages/database/src/models/topic/index.tsnew file mode 100644index 00000000000..e5082507c77--- /dev/null+++ b/packages/database/src/models/topic/index.ts@@ -0,0 +1,220 @@+import type { FtsSearchCandidateSource } from '../../repositories/ftsSearch';+import type { LobeChatDatabase } from '../../type';+import type { TopicModelContext } from './context';+import { createTopicModelContext } from './context';+import * as create from './create';+import * as remove from './delete';+import * as find from './find';+import * as list from './list';+import * as memoryExtractor from './memoryExtractor';+import * as runningOperation from './runningOperation';+import * as scheduledRun from './scheduledRun';+import * as shareVisitor from './shareVisitor';+import * as taskCallback from './taskCallback';+import * as trash from './trash';+import * as update from './update';++export { getTopicDeviceId } from './runningOperation';+export { hasLiveTaskCallbackReservation } from './taskCallback';+export type {+ CreateTopicParams,+ ListTopicsForMemoryExtractorCursor,+ ModelTimingContext,+ SettleRunningOperationOptions,+ TopicKeywordScope,+ TopicListItem,+ VisitorRunningOperation,+ VisitorTopicItem,+} from './types';++/**+ * NEVER null-test a jsonb arrow / path expression inside a WHERE clause:+ *+ * ```sql+ * (metadata ->> 'cronJobId') IS NULL -- π₯+ * (metadata #>> '{a,b}') IS NOT NULL -- π₯+ * ```+ *+ * The crash is `pg_search`'s (ParadeDB BM25) planner hook, and it fires on any+ * table carrying a `bm25` index: `rt_fetch used out-of-bounds`, SQLSTATE XX000.+ * Drizzle reports it as a bare `Failed query:`, with the real cause only in the+ * driver's `[cause]`. Four properties make it uniquely nasty:+ *+ * - It fires at PLAN time. `EXPLAIN` alone crashes, so a table with zero+ * matching rows crashes exactly like a full one.+ * - Stock Postgres, PGlite, and any table *without* a bm25 index run these+ * predicates happily β no test we can write will ever catch it.+ * - It has nothing to do with jsonb. `upper(col) IS NULL` and `(id + 1) IS NULL`+ * crash identically; the trigger is a null test over a *computed expression*+ * in a qual. A null test over a bare column is fine.+ * - Only quals crash β WHERE, JOIN ON, HAVING, and the WHERE of a subquery, CTE,+ * UPDATE or DELETE. SELECT lists, ORDER BY and `UPDATE β¦ SET` targets are safe.+ *+ * `topics` and `messages` carry bm25 indexes today, but so do `agents`, `files`,+ * `documents`, `chat_groups`, `knowledge_bases` and every `user_memories*`+ * table β and that list is one migration away from growing. A predicate written+ * today outlives the index list, so the rule is table-independent: never write+ * the shape.+ *+ * COALESCE the extracted value to a sentinel instead β same semantics, a shape+ * the planner survives:+ *+ * ```sql+ * COALESCE(metadata ->> 'cronJobId', '') = '' -- "is null"+ * COALESCE((metadata #>> '{a,b}')::numeric, 0) <= $1 -- numeric gate+ * COALESCE(metadata ->> 'status', '') <> 'done' -- IS DISTINCT FROM+ * ```+ *+ * (`IS DISTINCT FROM` measured safe on pg_search 0.15.26, but the guard bans it+ * anyway β it sits one planner-hook change from the crashing family and the+ * COALESCE form costs nothing.)+ *+ * This has now bitten three times: #13040, `getLatestSpineMessageId` (#16693)+ * and `getDueScheduledTopics` (#17077 β the scheduled-run cron crashed on every+ * tick from the day it shipped, so rate-limit continuations never once resumed).+ * `jsonbNullTest.test.ts` is the source-shape guard that holds the line.+ */+export interface TopicModelOptions {+ /**+ * Opt IN to agent-share visitor topics. Visitor conversations persist under+ * the CREATOR's `userId` (only `topics.senderId` marks them), so every+ * creator-facing read/write is default-scoped to exclude them. Only the+ * share-runtime surfaces (share-scoped tRPC routers, share abuse guards,+ * and the agent runtime paths that persist or clean up a visitor turn+ * under the creator's identity) should set this to `true`.+ */+ includeShareVisitor?: boolean;+}++export class TopicModel {+ private ctx: TopicModelContext;++ constructor(+ db: LobeChatDatabase,+ userId: string,+ workspaceId?: string,+ ftsSearchCandidateSource?: FtsSearchCandidateSource,+ options: TopicModelOptions = {},+ ) {+ this.ctx = createTopicModelContext({+ db,+ ftsSearchCandidateSource,+ includeShareVisitor: options.includeShareVisitor ?? false,+ userId,+ workspaceId,+ });+ }++ /**+ * Binds an operation module function to this instance's context. The context+ * is read at call time, so the bound methods can be class fields even though+ * the context is assigned in the constructor body.+ */+ private withContext<A extends unknown[], R>(fn: (ctx: TopicModelContext, ...args: A) => R) {+ return (...args: A): R => fn(this.ctx, ...args);+ }++ // **************** List *************** //++ query = this.withContext(list.query);+ queryTopics = this.withContext(list.queryTopics);++ // **************** Read *************** //++ findById = this.withContext(find.findById);+ findOwnTopicById = this.withContext(find.findOwnTopicById);+ findShareVisitorTopicIds = this.withContext(find.findShareVisitorTopicIds);+ findByIds = this.withContext(find.findByIds);+ findOwnTopicsByIds = this.withContext(find.findOwnTopicsByIds);+ findOwnersByIds = this.withContext(find.findOwnersByIds);+ findByAgentAndDocumentTrigger = this.withContext(find.findByAgentAndDocumentTrigger);+ findRunInitiators = this.withContext(find.findRunInitiators);+ findRecentByBotThread = this.withContext(find.findRecentByBotThread);+ queryByKeyword = this.withContext(find.queryByKeyword);+ count = this.withContext(find.countTopics);+ rank = this.withContext(find.rank);+ queryRecent = this.withContext(find.queryRecent);+ getCronTopicsGroupedByCronJob = this.withContext(find.getCronTopicsGroupedByCronJob);++ // **************** Agent Share (visitor-scoped) *************** //++ queryBySender = this.withContext(shareVisitor.queryBySender);+ countBySender = this.withContext(shareVisitor.countBySender);+ countShareVisitors = this.withContext(shareVisitor.countShareVisitors);++ // **************** Create *************** //++ create = this.withContext(create.create);+ batchInsert = this.withContext(create.batchInsert);++ // **************** Delete *************** //++ delete = this.withContext(remove.deleteTopic);+ batchDeleteBySessionId = this.withContext(remove.batchDeleteBySessionId);+ batchDeleteByGroupId = this.withContext(remove.batchDeleteByGroupId);+ batchDeleteByAgentId = this.withContext(remove.batchDeleteByAgentId);+ batchDelete = this.withContext(remove.batchDelete);+ batchDeleteIncludingTrashed = this.withContext(remove.batchDeleteIncludingTrashed);+ deleteAll = this.withContext(remove.deleteAll);++ // **************** Recycle bin *************** //++ softDelete = this.withContext(trash.softDelete);+ softDeleteBySessionId = this.withContext(trash.softDeleteBySessionId);+ softDeleteByGroupId = this.withContext(trash.softDeleteByGroupId);+ softDeleteByAgentId = this.withContext(trash.softDeleteByAgentId);+ softDeleteByParents = this.withContext(trash.softDeleteByParents);+ softDeleteAll = this.withContext(trash.softDeleteAll);+ restore = this.withContext(trash.restore);+ findTrashedByIds = this.withContext(trash.findTrashedByIds);+ purge = this.withContext(trash.purge);++ // **************** Update *************** //++ update = this.withContext(update.update);+ settleRunningStatus = this.withContext(update.settleRunningStatus);+ recomputeUsage = this.withContext(update.recomputeUsage);+ updateMetadata = this.withContext(update.updateMetadata);+ updateModelPin = this.withContext(update.updateModelPin);++ // **************** Running operation marker *************** //++ settleRunningOperation = this.withContext(runningOperation.settleRunningOperation);+ appendRunningOperationChild = this.withContext(runningOperation.appendRunningOperationChild);+ patchRunningOperation = this.withContext(runningOperation.patchRunningOperation);+ removeRunningOperationChild = this.withContext(runningOperation.removeRunningOperationChild);+ updateRunningOperationAssistantMessage = this.withContext(+ runningOperation.updateRunningOperationAssistantMessage,+ );+ takeRunningOperation = this.withContext(runningOperation.takeRunningOperation);+ isRunningOperationAlive = this.withContext(runningOperation.isRunningOperationAlive);++ // **************** Task-callback reservation *************** //++ tryReserveTaskCallback = this.withContext(taskCallback.tryReserveTaskCallback);+ repairAgentInterventionContinuation = this.withContext(+ taskCallback.repairAgentInterventionContinuation,+ );+ releaseTaskCallbackReservation = this.withContext(taskCallback.releaseTaskCallbackReservation);++ // **************** Scheduled run *************** //++ cancelRateLimitContinuation = this.withContext(scheduledRun.cancelRateLimitContinuation);+ armScheduledRun = this.withContext(scheduledRun.armScheduledRun);++ // **************** Memory extraction *************** //++ listTopicsForMemoryExtractor = this.withContext(memoryExtractor.listTopicsForMemoryExtractor);+ countTopicsForMemoryExtractor = this.withContext(memoryExtractor.countTopicsForMemoryExtractor);+ resetMemoryExtractStatus = this.withContext(memoryExtractor.resetMemoryExtractStatus);++ // **************** Scheduled run (backend cron) *************** //++ static getDueScheduledTopics = scheduledRun.getDueScheduledTopics;++ static claimScheduledTopic = scheduledRun.claimScheduledTopic;++ static clearScheduledRun = scheduledRun.clearScheduledRun;++ static repointScheduledRunFailedMessage = scheduledRun.repointScheduledRunFailedMessage;+}diff --git a/packages/database/src/models/topic/list.ts b/packages/database/src/models/topic/list.tsnew file mode 100644index 00000000000..e840a4754a7--- /dev/null+++ b/packages/database/src/models/topic/list.ts@@ -0,0 +1,597 @@+import type { ChatTopicStatus, TopicQuerySortBy } from '@lobechat/types';+import {+ getDurationMs,+ logTimingSink as logTiming,+ runTimedSinkStage as runTimedStage,+} from '@lobechat/utils';+import {+ and,+ asc,+ count,+ desc,+ eq,+ getTableColumns,+ inArray,+ isNotNull,+ isNull,+ ne,+ not,+ or,+ type SQL,+ sql,+} from 'drizzle-orm';++import { agentOperations, agents, chatGroups, messages, topics } from '../../schemas';+import { buildWorkspaceWhere } from '../../utils/workspace';+import { topicMetadataWithCreator } from '../topicCreator';+import type { TopicModelContext } from './context';+import type { QueryTopicParams, TopicListItem } from './types';++/**+ * How much of the last assistant reply `queryTopics` ships to a list view. Long+ * enough that a run summary arrives whole, short enough that 200 rows of raw+ * markdown never do β anything past it is marked with an ellipsis, and the full+ * text is one click away in the topic itself.+ */+export const LAST_MESSAGE_PREVIEW_LENGTH = 2000;++// Status priority for the sidebar "group by status" ordering. Lower rank =+// higher in the list. A NULL / unknown status falls through to `active` (3),+// matching the client which treats a missing status as active. Keep this in+// sync with `STATUS_GROUP_ORDER` / `resolveStatusBucket` in `@lobechat/utils`+// (client-side bucketing): `waitingForHuman`, `failed` and `unread` all collapse+// into the top `pending` bucket, so they must float to the top here too β+// otherwise such a topic could fall off the first page and vanish from the+// pending group.+export const STATUS_SORT_RANK = sql`CASE ${topics.status}+ WHEN 'waitingForHuman' THEN 0+ WHEN 'failed' THEN 1+ WHEN 'unread' THEN 2+ WHEN 'running' THEN 3+ WHEN 'scheduled' THEN 4+ WHEN 'active' THEN 5+ WHEN 'completed' THEN 6+ WHEN 'archived' THEN 7+ ELSE 5 END`;++// Favorites always float to the top; the rest are ordered by the requested+// strategy. `status` adds the priority bucket before the recency tiebreaker.+export const buildTopicOrderBy = (topicActivityAt: SQL, sortBy?: TopicQuerySortBy): SQL[] =>+ sortBy === 'status'+ ? [desc(topics.favorite), asc(STATUS_SORT_RANK), desc(topicActivityAt)]+ : [desc(topics.favorite), desc(topicActivityAt)];++export const query = async (+ ctx: TopicModelContext,+ {+ agentId,+ containerId,+ current = 0,+ editingAgentId,+ editingGroupId,+ excludeStatuses,+ excludeTriggers,+ includeTriggers,+ pageSize = 9999,+ groupId,+ isInbox,+ sortBy,+ timing,+ triggers,+ withDetails = false,+ }: QueryTopicParams = {},+) => {+ const queryStartedAt = Date.now();+ logTiming(timing, 'db.topic.query:start', {+ current,+ hasAgentId: !!agentId,+ hasContainerId: !!containerId,+ hasGroupId: !!groupId,+ isInbox: !!isInbox,+ pageSize,+ withDetails,+ });+ const offset = current * pageSize;++ // Heavier columns gated behind `withDetails` and used by the per-agent+ // Topics management page: real aggregates from the `messages` table+ // (firstUserMessage + messageCount), plus the `description` / `trigger`+ // columns that sidebar paths don't consume. `cost` and `tokenUsage`+ // intentionally stay undefined here β they need their own schema+ // migration before they can be backed by real numbers.+ //+ // The two correlated subqueries are built with Drizzle's query builder+ // (not a raw `sql` template) so the inner `eq(messages.topicId,+ // topics.id)` renders as `"messages"."topic_id" = "topics"."id"` β both+ // sides fully qualified. A bare `sql\`... ${topics.id} ...\`` template+ // renders `topics.id` as an unqualified `"id"`, which PostgreSQL then+ // resolves against the inner FROM (messages.id) and the WHERE silently+ // matches nothing.+ const firstUserMessageSubquery = ctx.db+ .select({ value: messages.content })+ .from(messages)+ .where(and(eq(messages.topicId, topics.id), eq(messages.role, 'user'), ctx.messageOwnership()))+ .orderBy(asc(messages.createdAt))+ .limit(1);+ const messageCountSubquery = ctx.db+ .select({ value: sql<number>`count(*)::int` })+ .from(messages)+ .where(and(eq(messages.topicId, topics.id), ctx.messageOwnership()));+ const latestMessageAtSubquery = ctx.db+ .select({ value: messages.updatedAt })+ .from(messages)+ .where(and(eq(messages.topicId, topics.id), ctx.messageOwnership()))+ .orderBy(desc(messages.updatedAt))+ .limit(1);+ const topicActivityAt =+ sql<Date>`COALESCE((${latestMessageAtSubquery}), ${topics.updatedAt})`.mapWith(+ topics.updatedAt,+ );++ // When the topic's current run started, so a sidebar can show live elapsed+ // time instead of `updatedAt` (which moves on every message write). The+ // latest *top-level* running operation is the current run: sub-operations+ // (callAgent) would restart the clock at their own spawn time, and an+ // abandoned `running` row from a crashed earlier run sorts below the live+ // one. Not scoped by `ownership()` β in a workspace the run may have been+ // started by another member, and the topic join is already ownership-gated.+ const runStartedAtSubquery = ctx.db+ .select({ value: agentOperations.startedAt })+ .from(agentOperations)+ .where(+ and(+ eq(agentOperations.topicId, topics.id),+ eq(agentOperations.status, 'running'),+ isNull(agentOperations.parentOperationId),+ isNotNull(agentOperations.startedAt),+ ),+ )+ .orderBy(desc(agentOperations.startedAt))+ .limit(1);++ // CASE-gated so only rows that are actually running pay for the lookup β+ // and a stale running op under a finished topic can't resurrect a timer.+ const runStartedAtColumn =+ sql<Date | null>`CASE WHEN ${topics.status} = 'running' THEN (${runStartedAtSubquery}) ELSE NULL END`+ .mapWith(agentOperations.startedAt)+ .as('run_started_at');++ const orderBy = buildTopicOrderBy(topicActivityAt, sortBy);++ const detailColumns = withDetails+ ? {+ description: topics.description,+ firstUserMessage: sql<string | null>`(${firstUserMessageSubquery})`.as(+ 'first_user_message',+ ),+ messageCount: sql<number>`(${messageCountSubquery})`.as('message_count'),+ trigger: topics.trigger,+ }+ : {};++ const includeTriggerCondition =+ includeTriggers && includeTriggers.length > 0+ ? inArray(topics.trigger, includeTriggers)+ : undefined;+ const excludeTriggerCondition = includeTriggerCondition+ ? undefined+ : excludeTriggers && excludeTriggers.length > 0+ ? or(isNull(topics.trigger), not(inArray(topics.trigger, excludeTriggers)))+ : undefined;+ const triggerCondition =+ triggers && triggers.length > 0 ? inArray(topics.trigger, triggers) : undefined;+ const excludeStatusCondition =+ excludeStatuses && excludeStatuses.length > 0+ ? or(isNull(topics.status), not(inArray(topics.status, excludeStatuses as ChatTopicStatus[])))+ : undefined;+ // Topics created before the marker existed carry neither key and therefore+ // match no target β they cannot: what they configured was never recorded+ // anywhere in the row. `topics_agent_id_idx` still drives the scan, so the+ // unindexed JSONB comparison only runs over one agent's rows.+ const editingTargetCondition = and(+ editingAgentId ? sql`${topics.metadata}->>'editingAgentId' = ${editingAgentId}` : undefined,+ editingGroupId ? sql`${topics.metadata}->>'editingGroupId' = ${editingGroupId}` : undefined,+ );++ if (groupId) {+ const whereCondition = and(+ ctx.ownership(),+ ctx.notShareVisitor(),+ eq(topics.groupId, groupId),+ includeTriggerCondition,+ excludeTriggerCondition,+ triggerCondition,+ excludeStatusCondition,+ );++ const [items, totalResult] = await Promise.all([+ runTimedStage(+ timing,+ 'db.topic.query.group.items.select',+ () =>+ ctx.db+ // Cast to `any` because Drizzle's `.select` infers a strict+ // SelectedFields shape and the conditional `detailColumns` widens+ // to a union; the runtime shape is correct and the client casts+ // back to `ChatTopic[]` after TRPC serialization.+ .select({+ completedAt: topics.completedAt,+ createdAt: topics.createdAt,+ favorite: topics.favorite,+ historySummary: topics.historySummary,+ id: topics.id,+ metadata: topicMetadataWithCreator(ctx.db, ctx.messageOwnership()),+ projectId: topics.projectId,+ projectWorkingDirectoryId: topics.projectWorkingDirectoryId,+ model: topics.model,+ provider: topics.provider,+ runStartedAt: runStartedAtColumn,+ status: topics.status,+ title: topics.title,+ updatedAt: topics.updatedAt,+ // Sidebar sorts/groups topics client-side by this `sortUpdatedAt` β the+ // same `topicActivityAt` the ORDER BY uses (latest message time, COALESCE+ // fallback to the row's own updatedAt). Keeping it separate from the+ // display `updatedAt` above matches the client-side sort key to the server+ // order (otherwise the two disagree and the list visibly jumps) while a+ // rename/favorite edit still shows its real edit time. See rankTopics for+ // the same activity-time pattern.+ sortUpdatedAt: topicActivityAt,+ // Workspace sidebars filter maintenance actions client-side by+ // ownership (own vs workspace scope) β the filter needs the row+ // owner even in the slim projection.+ userId: topics.userId,+ ...detailColumns,+ } as any)+ .from(topics)+ .where(whereCondition)+ .orderBy(...orderBy)+ .limit(pageSize)+ .offset(offset),+ { current, pageSize },+ ),+ runTimedStage(timing, 'db.topic.query.group.count.select', () =>+ ctx.db+ .select({ count: count(topics.id) })+ .from(topics)+ .where(whereCondition),+ ),+ ]);++ logTiming(timing, 'db.topic.query:done', {+ itemCount: items.length,+ stageMs: getDurationMs(queryStartedAt),+ total: totalResult[0].count,+ });+ return { items, total: totalResult[0].count };+ }++ // If agentId is provided, match topics by `topics.agentId` directly. The+ // inbox agent additionally adopts very old orphan rows where every owner+ // column (session / group / agent) is null.+ if (agentId) {+ const agentCondition = isInbox+ ? or(+ eq(topics.agentId, agentId),+ and(isNull(topics.sessionId), isNull(topics.groupId), isNull(topics.agentId)),+ )+ : eq(topics.agentId, agentId);++ const agentWhere = and(+ ctx.ownership(),+ ctx.notShareVisitor(),+ agentCondition,+ editingTargetCondition,+ includeTriggerCondition,+ excludeTriggerCondition,+ triggerCondition,+ excludeStatusCondition,+ );++ const [items, totalResult] = await Promise.all([+ runTimedStage(+ timing,+ 'db.topic.query.agent.items.select',+ () =>+ ctx.db+ // See note on the group-branch select above re: `as any` cast.+ .select({+ completedAt: topics.completedAt,+ createdAt: topics.createdAt,+ favorite: topics.favorite,+ historySummary: topics.historySummary,+ id: topics.id,+ metadata: topicMetadataWithCreator(ctx.db, ctx.messageOwnership()),+ projectId: topics.projectId,+ projectWorkingDirectoryId: topics.projectWorkingDirectoryId,+ model: topics.model,+ provider: topics.provider,+ runStartedAt: runStartedAtColumn,+ status: topics.status,+ title: topics.title,+ updatedAt: topics.updatedAt,+ // Sidebar sorts/groups topics client-side by this `sortUpdatedAt` β the+ // same `topicActivityAt` the ORDER BY uses (latest message time, COALESCE+ // fallback to the row's own updatedAt). Keeping it separate from the+ // display `updatedAt` above matches the client-side sort key to the server+ // order (otherwise the two disagree and the list visibly jumps) while a+ // rename/favorite edit still shows its real edit time. See rankTopics for+ // the same activity-time pattern.+ sortUpdatedAt: topicActivityAt,+ // Workspace sidebars filter maintenance actions client-side by+ // ownership (own vs workspace scope) β the filter needs the row+ // owner even in the slim projection.+ userId: topics.userId,+ ...detailColumns,+ } as any)+ .from(topics)+ .where(agentWhere)+ .orderBy(...orderBy)+ .limit(pageSize)+ .offset(offset),+ { current, isInbox: !!isInbox, pageSize },+ ),+ runTimedStage(+ timing,+ 'db.topic.query.agent.count.select',+ () =>+ ctx.db+ .select({ count: count(topics.id) })+ .from(topics)+ .where(agentWhere),+ { isInbox: !!isInbox },+ ),+ ]);++ logTiming(timing, 'db.topic.query:done', {+ itemCount: items.length,+ stageMs: getDurationMs(queryStartedAt),+ total: totalResult[0].count,+ });+ return { items, total: totalResult[0].count };+ }++ // Fallback to containerId-based query (backward compatibility)+ const whereCondition = and(+ ctx.ownership(),+ ctx.notShareVisitor(),+ ctx.matchContainer(containerId),+ includeTriggerCondition,+ excludeTriggerCondition,+ triggerCondition,+ excludeStatusCondition,+ );++ const [items, totalResult] = await Promise.all([+ runTimedStage(+ timing,+ 'db.topic.query.container.items.select',+ () =>+ ctx.db+ // See note on the group-branch select above re: `as any` cast.+ .select({+ agentId: topics.agentId,+ completedAt: topics.completedAt,+ createdAt: topics.createdAt,+ favorite: topics.favorite,+ historySummary: topics.historySummary,+ id: topics.id,+ metadata: topicMetadataWithCreator(ctx.db, ctx.messageOwnership()),+ projectId: topics.projectId,+ projectWorkingDirectoryId: topics.projectWorkingDirectoryId,+ model: topics.model,+ provider: topics.provider,+ runStartedAt: runStartedAtColumn,+ sessionId: topics.sessionId,+ status: topics.status,+ title: topics.title,+ updatedAt: topics.updatedAt,+ // Sidebar sorts/groups topics client-side by this `sortUpdatedAt` β the+ // same `topicActivityAt` the ORDER BY uses (latest message time, COALESCE+ // fallback to the row's own updatedAt). Keeping it separate from the+ // display `updatedAt` above matches the client-side sort key to the server+ // order (otherwise the two disagree and the list visibly jumps) while a+ // rename/favorite edit still shows its real edit time. See rankTopics for+ // the same activity-time pattern.+ sortUpdatedAt: topicActivityAt,+ // Workspace sidebars filter maintenance actions client-side by+ // ownership (own vs workspace scope) β the filter needs the row+ // owner even in the slim projection.+ userId: topics.userId,+ ...detailColumns,+ } as any)+ .from(topics)+ .where(whereCondition)+ .orderBy(...orderBy)+ .limit(pageSize)+ .offset(offset),+ { current, pageSize },+ ),+ runTimedStage(timing, 'db.topic.query.container.count.select', () =>+ ctx.db+ .select({ count: count(topics.id) })+ .from(topics)+ .where(whereCondition),+ ),+ ]);++ // Remove internal fields before returning++ const cleanItems = items.map(({ agentId: _agentId, sessionId: _sessionId, ...rest }) => rest);++ logTiming(timing, 'db.topic.query:done', {+ itemCount: cleanItems.length,+ stageMs: getDurationMs(queryStartedAt),+ total: totalResult[0].count,+ });++ return { items: cleanItems, total: totalResult[0].count };+};++/**+ * Query the current user's topics, optionally filtered by status β e.g. to+ * list actively-running topics across all agents without pulling the full+ * topic set to the client.+ *+ * `withLastMessage` additionally pulls each topic's last assistant reply, so a+ * list can show what the agent actually said instead of just a title. The+ * preview is truncated server-side β raw assistant output is unbounded+ * markdown, and a list only ever renders the head of it.+ */+export const queryTopics = async (+ ctx: TopicModelContext,+ {+ deviceId,+ statuses,+ pageSize = 200,+ withLastMessage,+ }: {+ /**+ * Only topics on this device β the one its in-flight run was dispatched to+ * (`metadata.runningOperation.deviceId`), else the one its turns are+ * pinned to (`metadata.boundDeviceId`). See {@link getTopicDeviceId},+ * which applies the same precedence in memory.+ */+ deviceId?: string;+ pageSize?: number;+ statuses?: string[];+ withLastMessage?: boolean;+ } = {},+): Promise<TopicListItem[]> => {+ const scope = { userId: ctx.userId, workspaceId: ctx.workspaceId };++ // Unlike the per-agent topic list, this feed is not scoped by agent at all:+ // in a workspace `ownership()` matches every member's rows, so a topic+ // whose owning agent/group is someone else's PRIVATE conversation would+ // surface here β title and last assistant reply included. Gate on the+ // parent the same way the Recent feed does. Rows with no resolvable parent+ // (legacy session-only topics) have nothing to check and keep the previous+ // behaviour.+ const visibleParentWhere = or(+ and(isNull(topics.agentId), isNull(topics.groupId)),+ and(isNotNull(topics.groupId), buildWorkspaceWhere(scope, chatGroups)),+ and(isNull(topics.groupId), isNotNull(topics.agentId), buildWorkspaceWhere(scope, agents)),+ );++ const where = and(+ ctx.ownership(),+ ctx.notShareVisitor(),+ visibleParentWhere,+ statuses && statuses.length > 0+ ? inArray(topics.status, statuses as ChatTopicStatus[])+ : undefined,+ deviceId+ ? sql`COALESCE(${topics.metadata} -> 'runningOperation' ->> 'deviceId', ${topics.metadata} ->> 'boundDeviceId') = ${deviceId}`+ : undefined,+ );++ // `buildWorkspaceWhere` keeps a member's OWN private rows visible, which is+ // right for a "mine" list and wrong for a shared one. Ship the parent's+ // visibility so the caller's team view can drop private conversations+ // without a second round trip.+ const parentVisibilityColumn = sql<+ 'private' | 'public' | null+ >`COALESCE(${chatGroups.visibility}, ${agents.visibility})`.as('parent_visibility');++ // When the topic's current run started, so a list can show live elapsed+ // time instead of `updatedAt` (which moves on every message write). The+ // latest *top-level* running operation is the current run: sub-operations+ // (callAgent) would restart the clock at their own spawn time, and an+ // abandoned `running` row from a crashed earlier run sorts below the live+ // one. Not scoped by `ownership()` β in a workspace the run may have been+ // started by another member, and the topic join is already ownership-gated.+ const runStartedAtSubquery = ctx.db+ .select({ value: agentOperations.startedAt })+ .from(agentOperations)+ .where(+ and(+ eq(agentOperations.topicId, topics.id),+ eq(agentOperations.status, 'running'),+ isNull(agentOperations.parentOperationId),+ isNotNull(agentOperations.startedAt),+ ),+ )+ .orderBy(desc(agentOperations.startedAt))+ .limit(1);++ // Client-executed runs (desktop heterogeneous CLI, in-browser runtime) never+ // reach `agent_operations` β nothing server-side creates the operation β so+ // their start is stamped onto the topic by the status write that claims it+ // (see {@link TopicModel.update}). The operation row still wins when both+ // exist: it is the server's own record of the run, while the stamp is a+ // client-reported time.+ const localRunStartedAt = sql`(${topics.metadata} ->> 'runStartedAt')::timestamptz`;++ // CASE-gated so only rows that are actually running pay for the lookup β+ // and a stale running op (or stamp) under a finished topic can't resurrect+ // a timer.+ const runStartedAtColumn =+ sql<Date | null>`CASE WHEN ${topics.status} = 'running' THEN COALESCE((${runStartedAtSubquery}), ${localRunStartedAt}) ELSE NULL END`+ .mapWith(agentOperations.startedAt)+ .as('run_started_at');++ if (!withLastMessage) {+ return ctx.db+ .select({+ ...getTableColumns(topics),+ metadata: topicMetadataWithCreator(ctx.db, ctx.messageOwnership()),+ parentVisibility: parentVisibilityColumn,+ runStartedAt: runStartedAtColumn,+ })+ .from(topics)+ .leftJoin(agents, eq(topics.agentId, agents.id))+ .leftJoin(chatGroups, eq(topics.groupId, chatGroups.id))+ .where(where)+ .orderBy(desc(topics.updatedAt))+ .limit(pageSize);+ }++ // Built with the query builder rather than a raw `sql` template so the inner+ // `eq(messages.topicId, topics.id)` renders both sides fully qualified β+ // see the note on `firstUserMessageSubquery` in `query()`.+ //+ // Assistant turns that only carried tool calls persist an empty `content`;+ // skipping them lands on the last thing the agent actually *said*.+ // One char past the limit, so the caller can tell "exactly this long" from+ // "cut short" and mark the cut instead of ending mid-sentence.+ const lastAssistantMessageSubquery = ctx.db+ .select({+ value: sql<string>`left(${messages.content}, ${LAST_MESSAGE_PREVIEW_LENGTH + 1})`,+ })+ .from(messages)+ .where(+ and(+ eq(messages.topicId, topics.id),+ eq(messages.role, 'assistant'),+ ctx.messageOwnership(),+ ne(messages.content, ''),+ ),+ )+ .orderBy(desc(messages.createdAt))+ .limit(1);++ const rows = await ctx.db+ .select({+ ...getTableColumns(topics),+ metadata: topicMetadataWithCreator(ctx.db, ctx.messageOwnership()),+ lastAssistantMessage: sql<string | null>`(${lastAssistantMessageSubquery})`.as(+ 'last_assistant_message',+ ),+ parentVisibility: parentVisibilityColumn,+ runStartedAt: runStartedAtColumn,+ })+ .from(topics)+ .leftJoin(agents, eq(topics.agentId, agents.id))+ .leftJoin(chatGroups, eq(topics.groupId, chatGroups.id))+ .where(where)+ .orderBy(desc(topics.updatedAt))+ .limit(pageSize);++ return rows.map((row) => ({+ ...row,+ lastAssistantMessage:+ row.lastAssistantMessage && row.lastAssistantMessage.length > LAST_MESSAGE_PREVIEW_LENGTH+ ? `${row.lastAssistantMessage.slice(0, LAST_MESSAGE_PREVIEW_LENGTH)}β¦`+ : row.lastAssistantMessage,+ }));+};diff --git a/packages/database/src/models/topic/memoryExtractor.ts b/packages/database/src/models/topic/memoryExtractor.tsnew file mode 100644index 00000000000..ce54a0f1829--- /dev/null+++ b/packages/database/src/models/topic/memoryExtractor.ts@@ -0,0 +1,104 @@+import { and, count, eq, gt, gte, lte, ne, or, sql } from 'drizzle-orm';++import { topics } from '../../schemas';+import type { TopicModelContext } from './context';+import type { ListTopicsForMemoryExtractorCursor } from './types';++export const listTopicsForMemoryExtractor = async (+ ctx: TopicModelContext,+ options: {+ cursor?: ListTopicsForMemoryExtractorCursor;+ endDate?: Date;+ ignoreExtracted?: boolean;+ limit?: number;+ startDate?: Date;+ } = {},+) => {+ const cursorCondition = options.cursor+ ? and(+ ne(topics.id, options.cursor.id),+ or(+ gt(topics.createdAt, options.cursor.createdAt),+ and(eq(topics.createdAt, options.cursor.createdAt), gt(topics.id, options.cursor.id)),+ ),+ )+ : undefined;++ return ctx.db.query.topics.findMany({+ columns: {+ createdAt: true,+ id: true,+ metadata: true,+ userId: true,+ },+ limit: options.limit,+ orderBy: (fields, { asc }) => [asc(fields.createdAt), asc(fields.id)],+ where: and(+ ctx.ownership(),+ // Share-visitor conversations are not the creator's own speech β never+ // feed them into the creator's memory extraction.+ ctx.notShareVisitor(),+ options.startDate ? gte(topics.createdAt, options.startDate) : undefined,+ options.endDate ? lte(topics.createdAt, options.endDate) : undefined,+ options.ignoreExtracted+ ? undefined+ : // COALESCE, not `IS DISTINCT FROM`: a null test on a jsonb arrow+ // expression crashes the production engine (see the note on the class).+ // A null `metadata` extracts to '' here too, so this covers it.+ sql`COALESCE(${topics.metadata}->>'userMemoryExtractStatus', '') <> 'completed'`,+ cursorCondition,+ ),+ });+};++export const countTopicsForMemoryExtractor = async (+ ctx: TopicModelContext,+ options: {+ endDate?: Date;+ ignoreExtracted?: boolean;+ startDate?: Date;+ } = {},+) => {+ const result = await ctx.db+ .select({ total: count(topics.id) })+ .from(topics)+ .where(+ and(+ ctx.ownership(),+ ctx.notShareVisitor(),+ options.startDate ? gte(topics.createdAt, options.startDate) : undefined,+ options.endDate ? lte(topics.createdAt, options.endDate) : undefined,+ options.ignoreExtracted+ ? undefined+ : sql`COALESCE(${topics.metadata}->>'userMemoryExtractStatus', '') <> 'completed'`,+ ),+ );++ return result[0]?.total ?? 0;+};++/**+ * Resets the memory-extraction state of all the caller's topics back to+ * `pending`, clearing any previous run summary. Used by "purge all+ * memories": after memories are deleted, topics keep `userMemoryExtractStatus =+ * 'completed'`, so `isTopicExtracted()` skips them forever and nothing can+ * ever be re-extracted. Resetting to `pending` makes the next memory+ * analysis re-process them. Fixes #18498.+ *+ * Scoped by `userId` only (not `mine()`): `deleteAll` removes every memory+ * belonging to the caller regardless of workspace scope, so the reset must+ * cover topics across personal and all workspace scopes alike, otherwise+ * topics in the other scope keep `completed` and stay stuck behind the+ * extraction skip gate.+ */+export const resetMemoryExtractStatus = async (ctx: TopicModelContext) => {+ return ctx.db+ .update(topics)+ .set({+ metadata: sql`jsonb_set(+ jsonb_set(${topics.metadata}, '{userMemoryExtractStatus}', to_jsonb('pending'::text), true),+ '{userMemoryExtractRunState}', '{}'::jsonb, true+ )`,+ })+ .where(eq(topics.userId, ctx.userId));+};diff --git a/packages/database/src/models/topic/runningOperation.ts b/packages/database/src/models/topic/runningOperation.tsnew file mode 100644index 00000000000..41bfb82aa8f--- /dev/null+++ b/packages/database/src/models/topic/runningOperation.ts@@ -0,0 +1,442 @@+import type { AgentOperationStatus, ChatTopicMetadata } from '@lobechat/types';+import { and, eq } from 'drizzle-orm';++import { agentOperations, type TopicItem, topics } from '../../schemas';+import type { LobeChatDatabase } from '../../type';+import type { TopicModelContext } from './context';+import type {+ RunningOperation,+ RunningOperationPatch,+ SettleRunningOperationOptions,+} from './types';++/**+ * The device a topic runs on: the one its in-flight run was dispatched to,+ * else the one its turns are pinned to. The live dispatch wins because a run+ * does not always follow the pin β an `auto` target, an explicit request+ * device or a fixed workspace target can send it elsewhere. The `deviceId`+ * filter of `TopicModel.queryTopics` applies the same precedence in SQL.+ */+export const getTopicDeviceId = (+ metadata: Pick<ChatTopicMetadata, 'boundDeviceId' | 'runningOperation'> | null | undefined,+): string | undefined => metadata?.runningOperation?.deviceId ?? metadata?.boundDeviceId;++/**+ * How long an operation that still claims `running` / `idle` may hold the topic+ * against a background start before it is treated as abandoned.+ *+ * Only a backstop for the case the operation row cannot describe: a process+ * killed mid-run leaves its row at `running` forever, and every marker clear+ * site is best-effort (`ServerOperationStore.clearRunningMark` swallows+ * failures; the gateway client clears it from `onSessionComplete`, which never+ * runs if the tab closed). Runs parked on a human or an async tool are exempt β+ * those legitimately last days β so this only has to be longer than a plausible+ * uninterrupted generation. The real reaper remains the gateway watchdog's+ * `finalize-abandoned` call.+ */+export const ABANDONED_OPERATION_TTL_MS = 6 * 60 * 60 * 1000;++/**+ * Operation statuses that mean "this run is still the topic's owner". Parked+ * states are included on purpose: a run waiting for approval is not stuck.+ */+export const LIVE_OPERATION_STATUSES = new Set([+ 'idle',+ 'running',+ 'waiting_for_human',+ 'waiting_for_async_tool',+ 'waiting_for_client',+]);++/** Parked states are exempt from the abandoned-age backstop β see above. */+export const UNBOUNDED_OPERATION_STATUSES = new Set([+ 'waiting_for_human',+ 'waiting_for_async_tool',+]);++/**+ * Operation statuses in which the server is still driving the run, so a+ * client-reported end must not clear its topic marker. `waiting_for_human` is+ * excluded on purpose: a run parked for approval is stream-terminal for the+ * client, which settles it to stop the spinner.+ */+export const CLIENT_UNSETTLEABLE_OPERATION_STATUSES = new Set<AgentOperationStatus>([+ 'running',+ 'waiting_for_async_tool',+ 'waiting_for_client',+]);++/**+ * Atomically clear and settle the operation that still owns a topic.+ * A row lock keeps a stale terminal callback from clearing a newer operation+ * between the ownership check and update. Missing markers are intentionally+ * not settled because a client-side run can set `status = 'running'` without+ * an operation marker, so there is no proof that the terminal callback owns it.+ *+ * The result distinguishes a missing marker from a conflicting operation:+ * some legitimate hetero callbacks arrive after another terminal path has+ * already cleared their marker, while a callback that observes a newer+ * operation must stop before dispatching lifecycle hooks for the wrong run.+ */+export const settleRunningOperation = async (+ ctx: TopicModelContext,+ id: string,+ operationId: string,+ status: TopicItem['status'] = 'unread',+ options: SettleRunningOperationOptions = {},+) => {+ return ctx.db.transaction(async (tx) => {+ const [existing] = await tx+ .select({+ metadata: topics.metadata,+ projectId: topics.projectId,+ projectWorkingDirectoryId: topics.projectWorkingDirectoryId,+ status: topics.status,+ })+ .from(topics)+ .where(and(eq(topics.id, id), ctx.ownership()))+ .for('update');++ const runningOperation = existing?.metadata?.runningOperation;+ if (!runningOperation) {+ const currentMessage = existing?.metadata?.heteroCurrentMsgId;+ if (+ existing?.metadata?.lastSettledOperationId === operationId &&+ existing.status === 'unread' &&+ status === 'active'+ ) {+ await tx+ .update(topics)+ .set({ status: 'active', updatedAt: new Date() })+ .where(and(eq(topics.id, id), ctx.ownership()));++ return {+ assistantMessageId:+ currentMessage?.operationId === operationId ? currentMessage.msgId : undefined,+ status: 'corrected' as const,+ };+ }++ return {+ assistantMessageId:+ currentMessage?.operationId === operationId ? currentMessage.msgId : undefined,+ status: 'missing' as const,+ };+ }+ const isRoot = runningOperation.operationId === operationId;+ const operation = isRoot+ ? runningOperation+ : runningOperation.childOperations?.find((child) => child.operationId === operationId);+ if (!operation) {+ return { activeOperationId: runningOperation.operationId, status: 'conflict' as const };+ }++ // A client only learns a run ended from a stream event, and a mirrored or+ // early event can arrive while the server is still driving the run (e.g. a+ // supervisor parked on `waiting_for_async_tool` for its group members).+ // Clearing the marker then drops the run's topic reservation, so the next+ // member start fails as "Topic β¦ remained busy". The server's own+ // `finish` clears the marker before it publishes the terminal event, so a+ // genuine end never reaches this check with the marker still in place.+ if (options.rejectInFlightOperation) {+ const [operationRow] = await tx+ .select({ status: agentOperations.status })+ .from(agentOperations)+ .where(eq(agentOperations.id, operationId))+ .limit(1);+ if (+ operationRow &&+ CLIENT_UNSETTLEABLE_OPERATION_STATUSES.has(operationRow.status as AgentOperationStatus)+ ) {+ return {+ activeOperationId: runningOperation.operationId,+ operationStatus: operationRow.status as AgentOperationStatus,+ status: 'in_flight' as const,+ };+ }+ }++ const metadata = {+ ...existing.metadata,+ ...(isRoot ? { lastSettledOperationId: operationId } : {}),+ runningOperation: isRoot+ ? null+ : {+ ...runningOperation,+ childOperations: runningOperation.childOperations?.filter(+ (child) => child.operationId !== operationId,+ ),+ },+ } as ChatTopicMetadata;++ await tx+ .update(topics)+ .set({+ metadata,+ ...(isRoot && existing.status === 'running' ? { status } : {}),+ updatedAt: new Date(),+ })+ .where(and(eq(topics.id, id), ctx.ownership()));++ const currentMessage = existing.metadata?.heteroCurrentMsgId;+ return {+ assistantMessageId:+ currentMessage?.operationId === operationId+ ? currentMessage.msgId+ : operation.assistantMessageId,+ hooks: operation.hooks,+ orchestrationRole: operation.orchestrationRole,+ status: 'settled' as const,+ threadId: operation.threadId ?? undefined,+ };+ });+};++export const appendRunningOperationChild = async (+ ctx: TopicModelContext,+ id: string,+ parentOperationId: string,+ child: RunningOperation,+): Promise<boolean> =>+ ctx.db.transaction(async (tx) => {+ const [existing] = await tx+ .select({ metadata: topics.metadata })+ .from(topics)+ .where(and(eq(topics.id, id), ctx.ownership()))+ .for('update');+ const runningOperation = existing?.metadata?.runningOperation;+ if (!existing || runningOperation?.operationId !== parentOperationId) return false;++ await tx+ .update(topics)+ .set({+ metadata: {+ ...existing.metadata,+ runningOperation: {+ ...runningOperation,+ childOperations: [+ ...(runningOperation.childOperations ?? []).filter(+ (operation) => operation.operationId !== child.operationId,+ ),+ child,+ ],+ },+ },+ })+ .where(and(eq(topics.id, id), ctx.ownership()));+ return true;+ });++export const patchRunningOperation = async (+ ctx: TopicModelContext,+ id: string,+ operationId: string,+ patch: RunningOperationPatch,+): Promise<boolean> =>+ ctx.db.transaction(async (tx) => {+ const [existing] = await tx+ .select({ metadata: topics.metadata })+ .from(topics)+ .where(and(eq(topics.id, id), ctx.ownership()))+ .for('update');+ const runningOperation = existing?.metadata?.runningOperation;+ if (!existing || !runningOperation) return false;++ let nextRunningOperation: RunningOperation;+ if (runningOperation.operationId === operationId) {+ nextRunningOperation = { ...runningOperation, ...patch };+ } else {+ let matched = false;+ const childOperations = runningOperation.childOperations?.map((child) => {+ if (child.operationId !== operationId) return child;+ matched = true;+ return { ...child, ...patch };+ });+ if (!matched) return false;+ nextRunningOperation = { ...runningOperation, childOperations };+ }++ await tx+ .update(topics)+ .set({+ metadata: { ...existing.metadata, runningOperation: nextRunningOperation },+ })+ .where(and(eq(topics.id, id), ctx.ownership()));+ return true;+ });++export const removeRunningOperationChild = async (+ ctx: TopicModelContext,+ id: string,+ operationId: string,+): Promise<boolean> =>+ ctx.db.transaction(async (tx) => {+ const [existing] = await tx+ .select({ metadata: topics.metadata })+ .from(topics)+ .where(and(eq(topics.id, id), ctx.ownership()))+ .for('update');+ const runningOperation = existing?.metadata?.runningOperation;+ if (!existing || !runningOperation?.childOperations) return false;+ await tx+ .update(topics)+ .set({+ metadata: {+ ...existing.metadata,+ runningOperation: {+ ...runningOperation,+ childOperations: runningOperation.childOperations.filter(+ (child) => child.operationId !== operationId,+ ),+ },+ },+ })+ .where(and(eq(topics.id, id), ctx.ownership()));+ return true;+ });++export const updateRunningOperationAssistantMessage = async (+ ctx: TopicModelContext,+ id: string,+ operationId: string,+ assistantMessageId: string,+): Promise<boolean> =>+ ctx.db.transaction(async (tx) => {+ const [existing] = await tx+ .select({ metadata: topics.metadata })+ .from(topics)+ .where(and(eq(topics.id, id), ctx.ownership()))+ .for('update');+ const runningOperation = existing?.metadata?.runningOperation;+ if (!existing || !runningOperation) return false;++ if (runningOperation.operationId === operationId) {+ await tx+ .update(topics)+ .set({+ metadata: {+ ...existing.metadata,+ heteroCurrentMsgId: { msgId: assistantMessageId, operationId },+ runningOperation: { ...runningOperation, assistantMessageId },+ },+ })+ .where(and(eq(topics.id, id), ctx.ownership()));+ return true;+ }++ const childOperations = runningOperation.childOperations?.map((child) =>+ child.operationId === operationId ? { ...child, assistantMessageId } : child,+ );+ if (!childOperations?.some((child) => child.operationId === operationId)) return false;++ await tx+ .update(topics)+ .set({+ metadata: {+ ...existing.metadata,+ heteroCurrentMsgId: { msgId: assistantMessageId, operationId },+ runningOperation: { ...runningOperation, childOperations },+ },+ })+ .where(and(eq(topics.id, id), ctx.ownership()));+ return true;+ });++export const takeRunningOperation = async (+ ctx: TopicModelContext,+ id: string,+ operationId: string,+): Promise<+ | {+ isRoot: boolean;+ operation: NonNullable<ChatTopicMetadata['runningOperation']>;+ }+ | undefined+> =>+ ctx.db.transaction(async (tx) => {+ const [existing] = await tx+ .select({ metadata: topics.metadata })+ .from(topics)+ .where(and(eq(topics.id, id), ctx.ownership()))+ .for('update');+ const runningOperation = existing?.metadata?.runningOperation;+ if (!existing || !runningOperation) return undefined;++ if (runningOperation.operationId === operationId) {+ await tx+ .update(topics)+ .set({+ metadata: { ...existing.metadata, runningOperation: null },+ })+ .where(and(eq(topics.id, id), ctx.ownership()));+ return { isRoot: true, operation: runningOperation };+ }++ const child = runningOperation.childOperations?.find(+ (candidate) => candidate.operationId === operationId,+ );+ if (!child) return undefined;++ await tx+ .update(topics)+ .set({+ metadata: {+ ...existing.metadata,+ runningOperation: {+ ...runningOperation,+ childOperations: runningOperation.childOperations?.filter(+ (candidate) => candidate.operationId !== operationId,+ ),+ },+ },+ })+ .where(and(eq(topics.id, id), ctx.ownership()));+ return { isRoot: false, operation: child };+ });++/**+ * Whether the run a `runningOperation` marker points at is still the topic's+ * legitimate owner.+ *+ * Public so the gateway-token refresh routers can refuse to reconnect a+ * client to a marker whose run has already ended (the marker is cleared+ * best-effort, so a stale one must not be taken at face value).+ *+ * The marker itself cannot answer this β it carries no heartbeat and is+ * cleared best-effort β so the authority is the operation row, which both the+ * in-process runtime (`createOperation`) and the heterogeneous path+ * (`CompletionLifecycle.recordStart`) write before publishing the marker.+ *+ * Falls back to the marker's own `startedAt` only when no row exists: hetero's+ * `recordStart` is deliberately non-fatal, so a DB hiccup can leave a live run+ * with a marker and no row. A marker with neither a row nor a stamp cannot be+ * proven live and must not keep an already-stuck topic stuck.+ */+export const isRunningOperationAlive = async (+ ctx: TopicModelContext,+ tx: Pick<LobeChatDatabase, 'select'>,+ runningOperation: NonNullable<ChatTopicMetadata['runningOperation']>,+): Promise<boolean> => {+ const [operation] = await tx+ .select({ createdAt: agentOperations.createdAt, status: agentOperations.status })+ .from(agentOperations)+ .where(eq(agentOperations.id, runningOperation.operationId))+ .limit(1);++ if (!operation) {+ const markerStartedAt = runningOperation.startedAt+ ? Date.parse(runningOperation.startedAt)+ : Number.NaN;+ return (+ Number.isFinite(markerStartedAt) && Date.now() - markerStartedAt < ABANDONED_OPERATION_TTL_MS+ );+ }++ if (!LIVE_OPERATION_STATUSES.has(operation.status)) return false;+ if (UNBOUNDED_OPERATION_STATUSES.has(operation.status)) return true;++ // Claims `running`/`idle`, but a killed process never writes a terminal+ // status β age it out so the topic is not held forever.+ const startedAt = operation.createdAt ? new Date(operation.createdAt).getTime() : Number.NaN;+ return !Number.isFinite(startedAt) || Date.now() - startedAt < ABANDONED_OPERATION_TTL_MS;+};diff --git a/packages/database/src/models/topic/scheduledRun.ts b/packages/database/src/models/topic/scheduledRun.tsnew file mode 100644index 00000000000..a8901b6faf3--- /dev/null+++ b/packages/database/src/models/topic/scheduledRun.ts@@ -0,0 +1,261 @@+import {+ type ChatTopicMetadata,+ type ChatTopicStatus,+ parseTopicScheduledRun,+ type TopicScheduledRun,+} from '@lobechat/types';+import { and, eq, or, sql } from 'drizzle-orm';++import { type TopicItem, topics } from '../../schemas';+import type { LobeChatDatabase } from '../../type';+import { notTrashed } from '../../utils/softDelete';+import type { TopicModelContext } from './context';++/** Atomically cancel an unclaimed rate-limit run, serialized with the dispatcher. */+export const cancelRateLimitContinuation = async (ctx: TopicModelContext, id: string) =>+ ctx.db.transaction(async (tx) => {+ const [row] = await tx+ .select({ metadata: topics.metadata, status: topics.status })+ .from(topics)+ .where(and(eq(topics.id, id), ctx.ownership()))+ .for('update');+ if (!row) return { status: 'unchanged' as const };+ if (row.status === 'running') return { status: 'busy' as const };+ const scheduledRun = parseTopicScheduledRun(row.metadata?.scheduledRun);+ if (row.status !== 'scheduled' || scheduledRun?.kind !== 'resume_after_rate_limit')+ return { status: 'unchanged' as const };+ // A lease expiring does not stop its dispatcher. Once claimed, a handoff+ // must not race that worker, even if its five-minute lease has elapsed.+ if (scheduledRun.claim) return { status: 'busy' as const };++ const metadata = { ...row.metadata, scheduledRun: null };+ await tx+ .update(topics)+ .set({ metadata, status: 'failed' })+ .where(and(eq(topics.id, id), ctx.ownership()));+ return { metadata, status: 'cancelled' as const };+ });++/**+ * Arm a scheduled run on an owned topic: writes `metadata.scheduledRun` and+ * flips the status to `scheduled` in a single update.+ *+ * The pair is one fact β a topic that is `scheduled` with no payload spins in+ * the dispatcher forever, and a payload on a non-`scheduled` topic never fires+ * β so they must never be written separately. The inverse is+ * {@link TopicModel.clearScheduledRun}.+ */+export const armScheduledRun = async (+ ctx: TopicModelContext,+ id: string,+ scheduledRun: TopicScheduledRun,+): Promise<void> => {+ await ctx.db.transaction(async (tx) => {+ const [existing] = await tx+ .select({ metadata: topics.metadata })+ .from(topics)+ .where(and(eq(topics.id, id), ctx.ownership()))+ .for('update');++ if (!existing) return;++ await tx+ .update(topics)+ .set({+ metadata: { ...existing.metadata, scheduledRun } as ChatTopicMetadata,+ status: 'scheduled',+ })+ .where(and(eq(topics.id, id), ctx.ownership()));+ });+};++/**+ * Topics with a scheduled run that has come due.+ * System-level sweep (no ownership filter) used by the cron dispatcher.+ *+ * Due = `status = 'scheduled'` AND the run's gate has passed AND there is no+ * live claim (`scheduledRun.claim.expiresAt` is absent, or already expired) β+ * so a topic another replica is mid-dispatch on is skipped.+ *+ * `runAt` is the gate for every {@link TopicScheduledRunKind}: a row carrying a+ * `kind` but no `runAt` is never due, which is what keeps a half-written+ * scheduled topic from being dispatched immediately.+ *+ * The one exception is a row parked by the pre-`kind` version, which has no+ * `runAt` and gated on the rate-limit reset instead. Those are still in the DB+ * on deploy, so this reproduces their old gate rather than stranding them at+ * `scheduled` forever β matching `parseTopicScheduledRun`, which upgrades the+ * payload the dispatcher then reads.+ */+export async function getDueScheduledTopics(+ db: LobeChatDatabase,+ now: Date = new Date(),+): Promise<TopicItem[]> {+ const nowIso = now.toISOString();+ const nowEpochSeconds = Math.floor(now.getTime() / 1000);++ // Every jsonb path below is COALESCE'd to a sentinel rather than null-tested:+ // `#>> β¦ IS NULL` in a WHERE clause takes the production engine down. See the+ // note on the class.+ const runAt = sql`COALESCE(${topics.metadata}#>>'{scheduledRun,runAt}', '')`;++ return db+ .select()+ .from(topics)+ .where(+ and(+ eq(topics.status, 'scheduled'),+ notTrashed(topics.isDeleted),+ or(+ // `''` is the absent-runAt sentinel, and it never satisfies this pair β+ // an absent gate must not read as "due now", which is what keeps a+ // half-written schedule parked.+ and(sql`${runAt} <> ''`, sql`${runAt} <= ${nowIso}`),+ // Legacy (pre-`kind`) payload: no `runAt`, gated on the rate-limit+ // reset, and an absent reset read as "due now" (hence the 0 default).+ and(+ sql`${runAt} = ''`,+ sql`COALESCE(${topics.metadata}#>>'{scheduledRun,reason}', '') = 'rate_limit'`,+ sql`COALESCE((${topics.metadata}#>>'{scheduledRun,rateLimit,resetsAt}')::numeric, 0) <= ${nowEpochSeconds}`,+ ),+ ),+ // No claim, or the lease has expired. `''` (no claim) sorts before every+ // ISO timestamp, so the same comparison covers both.+ sql`COALESCE(${topics.metadata}#>>'{scheduledRun,claim,expiresAt}', '') <= ${nowIso}`,+ ),+ );+}++/**+ * Atomically claim a scheduled topic before dispatch, so two concurrent cron+ * ticks can't trigger the same continuation twice. Serializes on the row with+ * `SELECT β¦ FOR UPDATE` (mirrors {@link updateMetadata}) and only writes the+ * lease if the topic is still `scheduled` and not already claimed by a live+ * lease. Returns `true` when this caller won the claim.+ */+export async function claimScheduledTopic(+ db: LobeChatDatabase,+ id: string,+ claim: { claimedAt: string; expiresAt: string; id: string },+ now: Date = new Date(),+): Promise<boolean> {+ return db.transaction(async (tx) => {+ const [row] = await tx+ .select({+ metadata: topics.metadata,+ projectId: topics.projectId,+ projectWorkingDirectoryId: topics.projectWorkingDirectoryId,+ status: topics.status,+ })+ .from(topics)+ .where(eq(topics.id, id))+ .for('update');++ if (!row || row.status !== 'scheduled') return false;++ const scheduledRun = row.metadata?.scheduledRun;+ if (!scheduledRun) return false;++ const existingClaim = scheduledRun.claim;+ const claimLive = existingClaim && new Date(existingClaim.expiresAt) > now;+ if (claimLive) return false;++ await tx+ .update(topics)+ .set({+ metadata: {+ ...row.metadata,+ scheduledRun: { ...scheduledRun, claim },+ } as ChatTopicMetadata,+ })+ .where(eq(topics.id, id));++ return true;+ });+}++/**+ * Clear the scheduled continuation and restore a normal status. Used both when+ * a continuation is successfully dispatched/executed and when it is cancelled.+ */+export async function clearScheduledRun(+ db: LobeChatDatabase,+ id: string,+ nextStatus: ChatTopicStatus = 'active',+ expectedClaimId?: string,+): Promise<void> {+ await db.transaction(async (tx) => {+ const [row] = await tx+ .select({+ metadata: topics.metadata,+ projectId: topics.projectId,+ projectWorkingDirectoryId: topics.projectWorkingDirectoryId,+ status: topics.status,+ })+ .from(topics)+ .where(eq(topics.id, id))+ .for('update');+ if (!row || row.status !== 'scheduled') return;+ if (expectedClaimId && row.metadata?.scheduledRun?.claim?.id !== expectedClaimId) return;++ const nextMetadata = { ...row.metadata, scheduledRun: null } as ChatTopicMetadata;+ await tx+ .update(topics)+ .set({ metadata: nextMetadata, status: nextStatus })+ .where(eq(topics.id, id));+ });+}++/**+ * Re-point a still-pending scheduled run at a new failed-attempt message. A+ * dispatch that fails inside execAgent leaves its own error bubble on the+ * placeholder it created; tracking that bubble as the run's+ * `failedAssistantMessageId` lets the next tick's pre-dispatch cleanup clear+ * it the same way it clears the original card, so retries don't strand one+ * stale error bubble per failed attempt.+ *+ * `expectedClaimId` fences stale writers the same way it does in+ * {@link TopicModel.clearScheduledRun}: a dispatch attempt that outlived its+ * claim lease β or one whose schedule the user cancelled and re-armed β must+ * not overwrite the pointer of a NEWER scheduled run, or the next cleanup+ * would delete / anchor against an unrelated message. No-ops when the+ * schedule was cleared or the claim no longer matches.+ */+export async function repointScheduledRunFailedMessage(+ db: LobeChatDatabase,+ id: string,+ failedAssistantMessageId: string,+ expectedClaimId: string,+): Promise<void> {+ await db.transaction(async (tx) => {+ const [row] = await tx+ .select({+ metadata: topics.metadata,+ projectId: topics.projectId,+ projectWorkingDirectoryId: topics.projectWorkingDirectoryId,+ status: topics.status,+ })+ .from(topics)+ .where(eq(topics.id, id))+ .for('update');+ if (!row || row.status !== 'scheduled') return;++ const scheduledRun = row.metadata?.scheduledRun;+ if (!scheduledRun) return;+ if (scheduledRun.claim?.id !== expectedClaimId) return;++ await tx+ .update(topics)+ .set({+ metadata: {+ ...row.metadata,+ scheduledRun: {+ ...scheduledRun,+ failedAssistantMessageId,+ updatedAt: new Date().toISOString(),+ },+ } as ChatTopicMetadata,+ })+ .where(eq(topics.id, id));+ });+}diff --git a/packages/database/src/models/topic/shareVisitor.ts b/packages/database/src/models/topic/shareVisitor.tsnew file mode 100644index 00000000000..c7c07cf4540--- /dev/null+++ b/packages/database/src/models/topic/shareVisitor.ts@@ -0,0 +1,141 @@+import { AGENT_SHARE_VISITOR_TOPIC_LIST_LIMIT } from '@lobechat/const';+import type { ChatTopicMetadata } from '@lobechat/types';+import { and, count, countDistinct, desc, eq, isNotNull } from 'drizzle-orm';++import { topics } from '../../schemas';+import type { TopicModelContext } from './context';+import type { VisitorRunningOperation, VisitorTopicItem } from './types';++/**+ * Fallback page size for {@link TopicModel.queryBySender} when a caller+ * doesn't pass one. Pinned to the package default per-visitor topic cap.+ *+ * Callers with a live share config (e.g. `shareChat.getTopics`) MUST pass the+ * share's actual resolved `maxTopicsPerVisitor` as `pageSize` instead of+ * relying on this default β a creator who raises the cap above the default+ * would otherwise have a visitor's list silently truncated below what that+ * visitor is actually allowed to create.+ */+export const VISITOR_TOPIC_PAGE_SIZE = AGENT_SHARE_VISITOR_TOPIC_LIST_LIMIT;++/**+ * Projects `topics.metadata.runningOperation` down to the visitor-safe subset+ * β see {@link VisitorRunningOperation}. Used by {@link TopicModel.queryBySender}+ * so a share visitor's topic list can drive `useGatewayReconnect` without ever+ * receiving the rest of `metadata` (creator-only fields β see the module doc).+ */+export const pickVisitorRunningOperation = (+ metadata: ChatTopicMetadata | null | undefined,+): VisitorRunningOperation | null => {+ const runningOperation = metadata?.runningOperation;+ if (!runningOperation) return null;++ const { assistantMessageId, heteroType, operationId, scope, startedAt, threadId } =+ runningOperation;+ return { assistantMessageId, heteroType, operationId, scope, startedAt, threadId };+};++/**+ * Share-visitor topic list for one visitor on one shared agent. The model is+ * constructed with the CREATOR's userId (visitor topics carry it), so the+ * caller β the shareChat router β must have already authorized the visitor+ * via the share access check; `agentId` + `senderId` together are the+ * per-visitor boundary.+ *+ * `agent_shares` is 1:1 per agent (`agent_shares_agent_id_unique`), so+ * `agentId` alone identifies which share a visitor topic belongs to β there+ * is no `topics.share_id` column to scope by. Turning sharing off and back+ * on keeps the same row and the same `agentId`, so a returning visitor's+ * older conversations DO resurface under the republished share. That is the+ * accepted trade-off of not carrying a share id on the row.+ *+ * Selects a visitor-facing DTO instead of the full row: the visitor surface+ * only renders id/title/runningOperation, and the row also carries+ * creator-only fields (owning userId, model/provider snapshot, cost/usage,+ * internal status and the rest of `metadata`) that must never reach a share+ * visitor. `metadata` itself IS selected (needed to project+ * `runningOperation`), but only the sanitized projection β never the raw+ * column β leaves this method; see {@link VisitorRunningOperation}.+ */+export const queryBySender = async (+ ctx: TopicModelContext,+ { agentId, senderId }: { agentId: string; senderId: string },+ { pageSize = VISITOR_TOPIC_PAGE_SIZE }: { pageSize?: number } = {},+): Promise<VisitorTopicItem[]> => {+ const rows = await ctx.db+ .select({+ createdAt: topics.createdAt,+ id: topics.id,+ metadata: topics.metadata,+ title: topics.title,+ updatedAt: topics.updatedAt,+ })+ .from(topics)+ .where(and(ctx.mine(), eq(topics.agentId, agentId), eq(topics.senderId, senderId)))+ .orderBy(desc(topics.updatedAt))+ .limit(pageSize);++ return rows.map(({ metadata, ...rest }) => ({+ ...rest,+ runningOperation: pickVisitorRunningOperation(metadata),+ }));+};++/**+ * Per-visitor topic count on a shared agent β drives `maxTopicsPerVisitor`.+ * Same `(agentId, senderId)` scoping as {@link queryBySender}; see that+ * method's JSDoc for why there is no share-id dimension.+ */+export const countBySender = async (+ ctx: TopicModelContext,+ {+ agentId,+ senderId,+ }: {+ agentId: string;+ senderId: string;+ },+): Promise<number> => {+ const result = await ctx.db+ .select({ count: count(topics.id) })+ .from(topics)+ .where(and(ctx.mine(), eq(topics.agentId, agentId), eq(topics.senderId, senderId)));++ return result[0].count;+};++/**+ * Creator-facing roll-up for one shared agent: how many conversations+ * visitors started, and how many distinct visitors started them.+ *+ * Counterpart to {@link countBySender}, which counts ONE visitor. Both rely+ * on `senderId` being non-null only for share-originated topics, so the+ * creator's own conversations with the same agent are excluded. Scoped by+ * `ctx.mine()` like every other read here, so the numbers can only ever+ * describe rows the caller owns.+ *+ * `agentShares` is 1:1 per agent, so `agentId` alone is the share dimension+ * β see {@link queryBySender} for why a disable β re-enable cycle keeps+ * counting the earlier conversations.+ */+export const countShareVisitors = async (+ ctx: TopicModelContext,+ {+ agentId,+ }: {+ agentId: string;+ },+): Promise<{ topicCount: number; visitorCount: number }> => {+ const [result] = await ctx.db+ .select({+ topicCount: count(topics.id),+ visitorCount: countDistinct(topics.senderId),+ })+ .from(topics)+ .where(and(ctx.mine(), eq(topics.agentId, agentId), isNotNull(topics.senderId)));++ return {+ topicCount: Number(result?.topicCount ?? 0),+ visitorCount: Number(result?.visitorCount ?? 0),+ };+};diff --git a/packages/database/src/models/topic/taskCallback.ts b/packages/database/src/models/topic/taskCallback.tsnew file mode 100644index 00000000000..3cc4f4827c1--- /dev/null+++ b/packages/database/src/models/topic/taskCallback.ts@@ -0,0 +1,230 @@+import type { ChatTopicMetadata } from '@lobechat/types';+import { and, eq } from 'drizzle-orm';++import { topics } from '../../schemas';+import type { TopicModelContext } from './context';+import { isRunningOperationAlive } from './runningOperation';++export const TASK_CALLBACK_RESERVATION_TTL_MS = 5 * 60 * 1000;++/**+ * Whether a turn start currently holds the topic's short start reservation.+ * A writer that changes where the topic runs must respect it as it would a+ * `runningOperation`: the reserving turn may already have resolved its target.+ */+export const hasLiveTaskCallbackReservation = (+ metadata: Pick<ChatTopicMetadata, 'taskCallbackReservation'> | null | undefined,+ now = Date.now(),+): boolean => {+ const reservation = metadata?.taskCallbackReservation;+ if (!reservation) return false;+ const reservedAt = Date.parse(reservation.reservedAt);+ return Number.isFinite(reservedAt) && now - reservedAt < TASK_CALLBACK_RESERVATION_TTL_MS;+};++/**+ * Atomically reserve an idle topic for one task-callback delivery.+ *+ * The topic row lock closes the check/set race between callback workers:+ * only one callback can observe both `runningOperation` and the reservation+ * as empty. Foreground/tool continuations clear `runningOperation` before a+ * callback can claim the topic, so the callback always re-anchors on the+ * completed turn's latest spine.+ */+export const tryReserveTaskCallback = async (+ ctx: TopicModelContext,+ id: string,+ messageId: string,+ options?: {+ /**+ * Permit a start that runs *under* this marker (a group member starting+ * beneath its supervisor). A pure permission check β it never takes the+ * reservation.+ */+ allowRunningOperationId?: string;+ /**+ * A deterministic intervention reservation is an initializer fence, not+ * a reentrant mutex. Its concurrent same-id caller must wait until the+ * owner releases (or the lease expires) instead of entering preparation+ * and overwriting an already-running continuation state.+ */+ allowSameReservationReentry?: boolean;+ /**+ * Skip the `runningOperation` check entirely and serialize only on the+ * short reservation. Set by interactive sends: "don't run two foreground+ * turns at once" is a UX policy the client already owns end to end (queue+ * tray, "Send now", FIFO drain), and it is the only layer that can show+ * the user anything. A second, blind copy of that policy here can only+ * fail worse β it used to destroy the message before it was ever+ * persisted. Background starts (task callbacks, cron, bots) have no such+ * queue and keep the check.+ */+ ignoreRunningOperation?: boolean;+ replacesOperationId?: string;+ },+): Promise<boolean | null> =>+ ctx.db.transaction(async (tx) => {+ const [existing] = await tx+ .select({ metadata: topics.metadata })+ .from(topics)+ .where(and(eq(topics.id, id), ctx.ownership()))+ .for('update');++ if (!existing) return null;++ const reservation = existing.metadata?.taskCallbackReservation;+ const hasLiveReservation = hasLiveTaskCallbackReservation(existing.metadata);++ if (+ reservation?.messageId === messageId &&+ hasLiveReservation &&+ options?.allowSameReservationReentry !== false+ ) {+ return true;+ }++ const runningOperation = existing.metadata?.runningOperation;+ const ownedRunningOperation =+ !!options?.allowRunningOperationId &&+ runningOperation?.operationId === options.allowRunningOperationId;+ if (options?.allowRunningOperationId) return ownedRunningOperation;++ const canReplaceRunningOperation =+ !!options?.replacesOperationId &&+ runningOperation?.operationId === options.replacesOperationId;++ // Only a run that can prove it is still alive may hold the topic. Ask the+ // operation row rather than the marker's age: the marker is never+ // refreshed, so age alone declares a legitimately long run (an approval+ // wait can last days) dead and lets a competing continuation start.+ const hasLiveRunningOperation =+ !!runningOperation &&+ !canReplaceRunningOperation &&+ !options?.ignoreRunningOperation &&+ (await isRunningOperationAlive(ctx, tx, runningOperation));++ if (hasLiveRunningOperation || hasLiveReservation) return false;++ await tx+ .update(topics)+ .set({+ metadata: {+ ...existing.metadata,+ ...(canReplaceRunningOperation && { runningOperation: null }),+ taskCallbackReservation: {+ messageId,+ reservedAt: new Date().toISOString(),+ },+ },+ })+ .where(and(eq(topics.id, id), ctx.ownership()));++ return true;+ });++/**+ * Repair the reconnect anchor after an intervention queue ACK. The same row+ * lock also releases only this continuation's reservation, closing the crash+ * window between provider ACK and execAgent's ordinary running-marker write.+ */+export const repairAgentInterventionContinuation = async (+ ctx: TopicModelContext,+ params: {+ active: boolean;+ assistantMessageId: string;+ continuationOperationId: string;+ reservationId: string;+ scope?: string | null;+ sourceOperationId: string;+ startedAt: string;+ threadId?: string | null;+ topicId: string;+ },+): Promise<'conflict' | 'repaired' | 'terminal'> =>+ ctx.db.transaction(async (tx) => {+ const [existing] = await tx+ .select({ metadata: topics.metadata })+ .from(topics)+ .where(and(eq(topics.id, params.topicId), ctx.ownership()))+ .for('update');+ if (!existing) return 'conflict';++ const current = existing.metadata?.runningOperation;+ const reservation = existing.metadata?.taskCallbackReservation;+ const hasLiveReservation = hasLiveTaskCallbackReservation(existing.metadata);+ const ownsCurrent =+ !current ||+ current.operationId === params.sourceOperationId ||+ current.operationId === params.continuationOperationId;+ const ownsReservation = reservation?.messageId === params.reservationId;+ if (hasLiveReservation && !ownsReservation) return 'conflict';+ if (!ownsCurrent) {+ if (ownsReservation) {+ await tx+ .update(topics)+ .set({+ metadata: { ...existing.metadata, taskCallbackReservation: null },+ updatedAt: new Date(),+ })+ .where(and(eq(topics.id, params.topicId), ctx.ownership()));+ }+ return 'conflict';+ }++ const runningOperation = params.active+ ? {+ ...(current?.operationId === params.continuationOperationId ? current : {}),+ assistantMessageId: params.assistantMessageId,+ heteroType: null,+ operationId: params.continuationOperationId,+ scope: params.scope ?? undefined,+ startedAt: params.startedAt,+ threadId: params.threadId ?? undefined,+ }+ : null;+ await tx+ .update(topics)+ .set({+ metadata: {+ ...existing.metadata,+ runningOperation,+ ...(ownsReservation || !hasLiveReservation ? { taskCallbackReservation: null } : {}),+ },+ updatedAt: new Date(),+ })+ .where(and(eq(topics.id, params.topicId), ctx.ownership()));++ return params.active ? 'repaired' : 'terminal';+ });++/**+ * Release only the caller's reservation. The ownership check prevents a+ * delayed finally block from clearing a newer callback's claim.+ */+export const releaseTaskCallbackReservation = async (+ ctx: TopicModelContext,+ id: string,+ messageId: string,+): Promise<'absent' | 'foreign' | 'released'> =>+ ctx.db.transaction(async (tx) => {+ const [existing] = await tx+ .select({ metadata: topics.metadata })+ .from(topics)+ .where(and(eq(topics.id, id), ctx.ownership()))+ .for('update');++ const reservation = existing?.metadata?.taskCallbackReservation;+ if (!reservation) return 'absent';+ if (reservation.messageId !== messageId) return 'foreign';++ await tx+ .update(topics)+ .set({+ metadata: {+ ...existing.metadata,+ taskCallbackReservation: null,+ },+ })+ .where(and(eq(topics.id, id), ctx.ownership()));+ return 'released';+ });diff --git a/packages/database/src/models/topic/trash.ts b/packages/database/src/models/topic/trash.tsnew file mode 100644index 00000000000..bdafc9652c0--- /dev/null+++ b/packages/database/src/models/topic/trash.ts@@ -0,0 +1,168 @@+import { and, eq, inArray, or, type SQL } from 'drizzle-orm';++import { type TopicItem, topics } from '../../schemas';+import {+ isTrashed,+ restoreStamp,+ type SoftDeleteOptions,+ trashStamp,+} from '../../utils/softDelete';+import type { TopicModelContext } from './context';++/**+ * Move topics to the recycle bin: stamp `deleted_at` and return the rows so+ * the caller can register them. Rows already trashed are left untouched (their+ * own registry row keeps their original stamp). Messages / threads are not+ * stamped β they are hidden by their parent and hard-cascade at purge time.+ */+export const softDelete = async (+ ctx: TopicModelContext,+ ids: string[],+ options: SoftDeleteOptions,+): Promise<TopicItem[]> => {+ if (ids.length === 0) return [];+ return ctx.db+ .update(topics)+ .set(trashStamp(options.deletedAt))+ .where(+ and(+ inArray(topics.id, ids),+ options.restrictToCreator ? ctx.mine() : ctx.ownership(),+ ctx.notShareVisitor(),+ ),+ )+ .returning();+};++/** Soft-delete counterpart of `batchDeleteBySessionId` (`sessionId` null = the agent's default session). */+export const softDeleteBySessionId = async (+ ctx: TopicModelContext,+ sessionId: string | null | undefined,+ options: SoftDeleteOptions,+): Promise<TopicItem[]> => {+ return ctx.db+ .update(topics)+ .set(trashStamp(options.deletedAt))+ .where(+ and(+ ctx.matchSession(sessionId),+ options.restrictToCreator ? ctx.mine() : ctx.ownership(),+ ctx.notShareVisitor(),+ ),+ )+ .returning();+};++export const softDeleteByGroupId = async (+ ctx: TopicModelContext,+ groupId: string | null | undefined,+ options: SoftDeleteOptions,+): Promise<TopicItem[]> => {+ return ctx.db+ .update(topics)+ .set(trashStamp(options.deletedAt))+ .where(+ and(+ ctx.matchGroup(groupId),+ options.restrictToCreator ? ctx.mine() : ctx.ownership(),+ ctx.notShareVisitor(),+ ),+ )+ .returning();+};++export const softDeleteByAgentId = async (+ ctx: TopicModelContext,+ agentId: string,+ options: SoftDeleteOptions,+): Promise<TopicItem[]> => {+ return ctx.db+ .update(topics)+ .set(trashStamp(options.deletedAt))+ .where(+ and(+ eq(topics.agentId, agentId),+ options.restrictToCreator ? ctx.mine() : ctx.ownership(),+ ctx.notShareVisitor(),+ ),+ )+ .returning();+};++/**+ * Cascade helper for trashing an agent / group / session: stamps every live+ * topic that hangs off any of the given parents (by `agent_id`, `session_id`+ * or `group_id`) in one statement.+ */+export const softDeleteByParents = async (+ ctx: TopicModelContext,+ parents: { agentIds?: string[]; groupIds?: string[]; sessionIds?: string[] },+ options: SoftDeleteOptions,+): Promise<TopicItem[]> => {+ const conditions: SQL[] = [];+ if (parents.agentIds?.length) conditions.push(inArray(topics.agentId, parents.agentIds));+ if (parents.sessionIds?.length) conditions.push(inArray(topics.sessionId, parents.sessionIds));+ if (parents.groupIds?.length) conditions.push(inArray(topics.groupId, parents.groupIds));+ if (conditions.length === 0) return [];++ return ctx.db+ .update(topics)+ .set(trashStamp(options.deletedAt))+ .where(+ and(+ or(...conditions),+ options.restrictToCreator ? ctx.mine() : ctx.ownership(),+ ctx.notShareVisitor(),+ ),+ )+ .returning();+};++export const softDeleteAll = async (+ ctx: TopicModelContext,+ options: SoftDeleteOptions,+): Promise<TopicItem[]> => {+ return ctx.db+ .update(topics)+ .set(trashStamp(options.deletedAt))+ .where(and(ctx.mine(), ctx.notShareVisitor()))+ .returning();+};++/** Bring trashed topics back. Only rows currently stamped are touched. */+export const restore = async (ctx: TopicModelContext, ids: string[]): Promise<TopicItem[]> => {+ if (ids.length === 0) return [];+ return ctx.db+ .update(topics)+ .set(restoreStamp())+ .where(and(inArray(topics.id, ids), ctx.trashScope(), isTrashed(topics.isDeleted)))+ .returning();+};++/** Trashed rows by id, bypassing the recycle-bin filter (restore / purge internals). */+export const findTrashedByIds = async (+ ctx: TopicModelContext,+ ids: string[],+): Promise<TopicItem[]> => {+ if (ids.length === 0) return [];+ return ctx.db+ .select()+ .from(topics)+ .where(and(inArray(topics.id, ids), ctx.trashScope(), isTrashed(topics.isDeleted)));+};++/**+ * Hard delete for the purge sweep: bypasses the recycle-bin filter so a+ * trashed row (invisible to `delete`) can actually be removed. FK cascades+ * take messages, threads and the rest with it.+ */+export const purge = async (ctx: TopicModelContext, ids: string[]): Promise<string[]> => {+ if (ids.length === 0) return [];+ // Only rows still stamped: a restore that commits between the registry+ // read and this delete must win, not be hard-deleted as a stale purge.+ const rows = await ctx.db+ .delete(topics)+ .where(and(inArray(topics.id, ids), ctx.trashScope(), isTrashed(topics.isDeleted)))+ .returning({ id: topics.id });+ return rows.map((row) => row.id);+};diff --git a/packages/database/src/models/topic/types.ts b/packages/database/src/models/topic/types.tsnew file mode 100644index 00000000000..27592c35080--- /dev/null+++ b/packages/database/src/models/topic/types.ts@@ -0,0 +1,208 @@+import type { ChatTopicMetadata, ChatTopicStatus, TopicQuerySortBy } from '@lobechat/types';+import type { TimingSink } from '@lobechat/utils';++import { type TopicItem } from '../../schemas';++export type OnboardingSessionMetadataPatch = Partial<+ NonNullable<ChatTopicMetadata['onboardingSession']>+>;++export type RunningOperation = NonNullable<ChatTopicMetadata['runningOperation']>;++export type RunningOperationPatch = Omit<+ Partial<RunningOperation>,+ 'childOperations' | 'operationId'+>;++export type TopicMetadataPatch = Omit<Partial<ChatTopicMetadata>, 'onboardingSession'> & {+ onboardingSession?: OnboardingSessionMetadataPatch;+};++export interface SettleRunningOperationOptions {+ /**+ * Refuse to clear a marker whose operation row is still `running` /+ * `waiting_for_async_tool`. Set for client-reported settles, which can be+ * triggered by an early or mirrored terminal event.+ */+ rejectInFlightOperation?: boolean;+}++export interface TopicListItem extends TopicItem {+ /** The topic's last non-empty assistant reply, truncated with a trailing `β¦`. Only set when `queryTopics` is called with `withLastMessage`. */+ lastAssistantMessage?: string | null;+ /**+ * Visibility of the agent/group this topic belongs to β `'private'` marks a+ * conversation that must stay out of shared/team listings even though the+ * viewer may own it. Null for legacy rows with no resolvable parent.+ */+ parentVisibility?: 'private' | 'public' | null;+ /**+ * When the topic's current run started (`agent_operations.startedAt` of its+ * latest top-level running operation). Only computed for `running` topics;+ * null for everything else, and for runs that never wrote an operation row+ * (e.g. client-mode runs) β callers must keep a fallback.+ */+ runStartedAt?: Date | null;+}++/**+ * Sanitized projection of `topics.metadata.runningOperation` for a visitor DTO+ * β only the fields `useGatewayReconnect`'s `RunningOperation` needs to resume+ * a streaming session on reload. Never the full `runningOperation` object: it+ * also carries device/hetero fields (`deviceId`, `deviceUserId`, `hooks`, β¦)+ * that describe creator-side dispatch and must not reach a visitor.+ */+export interface VisitorRunningOperation {+ assistantMessageId: string;+ heteroType?: string | null;+ operationId: string;+ scope?: string;+ /** Liveness/elapsed-time stamp β see `useGatewayReconnect`'s `startedAt`. */+ startedAt?: string;+ threadId?: string | null;+}++/**+ * Visitor-facing topic DTO for the agent-share surface. Deliberately narrow:+ * the underlying row is CREATOR-owned and also carries the creator's userId,+ * model/provider snapshot, cost/usage and internal metadata.+ */+export interface VisitorTopicItem {+ createdAt: Date;+ id: string;+ /**+ * Sanitized `runningOperation` marker, present only while a run is active on+ * this topic. Lets the share surface reconnect a Gateway stream after a page+ * reload β see {@link VisitorRunningOperation} for why it's projected+ * instead of forwarding `topics.metadata.runningOperation` as-is.+ */+ runningOperation?: VisitorRunningOperation | null;+ title: string | null;+ updatedAt: Date;+}++export interface CreateTopicParams {+ agentId?: string | null;+ favorite?: boolean;+ groupId?: string | null;+ messages?: string[];+ metadata?: ChatTopicMetadata;+ /** Pinned model snapshot, persisted to the top-level `topics.model` column. */+ model?: string | null;+ /** Owning business project, independent of the execution directory. */+ projectId?: string | null;+ /** Project directory this conversation is pinned to as its execution context. */+ projectWorkingDirectoryId?: string | null;+ provider?: string | null;+ /**+ * Agent-share visitor topics carry the CREATOR's `userId` (billing/data+ * attribution) plus the visitor's id here, so creator-facing listings+ * exclude them (`notShareVisitorTopic`, applied by `query`, `count`,+ * `queryTopics`, `queryRecent` and `rank`) while the share surface scopes+ * reads per visitor (`queryBySender` / `countBySender`).+ *+ * A future opt-in surface (`allowCreatorViewSessions`) may let a creator+ * explicitly browse visitor sessions; that is not wired up yet β every+ * creator-facing read today unconditionally excludes senderId rows.+ */+ senderId?: string | null;+ sessionId?: string | null;+ /**+ * Initial status. Defaults to the column default (`active`). A topic created+ * with `metadata.scheduledRun` must set `scheduled` here so the status and the+ * payload land in the same insert β the dispatcher treats the pair as one fact.+ */+ status?: ChatTopicStatus;+ title?: string;+ trigger?: string | null;+}++export interface QueryTopicParams {+ agentId?: string | null;+ /**+ * @deprecated Use agentId or groupId instead. Kept for backward compatibility.+ * Container ID (sessionId or groupId) to filter topics by+ */+ containerId?: string | null;+ current?: number;+ /**+ * Restrict an `agentId` query to the builder conversations that configured+ * one specific target (`metadata.editingAgentId` / `metadata.editingGroupId`).+ *+ * Builder panels run on a single builtin agent shared by every target, whose+ * topics deliberately carry no `groupId` / `sessionId` β those columns mark a+ * topic as part of the target's own chat read path. The builder panel itself+ * shows the unfiltered history on purpose; these exist so a caller that wants+ * one target's builds can ask for them. Only meaningful alongside `agentId`;+ * ignored by the group / container branches.+ */+ editingAgentId?: string | null;+ editingGroupId?: string | null;+ /**+ * Exclude topics by status (e.g. ['completed'])+ */+ excludeStatuses?: string[];+ /**+ * Exclude topics by trigger types (e.g. ['cron'])+ * Ignored when includeTriggers is provided.+ */+ excludeTriggers?: string[];+ /**+ * Group ID to filter topics by+ */+ groupId?: string | null;+ /**+ * Include only topics whose trigger matches one of these values.+ * Takes precedence over excludeTriggers when provided.+ */+ includeTriggers?: string[];+ /**+ * Whether this is an inbox agent query.+ * When true, also includes legacy inbox topics (sessionId IS NULL AND groupId IS NULL AND agentId IS NULL)+ */+ isInbox?: boolean;+ pageSize?: number;+ /**+ * Server-side ordering. Defaults to `updatedAt`. `status` orders by status+ * priority (see `STATUS_SORT_RANK`) so the sidebar "group by status" mode+ * keeps high-priority topics on the first page.+ */+ sortBy?: TopicQuerySortBy;+ timing?: ModelTimingContext;+ /**+ * Include only topics matching the given trigger types (positive filter)+ */+ triggers?: string[];+ /**+ * When true, the SELECT also returns the heavier card-detail columns used+ * by the per-agent Topics management page: `firstUserMessage` (subquery),+ * `messageCount` (subquery), `description`, `trigger`. `cost` and+ * `tokenUsage` are intentionally omitted until a dedicated schema migration+ * adds real columns to back them. Defaults to false so sidebar paths stay+ * cheap.+ */+ withDetails?: boolean;+}++export interface ModelTimingContext extends TimingSink {}++/**+ * Scope used to constrain a keyword search to a single conversation owner.+ * Mirrors the precedence of {@link TopicModel.query}: groupId > agentId >+ * containerId (legacy sessionId / groupId).+ */+export interface TopicKeywordScope {+ agentId?: string | null;+ /**+ * @deprecated Use agentId or groupId instead. Only consulted when neither+ * agentId nor groupId is provided (legacy / mobile string-arg callers).+ * Container ID (sessionId or groupId) to filter topics by.+ */+ containerId?: string | null;+ groupId?: string | null;+}++export interface ListTopicsForMemoryExtractorCursor {+ createdAt: Date;+ id: string;+}diff --git a/packages/database/src/models/topic/update.ts b/packages/database/src/models/topic/update.tsnew file mode 100644index 00000000000..57e6ca07817--- /dev/null+++ b/packages/database/src/models/topic/update.ts@@ -0,0 +1,185 @@+import type { ChatTopicMetadata } from '@lobechat/types';+import { and, eq, or, sql } from 'drizzle-orm';++import { type TopicItem, topics } from '../../schemas';+import { recomputeTopicUsage } from '../topicUsage';+import type { TopicModelContext } from './context';+import type { TopicMetadataPatch } from './types';++export const update = async (ctx: TopicModelContext, id: string, data: Partial<TopicItem>) => {+ /**+ * Older clients switch models through the general update endpoint. Clear+ * the old model's reasoning pin in the same statement, comparing against+ * the persisted row so partial writes and concurrent switches stay safe.+ * Explicit metadata remains the caller's replacement snapshot.+ */+ const modelChanged = or(+ data.model !== undefined ? sql`${topics.model} is distinct from ${data.model}` : undefined,+ data.provider !== undefined+ ? sql`${topics.provider} is distinct from ${data.provider}`+ : undefined,+ );+ const persistedMetadata = modelChanged+ ? sql`case when ${modelChanged} then coalesce(${topics.metadata}, '{}'::jsonb) - 'reasoningConfig' else coalesce(${topics.metadata}, '{}'::jsonb) end`+ : sql`coalesce(${topics.metadata}, '{}'::jsonb)`;++ /**+ * A locally executed run β desktop heterogeneous CLI, in-browser runtime β+ * has no `agent_operations` row: its runtime lives in the client, and the+ * only thing it tells the server is this status write. Stamp when the run+ * claimed the topic in the same statement, so a list can show a live+ * elapsed clock for those runs the same way it does for server-side ones+ * (see `runStartedAtColumn` in {@link TopicModel.queryTopics}).+ *+ * Compared against the PERSISTED status so a resume out of+ * `waitingForHuman` β the same run, continuing after an approval β keeps+ * its original start instead of restarting the clock. The stamp is left+ * behind on terminal statuses: every reader gates on `status = 'running'`,+ * and the next run overwrites it.+ */+ const metadata =+ data.metadata !== undefined+ ? data.metadata+ : data.status === 'running'+ ? sql`case when ${topics.status} in ('running', 'waitingForHuman') then ${persistedMetadata} else jsonb_set(${persistedMetadata}, '{runStartedAt}', to_jsonb(now())) end`+ : modelChanged+ ? persistedMetadata+ : undefined;++ return ctx.db+ .update(topics)+ .set({ ...data, metadata, updatedAt: new Date() })+ .where(and(eq(topics.id, id), ctx.ownership()))+ .returning();+};++/**+ * Settle a topic out of `running` once its run has terminated server-side.+ *+ * Guarded on `status = 'running'` so it is race-tolerant with clients: an+ * attached renderer writes 'active' (focused) or 'unread' (backgrounded) on+ * the terminal stream event, and whichever write lands first wins β this one+ * degrades to a no-op instead of clobbering it. Without a server-side settle,+ * a run with no client attached (cron-dispatched scheduled resume, app closed+ * mid-run) leaves the topic at `running` forever.+ *+ * Returns the settled row, or nothing when the guard didn't match.+ */+export const settleRunningStatus = async (+ ctx: TopicModelContext,+ id: string,+ status: TopicItem['status'] = 'unread',+) => {+ return ctx.db+ .update(topics)+ .set({ status, updatedAt: new Date() })+ .where(and(eq(topics.id, id), eq(topics.status, 'running'), ctx.ownership()))+ .returning({ id: topics.id, status: topics.status });+};++/**+ * Recompute this topic's denormalized usage/cost rollup from its assistant+ * messages. The canonical aggregation lives in `recomputeTopicUsage`; the+ * live path (MessageModel) calls it inline within its own transaction, while+ * external callers use this wrapper. Runs in a transaction for consistency.+ */+export const recomputeUsage = async (ctx: TopicModelContext, id: string) =>+ ctx.db.transaction((trx) => recomputeTopicUsage(trx, ctx.userId, id, ctx.workspaceId));++/**+ * Update topic metadata with merge logic+ * This method merges new metadata with existing metadata instead of replacing it+ */+export const updateMetadata = async (+ ctx: TopicModelContext,+ id: string,+ metadata: TopicMetadataPatch,+) => {+ // Merge into the existing metadata under a row lock so concurrent writers+ // can't lose each other's keys. The old read-then-write was a non-atomic+ // read-modify-write: a hetero run seeds `metadata.runningOperation` while+ // heteroIngest concurrently writes `metadata.heteroCurrentMsgId`, and a write+ // built on a stale snapshot (interleaved read, or a read-replica that hadn't+ // caught up) silently dropped `runningOperation` β stranding the finished+ // task at `task_topics.status = 'running'` because heteroFinish then had no+ // hooks to deliver. `SELECT β¦ FOR UPDATE` forces a primary read + serializes+ // writers on the row, killing both the interleave and replica-lag variants+ // while preserving the exact (shallow + nested onboardingSession) merge.+ return ctx.db.transaction(async (tx) => {+ const [existing] = await tx+ .select({ metadata: topics.metadata })+ .from(topics)+ .where(and(eq(topics.id, id), ctx.ownership()))+ .for('update');++ // No row (missing or not owned) β nothing to update, mirror the old no-op.+ if (!existing) return [];++ const mergedOnboardingSession =+ existing.metadata?.onboardingSession && metadata.onboardingSession+ ? {+ ...existing.metadata.onboardingSession,+ ...metadata.onboardingSession,+ }+ : metadata.onboardingSession;++ const mergedMetadata = {+ ...existing.metadata,+ ...metadata,+ ...(mergedOnboardingSession && { onboardingSession: mergedOnboardingSession }),+ } as ChatTopicMetadata;++ return tx+ .update(topics)+ .set({ metadata: mergedMetadata })+ .where(and(eq(topics.id, id), ctx.ownership()))+ .returning();+ });+};++/**+ * Switch a topic's pinned model together with its model-scoped effort pin+ * (`metadata.reasoningConfig` / `metadata.heteroEffort`) in one row-locked+ * statement, so neither a concurrent switch nor an in-flight run can observe+ * the new model paired with the previous model's pin. `reasoningConfig` is+ * model-keyed and therefore always replaced (dropped when not provided);+ * `heteroEffort` and `heteroSpeed` are only touched when given.+ */+export const updateModelPin = async (+ ctx: TopicModelContext,+ id: string,+ {+ metadata,+ model,+ provider,+ }: {+ metadata?: Pick<ChatTopicMetadata, 'heteroEffort' | 'heteroSpeed' | 'reasoningConfig'>;+ model: string;+ provider: string;+ },+) =>+ ctx.db.transaction(async (tx) => {+ const [existing] = await tx+ .select({ metadata: topics.metadata })+ .from(topics)+ .where(and(eq(topics.id, id), ctx.ownership()))+ .for('update');++ if (!existing) return [];++ const { reasoningConfig: _stale, ...rest } = existing.metadata ?? {};+ const mergedMetadata: ChatTopicMetadata = {+ ...rest,+ ...(metadata?.heteroEffort !== undefined && { heteroEffort: metadata.heteroEffort }),+ ...(metadata?.heteroSpeed !== undefined && { heteroSpeed: metadata.heteroSpeed }),+ ...(metadata?.reasoningConfig !== undefined && {+ reasoningConfig: metadata.reasoningConfig,+ }),+ };++ return tx+ .update(topics)+ .set({ metadata: mergedMetadata, model, provider, updatedAt: new Date() })+ .where(and(eq(topics.id, id), ctx.ownership()))+ .returning();+ });diff --git a/packages/database/src/models/__tests__/topics/topic.create.test.ts b/packages/database/src/repositories/topic/__tests__/create.test.tssimilarity index 55%rename from packages/database/src/models/__tests__/topics/topic.create.test.tsrename to packages/database/src/repositories/topic/__tests__/create.test.tsindex f0842dbfd3f..75d9df6efd8 100644--- a/packages/database/src/models/__tests__/topics/topic.create.test.ts+++ b/packages/database/src/repositories/topic/__tests__/create.test.ts@@ -2,9 +2,11 @@ import { asc, eq, inArray } from 'drizzle-orm';import { afterEach, beforeEach, describe, expect, it } from 'vitest';import { getTestDB } from '../../../core/getTestDB';+import type { CreateTopicParams } from '../../../models/topic';+import { TopicModel } from '../../../models/topic';import {agents,- messagePlugins,+ chatGroups,messages,sessions,topics,@@ -12,16 +14,16 @@ import {workspaces,} from '../../../schemas';import type { LobeChatDatabase } from '../../../type';-import type { CreateTopicParams } from '../../topic';-import { TopicModel } from '../../topic';+import { TopicRepository } from '../index';const userId = 'topic-create-user';const userId2 = 'topic-create-user-2';const sessionId = 'topic-create-session';const serverDB: LobeChatDatabase = await getTestDB();const topicModel = new TopicModel(serverDB, userId);+const topicRepo = new TopicRepository(serverDB, userId);-describe('TopicModel - Create', () => {+describe('TopicRepository - create', () => {beforeEach(async () => {await serverDB.delete(users);await serverDB.transaction(async (tx) => {@@ -51,7 +53,7 @@ describe('TopicModel - Create', () => {{ id: 'message3', role: 'user', userId, sessionId },]);- const createdTopic = await topicModel.create(topicData, topicId);+ const createdTopic = await topicRepo.create(topicData, topicId);expect(createdTopic).toMatchObject({id: topicId,@@ -106,7 +108,7 @@ describe('TopicModel - Create', () => {it('should associate workspace messages created by another member', async () => {const workspaceId = 'topic-create-workspace';const workspaceSessionId = 'topic-create-workspace-session';- const workspaceTopicModel = new TopicModel(serverDB, userId, workspaceId);+ const workspaceTopicRepo = new TopicRepository(serverDB, userId, workspaceId);await serverDB.transaction(async (tx) => {await tx.insert(workspaces).values({@@ -129,7 +131,7 @@ describe('TopicModel - Create', () => {});});- const createdTopic = await workspaceTopicModel.create(+ const createdTopic = await workspaceTopicRepo.create({messages: ['workspace-message-other-member'],sessionId: workspaceSessionId,@@ -157,7 +159,7 @@ describe('TopicModel - Create', () => {const topicId = 'new-topic';const timingEvents: string[] = [];- const createdTopic = await topicModel.create(topicData, topicId, {+ const createdTopic = await topicRepo.create(topicData, topicId, {log: (event) => timingEvents.push(event),});@@ -212,7 +214,7 @@ describe('TopicModel - Create', () => {const topicId = 'topic-with-agent';- const createdTopic = await topicModel.create(topicData, topicId);+ const createdTopic = await topicRepo.create(topicData, topicId);expect(createdTopic.id).toBe(topicId);expect(createdTopic.title).toBe('Topic with Agent');@@ -235,11 +237,34 @@ describe('TopicModel - Create', () => {const topicId = 'agent-only-topic';- const createdTopic = await topicModel.create(topicData, topicId);+ const createdTopic = await topicRepo.create(topicData, topicId);expect(createdTopic.agentId).toBe('agent-only');expect(createdTopic.sessionId).toBeNull();});++ it('attaches given messages to the new topic in one transaction', async () => {+ await serverDB.insert(messages).values([+ { content: 'm1', id: 'msg-1', role: 'user', userId },+ { content: 'm2', id: 'msg-2', role: 'assistant', userId },+ ]);++ const topic = await topicRepo.create({ messages: ['msg-1', 'msg-2'], title: 'with msgs' });++ const linked = await serverDB+ .select({ id: messages.id, topicId: messages.topicId })+ .from(messages)+ .where(eq(messages.topicId, topic.id));++ expect(linked.map((m) => m.id).sort()).toEqual(['msg-1', 'msg-2']);+ });++ it('leaves TopicModel.create single-table: re-parenting messages there is refused', async () => {+ await expect(+ topicModel.create({ messages: ['msg-1'], title: 'model only' } as CreateTopicParams),+ ).rejects.toThrow('TopicRepository.create');+ expect(await serverDB.select().from(topics)).toHaveLength(0);+ });});describe('batchCreate', () => {@@ -254,7 +279,7 @@ describe('TopicModel - Create', () => {{ id: 'message3', role: 'user', userId },]);- const createdTopics = await topicModel.batchCreate(topicParams);+ const createdTopics = await topicRepo.batchCreate(topicParams);expect(createdTopics).toHaveLength(2);expect(createdTopics[0]).toMatchObject({@@ -285,7 +310,7 @@ describe('TopicModel - Create', () => {it('should batch associate workspace messages created by other members', async () => {const workspaceId = 'topic-batch-workspace';const workspaceSessionId = 'topic-batch-workspace-session';- const workspaceTopicModel = new TopicModel(serverDB, userId, workspaceId);+ const workspaceTopicRepo = new TopicRepository(serverDB, userId, workspaceId);await serverDB.transaction(async (tx) => {await tx.insert(workspaces).values({@@ -317,7 +342,7 @@ describe('TopicModel - Create', () => {]);});- const createdTopics = await workspaceTopicModel.batchCreate([+ const createdTopics = await workspaceTopicRepo.batchCreate([{messages: ['workspace-batch-message-1', 'workspace-batch-message-2'],sessionId: workspaceSessionId,@@ -344,7 +369,7 @@ describe('TopicModel - Create', () => {{ title: 'Topic 2', favorite: false, sessionId },];- const createdTopics = await topicModel.batchCreate(topicParams);+ const createdTopics = await topicRepo.batchCreate(topicParams);expect(createdTopics[0].id).toBeDefined();expect(createdTopics[1].id).toBeDefined();@@ -362,7 +387,7 @@ describe('TopicModel - Create', () => {{ title: 'Topic with Agent 2', favorite: false, agentId: 'batch-agent-2' },];- const createdTopics = await topicModel.batchCreate(topicParams);+ const createdTopics = await topicRepo.batchCreate(topicParams);expect(createdTopics).toHaveLength(2);expect(createdTopics[0].agentId).toBe('batch-agent-1');@@ -383,253 +408,41 @@ describe('TopicModel - Create', () => {expect(dbTopics.find((t) => t.id === createdTopics[0].id)?.agentId).toBe('batch-agent-1');expect(dbTopics.find((t) => t.id === createdTopics[1].id)?.agentId).toBe('batch-agent-2');});- });-- describe('duplicate', () => {- it('should duplicate a topic and its associated messages', async () => {- const topicId = 'topic-duplicate';- const newTitle = 'Duplicated Topic';-- await serverDB.transaction(async (tx) => {- await tx.insert(topics).values({ id: topicId, sessionId, userId, title: 'Original Topic' });- // Distinct createdAt so `duplicate`'s `orderBy(createdAt)` is- // deterministic β inserting both in one tx would otherwise give them the- // same `now()` default, leaving the tied rows in arbitrary order.- await tx.insert(messages).values([- {- id: 'message1',- role: 'user',- topicId,- userId,- content: 'User message',- createdAt: new Date('2024-01-01T00:00:00Z'),- },- {- id: 'message2',- role: 'assistant',- topicId,- userId,- content: 'Assistant message',- createdAt: new Date('2024-01-01T00:00:01Z'),- },- ]);- });-- const { topic: duplicatedTopic, messages: duplicatedMessages } = await topicModel.duplicate(- topicId,- newTitle,- );-- expect(duplicatedTopic.id).not.toBe(topicId);- expect(duplicatedTopic.title).toBe(newTitle);- expect(duplicatedTopic.sessionId).toBe(sessionId);- expect(duplicatedTopic.userId).toBe(userId);-- expect(duplicatedMessages).toHaveLength(2);- expect(duplicatedMessages[0].id).not.toBe('message1');- expect(duplicatedMessages[0].topicId).toBe(duplicatedTopic.id);- expect(duplicatedMessages[0].content).toBe('User message');- expect(duplicatedMessages[1].id).not.toBe('message2');- expect(duplicatedMessages[1].topicId).toBe(duplicatedTopic.id);- expect(duplicatedMessages[1].content).toBe('Assistant message');- });-- it('should duplicate workspace messages created by other members', async () => {- const workspaceId = 'topic-duplicate-workspace';- const topicId = 'workspace-topic-duplicate';- const workspaceTopicModel = new TopicModel(serverDB, userId, workspaceId);-- await serverDB.transaction(async (tx) => {- await tx.insert(workspaces).values({- id: workspaceId,- name: 'Topic Duplicate Workspace',- primaryOwnerId: userId,- slug: workspaceId,- });- await tx.insert(topics).values({- id: topicId,- title: 'Workspace Original Topic',- userId: userId2,- workspaceId,- });- await tx.insert(messages).values([- {- content: 'Other member user message',- id: 'workspace-duplicate-message-1',- role: 'user',- topicId,- userId: userId2,- workspaceId,- },- {- content: 'Current member assistant message',- id: 'workspace-duplicate-message-2',- role: 'assistant',- topicId,- userId,- workspaceId,- },- ]);- });- const { topic: duplicatedTopic, messages: duplicatedMessages } =- await workspaceTopicModel.duplicate(topicId, 'Workspace Duplicated Topic');+ it('keeps a session topic session-scoped and a group topic group-scoped', async () => {+ await serverDB.insert(agents).values({ id: 'agent-b', userId });+ await serverDB.insert(sessions).values({ id: 'session-x', userId });+ await serverDB.insert(chatGroups).values({ id: 'group-b', userId });- expect(duplicatedTopic.workspaceId).toBe(workspaceId);- expect(duplicatedMessages).toHaveLength(2);- expect(duplicatedMessages.map((message) => message.content).sort()).toEqual([- 'Current member assistant message',- 'Other member user message',+ const created = await topicRepo.batchCreate([+ { agentId: 'agent-b', sessionId: 'session-x', title: 'session topic' },+ { groupId: 'group-b', title: 'group topic' },]);- expect(duplicatedMessages.every((message) => message.workspaceId === workspaceId)).toBe(true);- });-- it('should correctly map parentId references when duplicating messages', async () => {- const topicId = 'topic-with-parent-refs';-- await serverDB.transaction(async (tx) => {- await tx.insert(topics).values({ id: topicId, sessionId, userId, title: 'Original Topic' });- await tx.insert(messages).values([- { id: 'msg1', role: 'user', topicId, userId, content: 'First message', parentId: null },- {- id: 'msg2',- role: 'assistant',- topicId,- userId,- content: 'Reply to first',- parentId: 'msg1',- },- {- id: 'msg3',- role: 'tool',- topicId,- userId,- content: 'Tool response',- parentId: 'msg2',- },- {- id: 'msg4',- role: 'assistant',- topicId,- userId,- content: 'Final message',- parentId: 'msg3',- },- ]);- });-- const { topic: duplicatedTopic, messages: duplicatedMessages } = await topicModel.duplicate(- topicId,- 'Duplicated Topic',- );-- expect(duplicatedMessages).toHaveLength(4);-- const msgMap = new Map(duplicatedMessages.map((m) => [m.content, m]));- const newMsg1 = msgMap.get('First message')!;- const newMsg2 = msgMap.get('Reply to first')!;- const newMsg3 = msgMap.get('Tool response')!;- const newMsg4 = msgMap.get('Final message')!;-- expect(newMsg1.parentId).toBeNull();- expect(newMsg2.parentId).toBe(newMsg1.id);- expect(newMsg3.parentId).toBe(newMsg2.id);- expect(newMsg4.parentId).toBe(newMsg3.id);-- expect(newMsg1.id).not.toBe('msg1');- expect(newMsg2.id).not.toBe('msg2');- expect(newMsg3.id).not.toBe('msg3');- expect(newMsg4.id).not.toBe('msg4');- });-- it('should correctly map tool_call_id when duplicating messages with tools', async () => {- const topicId = 'topic-with-tools';- const originalToolId = 'toolu_original_123';- await serverDB.transaction(async (tx) => {- await tx.insert(topics).values({ id: topicId, sessionId, userId, title: 'Original Topic' });-- // Insert assistant message with tools- await tx.insert(messages).values({- id: 'msg1',- role: 'assistant',- topicId,- userId,- content: 'Using tool',- parentId: null,- tools: [{ id: originalToolId, type: 'builtin', apiName: 'broadcast' }],- });-- // Insert tool message- await tx.insert(messages).values({- id: 'msg2',- role: 'tool',- topicId,- userId,- content: 'Tool response',- parentId: 'msg1',- });-- // Insert messagePlugins entry- await tx.insert(messagePlugins).values({- id: 'msg2',- userId,- toolCallId: originalToolId,- apiName: 'broadcast',- });- });+ const bySession = created.find((t) => t.title === 'session topic')!;+ const byGroup = created.find((t) => t.title === 'group topic')!;- const { topic: duplicatedTopic, messages: duplicatedMessages } = await topicModel.duplicate(- topicId,- 'Duplicated Topic',- );-- expect(duplicatedMessages).toHaveLength(2);-- const msgMap = new Map(duplicatedMessages.map((m) => [m.role, m]));- const newAssistant = msgMap.get('assistant')!;- const newTool = msgMap.get('tool')!;-- // Check that tools array has new IDs- expect(newAssistant.tools).toBeDefined();- const newTools = newAssistant.tools as any[];- expect(newTools).toHaveLength(1);- expect(newTools[0].id).not.toBe(originalToolId);- expect(newTools[0].id).toMatch(/^toolu_/);+ // sessionId given (no groupId) β sessionId kept, groupId stays null+ expect(bySession.sessionId).toBe('session-x');+ expect(bySession.groupId).toBeNull();- // Check that messagePlugins was copied with new toolCallId- const newPlugin = await serverDB.query.messagePlugins.findFirst({- where: eq(messagePlugins.id, newTool.id),- });-- expect(newPlugin).toBeDefined();- expect(newPlugin!.toolCallId).toBe(newTools[0].id);- expect(newPlugin!.toolCallId).not.toBe(originalToolId);+ // groupId given (no sessionId) β groupId kept, sessionId stays null+ expect(byGroup.groupId).toBe('group-b');+ expect(byGroup.sessionId).toBeNull();});- it('should throw an error if the topic to duplicate does not exist', async () => {- const topicId = 'nonexistent-topic';+ it('drops both owner ids when sessionId and groupId are passed together', async () => {+ await serverDB.insert(sessions).values({ id: 'session-both', userId });+ await serverDB.insert(chatGroups).values({ id: 'group-both', userId });- await expect(topicModel.duplicate(topicId)).rejects.toThrow(- `Topic with id ${topicId} not found`,- );- });-- it('should duplicate a topic with no messages (empty messageIds)', async () => {- const topicId = 'topic-no-messages';-- await serverDB- .insert(topics)- .values({ id: topicId, sessionId, userId, title: 'Empty Topic' });-- const { topic: duplicated, messages: duplicatedMessages } = await topicModel.duplicate(- topicId,- 'Duplicated Empty',- );+ // Each field is nulled based on the *other* being present, so passing both+ // detaches the topic from both β callers must pick exactly one.+ const [created] = await topicRepo.batchCreate([+ { groupId: 'group-both', sessionId: 'session-both', title: 'ambiguous' },+ ]);- expect(duplicated.id).not.toBe(topicId);- expect(duplicated.title).toBe('Duplicated Empty');- expect(duplicatedMessages).toHaveLength(0);+ expect(created.sessionId).toBeNull();+ expect(created.groupId).toBeNull();});});});diff --git a/packages/database/src/repositories/topic/__tests__/duplicate.test.ts b/packages/database/src/repositories/topic/__tests__/duplicate.test.tsnew file mode 100644index 00000000000..9a6b98ac743--- /dev/null+++ b/packages/database/src/repositories/topic/__tests__/duplicate.test.ts@@ -0,0 +1,476 @@+import { eq } from 'drizzle-orm';+import { afterEach, beforeEach, describe, expect, it } from 'vitest';++import { getTestDB } from '../../../core/getTestDB';+import { TopicModel } from '../../../models/topic';+import { messagePlugins, messages, sessions, topics, users, workspaces } from '../../../schemas';+import type { LobeChatDatabase } from '../../../type';+import { TopicRepository } from '../index';++const userId = 'topic-duplicate-user';+const userId2 = 'topic-duplicate-user-2';+const sessionId = 'topic-create-session';+const serverDB: LobeChatDatabase = await getTestDB();+const topicModel = new TopicModel(serverDB, userId);+const topicRepo = new TopicRepository(serverDB, userId);++describe('TopicRepository - duplicate', () => {+ beforeEach(async () => {+ await serverDB.delete(users);+ await serverDB.transaction(async (tx) => {+ await tx.insert(users).values([{ id: userId }, { id: userId2 }]);+ await tx.insert(sessions).values({ id: sessionId, userId });+ });+ });++ afterEach(async () => {+ await serverDB.delete(users);+ });++ describe('duplicate', () => {+ it('should duplicate a topic and its associated messages', async () => {+ const topicId = 'topic-duplicate';+ const newTitle = 'Duplicated Topic';++ await serverDB.transaction(async (tx) => {+ await tx.insert(topics).values({ id: topicId, sessionId, userId, title: 'Original Topic' });+ // Distinct createdAt so `duplicate`'s `orderBy(createdAt)` is+ // deterministic β inserting both in one tx would otherwise give them the+ // same `now()` default, leaving the tied rows in arbitrary order.+ await tx.insert(messages).values([+ {+ id: 'message1',+ role: 'user',+ topicId,+ userId,+ content: 'User message',+ createdAt: new Date('2024-01-01T00:00:00Z'),+ },+ {+ id: 'message2',+ role: 'assistant',+ topicId,+ userId,+ content: 'Assistant message',+ createdAt: new Date('2024-01-01T00:00:01Z'),+ },+ ]);+ });++ const { topic: duplicatedTopic, messages: duplicatedMessages } = await topicRepo.duplicate(+ topicId,+ newTitle,+ );++ expect(duplicatedTopic.id).not.toBe(topicId);+ expect(duplicatedTopic.title).toBe(newTitle);+ expect(duplicatedTopic.sessionId).toBe(sessionId);+ expect(duplicatedTopic.userId).toBe(userId);++ expect(duplicatedMessages).toHaveLength(2);+ expect(duplicatedMessages[0].id).not.toBe('message1');+ expect(duplicatedMessages[0].topicId).toBe(duplicatedTopic.id);+ expect(duplicatedMessages[0].content).toBe('User message');+ expect(duplicatedMessages[1].id).not.toBe('message2');+ expect(duplicatedMessages[1].topicId).toBe(duplicatedTopic.id);+ expect(duplicatedMessages[1].content).toBe('Assistant message');+ });++ it('should duplicate workspace messages created by other members', async () => {+ const workspaceId = 'topic-duplicate-workspace';+ const topicId = 'workspace-topic-duplicate';+ const workspaceTopicRepo = new TopicRepository(serverDB, userId, workspaceId);++ await serverDB.transaction(async (tx) => {+ await tx.insert(workspaces).values({+ id: workspaceId,+ name: 'Topic Duplicate Workspace',+ primaryOwnerId: userId,+ slug: workspaceId,+ });+ await tx.insert(topics).values({+ id: topicId,+ title: 'Workspace Original Topic',+ userId: userId2,+ workspaceId,+ });+ await tx.insert(messages).values([+ {+ content: 'Other member user message',+ id: 'workspace-duplicate-message-1',+ role: 'user',+ topicId,+ userId: userId2,+ workspaceId,+ },+ {+ content: 'Current member assistant message',+ id: 'workspace-duplicate-message-2',+ role: 'assistant',+ topicId,+ userId,+ workspaceId,+ },+ ]);+ });++ const { topic: duplicatedTopic, messages: duplicatedMessages } =+ await workspaceTopicRepo.duplicate(topicId, 'Workspace Duplicated Topic');++ expect(duplicatedTopic.workspaceId).toBe(workspaceId);+ expect(duplicatedMessages).toHaveLength(2);+ expect(duplicatedMessages.map((message) => message.content).sort()).toEqual([+ 'Current member assistant message',+ 'Other member user message',+ ]);+ expect(duplicatedMessages.every((message) => message.workspaceId === workspaceId)).toBe(true);+ });++ it('should correctly map parentId references when duplicating messages', async () => {+ const topicId = 'topic-with-parent-refs';++ await serverDB.transaction(async (tx) => {+ await tx.insert(topics).values({ id: topicId, sessionId, userId, title: 'Original Topic' });+ await tx.insert(messages).values([+ { id: 'msg1', role: 'user', topicId, userId, content: 'First message', parentId: null },+ {+ id: 'msg2',+ role: 'assistant',+ topicId,+ userId,+ content: 'Reply to first',+ parentId: 'msg1',+ },+ {+ id: 'msg3',+ role: 'tool',+ topicId,+ userId,+ content: 'Tool response',+ parentId: 'msg2',+ },+ {+ id: 'msg4',+ role: 'assistant',+ topicId,+ userId,+ content: 'Final message',+ parentId: 'msg3',+ },+ ]);+ });++ const { messages: duplicatedMessages } = await topicRepo.duplicate(+ topicId,+ 'Duplicated Topic',+ );++ expect(duplicatedMessages).toHaveLength(4);++ const msgMap = new Map(duplicatedMessages.map((m) => [m.content, m]));+ const newMsg1 = msgMap.get('First message')!;+ const newMsg2 = msgMap.get('Reply to first')!;+ const newMsg3 = msgMap.get('Tool response')!;+ const newMsg4 = msgMap.get('Final message')!;++ expect(newMsg1.parentId).toBeNull();+ expect(newMsg2.parentId).toBe(newMsg1.id);+ expect(newMsg3.parentId).toBe(newMsg2.id);+ expect(newMsg4.parentId).toBe(newMsg3.id);++ expect(newMsg1.id).not.toBe('msg1');+ expect(newMsg2.id).not.toBe('msg2');+ expect(newMsg3.id).not.toBe('msg3');+ expect(newMsg4.id).not.toBe('msg4');+ });++ it('should correctly map tool_call_id when duplicating messages with tools', async () => {+ const topicId = 'topic-with-tools';+ const originalToolId = 'toolu_original_123';++ await serverDB.transaction(async (tx) => {+ await tx.insert(topics).values({ id: topicId, sessionId, userId, title: 'Original Topic' });++ // Insert assistant message with tools+ await tx.insert(messages).values({+ id: 'msg1',+ role: 'assistant',+ topicId,+ userId,+ content: 'Using tool',+ parentId: null,+ tools: [{ id: originalToolId, type: 'builtin', apiName: 'broadcast' }],+ });++ // Insert tool message+ await tx.insert(messages).values({+ id: 'msg2',+ role: 'tool',+ topicId,+ userId,+ content: 'Tool response',+ parentId: 'msg1',+ });++ // Insert messagePlugins entry+ await tx.insert(messagePlugins).values({+ id: 'msg2',+ userId,+ toolCallId: originalToolId,+ apiName: 'broadcast',+ });+ });++ const { messages: duplicatedMessages } = await topicRepo.duplicate(+ topicId,+ 'Duplicated Topic',+ );++ expect(duplicatedMessages).toHaveLength(2);++ const msgMap = new Map(duplicatedMessages.map((m) => [m.role, m]));+ const newAssistant = msgMap.get('assistant')!;+ const newTool = msgMap.get('tool')!;++ // Check that tools array has new IDs+ expect(newAssistant.tools).toBeDefined();+ const newTools = newAssistant.tools as any[];+ expect(newTools).toHaveLength(1);+ expect(newTools[0].id).not.toBe(originalToolId);+ expect(newTools[0].id).toMatch(/^toolu_/);++ // Check that messagePlugins was copied with new toolCallId+ const newPlugin = await serverDB.query.messagePlugins.findFirst({+ where: eq(messagePlugins.id, newTool.id),+ });++ expect(newPlugin).toBeDefined();+ expect(newPlugin!.toolCallId).toBe(newTools[0].id);+ expect(newPlugin!.toolCallId).not.toBe(originalToolId);+ });++ it('should throw an error if the topic to duplicate does not exist', async () => {+ const topicId = 'nonexistent-topic';++ await expect(topicRepo.duplicate(topicId)).rejects.toThrow(+ `Topic with id ${topicId} not found`,+ );+ });++ it('should duplicate a topic with no messages (empty messageIds)', async () => {+ const topicId = 'topic-no-messages';++ await serverDB+ .insert(topics)+ .values({ id: topicId, sessionId, userId, title: 'Empty Topic' });++ const { topic: duplicated, messages: duplicatedMessages } = await topicRepo.duplicate(+ topicId,+ 'Duplicated Empty',+ );++ expect(duplicated.id).not.toBe(topicId);+ expect(duplicated.title).toBe('Duplicated Empty');+ expect(duplicatedMessages).toHaveLength(0);+ });+ });++ describe('duplicate', () => {+ it('copies the topic and its messages under a new id', async () => {+ const topic = await topicModel.create({ title: 'original' });+ await serverDB.insert(messages).values([+ { content: 'hi', id: 'dup-m1', role: 'user', topicId: topic.id, userId },+ { content: 'yo', id: 'dup-m2', role: 'assistant', topicId: topic.id, userId },+ ]);++ const { topic: cloned, messages: clonedMessages } = await topicRepo.duplicate(+ topic.id,+ 'copy',+ );++ expect(cloned.id).not.toBe(topic.id);+ expect(cloned.title).toBe('copy');+ expect(clonedMessages).toHaveLength(2);+ expect(clonedMessages.every((m) => m.topicId === cloned.id)).toBe(true);+ expect(clonedMessages.map((m) => m.id)).not.toContain('dup-m1');+ });++ it('marks duplicated messages and resets the topic-level rollups', async () => {+ const usage = { cost: 0.05, totalInputTokens: 100, totalOutputTokens: 50 };+ const topic = await topicModel.create({ title: 'billed' });+ await serverDB+ .update(topics)+ .set({ totalCost: '0.05' as any, totalTokens: 150 })+ .where(eq(topics.id, topic.id));+ await serverDB.insert(messages).values([+ {+ content: 'answer',+ id: 'dup-billed',+ metadata: { performance: { tps: 42 }, usage },+ role: 'assistant',+ topicId: topic.id,+ usage,+ userId,+ },+ ]);++ const { topic: cloned, messages: clonedMessages } = await topicRepo.duplicate(topic.id);++ // per-message figures are transcript facts and survive the copy...+ const clone = clonedMessages[0];+ expect(clone.usage).toEqual(usage);+ const metadata = clone.metadata as Record<string, unknown>;+ expect(metadata.usage).toEqual(usage);+ expect(metadata.performance).toEqual({ tps: 42 });+ // ...but the row is marked, so usage reports skip it+ expect(metadata.copied).toBe(true);++ // the topic rollup answers "what did this topic cost this scope", and a+ // fresh duplicate has spent nothing yet+ const clonedTopic = await serverDB.query.topics.findFirst({+ where: (t, { eq: is }) => is(t.id, cloned.id),+ });+ expect(clonedTopic?.totalCost).toBeNull();+ expect(clonedTopic?.totalTokens).toBeNull();+ });++ it('throws when the source topic does not exist', async () => {+ await expect(topicRepo.duplicate('nope')).rejects.toThrow('not found');+ });++ it('copies only the ancestor chain when forking up to a message', async () => {+ const topic = await topicModel.create({ title: 'fork source' });+ await serverDB.insert(messages).values([+ { content: 'q1', id: 'fork-m1', role: 'user', topicId: topic.id, userId },+ {+ content: 'a1',+ id: 'fork-m2',+ parentId: 'fork-m1',+ role: 'assistant',+ topicId: topic.id,+ userId,+ },+ {+ content: 'q2',+ id: 'fork-m3',+ parentId: 'fork-m2',+ role: 'user',+ topicId: topic.id,+ userId,+ },+ ]);++ const { topic: forked, messages: forkedMessages } = await topicRepo.duplicate(+ topic.id,+ 'forked',+ { upToMessageId: 'fork-m2' },+ );++ // only the selected prefix is copied, in root β selected order+ expect(forkedMessages.map((m) => m.content)).toEqual(['q1', 'a1']);+ expect(forkedMessages.every((m) => m.topicId === forked.id)).toBe(true);++ // the chain is re-parented inside the fork: root stays root, child points at the copy+ const [root, child] = forkedMessages;+ expect(root.parentId).toBeNull();+ expect(child.parentId).toBe(root.id);++ // the unselected tail stays behind in the source topic+ const sourceMessages = await serverDB+ .select()+ .from(messages)+ .where(eq(messages.topicId, topic.id));+ expect(sourceMessages.map((m) => m.id).sort()).toEqual(['fork-m1', 'fork-m2', 'fork-m3']);+ });++ it('leaves sibling branches out of the fork', async () => {+ const topic = await topicModel.create({ title: 'branched source' });+ await serverDB.insert(messages).values([+ { content: 'q1', id: 'br-m1', role: 'user', topicId: topic.id, userId },+ {+ content: 'draft',+ id: 'br-m2a',+ parentId: 'br-m1',+ role: 'assistant',+ topicId: topic.id,+ userId,+ },+ {+ content: 'regenerated',+ id: 'br-m2b',+ parentId: 'br-m1',+ role: 'assistant',+ topicId: topic.id,+ userId,+ },+ ]);++ const { messages: forkedMessages } = await topicRepo.duplicate(topic.id, 'forked', {+ upToMessageId: 'br-m2b',+ });++ expect(forkedMessages.map((m) => m.content)).toEqual(['q1', 'regenerated']);+ });++ it('throws when the fork anchor message is not in the topic', async () => {+ const topic = await topicModel.create({ title: 'no anchor' });++ await expect(+ topicRepo.duplicate(topic.id, 'forked', { upToMessageId: 'missing' }),+ ).rejects.toThrow('not found in topic');+ });++ it('stamps the copy with fresh activity time instead of inheriting the source date', async () => {+ const sourceDate = new Date('2020-01-02T03:04:05Z');+ const topic = await topicModel.create({ title: 'stale source' });+ await serverDB.insert(messages).values([+ {+ content: 'old q',+ createdAt: sourceDate,+ id: 'stale-m1',+ role: 'user',+ topicId: topic.id,+ updatedAt: sourceDate,+ userId,+ },+ {+ content: 'old a',+ createdAt: new Date(sourceDate.getTime() + 1000),+ id: 'stale-m2',+ parentId: 'stale-m1',+ role: 'assistant',+ topicId: topic.id,+ updatedAt: new Date(sourceDate.getTime() + 1000),+ userId,+ },+ ]);++ const before = Date.now();+ const { topic: cloned, messages: clonedMessages } = await topicRepo.duplicate(+ topic.id,+ 'fresh copy',+ { upToMessageId: 'stale-m2' },+ );++ // A copy is new activity: its own row and every copied message carry the+ // copy moment. The sidebar keys topics by the newest message activity, so+ // inheriting the source's 2020 timestamps would re-file the copy under the+ // source's date group instead of today.+ expect(new Date(cloned.createdAt).getTime()).toBeGreaterThanOrEqual(before - 1000);+ for (const message of clonedMessages) {+ expect(new Date(message.updatedAt).getTime()).toBeGreaterThanOrEqual(before - 1000);+ }++ // The retained order survives retiming: rows still increase root β leaf.+ const [root, child] = clonedMessages;+ expect(new Date(root.createdAt).getTime()).toBeLessThan(new Date(child.createdAt).getTime());++ // The source keeps its own timestamps untouched.+ const sourceMessages = await serverDB+ .select()+ .from(messages)+ .where(eq(messages.topicId, topic.id));+ expect(sourceMessages.every((m) => new Date(m.updatedAt).getTime() < before)).toBe(true);+ });+ });+});diff --git a/packages/database/src/models/__tests__/topics/topic.move.test.ts b/packages/database/src/repositories/topic/__tests__/move.test.tssimilarity index 77%rename from packages/database/src/models/__tests__/topics/topic.move.test.tsrename to packages/database/src/repositories/topic/__tests__/move.test.tsindex 44f0cfe2de0..2306b15d7cc 100644--- a/packages/database/src/models/__tests__/topics/topic.move.test.ts+++ b/packages/database/src/repositories/topic/__tests__/move.test.ts@@ -4,14 +4,14 @@ import { afterEach, beforeEach, describe, expect, it } from 'vitest';import { getTestDB } from '../../../core/getTestDB';import { agents, messages, sessions, threads, topics, users } from '../../../schemas';import type { LobeChatDatabase } from '../../../type';-import { TopicModel } from '../../topic';+import { TopicRepository } from '../index';const userId = 'topic-move-user';const otherUserId = 'topic-move-user-2';const serverDB: LobeChatDatabase = await getTestDB();-const topicModel = new TopicModel(serverDB, userId);+const topicRepo = new TopicRepository(serverDB, userId);-describe('TopicModel - batchMoveToAgent', () => {+describe('TopicRepository - batchMoveToAgent', () => {beforeEach(async () => {await serverDB.delete(users);await serverDB.transaction(async (tx) => {@@ -42,7 +42,7 @@ describe('TopicModel - batchMoveToAgent', () => {]);});- await topicModel.batchMoveToAgent(['topic-1', 'topic-2'], 'target-agent');+ await topicRepo.batchMoveToAgent(['topic-1', 'topic-2'], 'target-agent');const movedTopics = await serverDB.select()@@ -89,7 +89,7 @@ describe('TopicModel - batchMoveToAgent', () => {]);});- await topicModel.batchMoveToAgent(['topic-t'], 'target-agent');+ await topicRepo.batchMoveToAgent(['topic-t'], 'target-agent');// Thread under the moved topic follows the topic to the target agent β// critical because threads.agentId is a cascade-on-delete FK.@@ -119,7 +119,7 @@ describe('TopicModel - batchMoveToAgent', () => {]);});- await topicModel.batchMoveToAgent(['topic-s'], 'target-agent');+ await topicRepo.batchMoveToAgent(['topic-s'], 'target-agent');const [topic] = await serverDB.select().from(topics).where(eq(topics.id, 'topic-s'));expect(topic.agentId).toBe('target-agent');@@ -149,7 +149,7 @@ describe('TopicModel - batchMoveToAgent', () => {]);});- await topicModel.batchMoveToAgent(['mine', 'theirs'], 'target-agent');+ await topicRepo.batchMoveToAgent(['mine', 'theirs'], 'target-agent');const [theirTopic] = await serverDB.select().from(topics).where(eq(topics.id, 'theirs'));expect(theirTopic.agentId).toBe('source-agent');@@ -174,7 +174,7 @@ describe('TopicModel - batchMoveToAgent', () => {]);});- await expect(topicModel.batchMoveToAgent(['topic-x'], 'foreign-agent')).rejects.toThrow();+ await expect(topicRepo.batchMoveToAgent(['topic-x'], 'foreign-agent')).rejects.toThrow();// Transaction rolled back β topic and message still point at the source agent.const [topic] = await serverDB.select().from(topics).where(eq(topics.id, 'topic-x'));@@ -187,9 +187,53 @@ describe('TopicModel - batchMoveToAgent', () => {it('is a no-op when given an empty topic list', async () => {await serverDB.insert(topics).values([{ id: 'topic-noop', userId, agentId: 'source-agent' }]);- await topicModel.batchMoveToAgent([], 'target-agent');+ await topicRepo.batchMoveToAgent([], 'target-agent');const [topic] = await serverDB.select().from(topics).where(eq(topics.id, 'topic-noop'));expect(topic.agentId).toBe('source-agent');});++ it('reassigns agentId, clears sessionId, and moves child messages', async () => {+ await serverDB.insert(agents).values([+ { id: 'agent-src', userId },+ { id: 'agent-dst', userId },+ ]);+ await serverDB.insert(topics).values({+ agentId: 'agent-src',+ id: 'move-1',+ sessionId: null,+ title: 'movable',+ userId,+ });+ await serverDB.insert(messages).values({+ agentId: 'agent-src',+ content: 'm',+ id: 'move-msg',+ role: 'user',+ topicId: 'move-1',+ userId,+ });++ await topicRepo.batchMoveToAgent(['move-1'], 'agent-dst');++ const [topic] = await serverDB.select().from(topics).where(eq(topics.id, 'move-1'));+ expect(topic.agentId).toBe('agent-dst');+ expect(topic.sessionId).toBeNull();++ const [msg] = await serverDB.select().from(messages).where(eq(messages.id, 'move-msg'));+ expect(msg.agentId).toBe('agent-dst');+ });++ it('throws when the target agent is not accessible', async () => {+ await serverDB.insert(agents).values({ id: 'agent-foreign', userId: otherUserId });+ await serverDB.insert(topics).values({ id: 'move-x', title: 'x', userId });++ await expect(topicRepo.batchMoveToAgent(['move-x'], 'agent-foreign')).rejects.toThrow(+ 'not found or not accessible',+ );+ });++ it('is a no-op for an empty id list', async () => {+ await expect(topicRepo.batchMoveToAgent([], 'whatever')).resolves.toBeUndefined();+ });});diff --git a/packages/database/src/repositories/topic/create.ts b/packages/database/src/repositories/topic/create.tsnew file mode 100644index 00000000000..302f7676ab6--- /dev/null+++ b/packages/database/src/repositories/topic/create.ts@@ -0,0 +1,96 @@+import { runTimedSinkStage as runTimedStage } from '@lobechat/utils';+import { and, inArray } from 'drizzle-orm';+import pMap from 'p-map';++import { type CreateTopicParams, type ModelTimingContext, TopicModel } from '../../models/topic';+import { messages, type TopicItem } from '../../schemas';+import type { LobeChatDatabase } from '../../type';+import { messageOwnership, type TopicRepositoryScope } from './scope';++/** Bounds the per-topic message re-parenting fan-out inside one transaction. */+const BATCH_CREATE_MESSAGE_UPDATE_CONCURRENCY = 5;++const topicModelFor = (scope: TopicRepositoryScope, db: LobeChatDatabase = scope.db) =>+ new TopicModel(db, scope.userId, scope.workspaceId);++const reparentMessages = (+ db: LobeChatDatabase,+ scope: TopicRepositoryScope,+ topicId: string,+ messageIds: string[],+) =>+ db+ .update(messages)+ .set({ topicId })+ .where(and(messageOwnership(scope), inArray(messages.id, messageIds)));++/**+ * Creates a topic and, when `messages` is given, re-parents those existing+ * messages onto it in the same transaction.+ *+ * Without messages this is a single-table insert ({@link TopicModel.create}) and+ * opens no transaction.+ */+export const createTopic = async (+ scope: TopicRepositoryScope,+ { messages: messageIds, ...params }: CreateTopicParams,+ id?: string,+ timing?: ModelTimingContext,+): Promise<TopicItem> => {+ if (!messageIds || messageIds.length === 0) {+ return topicModelFor(scope).create(params, id, timing);+ }++ return runTimedStage(+ timing,+ 'db.topic.create.transaction',+ () =>+ scope.db.transaction(async (tx) => {+ const trx = tx as unknown as LobeChatDatabase;+ const topic = await topicModelFor(scope, trx).create(params, id, timing);++ await runTimedStage(+ timing,+ 'db.topic.create.messages.updateTopic',+ () => reparentMessages(trx, scope, topic.id, messageIds),+ { messageCount: messageIds.length },+ );++ return topic;+ }),+ {+ hasAgentId: !!params.agentId,+ hasGroupId: !!params.groupId,+ hasSessionId: !!params.sessionId,+ messageCount: messageIds.length,+ },+ );+};++/**+ * Batch-creates topics and re-parents each topic's `messages` onto it, all in+ * one transaction.+ */+export const batchCreateTopics = async (+ scope: TopicRepositoryScope,+ topicParams: (CreateTopicParams & { id?: string })[],+) =>+ scope.db.transaction(async (tx) => {+ const trx = tx as unknown as LobeChatDatabase;+ const createdTopics = await topicModelFor(scope, trx).batchInsert(+ topicParams.map(({ messages: _messages, ...params }) => params),+ );++ await pMap(+ createdTopics,+ async (topic, index) => {+ const messageIds = topicParams[index].messages;+ if (messageIds && messageIds.length > 0) {+ await reparentMessages(trx, scope, topic.id, messageIds);+ }+ },+ { concurrency: BATCH_CREATE_MESSAGE_UPDATE_CONCURRENCY },+ );++ return createdTopics;+ });diff --git a/packages/database/src/repositories/topic/duplicate.ts b/packages/database/src/repositories/topic/duplicate.tsnew file mode 100644index 00000000000..c149bf402d6--- /dev/null+++ b/packages/database/src/repositories/topic/duplicate.ts@@ -0,0 +1,181 @@+import type { DBMessageItem } from '@lobechat/types';+import { and, eq, inArray } from 'drizzle-orm';++import { clampToolIdentifier } from '@/utils/clampToolIdentifier';++import { messagePlugins, messages, topics } from '../../schemas';+import { COPIED_TOPIC_USAGE_RESET } from '../../utils/copiedTranscript';+import { markCopiedMessageMetadata } from '../../utils/copyMessagesInDatabase';+import { idGenerator } from '../../utils/idGenerator';+import { buildWorkspacePayload } from '../../utils/workspace';+import { messageOwnership, topicOwnership, type TopicRepositoryScope } from './scope';++/**+ * Copy a topic into a new one.+ *+ * `options.upToMessageId` narrows the copy to the ancestor chain ending at+ * that message (first message β that message) β the "fork from here" path.+ * Without it the whole topic is copied, matching the duplicate action.+ */+export const duplicateTopic = async (+ scope: TopicRepositoryScope,+ topicId: string,+ newTitle?: string,+ options?: { upToMessageId?: string },+) => {+ return scope.db.transaction(async (tx) => {+ // find original topic+ const originalTopic = await tx.query.topics.findFirst({+ where: and(eq(topics.id, topicId), topicOwnership(scope)),+ });++ if (!originalTopic) {+ throw new Error(`Topic with id ${topicId} not found`);+ }++ // A copy is a brand-new topic: stamp its own timestamps instead of+ // inheriting the source's. The sidebar sorts and groups by the latest+ // activity time (`topicActivityAt`, i.e. the newest message), so a copy+ // that kept the source's date would re-file itself under the source's+ // original day instead of showing up as what it is β activity now.+ const copiedAt = new Date();++ // copy topic+ const [duplicatedTopic] = await tx+ .insert(topics)+ .values(+ buildWorkspacePayload(+ { userId: scope.userId, workspaceId: scope.workspaceId },+ {+ ...originalTopic,+ ...COPIED_TOPIC_USAGE_RESET,+ clientId: null,+ createdAt: copiedAt,+ id: idGenerator('topics'),+ title: newTitle || originalTopic?.title,+ updatedAt: copiedAt,+ },+ ),+ )+ .returning();++ // Find messages associated with the original topic, ordered by createdAt+ const topicMessages = await tx+ .select()+ .from(messages)+ .where(and(eq(messages.topicId, topicId), messageOwnership(scope)))+ .orderBy(messages.createdAt);++ // A fork copies only the selected prefix of the conversation (first+ // message β `upToMessageId`), so sibling branches left behind by+ // regenerate stay in the source topic; a duplicate copies the whole topic.+ let originalMessages = topicMessages;+ if (options?.upToMessageId) {+ const byId = new Map(topicMessages.map((message) => [message.id, message]));+ const selected = byId.get(options.upToMessageId);+ if (!selected) {+ throw new Error(`Message with id ${options.upToMessageId} not found in topic ${topicId}`);+ }++ // Walk up to the root, then reverse back to root β selected so parents+ // are inserted before their children.+ const chain: typeof topicMessages = [];+ const visited = new Set<string>();+ let cursor: (typeof topicMessages)[number] | undefined = selected;+ while (cursor && !visited.has(cursor.id)) {+ visited.add(cursor.id);+ chain.push(cursor);+ cursor = cursor.parentId ? byId.get(cursor.parentId) : undefined;+ }++ originalMessages = chain.reverse();+ }++ // Find all messagePlugins for this topic+ const messageIds = originalMessages.map((m) => m.id);+ const originalPlugins =+ messageIds.length > 0+ ? await tx.select().from(messagePlugins).where(inArray(messagePlugins.id, messageIds))+ : [];++ // Build oldId -> newId mapping for messages+ const idMap = new Map<string, string>();+ originalMessages.forEach((message) => {+ idMap.set(message.id, idGenerator('messages'));+ });++ // Build oldToolId -> newToolId mapping for tools+ const toolIdMap = new Map<string, string>();+ originalMessages.forEach((message) => {+ if (message.tools && Array.isArray(message.tools)) {+ (message.tools as any[]).forEach((tool: any) => {+ if (tool.id) {+ toolIdMap.set(tool.id, `toolu_${idGenerator('messages')}`);+ }+ });+ }+ });++ // copy messages sequentially to respect foreign key constraints+ const duplicatedMessages: DBMessageItem[] = [];+ for (const [index, message] of originalMessages.entries()) {+ const newId = idMap.get(message.id)!;+ const newParentId = message.parentId ? idMap.get(message.parentId) || null : null;++ // Retime the copy to the copy moment while preserving its internal+ // order (monotonic, 1ms apart, ending at `copiedAt`). The sidebar's+ // activity key is the newest message time, so carrying the source's+ // timestamps would keep the new topic in the source's date group.+ const messageAt = new Date(copiedAt.getTime() - (originalMessages.length - 1 - index));++ // Update tool IDs in tools array+ let newTools = message.tools;+ if (newTools && Array.isArray(newTools)) {+ newTools = (newTools as any[]).map((tool: any) => ({+ ...tool,+ id: tool.id ? toolIdMap.get(tool.id) || tool.id : tool.id,+ }));+ }++ const result = (await tx+ .insert(messages)+ .values({+ ...message,+ clientId: null,+ createdAt: messageAt,+ id: newId,+ // A duplicate consumed no tokens: mark it so usage reports do not+ // count the source's generation twice (the figures themselves stay+ // β they are what the transcript records).+ metadata: markCopiedMessageMetadata(message.metadata),+ parentId: newParentId,+ tools: newTools,+ topicId: duplicatedTopic.id,+ updatedAt: messageAt,+ })+ .returning()) as DBMessageItem[];++ duplicatedMessages.push(result[0]);++ // Copy messagePlugins if exists for this message+ const plugin = originalPlugins.find((p) => p.id === message.id);+ if (plugin) {+ const newToolCallId = plugin.toolCallId ? toolIdMap.get(plugin.toolCallId) || null : null;++ await tx.insert(messagePlugins).values({+ ...plugin,+ apiName: clampToolIdentifier(plugin.apiName),+ clientId: null,+ id: newId,+ identifier: clampToolIdentifier(plugin.identifier),+ toolCallId: newToolCallId,+ });+ }+ }++ return {+ messages: duplicatedMessages,+ topic: duplicatedTopic,+ };+ });+};diff --git a/packages/database/src/repositories/topic/index.ts b/packages/database/src/repositories/topic/index.tsindex 3da1dd303be..38719162c17 100644--- a/packages/database/src/repositories/topic/index.ts+++ b/packages/database/src/repositories/topic/index.ts@@ -1,12 +1,16 @@import type { ChatTopicMetadata } from '@lobechat/types';import { and, eq, sql } from 'drizzle-orm';+import type { CreateTopicParams, ModelTimingContext } from '../../models/topic';import { messageGroups, messages, topics } from '../../schemas';import type { LobeChatDatabase } from '../../type';import { copyMessagesInDatabase } from '../../utils/copyMessagesInDatabase';import { idGenerator } from '../../utils/idGenerator';-import { notShareVisitorTopic } from '../../utils/shareVisitor';import { buildWorkspacePayload, buildWorkspaceWhere } from '../../utils/workspace';+import { batchCreateTopics, createTopic } from './create';+import { duplicateTopic } from './duplicate';+import { batchMoveToAgent } from './move';+import { messageOwnership, topicOwnership, type TopicRepositoryScope } from './scope';/*** Run configuration a branched topic keeps from its source. Everything else in@@ -46,14 +50,37 @@ export class TopicRepository {private readonly workspaceId?: string,) {}- private ownership = () =>- and(- buildWorkspaceWhere({ userId: this.userId, workspaceId: this.workspaceId }, topics),- notShareVisitorTopic(),- );+ private get scope(): TopicRepositoryScope {+ return { db: this.db, userId: this.userId, workspaceId: this.workspaceId };+ }- private messageOwnership = () =>- buildWorkspaceWhere({ userId: this.userId, workspaceId: this.workspaceId }, messages);+ /**+ * Creates a topic, re-parenting the given `messages` onto it atomically.+ *+ * Call stack:+ *+ * aiChatRouter.sendMessageInServer / topicRouter.createTopic+ * -> TopicRepository.create+ * -> TopicModel.create (+ messages.topicId update in the same transaction)+ */+ create = (params: CreateTopicParams, id?: string, timing?: ModelTimingContext) =>+ createTopic(this.scope, params, id, timing);++ /** Batch-creates topics, re-parenting each topic's `messages` atomically. */+ batchCreate = (topicParams: (CreateTopicParams & { id?: string })[]) =>+ batchCreateTopics(this.scope, topicParams);++ /** Copies a topic and its messages (or a fork prefix) into a new topic atomically. */+ duplicate = (topicId: string, newTitle?: string, options?: { upToMessageId?: string }) =>+ duplicateTopic(this.scope, topicId, newTitle, options);++ /** Moves topics with their messages and threads to another owned agent atomically. */+ batchMoveToAgent = (topicIds: string[], targetAgentId: string) =>+ batchMoveToAgent(this.scope, topicIds, targetAgentId);++ private ownership = () => topicOwnership(this.scope);++ private messageOwnership = () => messageOwnership(this.scope);/*** Copies the conversation that leads up to one user message into a newdiff --git a/packages/database/src/repositories/topic/move.ts b/packages/database/src/repositories/topic/move.tsnew file mode 100644index 00000000000..ccccfb54de6--- /dev/null+++ b/packages/database/src/repositories/topic/move.ts@@ -0,0 +1,73 @@+import { and, eq, inArray } from 'drizzle-orm';++import { agents, messages, threads, topics } from '../../schemas';+import { buildWorkspaceWhere } from '../../utils/workspace';+import { messageOwnership, topicOwnership, type TopicRepositoryScope } from './scope';++/**+ * Move multiple topics (and all their messages) to another agent.+ *+ * Reassigns ownership purely through the `agentId` foreign key (the new data+ * model). Every child entity of the topic that carries its own `agentId` FK+ * MUST be updated together β `topics`, `messages`, and `threads`. Topic lists+ * query by `topics.agentId` and message queries filter by `messages.agentId`,+ * so updating only the topic would leave the moved conversation showing up+ * empty under the target agent; and `threads.agentId` is itself a+ * cascade-on-delete FK, so a thread left pointing at the source agent would+ * be destroyed if that agent is later deleted.+ *+ * `sessionId` is cleared on `topics` and `messages` so the rows fully detach+ * from the source agent's legacy session and can't leak back through the+ * sessionId-based legacy query fallback (`threads` has no `sessionId`).+ *+ * Topics can only be moved to an agent owned by the same user/workspace. The+ * target agent is verified with the same ownership predicate before applying+ * the move β `topics.agentId` / `messages.agentId` are plain FKs to+ * `agents.id` with cascade-on-delete, so attaching rows to a foreign agent+ * would both leak them across tenants and risk losing them if that agent is+ * later deleted.+ */+export const batchMoveToAgent = async (+ scope: TopicRepositoryScope,+ topicIds: string[],+ targetAgentId: string,+) => {+ if (topicIds.length === 0) return;++ return scope.db.transaction(async (tx) => {+ const [targetAgent] = await tx+ .select({ id: agents.id })+ .from(agents)+ .where(+ and(+ eq(agents.id, targetAgentId),+ buildWorkspaceWhere({ userId: scope.userId, workspaceId: scope.workspaceId }, agents),+ ),+ )+ .limit(1);++ if (!targetAgent) {+ throw new Error(`Target agent ${targetAgentId} not found or not accessible`);+ }++ await tx+ .update(topics)+ .set({ agentId: targetAgentId, sessionId: null, updatedAt: new Date() })+ .where(and(inArray(topics.id, topicIds), topicOwnership(scope)));++ await tx+ .update(messages)+ .set({ agentId: targetAgentId, sessionId: null })+ .where(and(inArray(messages.topicId, topicIds), messageOwnership(scope)));++ await tx+ .update(threads)+ .set({ agentId: targetAgentId })+ .where(+ and(+ inArray(threads.topicId, topicIds),+ buildWorkspaceWhere({ userId: scope.userId, workspaceId: scope.workspaceId }, threads),+ ),+ );+ });+};diff --git a/packages/database/src/repositories/topic/scope.ts b/packages/database/src/repositories/topic/scope.tsnew file mode 100644index 00000000000..f14dba734dd--- /dev/null+++ b/packages/database/src/repositories/topic/scope.ts@@ -0,0 +1,24 @@+import type { SQL } from 'drizzle-orm';+import { and } from 'drizzle-orm';++import { messages, topics } from '../../schemas';+import type { LobeChatDatabase } from '../../type';+import { notShareVisitorTopic } from '../../utils/shareVisitor';+import { buildWorkspaceWhere } from '../../utils/workspace';++/** Caller identity every TopicRepository write is scoped to. */+export interface TopicRepositoryScope {+ db: LobeChatDatabase;+ userId: string;+ workspaceId?: string;+}++/** Creator-facing topic scope: workspace/user ownership minus share-visitor topics. */+export const topicOwnership = (scope: TopicRepositoryScope): SQL | undefined =>+ and(+ buildWorkspaceWhere({ userId: scope.userId, workspaceId: scope.workspaceId }, topics),+ notShareVisitorTopic(),+ );++export const messageOwnership = (scope: TopicRepositoryScope): SQL | undefined =>+ buildWorkspaceWhere({ userId: scope.userId, workspaceId: scope.workspaceId }, messages);