Skip to content

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

♻️ refactor(server): split the 1,218-line topic router into sub-domain modules (#21102)

Arvin Xu2c95c0765914
diff --git a/apps/server/src/routers/lambda/topic.ts b/apps/server/src/routers/lambda/topic.ts
deleted file mode 100644
index c85b4cc7f41..00000000000
--- a/apps/server/src/routers/lambda/topic.ts
+++ /dev/null
@@ -1,1218 +0,0 @@
-import { PERMISSION_ACTIONS } from '@lobechat/const/rbac';
-import {
- canPublishAgentTopicLink,
- chatTopicCreateMetadataSchema,
- chatTopicMetadataUpdateSchema,
- chatTopicStatusSchema,
- type HeteroSessionImportPayload,
- heteroSessionImportPayloadSchema,
- type RecentTopic,
- type RecentTopicGroup,
- type RecentTopicGroupMember,
-} from '@lobechat/types';
-import { cleanObject } from '@lobechat/utils';
-import { TRPCError } from '@trpc/server';
-import { and, inArray } from 'drizzle-orm';
-import { z } from 'zod';
-
-import { withScopedPermission } from '@/business/server/trpc-middlewares/rbacPermission';
-import { wsCompatProcedure } from '@/business/server/trpc-middlewares/workspaceAuth';
-import { AgentModel } from '@/database/models/agent';
-import { AgentOperationModel } from '@/database/models/agentOperation';
-import { ChatGroupModel } from '@/database/models/chatGroup';
-import { FileModel } from '@/database/models/file';
-import { MessageModel } from '@/database/models/message';
-import { ProjectWorkingDirectoryModel } from '@/database/models/projectWorkingDirectory';
-import { RbacModel } from '@/database/models/rbac';
-import { TopicModel } from '@/database/models/topic';
-import { TopicShareModel } from '@/database/models/topicShare';
-import { WorkspaceAuditLogModel } from '@/database/models/workspaceAuditLog';
-import { AgentMigrationRepo } from '@/database/repositories/agentMigration';
-import { HeteroSessionImporterRepo } from '@/database/repositories/heteroSessionImporter';
-import { TopicRepository } from '@/database/repositories/topic';
-import { TopicImporterRepo } from '@/database/repositories/topicImporter';
-import { chatGroups } from '@/database/schemas';
-import type { LobeChatDatabase } from '@/database/type';
-import { notTrashed } from '@/database/utils/softDelete';
-import { router } from '@/libs/trpc/lambda';
-import { serverDatabase } from '@/libs/trpc/lambda/middleware';
-import { createFtsSearchRepo } from '@/server/services/ftsSearch';
-import { TopicReferenceService } from '@/server/services/topicReference';
-import { TrashService } from '@/server/services/trash';
-import { after } from '@/server/utils/scheduleAfterResponse';
-import { type BatchTaskResult } from '@/types/service';
-
-import {
- assertWorkspaceRowManageable,
- shouldRestrictBulkDeleteToCreator,
-} from './_helpers/assertWorkspaceRowManageable';
-import {
- assertCanUseConversationTargets,
- assertCanUseSessionTargets,
- assertCanUseTopicTargets,
-} from './_helpers/conversationResourceGuard';
-import {
- batchResolveAgentIdFromSessions,
- resolveAgentIdFromSession,
- resolveContext,
- resolveContextWithAgentId,
-} from './_helpers/resolveContext';
-import {
- assertCreatorMessageTargets,
- assertCreatorTopicTargets,
-} from './_helpers/shareVisitorTargetGuard';
-import { basicContextSchema } from './_schema/context';
-
-/** Ctx slice consumed by the conversation General-access guards. */
-const guardCtx = (ctx: {
- serverDB: LobeChatDatabase;
- userId: string;
- workspaceId?: string | null;
-}) => ({ db: ctx.serverDB, userId: ctx.userId, workspaceId: ctx.workspaceId });
-
-const topicProcedure = wsCompatProcedure.use(serverDatabase).use(async (opts) => {
- const { ctx } = opts;
- const wsId = ctx.workspaceId ?? undefined;
-
- return opts.next({
- ctx: {
- agentMigrationRepo: new AgentMigrationRepo(ctx.serverDB, ctx.userId, wsId),
- agentModel: new AgentModel(ctx.serverDB, ctx.userId, wsId),
- agentOperationModel: new AgentOperationModel(ctx.serverDB, ctx.userId, wsId),
- chatGroupModel: new ChatGroupModel(ctx.serverDB, ctx.userId, wsId),
- fileModel: new FileModel(ctx.serverDB, ctx.userId, wsId),
- heteroSessionImporterRepo: new HeteroSessionImporterRepo(ctx.serverDB, ctx.userId, wsId),
- messageModel: new MessageModel(ctx.serverDB, ctx.userId, wsId),
- topicImporterRepo: new TopicImporterRepo(ctx.serverDB, ctx.userId, wsId),
- topicModel: new TopicModel(ctx.serverDB, ctx.userId, wsId),
- topicRepo: new TopicRepository(ctx.serverDB, ctx.userId, wsId),
- topicShareModel: new TopicShareModel(ctx.serverDB, ctx.userId, wsId),
- trashService: new TrashService(ctx.serverDB, ctx.userId, wsId),
- },
- });
-});
-
-const topicSearchProcedure = topicProcedure.use(async (opts) => {
- const { ctx } = opts;
- const workspaceId = ctx.workspaceId ?? undefined;
- const ftsSearchRepo = await createFtsSearchRepo({
- db: ctx.serverDB,
- userId: ctx.userId,
- usage: 'topic_search',
- workspaceId,
- });
-
- return opts.next({
- ctx: {
- topicModel: new TopicModel(ctx.serverDB, ctx.userId, workspaceId, ftsSearchRepo),
- },
- });
-});
-
-const topicBulkDeleteScopeSchema = z.enum(['own', 'workspace']).default('own');
-
-interface TopicShareCtx {
- agentModel: AgentModel;
- chatGroupModel: ChatGroupModel;
- serverDB: LobeChatDatabase;
- topicModel: TopicModel;
- userId: string;
- workspaceId?: string | null;
-}
-
-/** Workspace owners hold the `:all` scope; everyone else is capped to `:owner`. */
-const isWorkspaceTopicOwner = (ctx: TopicShareCtx) =>
- new RbacModel(ctx.serverDB, ctx.userId).hasPermission(`${PERMISSION_ACTIONS.TOPIC_UPDATE}:all`, {
- workspaceId: ctx.workspaceId!,
- });
-
-/**
- * The agent a topic answers to, for policy purposes.
- *
- * Group topics resolve through their supervisor first: a group conversation
- * *is* a conversation with its supervisor, that is the row the group's
- * Permission page writes, and `createTopic` accepts a `groupId` with no agent
- * or session at all β€” so reading `agentId` first would leave those rows with
- * no policy to apply. Agent-native topics then carry `agentId` directly, and
- * legacy session-only rows predate that column, so resolve through the session
- * rather than letting them slip past the policy.
- */
-const resolveTopicShareAgent = async (
- ctx: TopicShareCtx,
- topic: { agentId?: string | null; groupId?: string | null; sessionId?: string | null },
-) => {
- const agentId =
- (topic.groupId ? await ctx.chatGroupModel.getSupervisorAgentId(topic.groupId) : null) ??
- topic.agentId ??
- (topic.sessionId
- ? await resolveAgentIdFromSession(topic.sessionId, ctx.serverDB, ctx.userId, ctx.workspaceId!)
- : undefined);
- if (!agentId) return null;
-
- return ctx.agentModel.getTopicShareSubject(agentId);
-};
-
-/**
- * Workspace gate for topic-share management.
- *
- * The baseline is the co-editing rule (same gate as `updateTopic`): any member
- * with `use`-level General access on the topic's conversation may manage its
- * share β€” view-only members stay read-only. Personal mode needs no extra check
- * β€” the model's ownership filter already scopes mutations to the caller.
- *
- * A topic that backs no conversation at all (legacy rows carrying neither an
- * agent, a group, nor a resolvable session) resolves to zero targets, so the
- * guard would pass for every member. Sharing is a wider grant than editing β€”
- * a link exposes the whole conversation to anyone holding it β€” so those fall
- * back to the stricter creator-or-workspace-owner rule rather than inheriting
- * the vacuous pass.
- *
- * *Publishing* narrows that further, governed by the owning agent's
- * `topicSharePolicy`. Under `restricted` only the agent's creator and
- * workspace owners may publish, which overrides even topic ownership β€” that is
- * the whole point of the policy. Revoking a link, and the `private`
- * placeholder the share popover creates when it opens, are never restricted:
- * pulling a topic out of circulation is always safe, and gating the
- * placeholder would leave a restricted member with a popover that cannot even
- * load its state. Pass `targetVisibility: 'link'` when the operation would
- * publish.
- */
-const assertCanManageTopicShare = async (
- ctx: TopicShareCtx,
- topicId: string,
- targetVisibility?: 'link' | 'private',
-) => {
- // `findOwnTopicById`: an agent-share visitor topic is stored under the
- // creator's userId, and publishing a public link for one would expose the
- // visitor's conversation. It is never a shareable topic β€” fail closed, and
- // do so BEFORE the personal-mode short-circuit below: visitor topics exist
- // in personal mode too, so the exclusion cannot depend on a workspace.
- const topic = await ctx.topicModel.findOwnTopicById(topicId);
- if (!topic) {
- throw new TRPCError({ code: 'NOT_FOUND', message: 'Topic not found' });
- }
-
- // Outside a workspace the remaining checks (agent publish policy, workspace
- // ownership) have no subject β€” personal-mode ownership is the whole story.
- if (!ctx.workspaceId) return;
-
- // Publishing under a restricted agent overrides even topic ownership β€”
- // that is the whole point of the policy. Resolved only on the publish path
- // so the common case keeps the query count it had.
- if (targetVisibility === 'link') {
- const agent = await resolveTopicShareAgent(ctx, topic);
-
- if (agent && !canPublishAgentTopicLink(agent, { userId: ctx.userId })) {
- if (await isWorkspaceTopicOwner(ctx)) return;
-
- throw new TRPCError({
- cause: { data: { code: 'TopicShareRestrictedByAgent' } },
- code: 'FORBIDDEN',
- message: "Only the agent creator or a workspace owner can share this agent's topics",
- });
- }
- }
-
- if (topic.userId === ctx.userId) return;
-
- const guardedConversations = await assertCanUseTopicTargets(guardCtx(ctx), [topicId]);
- if (guardedConversations.length > 0) return;
-
- const isWorkspaceAdmin = await isWorkspaceTopicOwner(ctx);
- if (!isWorkspaceAdmin) {
- throw new TRPCError({
- code: 'FORBIDDEN',
- message: 'Only the topic creator or a workspace owner can manage this share',
- });
- }
-};
-
-/**
- * Audit trail for workspace share state changes, mirroring the page-share
- * `resource.shared` / `resource.unshared` events. Personal mode is not
- * audited. A share record with 'private' visibility is an unshared
- * placeholder, so only transitions in/out of 'link' are recorded.
- */
-const recordTopicShareAudit = async (
- ctx: TopicShareCtx,
- params: { currentVisibility: string; previousVisibility: string; topicId: string },
-) => {
- if (!ctx.workspaceId) return;
- const { currentVisibility, previousVisibility, topicId } = params;
- if (currentVisibility === previousVisibility) return;
- if (currentVisibility !== 'link' && previousVisibility !== 'link') return;
-
- await new WorkspaceAuditLogModel(ctx.serverDB).create({
- action: currentVisibility === 'link' ? 'resource.shared' : 'resource.unshared',
- metadata: { currentVisibility, previousVisibility },
- resourceId: topicId,
- resourceType: 'topic',
- userId: ctx.userId,
- workspaceId: ctx.workspaceId,
- });
-};
-
-export const topicRouter = router({
- cancelRateLimitContinuation: topicProcedure
- .use(withScopedPermission('topic:update'))
- .input(z.object({ id: z.string() }))
- .mutation(async ({ input, ctx }) => {
- await assertCanUseTopicTargets(guardCtx(ctx), [input.id]);
- await assertCreatorTopicTargets(guardCtx(ctx), [input.id]);
- const result = await ctx.topicModel.cancelRateLimitContinuation(input.id);
- if (result.status === 'busy')
- throw new TRPCError({
- code: 'CONFLICT',
- message: 'The source continuation has already been claimed or started.',
- });
- if (result.status === 'unchanged') return null;
- return { metadata: result.metadata };
- }),
-
- getTopicDetail: topicProcedure
- .input(z.object({ id: z.string() }))
- .query(async ({ input, ctx }) => {
- const topic = await ctx.topicModel.findOwnTopicById(input.id);
- if (!topic) return null;
- return topic;
- }),
-
- getTopicTranscript: topicProcedure
- .input(
- z.object({
- includeMessages: z.boolean().default(true),
- limit: z.number().int().min(1).max(500).default(50),
- offset: z.number().int().min(0).default(0),
- topicId: z.string(),
- }),
- )
- .query(async ({ input, ctx }) => {
- // `lh topic view` from a workspace run may be given one of the user's personal topic ids.
- const topic = await new TopicReferenceService(
- ctx.serverDB,
- ctx.userId,
- ctx.workspaceId ?? undefined,
- ).findTopic(input.topicId);
-
- if (!topic) {
- throw new TRPCError({
- code: 'NOT_FOUND',
- message: `Topic not found: ${input.topicId}`,
- });
- }
-
- if (!input.includeMessages) {
- return { items: [], topic, total: null };
- }
-
- const messageModel =
- (topic.workspaceId ?? undefined) === (ctx.workspaceId ?? undefined)
- ? ctx.messageModel
- : new MessageModel(ctx.serverDB, ctx.userId, topic.workspaceId ?? undefined);
- const transcript = await messageModel.queryTopicTranscript({
- limit: input.limit,
- offset: input.offset,
- topicId: input.topicId,
- });
-
- return { ...transcript, topic };
- }),
-
- /**
- * @deprecated The `lobe-topic-reference` tool was removed; agents read topics with
- * `lh topic view`. Kept for released Desktop builds and cached web bundles whose
- * client executor still calls this. Remove once those clients have aged out.
- */
- getTopicContext: topicProcedure
- .input(z.object({ topicId: z.string() }))
- .query(async ({ input, ctx }) =>
- new TopicReferenceService(
- ctx.serverDB,
- ctx.userId,
- ctx.workspaceId ?? undefined,
- ).getTopicContext(input),
- ),
-
- batchCreateTopics: topicProcedure
- .use(withScopedPermission('topic:create'))
- .input(
- z.array(
- z
- .object({
- favorite: z.boolean().optional(),
- id: z.string().optional(),
- messages: z.array(z.string()).optional(),
- title: z.string(),
- })
- .extend(basicContextSchema.shape),
- ),
- )
- .mutation(async ({ input, ctx }): Promise<BatchTaskResult> => {
- // Resolve both directions before authorization: legacy callers may send
- // only sessionId, while the ACL is attached to the owning agent.
- const resolvedTopics = await Promise.all(
- input.map(async (item) => {
- const { agentId, ...rest } = item;
- const resolved = await resolveContextWithAgentId(
- { agentId, groupId: rest.groupId, sessionId: rest.sessionId },
- ctx.serverDB,
- ctx.userId,
- ctx.workspaceId ?? undefined,
- );
- return { ...rest, agentId: resolved.agentId, sessionId: resolved.sessionId };
- }),
- );
-
- await assertCanUseConversationTargets(
- guardCtx(ctx),
- resolvedTopics.map((item) => ({ agentId: item.agentId, groupId: item.groupId })),
- );
- // `messages` are REPARENTED onto the new topic by ownership only. A
- // visitor message (creator-owned row under a `senderId` topic) moved to
- // a creator topic would escape `notShareVisitorMessage()` for good.
- await assertCreatorMessageTargets(
- guardCtx(ctx),
- resolvedTopics.flatMap((item) => item.messages ?? []),
- );
-
- const data = await ctx.topicModel.batchCreate(resolvedTopics as any);
-
- return { added: data.length, ids: [], skips: [], success: true };
- }),
-
- batchDelete: topicProcedure
- .use(withScopedPermission('topic:delete'))
- .input(z.object({ ids: z.array(z.string()) }))
- .mutation(async ({ input, ctx }) => {
- const rows = await ctx.topicModel.findOwnersByIds(input.ids);
- for (const userId of new Set(rows.map((row) => row.userId))) {
- assertWorkspaceRowManageable(ctx, userId, 'topic');
- }
-
- await ctx.trashService.trashTopics(input.ids);
- }),
-
- batchDeleteByAgentId: topicProcedure
- .use(withScopedPermission('topic:delete'))
- .input(z.object({ agentId: z.string(), scope: topicBulkDeleteScopeSchema }))
- .mutation(async ({ input, ctx }) => {
- const restrictToCreator = shouldRestrictBulkDeleteToCreator(ctx, input.scope);
-
- await ctx.trashService.trashTopicsByAgent(input.agentId, { restrictToCreator });
- }),
-
- batchDeleteByGroupId: topicProcedure
- .use(withScopedPermission('topic:delete'))
- .input(z.object({ groupId: z.string(), scope: topicBulkDeleteScopeSchema }))
- .mutation(async ({ input, ctx }) => {
- await assertCanUseConversationTargets(guardCtx(ctx), [{ groupId: input.groupId }]);
- const restrictToCreator = shouldRestrictBulkDeleteToCreator(ctx, input.scope);
-
- await ctx.trashService.trashTopicsByGroup(input.groupId, { restrictToCreator });
- }),
-
- batchDeleteBySessionId: topicProcedure
- .use(withScopedPermission('topic:delete'))
- .input(
- z.object({
- agentId: z.string().optional(),
- id: z.string().nullish(),
- scope: topicBulkDeleteScopeSchema,
- }),
- )
- .mutation(async ({ input, ctx }) => {
- const resolved = await resolveContext(
- { agentId: input.agentId, sessionId: input.id },
- ctx.serverDB,
- ctx.userId,
- ctx.workspaceId ?? undefined,
- );
-
- if (input.agentId) {
- await assertCanUseConversationTargets(guardCtx(ctx), [{ agentId: input.agentId }]);
- } else if (resolved.sessionId) {
- await assertCanUseSessionTargets(guardCtx(ctx), [resolved.sessionId]);
- }
-
- const restrictToCreator = shouldRestrictBulkDeleteToCreator(ctx, input.scope);
-
- await ctx.trashService.trashTopicsBySession(resolved.sessionId, { restrictToCreator });
- }),
-
- batchMoveTopics: topicProcedure
- .use(withScopedPermission('topic:update'))
- .input(
- z.object({
- targetAgentId: z.string(),
- topicIds: z.array(z.string()),
- }),
- )
- .mutation(async ({ input, ctx }) => {
- const rows = await ctx.topicModel.findOwnersByIds(input.topicIds);
- for (const userId of new Set(rows.map((row) => row.userId))) {
- assertWorkspaceRowManageable(ctx, userId, 'topic');
- }
- // Moving needs `use` on both the source conversations and the target agent.
- await assertCanUseTopicTargets(guardCtx(ctx), input.topicIds);
- await assertCanUseConversationTargets(guardCtx(ctx), [{ agentId: input.targetAgentId }]);
- // Moving a visitor topic re-parents it off the share and strands the
- // visitor outside the senderId scope the share depends on β€” see
- // `assertCreatorTopicTargets` for why this guard sits at the RPC
- // boundary rather than in the model defaults.
- await assertCreatorTopicTargets(guardCtx(ctx), input.topicIds);
-
- return ctx.topicModel.batchMoveToAgent(input.topicIds, input.targetAgentId);
- }),
-
- cloneTopic: topicProcedure
- .use(withScopedPermission('topic:create'))
- .input(z.object({ id: z.string(), newTitle: z.string().optional() }))
- .mutation(async ({ input, ctx }) => {
- await assertCanUseTopicTargets(guardCtx(ctx), [input.id]);
- // 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);
-
- return data.topic.id;
- }),
-
- /**
- * Fork a topic from one of its messages: copy the conversation prefix
- * (first message β†’ `messageId`) into a brand new topic and return its id.
- *
- * Shares `cloneTopic`'s guards: a fork writes a new topic and copies content
- * out of the source, so it needs the same `topic:create` capability and the
- * same refusal to lift a visitor topic's content into creator scope.
- */
- forkTopic: topicProcedure
- .use(withScopedPermission('topic:create'))
- .input(
- z.object({
- id: z.string(),
- messageId: z.string(),
- newTitle: z.string().optional(),
- }),
- )
- .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, {
- upToMessageId: input.messageId,
- });
-
- return data.topic.id;
- }),
-
- /**
- * Edit-and-resend for runtimes whose native history cannot be rewound
- * (Codex): copies the conversation up to one user message into a new topic
- * with the edited content. The source topic is left as it was.
- */
- branchTopicAtMessage: topicProcedure
- .use(withScopedPermission('topic:create'))
- .input(
- z.object({
- content: z.string(),
- editorData: z.record(z.string(), z.any()).nullish(),
- messageId: z.string(),
- title: z.string().optional(),
- topicId: z.string(),
- }),
- )
- .mutation(async ({ input, ctx }) => {
- const { topicId, messageId, ...edit } = input;
- await assertCanUseTopicTargets(guardCtx(ctx), [topicId]);
- // Same visitor guard as `cloneTopic` above.
- await assertCreatorTopicTargets(guardCtx(ctx), [topicId]);
- const branch = await ctx.topicRepo.branchAtMessage(topicId, messageId, edit);
- if (!branch) throw new TRPCError({ code: 'NOT_FOUND', message: 'User message not found' });
-
- return { messageId: branch.messageId, topicId: branch.topic.id };
- }),
-
- countTopics: topicProcedure
- .input(
- z
- .object({
- agentId: z.string().optional(),
- containerId: z.string().nullish(),
- endDate: z.string().optional(),
- range: z.tuple([z.string(), z.string()]).optional(),
- startDate: z.string().optional(),
- })
- .optional(),
- )
- .query(async ({ ctx, input }) => {
- return ctx.topicModel.count(input);
- }),
-
- createTopic: topicProcedure
- .use(withScopedPermission('topic:create'))
- .input(
- z
- .object({
- favorite: z.boolean().optional(),
- groupId: z.string().nullish(),
- messages: z.array(z.string()).optional(),
- // The pinned reasoning snapshot taken next to the pinned model
- // (`snapshotAgentReasoning`); other metadata keys are server-owned.
- metadata: chatTopicCreateMetadataSchema.optional(),
- // The topic's pinned model snapshot, persisted to the top-level
- // `topics.model`/`provider` columns (config source of truth).
- model: z.string().optional(),
- // Bind the new row to a project working directory. Resolved and
- // pinned below, mirroring `projectWorkingDirectory.startTopic`.
- projectWorkingDirectoryId: z.string().optional(),
- provider: z.string().optional(),
- title: z.string(),
- trigger: z.string().optional(),
- })
- .extend(basicContextSchema.shape),
- )
- .mutation(async ({ input, ctx }) => {
- const { agentId, projectWorkingDirectoryId, ...rest } = input;
- const resolved = await resolveContextWithAgentId(
- { agentId, groupId: rest.groupId, sessionId: rest.sessionId },
- ctx.serverDB,
- ctx.userId,
- ctx.workspaceId ?? undefined,
- );
- await assertCanUseConversationTargets(guardCtx(ctx), [
- { agentId: resolved.agentId, groupId: rest.groupId },
- ]);
- // See batchCreateTopics β€” reparenting a visitor message would leak it.
- await assertCreatorMessageTargets(guardCtx(ctx), rest.messages ?? []);
-
- // A topic started from a project group's "+" defers its row to the first
- // message. Pin the directory here so the row is born inside the project β€”
- // list, sidebar group and execution routing β€” instead of dropping into a
- // path-only conversation. A directory that can no longer be resolved
- // (deleted, unlinked from its environment, or another user's) is logged
- // and skipped: losing the binding must not fail the user's first send.
- const directory = projectWorkingDirectoryId
- ? await new ProjectWorkingDirectoryModel(
- ctx.serverDB,
- ctx.userId,
- ctx.workspaceId ?? undefined,
- )
- .resolve(projectWorkingDirectoryId)
- .catch((error) => {
- console.error(
- '[topic.createTopic] Failed to resolve the project directory binding:',
- error,
- );
- return undefined;
- })
- : undefined;
-
- const data = await ctx.topicModel.create({
- ...rest,
- agentId: resolved.agentId,
- sessionId: resolved.sessionId,
- ...(directory
- ? {
- metadata: {
- ...rest.metadata,
- boundDeviceId: directory.deviceId,
- workingDirectory: directory.path,
- workingDirectoryConfig: { path: directory.path },
- },
- projectId: directory.projectId,
- projectWorkingDirectoryId: directory.id,
- }
- : {}),
- });
-
- return data.id;
- }),
-
- /**
- * Disable sharing for a topic (deletes share record)
- */
- disableSharing: topicProcedure
- .use(withScopedPermission('topic:update'))
- .input(z.object({ topicId: z.string() }))
- .mutation(async ({ input, ctx }) => {
- await assertCanManageTopicShare(ctx, input.topicId);
-
- const previous = await ctx.topicShareModel.getByTopicId(input.topicId);
- const result = await ctx.topicShareModel.deleteByTopicId(input.topicId);
-
- if (previous) {
- await recordTopicShareAudit(ctx, {
- currentVisibility: 'private',
- previousVisibility: previous.visibility,
- topicId: input.topicId,
- });
- }
-
- return result;
- }),
-
- /**
- * Enable sharing for a topic (creates share record)
- */
- enableSharing: topicProcedure
- .use(withScopedPermission('topic:update'))
- .input(
- z.object({
- topicId: z.string(),
- visibility: z.enum(['private', 'link']).optional(),
- }),
- )
- .mutation(async ({ input, ctx }) => {
- await assertCanManageTopicShare(ctx, input.topicId, input.visibility);
-
- const previous = await ctx.topicShareModel.getByTopicId(input.topicId);
- const result = await ctx.topicShareModel.create(input.topicId, input.visibility);
-
- if (result) {
- await recordTopicShareAudit(ctx, {
- currentVisibility: result.visibility,
- previousVisibility: previous?.visibility ?? 'private',
- topicId: input.topicId,
- });
- }
-
- return result;
- }),
-
- queryTopics: topicProcedure
- .input(
- z
- .object({
- pageSize: z.number().max(500).optional(),
- statuses: z.array(z.string()).optional(),
- withLastMessage: z.boolean().optional(),
- })
- .optional(),
- )
- .query(async ({ input, ctx }) => {
- return ctx.topicModel.queryTopics({
- pageSize: input?.pageSize,
- statuses: input?.statuses,
- withLastMessage: input?.withLastMessage,
- });
- }),
-
- getShareInfo: topicProcedure
- .input(z.object({ topicId: z.string() }))
- .query(async ({ input, ctx }) => {
- return ctx.topicShareModel.getByTopicId(input.topicId);
- }),
-
- getTopics: topicProcedure
- .input(
- z.object({
- agentId: z.string().nullish(),
- current: z.number().optional(),
- /**
- * Scope an `agentId` query to the builder conversations that configured
- * one target. Builder panels show their full history on purpose; these
- * are for callers that want a single agent's / group's builds.
- */
- editingAgentId: z.string().nullish(),
- editingGroupId: z.string().nullish(),
- excludeStatuses: z.array(z.string()).optional(),
- excludeTriggers: z.array(z.string()).optional(),
- groupId: z.string().nullish(),
- includeTriggers: z.array(z.string()).optional(),
- isInbox: z.boolean().optional(),
- pageSize: z.number().max(100).optional(),
- sessionId: z.string().nullish(),
- /**
- * Server-side ordering. Defaults to `updatedAt`; `status` orders by
- * status priority for the sidebar "group by status" mode.
- */
- sortBy: z.enum(['updatedAt', 'status']).optional(),
- triggers: z.array(z.string()).optional(),
- /**
- * When true, returns extra card-detail columns (firstUserMessage,
- * messageCount, cost, tokenUsage, description, trigger). Default false
- * so the sidebar list stays cheap β€” only the management page opts in.
- */
- withDetails: z.boolean().optional(),
- }),
- )
- .query(async ({ input, ctx }) => {
- const {
- sessionId,
- isInbox,
- groupId,
- excludeStatuses,
- excludeTriggers,
- includeTriggers,
- triggers,
- ...rest
- } = input;
-
- // If groupId is provided, query by groupId directly
- if (groupId) {
- const result = await ctx.topicModel.query({
- excludeStatuses,
- excludeTriggers,
- groupId,
- includeTriggers,
- triggers,
- ...rest,
- });
- return { items: result.items, total: result.total };
- }
-
- // If sessionId is provided but no agentId, need to reverse lookup agentId
- let effectiveAgentId = rest.agentId;
- if (!effectiveAgentId && sessionId) {
- effectiveAgentId = await resolveAgentIdFromSession(
- sessionId,
- ctx.serverDB,
- ctx.userId,
- ctx.workspaceId ?? undefined,
- );
- }
-
- const result = await ctx.topicModel.query({
- ...rest,
- agentId: effectiveAgentId,
- excludeStatuses,
- excludeTriggers,
- includeTriggers,
- isInbox,
- triggers,
- });
-
- // Runtime migration: backfill agentId for ALL legacy topics and messages under this agent
- const runMigration = async () => {
- if (!effectiveAgentId) return;
-
- // Get the associated sessionId for migration
- const resolved = await resolveContext(
- { agentId: effectiveAgentId },
- ctx.serverDB,
- ctx.userId,
- ctx.workspaceId ?? undefined,
- );
-
- const migrationParams = isInbox
- ? { agentId: effectiveAgentId, isInbox: true as const, sessionId: resolved.sessionId }
- : resolved.sessionId
- ? { agentId: effectiveAgentId, sessionId: resolved.sessionId }
- : null;
-
- if (migrationParams) {
- try {
- await ctx.agentMigrationRepo.migrateAgentId(migrationParams);
- } catch (error) {
- console.error('[AgentMigration] Failed to migrate agentId:', error);
- }
- }
- };
-
- after(runMigration);
-
- return { items: result.items, total: result.total };
- }),
-
- hasTopicFiles: topicProcedure
- .use(withScopedPermission('topic:delete'))
- .input(z.object({ ids: z.array(z.string()).min(1) }))
- .query(async ({ input, ctx }) => {
- try {
- const hasFiles = await ctx.fileModel.hasFilesByTopicIds(input.ids);
- return { data: { hasFiles }, success: true };
- } catch (error) {
- console.error('[topic:hasTopicFiles]', error);
- throw new TRPCError({
- cause: error,
- code: 'INTERNAL_SERVER_ERROR',
- message: 'Failed to check topic files',
- });
- }
- }),
-
- hasTopics: topicProcedure.query(async ({ ctx }) => {
- return (await ctx.topicModel.count()) === 0;
- }),
-
- getHeteroSessionImportStatus: topicProcedure.query(async ({ ctx }) => {
- return ctx.heteroSessionImporterRepo.getImportStatus();
- }),
-
- importHeteroSessions: topicProcedure
- .use(withScopedPermission('topic:create'))
- .input(
- z.object({
- agentId: z.string(),
- groupId: z.string().nullish(),
- sessions: z.array(heteroSessionImportPayloadSchema),
- }),
- )
- .mutation(async ({ input, ctx }) => {
- await assertCanUseConversationTargets(guardCtx(ctx), [
- { agentId: input.agentId, groupId: input.groupId },
- ]);
-
- return ctx.heteroSessionImporterRepo.importSessions({
- agentId: input.agentId,
- groupId: input.groupId,
- sessions: input.sessions as HeteroSessionImportPayload[],
- });
- }),
-
- importTopic: topicProcedure
- .use(withScopedPermission('topic:create'))
- .input(
- z.object({
- agentId: z.string(),
- data: z.string(),
- groupId: z.string().nullish(),
- }),
- )
- .mutation(async ({ input, ctx }) => {
- await assertCanUseConversationTargets(guardCtx(ctx), [
- { agentId: input.agentId, groupId: input.groupId },
- ]);
-
- const result = await ctx.topicImporterRepo.importTopic({
- agentId: input.agentId,
- data: input.data,
- groupId: input.groupId,
- });
-
- return result;
- }),
-
- getMaxTaskDuration: topicProcedure.query(async ({ ctx }) => {
- return ctx.agentOperationModel.getMaxDurationSeconds();
- }),
-
- rankTopics: topicProcedure.input(z.number().max(50).optional()).query(async ({ ctx, input }) => {
- return ctx.topicModel.rank(input);
- }),
-
- recentTopics: topicProcedure
- .input(z.object({ limit: z.number().max(50).optional() }).optional())
- .query(async ({ ctx, input }): Promise<RecentTopic[]> => {
- const recentTopics = await ctx.topicModel.queryRecent(input?.limit ?? 12);
-
- // Separate agent topics and group topics
- const agentTopics = recentTopics.filter((t) => t.type === 'agent');
- const groupTopics = recentTopics.filter((t) => t.type === 'group');
-
- // Find legacy topics: no agentId but has sessionId
- const legacyTopics = agentTopics.filter(
- (topic) => topic.agentId === null && topic.sessionId !== null,
- );
-
- // Batch resolve agentId for legacy topics
- const sessionIds = [...new Set(legacyTopics.map((t) => t.sessionId!))];
- const sessionAgentMap = await batchResolveAgentIdFromSessions(
- sessionIds,
- ctx.serverDB,
- ctx.userId,
- ctx.workspaceId ?? undefined,
- );
-
- // Build agentId map: merge existing agentId with resolved ones
- const topicAgentIdMap = new Map<string, string>();
- for (const topic of agentTopics) {
- if (topic.agentId) {
- topicAgentIdMap.set(topic.id, topic.agentId);
- } else if (topic.sessionId) {
- const resolvedAgentId = sessionAgentMap.get(topic.sessionId);
- if (resolvedAgentId) {
- topicAgentIdMap.set(topic.id, resolvedAgentId);
- }
- }
- }
-
- // Collect all agentIds to fetch agent info
- const allAgentIds = [...new Set(topicAgentIdMap.values())];
-
- // Batch query agent info (already normalized for the inbox agent)
- const agentInfoMap = new Map<
- string,
- { avatar: string | null; backgroundColor: string | null; id: string; title: string | null }
- >();
-
- if (allAgentIds.length > 0) {
- const agentInfos = await ctx.agentModel.getAgentAvatarsByIds(allAgentIds);
-
- for (const agent of agentInfos) {
- agentInfoMap.set(agent.id, agent);
- }
- }
-
- // Batch query group info with member avatars
- const groupInfoMap = new Map<string, RecentTopicGroup>();
- const allGroupIds = [...new Set(groupTopics.map((t) => t.groupId!).filter(Boolean))];
-
- if (allGroupIds.length > 0) {
- // Query chat groups
- const chatGroupInfos = await ctx.serverDB
- .select({
- id: chatGroups.id,
- title: chatGroups.title,
- })
- .from(chatGroups)
- .where(and(inArray(chatGroups.id, allGroupIds), notTrashed(chatGroups.isDeleted)));
-
- // Query group member avatars (already normalized for the inbox agent)
- const groupMembersMap: Map<string, RecentTopicGroupMember[]> =
- await ctx.chatGroupModel.getMemberAvatarsByGroupIds(allGroupIds);
-
- // Build group info map
- for (const group of chatGroupInfos) {
- groupInfoMap.set(group.id, {
- id: group.id,
- members: groupMembersMap.get(group.id) || [],
- title: group.title,
- });
- }
- }
-
- // Runtime migration: backfill agentId for legacy topics
- const runMigration = async () => {
- for (const [sessionId, agentId] of sessionAgentMap) {
- try {
- await ctx.agentMigrationRepo.migrateAgentId({ agentId, sessionId });
- } catch (error) {
- console.error('[AgentMigration] Failed to migrate agentId for recentTopics:', error);
- }
- }
- };
-
- after(runMigration);
-
- // Assemble final result
- return recentTopics.map((topic) => {
- if (topic.type === 'group' && topic.groupId) {
- const groupInfo = groupInfoMap.get(topic.groupId);
- return {
- agent: null,
- group: groupInfo ?? null,
- id: topic.id,
- title: topic.title,
- type: 'group' as const,
- updatedAt: topic.updatedAt,
- };
- }
-
- // Agent topic
- const agentId = topicAgentIdMap.get(topic.id);
- const agentInfo = agentId ? agentInfoMap.get(agentId) : null;
-
- // Always return agent with id if agentId exists (even if avatar/title are null)
- // Frontend needs agent.id to generate links
- const validAgent = agentInfo ? cleanObject(agentInfo) : null;
-
- return {
- agent: validAgent,
- group: null,
- id: topic.id,
- title: topic.title,
- type: 'agent' as const,
- updatedAt: topic.updatedAt,
- };
- });
- }),
-
- removeAllTopics: topicProcedure
- .use(withScopedPermission('topic:delete'))
- .mutation(async ({ ctx }) => {
- await ctx.trashService.trashAllTopics();
- }),
-
- /**
- * Move a topic to the recycle bin. With `removeFiles`, the attachments only
- * this topic references go along as children and are dropped from storage
- * when the topic is purged (restore brings them back too).
- */
- removeTopic: topicProcedure
- .use(withScopedPermission('topic:delete'))
- .input(z.object({ id: z.string(), removeFiles: z.boolean().optional() }))
- .mutation(async ({ input, ctx }) => {
- // `findOwnTopicById` (not `findById`): an agent-share visitor topic is
- // stored under the creator's `userId`, and `TopicModel.delete` refuses to
- // remove it. Resolving through the visitor-excluding lookup keeps the
- // file cleanup below from destroying a visitor conversation's attachments
- // (DB rows + S3 objects) while the topic itself survives.
- const topic = await ctx.topicModel.findOwnTopicById(input.id);
- if (topic) assertWorkspaceRowManageable(ctx, topic.userId, 'topic');
-
- // No creator-visible topic behind this id: nothing to trash.
- if (!topic) return;
-
- await ctx.trashService.trashTopics([input.id], { removeFiles: input.removeFiles });
- }),
-
- searchTopics: topicSearchProcedure
- .input(
- z.object({
- agentId: z.string().optional(),
- groupId: z.string().nullish(),
- keywords: z.string(),
- sessionId: z.string().nullish(),
- }),
- )
- .query(async ({ input, ctx }) => {
- const resolved = await resolveContext(
- { agentId: input.agentId, sessionId: input.sessionId },
- ctx.serverDB,
- ctx.userId,
- ctx.workspaceId ?? undefined,
- );
-
- // Scope the search exactly like the topics list (`query`): by agentId
- // directly (the new agent system stamps every topic with an agentId).
- // Passing only the resolved sessionId used to miss every agentId-scoped
- // topic β€” the cause of "no topics match" in the per-agent Topics search.
- // `containerId` is only the fallback for legacy callers that pass no
- // agentId/groupId.
- return ctx.topicModel.queryByKeyword(input.keywords, {
- agentId: input.agentId,
- containerId: resolved.sessionId,
- groupId: input.groupId,
- });
- }),
-
- /**
- * Update share visibility
- */
- updateShareVisibility: topicProcedure
- .use(withScopedPermission('topic:update'))
- .input(
- z.object({
- topicId: z.string(),
- visibility: z.enum(['private', 'link']),
- }),
- )
- .mutation(async ({ input, ctx }) => {
- await assertCanManageTopicShare(ctx, input.topicId, input.visibility);
-
- const previous = await ctx.topicShareModel.getByTopicId(input.topicId);
- const result = await ctx.topicShareModel.updateVisibility(input.topicId, input.visibility);
-
- if (result && previous) {
- await recordTopicShareAudit(ctx, {
- currentVisibility: result.visibility,
- previousVisibility: previous.visibility,
- topicId: input.topicId,
- });
- }
-
- return result;
- }),
-
- updateTopic: topicProcedure
- .use(withScopedPermission('topic:update'))
- .input(
- z.object({
- id: z.string(),
- value: z.object({
- agentId: z.string().optional(),
- completedAt: z.date().nullish(),
- favorite: z.boolean().optional(),
- historySummary: z.string().optional(),
- messages: z.array(z.string()).optional(),
- // The topic's pinned model (top-level columns) β€” written when the user
- // switches model while the topic is active (see updateTopicModel).
- // Nullish to match `Partial<ChatTopic>` whose model/provider are `string | null`.
- model: z.string().nullish(),
- provider: z.string().nullish(),
- sessionId: z.string().optional(),
- status: chatTopicStatusSchema.nullish(),
- title: z.string().optional(),
- }),
- }),
- )
- .mutation(async ({ input, ctx }) => {
- // Intentionally no creator/owner gate: shared topics are co-editable by
- // members (title/status/metadata); only delete/transfer is creator-scoped.
- // Co-editing still requires `use`-level General access on the agent β€”
- // view-only members are read-only.
- await assertCanUseTopicTargets(guardCtx(ctx), [input.id]);
- await assertCreatorTopicTargets(guardCtx(ctx), [input.id]);
- const { agentId, ...restValue } = input.value;
- if (agentId) await assertCanUseConversationTargets(guardCtx(ctx), [{ agentId }]);
-
- // If agentId is provided, resolve to sessionId
- let resolvedSessionId = restValue.sessionId;
- if (agentId && !resolvedSessionId) {
- const resolved = await resolveContext(
- { agentId },
- ctx.serverDB,
- ctx.userId,
- ctx.workspaceId ?? undefined,
- );
- resolvedSessionId = resolved.sessionId ?? undefined;
- }
-
- return ctx.topicModel.update(input.id, { ...restValue, sessionId: resolvedSessionId });
- }),
-
- /**
- * Switch the topic's pinned model and its effort pin atomically β€” see
- * `TopicModel.updateModelPin`. Same co-editing rules as `updateTopic`.
- */
- updateTopicModel: topicProcedure
- .use(withScopedPermission('topic:update'))
- .input(
- z.object({
- id: z.string(),
- metadata: chatTopicCreateMetadataSchema.optional(),
- model: z.string(),
- provider: z.string(),
- }),
- )
- .mutation(async ({ input, ctx }) => {
- await assertCanUseTopicTargets(guardCtx(ctx), [input.id]);
- await assertCreatorTopicTargets(guardCtx(ctx), [input.id]);
-
- const { id, ...value } = input;
- return ctx.topicModel.updateModelPin(id, value);
- }),
-
- updateTopicMetadata: topicProcedure
- .use(withScopedPermission('topic:update'))
- .input(
- z.object({
- id: z.string(),
- metadata: chatTopicMetadataUpdateSchema,
- }),
- )
- .mutation(async ({ input, ctx }) => {
- // Intentionally no creator/owner gate: metadata follows the same
- // co-editable path as updateTopic (chat/tool flows write fields like
- // runningOperation on shared topics); only delete/transfer is gated.
- // Co-editing still requires `use`-level General access on the agent.
- await assertCanUseTopicTargets(guardCtx(ctx), [input.id]);
- await assertCreatorTopicTargets(guardCtx(ctx), [input.id]);
-
- return ctx.topicModel.updateMetadata(input.id, input.metadata);
- }),
-
- settleRunningOperation: topicProcedure
- .use(withScopedPermission('topic:update'))
- .input(
- z.object({
- id: z.string(),
- operationId: z.string(),
- status: chatTopicStatusSchema.optional(),
- }),
- )
- .mutation(async ({ input, ctx }) => {
- await assertCanUseTopicTargets(guardCtx(ctx), [input.id]);
- // Same visitor guard as `batchMoveTopics`/`cloneTopic` above.
- await assertCreatorTopicTargets(guardCtx(ctx), [input.id]);
-
- // Client-reported end: never clear the marker of a run the server is still
- // driving (an early / mirrored terminal event would otherwise drop the
- // supervisor's topic reservation mid group turn).
- return ctx.topicModel.settleRunningOperation(input.id, input.operationId, input.status, {
- rejectInFlightOperation: true,
- });
- }),
-});
-
-export type TopicRouter = typeof topicRouter;
diff --git a/apps/server/src/routers/lambda/topic/create.test.ts b/apps/server/src/routers/lambda/topic/create.test.ts
new file mode 100644
index 00000000000..b691a76ce8d
--- /dev/null
+++ b/apps/server/src/routers/lambda/topic/create.test.ts
@@ -0,0 +1,59 @@
+// @vitest-environment node
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+vi.mock('@/database/core/db-adaptor', () => ({
+ getServerDB: vi.fn(function () {
+ return {};
+ }),
+}));
+
+const mockTopicBatchCreate = vi.fn();
+vi.mock('@/database/models/topic', () => ({
+ TopicModel: vi.fn(function () {
+ return { batchCreate: mockTopicBatchCreate };
+ }),
+}));
+
+let inFlight = 0;
+let maxInFlight = 0;
+vi.mock('../_helpers/resolveContext', async (importOriginal) => ({
+ ...(await importOriginal<Record<string, unknown>>()),
+ resolveContextWithAgentId: vi.fn(async (input: { agentId?: string }) => {
+ inFlight += 1;
+ maxInFlight = Math.max(maxInFlight, inFlight);
+ // Later items settle first, so result order must not follow completion order.
+ const index = Number(input.agentId?.split('-')[1]);
+ await new Promise((resolve) => setTimeout(resolve, 20 - index));
+ inFlight -= 1;
+ return { agentId: input.agentId, sessionId: `session-${index}` };
+ }),
+}));
+
+const { topicRouter } = await import('./index');
+
+const caller = () => topicRouter.createCaller({ userId: 'user-1' } as any);
+
+describe('topic.batchCreateTopics', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ inFlight = 0;
+ maxInFlight = 0;
+ mockTopicBatchCreate.mockImplementation(async (rows: unknown[]) => rows);
+ });
+
+ it('resolves every item in input order with bounded concurrency', async () => {
+ const input = Array.from({ length: 12 }, (_, index) => ({
+ agentId: `agent-${index}`,
+ title: `Topic ${index}`,
+ }));
+
+ const result = await caller().batchCreateTopics(input);
+
+ expect(result).toEqual({ added: 12, ids: [], skips: [], success: true });
+ expect(mockTopicBatchCreate).toHaveBeenCalledWith(
+ input.map((item, index) => ({ ...item, sessionId: `session-${index}` })),
+ );
+ expect(maxInFlight).toBeGreaterThan(1);
+ expect(maxInFlight).toBeLessThanOrEqual(5);
+ });
+});
diff --git a/apps/server/src/routers/lambda/topic/create.ts b/apps/server/src/routers/lambda/topic/create.ts
new file mode 100644
index 00000000000..2c5f4d18f4e
--- /dev/null
+++ b/apps/server/src/routers/lambda/topic/create.ts
@@ -0,0 +1,268 @@
+import {
+ chatTopicCreateMetadataSchema,
+ type HeteroSessionImportPayload,
+ heteroSessionImportPayloadSchema,
+} from '@lobechat/types';
+import { TRPCError } from '@trpc/server';
+import pMap from 'p-map';
+import { z } from 'zod';
+
+import { withScopedPermission } from '@/business/server/trpc-middlewares/rbacPermission';
+import { ProjectWorkingDirectoryModel } from '@/database/models/projectWorkingDirectory';
+import { router } from '@/libs/trpc/lambda';
+import { type BatchTaskResult } from '@/types/service';
+
+import {
+ assertCanUseConversationTargets,
+ assertCanUseTopicTargets,
+} from '../_helpers/conversationResourceGuard';
+import { resolveContextWithAgentId } from '../_helpers/resolveContext';
+import {
+ assertCreatorMessageTargets,
+ assertCreatorTopicTargets,
+} from '../_helpers/shareVisitorTargetGuard';
+import { basicContextSchema } from '../_schema/context';
+import { guardCtx, topicProcedure } from './procedures';
+
+// Each batch item resolves its agent/session through the DB; cap the fan-out
+// so a large client-supplied batch does not burst concurrent lookups.
+const BATCH_CREATE_CONTEXT_RESOLUTION_CONCURRENCY = 5;
+
+export const createRouter = router({
+ batchCreateTopics: topicProcedure
+ .use(withScopedPermission('topic:create'))
+ .input(
+ z.array(
+ z
+ .object({
+ favorite: z.boolean().optional(),
+ id: z.string().optional(),
+ messages: z.array(z.string()).optional(),
+ title: z.string(),
+ })
+ .extend(basicContextSchema.shape),
+ ),
+ )
+ .mutation(async ({ input, ctx }): Promise<BatchTaskResult> => {
+ // Resolve both directions before authorization: legacy callers may send
+ // only sessionId, while the ACL is attached to the owning agent.
+ const resolvedTopics = await pMap(
+ input,
+ async (item) => {
+ const { agentId, ...rest } = item;
+ const resolved = await resolveContextWithAgentId(
+ { agentId, groupId: rest.groupId, sessionId: rest.sessionId },
+ ctx.serverDB,
+ ctx.userId,
+ ctx.workspaceId ?? undefined,
+ );
+ return { ...rest, agentId: resolved.agentId, sessionId: resolved.sessionId };
+ },
+ { concurrency: BATCH_CREATE_CONTEXT_RESOLUTION_CONCURRENCY },
+ );
+
+ await assertCanUseConversationTargets(
+ guardCtx(ctx),
+ resolvedTopics.map((item) => ({ agentId: item.agentId, groupId: item.groupId })),
+ );
+ // `messages` are REPARENTED onto the new topic by ownership only. A
+ // visitor message (creator-owned row under a `senderId` topic) moved to
+ // a creator topic would escape `notShareVisitorMessage()` for good.
+ await assertCreatorMessageTargets(
+ guardCtx(ctx),
+ resolvedTopics.flatMap((item) => item.messages ?? []),
+ );
+
+ const data = await ctx.topicModel.batchCreate(resolvedTopics as any);
+
+ return { added: data.length, ids: [], skips: [], success: true };
+ }),
+ cloneTopic: topicProcedure
+ .use(withScopedPermission('topic:create'))
+ .input(z.object({ id: z.string(), newTitle: z.string().optional() }))
+ .mutation(async ({ input, ctx }) => {
+ await assertCanUseTopicTargets(guardCtx(ctx), [input.id]);
+ // 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);
+
+ return data.topic.id;
+ }),
+ /**
+ * Fork a topic from one of its messages: copy the conversation prefix
+ * (first message β†’ `messageId`) into a brand new topic and return its id.
+ *
+ * Shares `cloneTopic`'s guards: a fork writes a new topic and copies content
+ * out of the source, so it needs the same `topic:create` capability and the
+ * same refusal to lift a visitor topic's content into creator scope.
+ */
+ forkTopic: topicProcedure
+ .use(withScopedPermission('topic:create'))
+ .input(
+ z.object({
+ id: z.string(),
+ messageId: z.string(),
+ newTitle: z.string().optional(),
+ }),
+ )
+ .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, {
+ upToMessageId: input.messageId,
+ });
+
+ return data.topic.id;
+ }),
+ /**
+ * Edit-and-resend for runtimes whose native history cannot be rewound
+ * (Codex): copies the conversation up to one user message into a new topic
+ * with the edited content. The source topic is left as it was.
+ */
+ branchTopicAtMessage: topicProcedure
+ .use(withScopedPermission('topic:create'))
+ .input(
+ z.object({
+ content: z.string(),
+ editorData: z.record(z.string(), z.any()).nullish(),
+ messageId: z.string(),
+ title: z.string().optional(),
+ topicId: z.string(),
+ }),
+ )
+ .mutation(async ({ input, ctx }) => {
+ const { topicId, messageId, ...edit } = input;
+ await assertCanUseTopicTargets(guardCtx(ctx), [topicId]);
+ // Same visitor guard as `cloneTopic` above.
+ await assertCreatorTopicTargets(guardCtx(ctx), [topicId]);
+ const branch = await ctx.topicRepo.branchAtMessage(topicId, messageId, edit);
+ if (!branch) throw new TRPCError({ code: 'NOT_FOUND', message: 'User message not found' });
+
+ return { messageId: branch.messageId, topicId: branch.topic.id };
+ }),
+ createTopic: topicProcedure
+ .use(withScopedPermission('topic:create'))
+ .input(
+ z
+ .object({
+ favorite: z.boolean().optional(),
+ groupId: z.string().nullish(),
+ messages: z.array(z.string()).optional(),
+ // The pinned reasoning snapshot taken next to the pinned model
+ // (`snapshotAgentReasoning`); other metadata keys are server-owned.
+ metadata: chatTopicCreateMetadataSchema.optional(),
+ // The topic's pinned model snapshot, persisted to the top-level
+ // `topics.model`/`provider` columns (config source of truth).
+ model: z.string().optional(),
+ // Bind the new row to a project working directory. Resolved and
+ // pinned below, mirroring `projectWorkingDirectory.startTopic`.
+ projectWorkingDirectoryId: z.string().optional(),
+ provider: z.string().optional(),
+ title: z.string(),
+ trigger: z.string().optional(),
+ })
+ .extend(basicContextSchema.shape),
+ )
+ .mutation(async ({ input, ctx }) => {
+ const { agentId, projectWorkingDirectoryId, ...rest } = input;
+ const resolved = await resolveContextWithAgentId(
+ { agentId, groupId: rest.groupId, sessionId: rest.sessionId },
+ ctx.serverDB,
+ ctx.userId,
+ ctx.workspaceId ?? undefined,
+ );
+ await assertCanUseConversationTargets(guardCtx(ctx), [
+ { agentId: resolved.agentId, groupId: rest.groupId },
+ ]);
+ // See batchCreateTopics β€” reparenting a visitor message would leak it.
+ await assertCreatorMessageTargets(guardCtx(ctx), rest.messages ?? []);
+
+ // A topic started from a project group's "+" defers its row to the first
+ // message. Pin the directory here so the row is born inside the project β€”
+ // list, sidebar group and execution routing β€” instead of dropping into a
+ // path-only conversation. A directory that can no longer be resolved
+ // (deleted, unlinked from its environment, or another user's) is logged
+ // and skipped: losing the binding must not fail the user's first send.
+ const directory = projectWorkingDirectoryId
+ ? await new ProjectWorkingDirectoryModel(
+ ctx.serverDB,
+ ctx.userId,
+ ctx.workspaceId ?? undefined,
+ )
+ .resolve(projectWorkingDirectoryId)
+ .catch((error) => {
+ console.error(
+ '[topic.createTopic] Failed to resolve the project directory binding:',
+ error,
+ );
+ return undefined;
+ })
+ : undefined;
+
+ const data = await ctx.topicModel.create({
+ ...rest,
+ agentId: resolved.agentId,
+ sessionId: resolved.sessionId,
+ ...(directory
+ ? {
+ metadata: {
+ ...rest.metadata,
+ boundDeviceId: directory.deviceId,
+ workingDirectory: directory.path,
+ workingDirectoryConfig: { path: directory.path },
+ },
+ projectId: directory.projectId,
+ projectWorkingDirectoryId: directory.id,
+ }
+ : {}),
+ });
+
+ return data.id;
+ }),
+ importTopic: topicProcedure
+ .use(withScopedPermission('topic:create'))
+ .input(
+ z.object({
+ agentId: z.string(),
+ data: z.string(),
+ groupId: z.string().nullish(),
+ }),
+ )
+ .mutation(async ({ input, ctx }) => {
+ await assertCanUseConversationTargets(guardCtx(ctx), [
+ { agentId: input.agentId, groupId: input.groupId },
+ ]);
+
+ const result = await ctx.topicImporterRepo.importTopic({
+ agentId: input.agentId,
+ data: input.data,
+ groupId: input.groupId,
+ });
+
+ return result;
+ }),
+ importHeteroSessions: topicProcedure
+ .use(withScopedPermission('topic:create'))
+ .input(
+ z.object({
+ agentId: z.string(),
+ groupId: z.string().nullish(),
+ sessions: z.array(heteroSessionImportPayloadSchema),
+ }),
+ )
+ .mutation(async ({ input, ctx }) => {
+ await assertCanUseConversationTargets(guardCtx(ctx), [
+ { agentId: input.agentId, groupId: input.groupId },
+ ]);
+
+ return ctx.heteroSessionImporterRepo.importSessions({
+ agentId: input.agentId,
+ groupId: input.groupId,
+ sessions: input.sessions as HeteroSessionImportPayload[],
+ });
+ }),
+ getHeteroSessionImportStatus: topicProcedure.query(async ({ ctx }) => {
+ return ctx.heteroSessionImporterRepo.getImportStatus();
+ }),
+});
diff --git a/apps/server/src/routers/lambda/topic/index.procedures.test.ts b/apps/server/src/routers/lambda/topic/index.procedures.test.ts
new file mode 100644
index 00000000000..fea367c688f
--- /dev/null
+++ b/apps/server/src/routers/lambda/topic/index.procedures.test.ts
@@ -0,0 +1,65 @@
+// @vitest-environment node
+import { describe, expect, it } from 'vitest';
+
+import { topicRouter } from '.';
+
+/**
+ * Pins the router's public surface: every procedure path, its kind, and its
+ * middleware chain length (which encodes the procedure builder and its input
+ * parsers). Splitting the router across files must keep all three.
+ */
+describe('topicRouter procedures', () => {
+ const procedures = (topicRouter as any)._def.procedures as Record<string, any>;
+
+ it('exposes exactly the expected procedure paths', () => {
+ expect(Object.keys(procedures).sort()).toEqual(expected().map(([name]) => name));
+ });
+
+ it.each(expected())('%s is a %s with %i middlewares', (name, type, middlewares) => {
+ expect(procedures[name]._def.type).toBe(type);
+ expect(procedures[name]._def.middlewares).toHaveLength(middlewares);
+ });
+});
+
+function expected(): Array<
+ [name: string, type: 'mutation' | 'query' | 'subscription', middlewares: number]
+> {
+ return [
+ ['batchCreateTopics', 'mutation', 13],
+ ['batchDelete', 'mutation', 13],
+ ['batchDeleteByAgentId', 'mutation', 13],
+ ['batchDeleteByGroupId', 'mutation', 13],
+ ['batchDeleteBySessionId', 'mutation', 13],
+ ['batchMoveTopics', 'mutation', 13],
+ ['branchTopicAtMessage', 'mutation', 13],
+ ['cancelRateLimitContinuation', 'mutation', 13],
+ ['cloneTopic', 'mutation', 13],
+ ['countTopics', 'query', 12],
+ ['createTopic', 'mutation', 13],
+ ['disableSharing', 'mutation', 13],
+ ['enableSharing', 'mutation', 13],
+ ['forkTopic', 'mutation', 13],
+ ['getHeteroSessionImportStatus', 'query', 11],
+ ['getMaxTaskDuration', 'query', 11],
+ ['getShareInfo', 'query', 12],
+ ['getTopicContext', 'query', 12],
+ ['getTopicDetail', 'query', 12],
+ ['getTopicTranscript', 'query', 12],
+ ['getTopics', 'query', 12],
+ ['hasTopicFiles', 'query', 13],
+ ['hasTopics', 'query', 11],
+ ['importHeteroSessions', 'mutation', 13],
+ ['importTopic', 'mutation', 13],
+ ['queryTopics', 'query', 12],
+ ['rankTopics', 'query', 12],
+ ['recentTopics', 'query', 12],
+ ['removeAllTopics', 'mutation', 12],
+ ['removeTopic', 'mutation', 13],
+ ['searchTopics', 'query', 13],
+ ['settleRunningOperation', 'mutation', 13],
+ ['updateShareVisibility', 'mutation', 13],
+ ['updateTopic', 'mutation', 13],
+ ['updateTopicMetadata', 'mutation', 13],
+ ['updateTopicModel', 'mutation', 13],
+ ];
+}
diff --git a/apps/server/src/routers/lambda/topic/index.ts b/apps/server/src/routers/lambda/topic/index.ts
new file mode 100644
index 00000000000..a92d958609a
--- /dev/null
+++ b/apps/server/src/routers/lambda/topic/index.ts
@@ -0,0 +1,17 @@
+import { mergeRouters } from '@/libs/trpc/lambda';
+
+import { createRouter } from './create';
+import { queryRouter } from './queries';
+import { removeRouter } from './remove';
+import { shareRouter } from './share';
+import { updateRouter } from './update';
+
+export const topicRouter = mergeRouters(
+ updateRouter,
+ queryRouter,
+ createRouter,
+ removeRouter,
+ shareRouter,
+);
+
+export type TopicRouter = typeof topicRouter;
diff --git a/apps/server/src/routers/lambda/topic/procedures.ts b/apps/server/src/routers/lambda/topic/procedures.ts
new file mode 100644
index 00000000000..615045aca49
--- /dev/null
+++ b/apps/server/src/routers/lambda/topic/procedures.ts
@@ -0,0 +1,62 @@
+import { wsCompatProcedure } from '@/business/server/trpc-middlewares/workspaceAuth';
+import { AgentModel } from '@/database/models/agent';
+import { AgentOperationModel } from '@/database/models/agentOperation';
+import { ChatGroupModel } from '@/database/models/chatGroup';
+import { FileModel } from '@/database/models/file';
+import { MessageModel } from '@/database/models/message';
+import { TopicModel } from '@/database/models/topic';
+import { TopicShareModel } from '@/database/models/topicShare';
+import { AgentMigrationRepo } from '@/database/repositories/agentMigration';
+import { HeteroSessionImporterRepo } from '@/database/repositories/heteroSessionImporter';
+import { TopicRepository } from '@/database/repositories/topic';
+import { TopicImporterRepo } from '@/database/repositories/topicImporter';
+import type { LobeChatDatabase } from '@/database/type';
+import { serverDatabase } from '@/libs/trpc/lambda/middleware';
+import { createFtsSearchRepo } from '@/server/services/ftsSearch';
+import { TrashService } from '@/server/services/trash';
+
+/** Ctx slice consumed by the conversation General-access guards. */
+export const guardCtx = (ctx: {
+ serverDB: LobeChatDatabase;
+ userId: string;
+ workspaceId?: string | null;
+}) => ({ db: ctx.serverDB, userId: ctx.userId, workspaceId: ctx.workspaceId });
+
+export const topicProcedure = wsCompatProcedure.use(serverDatabase).use(async (opts) => {
+ const { ctx } = opts;
+ const wsId = ctx.workspaceId ?? undefined;
+
+ return opts.next({
+ ctx: {
+ agentMigrationRepo: new AgentMigrationRepo(ctx.serverDB, ctx.userId, wsId),
+ agentModel: new AgentModel(ctx.serverDB, ctx.userId, wsId),
+ agentOperationModel: new AgentOperationModel(ctx.serverDB, ctx.userId, wsId),
+ chatGroupModel: new ChatGroupModel(ctx.serverDB, ctx.userId, wsId),
+ fileModel: new FileModel(ctx.serverDB, ctx.userId, wsId),
+ heteroSessionImporterRepo: new HeteroSessionImporterRepo(ctx.serverDB, ctx.userId, wsId),
+ messageModel: new MessageModel(ctx.serverDB, ctx.userId, wsId),
+ topicImporterRepo: new TopicImporterRepo(ctx.serverDB, ctx.userId, wsId),
+ topicModel: new TopicModel(ctx.serverDB, ctx.userId, wsId),
+ topicRepo: new TopicRepository(ctx.serverDB, ctx.userId, wsId),
+ topicShareModel: new TopicShareModel(ctx.serverDB, ctx.userId, wsId),
+ trashService: new TrashService(ctx.serverDB, ctx.userId, wsId),
+ },
+ });
+});
+
+export const topicSearchProcedure = topicProcedure.use(async (opts) => {
+ const { ctx } = opts;
+ const workspaceId = ctx.workspaceId ?? undefined;
+ const ftsSearchRepo = await createFtsSearchRepo({
+ db: ctx.serverDB,
+ userId: ctx.userId,
+ usage: 'topic_search',
+ workspaceId,
+ });
+
+ return opts.next({
+ ctx: {
+ topicModel: new TopicModel(ctx.serverDB, ctx.userId, workspaceId, ftsSearchRepo),
+ },
+ });
+});
diff --git a/apps/server/src/routers/lambda/topic/queries.ts b/apps/server/src/routers/lambda/topic/queries.ts
new file mode 100644
index 00000000000..2fed485af18
--- /dev/null
+++ b/apps/server/src/routers/lambda/topic/queries.ts
@@ -0,0 +1,410 @@
+import {
+ type RecentTopic,
+ type RecentTopicGroup,
+ type RecentTopicGroupMember,
+} from '@lobechat/types';
+import { cleanObject } from '@lobechat/utils';
+import { TRPCError } from '@trpc/server';
+import { and, inArray } from 'drizzle-orm';
+import { z } from 'zod';
+
+import { withScopedPermission } from '@/business/server/trpc-middlewares/rbacPermission';
+import { MessageModel } from '@/database/models/message';
+import { chatGroups } from '@/database/schemas';
+import { notTrashed } from '@/database/utils/softDelete';
+import { router } from '@/libs/trpc/lambda';
+import { TopicReferenceService } from '@/server/services/topicReference';
+import { after } from '@/server/utils/scheduleAfterResponse';
+
+import {
+ batchResolveAgentIdFromSessions,
+ resolveAgentIdFromSession,
+ resolveContext,
+} from '../_helpers/resolveContext';
+import { topicProcedure, topicSearchProcedure } from './procedures';
+
+export const queryRouter = router({
+ getTopicDetail: topicProcedure
+ .input(z.object({ id: z.string() }))
+ .query(async ({ input, ctx }) => {
+ const topic = await ctx.topicModel.findOwnTopicById(input.id);
+ if (!topic) return null;
+ return topic;
+ }),
+ getTopicTranscript: topicProcedure
+ .input(
+ z.object({
+ includeMessages: z.boolean().default(true),
+ limit: z.number().int().min(1).max(500).default(50),
+ offset: z.number().int().min(0).default(0),
+ topicId: z.string(),
+ }),
+ )
+ .query(async ({ input, ctx }) => {
+ // `lh topic view` from a workspace run may be given one of the user's personal topic ids.
+ const topic = await new TopicReferenceService(
+ ctx.serverDB,
+ ctx.userId,
+ ctx.workspaceId ?? undefined,
+ ).findTopic(input.topicId);
+
+ if (!topic) {
+ throw new TRPCError({
+ code: 'NOT_FOUND',
+ message: `Topic not found: ${input.topicId}`,
+ });
+ }
+
+ if (!input.includeMessages) {
+ return { items: [], topic, total: null };
+ }
+
+ const messageModel =
+ (topic.workspaceId ?? undefined) === (ctx.workspaceId ?? undefined)
+ ? ctx.messageModel
+ : new MessageModel(ctx.serverDB, ctx.userId, topic.workspaceId ?? undefined);
+ const transcript = await messageModel.queryTopicTranscript({
+ limit: input.limit,
+ offset: input.offset,
+ topicId: input.topicId,
+ });
+
+ return { ...transcript, topic };
+ }),
+ /**
+ * @deprecated The `lobe-topic-reference` tool was removed; agents read topics with
+ * `lh topic view`. Kept for released Desktop builds and cached web bundles whose
+ * client executor still calls this. Remove once those clients have aged out.
+ */
+ getTopicContext: topicProcedure
+ .input(z.object({ topicId: z.string() }))
+ .query(async ({ input, ctx }) =>
+ new TopicReferenceService(
+ ctx.serverDB,
+ ctx.userId,
+ ctx.workspaceId ?? undefined,
+ ).getTopicContext(input),
+ ),
+ countTopics: topicProcedure
+ .input(
+ z
+ .object({
+ agentId: z.string().optional(),
+ containerId: z.string().nullish(),
+ endDate: z.string().optional(),
+ range: z.tuple([z.string(), z.string()]).optional(),
+ startDate: z.string().optional(),
+ })
+ .optional(),
+ )
+ .query(async ({ ctx, input }) => {
+ return ctx.topicModel.count(input);
+ }),
+ queryTopics: topicProcedure
+ .input(
+ z
+ .object({
+ pageSize: z.number().max(500).optional(),
+ statuses: z.array(z.string()).optional(),
+ withLastMessage: z.boolean().optional(),
+ })
+ .optional(),
+ )
+ .query(async ({ input, ctx }) => {
+ return ctx.topicModel.queryTopics({
+ pageSize: input?.pageSize,
+ statuses: input?.statuses,
+ withLastMessage: input?.withLastMessage,
+ });
+ }),
+ getTopics: topicProcedure
+ .input(
+ z.object({
+ agentId: z.string().nullish(),
+ current: z.number().optional(),
+ /**
+ * Scope an `agentId` query to the builder conversations that configured
+ * one target. Builder panels show their full history on purpose; these
+ * are for callers that want a single agent's / group's builds.
+ */
+ editingAgentId: z.string().nullish(),
+ editingGroupId: z.string().nullish(),
+ excludeStatuses: z.array(z.string()).optional(),
+ excludeTriggers: z.array(z.string()).optional(),
+ groupId: z.string().nullish(),
+ includeTriggers: z.array(z.string()).optional(),
+ isInbox: z.boolean().optional(),
+ pageSize: z.number().max(100).optional(),
+ sessionId: z.string().nullish(),
+ /**
+ * Server-side ordering. Defaults to `updatedAt`; `status` orders by
+ * status priority for the sidebar "group by status" mode.
+ */
+ sortBy: z.enum(['updatedAt', 'status']).optional(),
+ triggers: z.array(z.string()).optional(),
+ /**
+ * When true, returns extra card-detail columns (firstUserMessage,
+ * messageCount, cost, tokenUsage, description, trigger). Default false
+ * so the sidebar list stays cheap β€” only the management page opts in.
+ */
+ withDetails: z.boolean().optional(),
+ }),
+ )
+ .query(async ({ input, ctx }) => {
+ const {
+ sessionId,
+ isInbox,
+ groupId,
+ excludeStatuses,
+ excludeTriggers,
+ includeTriggers,
+ triggers,
+ ...rest
+ } = input;
+
+ // If groupId is provided, query by groupId directly
+ if (groupId) {
+ const result = await ctx.topicModel.query({
+ excludeStatuses,
+ excludeTriggers,
+ groupId,
+ includeTriggers,
+ triggers,
+ ...rest,
+ });
+ return { items: result.items, total: result.total };
+ }
+
+ // If sessionId is provided but no agentId, need to reverse lookup agentId
+ let effectiveAgentId = rest.agentId;
+ if (!effectiveAgentId && sessionId) {
+ effectiveAgentId = await resolveAgentIdFromSession(
+ sessionId,
+ ctx.serverDB,
+ ctx.userId,
+ ctx.workspaceId ?? undefined,
+ );
+ }
+
+ const result = await ctx.topicModel.query({
+ ...rest,
+ agentId: effectiveAgentId,
+ excludeStatuses,
+ excludeTriggers,
+ includeTriggers,
+ isInbox,
+ triggers,
+ });
+
+ // Runtime migration: backfill agentId for ALL legacy topics and messages under this agent
+ const runMigration = async () => {
+ if (!effectiveAgentId) return;
+
+ // Get the associated sessionId for migration
+ const resolved = await resolveContext(
+ { agentId: effectiveAgentId },
+ ctx.serverDB,
+ ctx.userId,
+ ctx.workspaceId ?? undefined,
+ );
+
+ const migrationParams = isInbox
+ ? { agentId: effectiveAgentId, isInbox: true as const, sessionId: resolved.sessionId }
+ : resolved.sessionId
+ ? { agentId: effectiveAgentId, sessionId: resolved.sessionId }
+ : null;
+
+ if (migrationParams) {
+ try {
+ await ctx.agentMigrationRepo.migrateAgentId(migrationParams);
+ } catch (error) {
+ console.error('[AgentMigration] Failed to migrate agentId:', error);
+ }
+ }
+ };
+
+ after(runMigration);
+
+ return { items: result.items, total: result.total };
+ }),
+ hasTopicFiles: topicProcedure
+ .use(withScopedPermission('topic:delete'))
+ .input(z.object({ ids: z.array(z.string()).min(1) }))
+ .query(async ({ input, ctx }) => {
+ try {
+ const hasFiles = await ctx.fileModel.hasFilesByTopicIds(input.ids);
+ return { data: { hasFiles }, success: true };
+ } catch (error) {
+ console.error('[topic:hasTopicFiles]', error);
+ throw new TRPCError({
+ cause: error,
+ code: 'INTERNAL_SERVER_ERROR',
+ message: 'Failed to check topic files',
+ });
+ }
+ }),
+ hasTopics: topicProcedure.query(async ({ ctx }) => {
+ return (await ctx.topicModel.count()) === 0;
+ }),
+ getMaxTaskDuration: topicProcedure.query(async ({ ctx }) => {
+ return ctx.agentOperationModel.getMaxDurationSeconds();
+ }),
+ rankTopics: topicProcedure.input(z.number().max(50).optional()).query(async ({ ctx, input }) => {
+ return ctx.topicModel.rank(input);
+ }),
+ recentTopics: topicProcedure
+ .input(z.object({ limit: z.number().max(50).optional() }).optional())
+ .query(async ({ ctx, input }): Promise<RecentTopic[]> => {
+ const recentTopics = await ctx.topicModel.queryRecent(input?.limit ?? 12);
+
+ // Separate agent topics and group topics
+ const agentTopics = recentTopics.filter((t) => t.type === 'agent');
+ const groupTopics = recentTopics.filter((t) => t.type === 'group');
+
+ // Find legacy topics: no agentId but has sessionId
+ const legacyTopics = agentTopics.filter(
+ (topic) => topic.agentId === null && topic.sessionId !== null,
+ );
+
+ // Batch resolve agentId for legacy topics
+ const sessionIds = [...new Set(legacyTopics.map((t) => t.sessionId!))];
+ const sessionAgentMap = await batchResolveAgentIdFromSessions(
+ sessionIds,
+ ctx.serverDB,
+ ctx.userId,
+ ctx.workspaceId ?? undefined,
+ );
+
+ // Build agentId map: merge existing agentId with resolved ones
+ const topicAgentIdMap = new Map<string, string>();
+ for (const topic of agentTopics) {
+ if (topic.agentId) {
+ topicAgentIdMap.set(topic.id, topic.agentId);
+ } else if (topic.sessionId) {
+ const resolvedAgentId = sessionAgentMap.get(topic.sessionId);
+ if (resolvedAgentId) {
+ topicAgentIdMap.set(topic.id, resolvedAgentId);
+ }
+ }
+ }
+
+ // Collect all agentIds to fetch agent info
+ const allAgentIds = [...new Set(topicAgentIdMap.values())];
+
+ // Batch query agent info (already normalized for the inbox agent)
+ const agentInfoMap = new Map<
+ string,
+ { avatar: string | null; backgroundColor: string | null; id: string; title: string | null }
+ >();
+
+ if (allAgentIds.length > 0) {
+ const agentInfos = await ctx.agentModel.getAgentAvatarsByIds(allAgentIds);
+
+ for (const agent of agentInfos) {
+ agentInfoMap.set(agent.id, agent);
+ }
+ }
+
+ // Batch query group info with member avatars
+ const groupInfoMap = new Map<string, RecentTopicGroup>();
+ const allGroupIds = [...new Set(groupTopics.map((t) => t.groupId!).filter(Boolean))];
+
+ if (allGroupIds.length > 0) {
+ // Query chat groups
+ const chatGroupInfos = await ctx.serverDB
+ .select({
+ id: chatGroups.id,
+ title: chatGroups.title,
+ })
+ .from(chatGroups)
+ .where(and(inArray(chatGroups.id, allGroupIds), notTrashed(chatGroups.isDeleted)));
+
+ // Query group member avatars (already normalized for the inbox agent)
+ const groupMembersMap: Map<string, RecentTopicGroupMember[]> =
+ await ctx.chatGroupModel.getMemberAvatarsByGroupIds(allGroupIds);
+
+ // Build group info map
+ for (const group of chatGroupInfos) {
+ groupInfoMap.set(group.id, {
+ id: group.id,
+ members: groupMembersMap.get(group.id) || [],
+ title: group.title,
+ });
+ }
+ }
+
+ // Runtime migration: backfill agentId for legacy topics
+ const runMigration = async () => {
+ for (const [sessionId, agentId] of sessionAgentMap) {
+ try {
+ await ctx.agentMigrationRepo.migrateAgentId({ agentId, sessionId });
+ } catch (error) {
+ console.error('[AgentMigration] Failed to migrate agentId for recentTopics:', error);
+ }
+ }
+ };
+
+ after(runMigration);
+
+ // Assemble final result
+ return recentTopics.map((topic) => {
+ if (topic.type === 'group' && topic.groupId) {
+ const groupInfo = groupInfoMap.get(topic.groupId);
+ return {
+ agent: null,
+ group: groupInfo ?? null,
+ id: topic.id,
+ title: topic.title,
+ type: 'group' as const,
+ updatedAt: topic.updatedAt,
+ };
+ }
+
+ // Agent topic
+ const agentId = topicAgentIdMap.get(topic.id);
+ const agentInfo = agentId ? agentInfoMap.get(agentId) : null;
+
+ // Always return agent with id if agentId exists (even if avatar/title are null)
+ // Frontend needs agent.id to generate links
+ const validAgent = agentInfo ? cleanObject(agentInfo) : null;
+
+ return {
+ agent: validAgent,
+ group: null,
+ id: topic.id,
+ title: topic.title,
+ type: 'agent' as const,
+ updatedAt: topic.updatedAt,
+ };
+ });
+ }),
+ searchTopics: topicSearchProcedure
+ .input(
+ z.object({
+ agentId: z.string().optional(),
+ groupId: z.string().nullish(),
+ keywords: z.string(),
+ sessionId: z.string().nullish(),
+ }),
+ )
+ .query(async ({ input, ctx }) => {
+ const resolved = await resolveContext(
+ { agentId: input.agentId, sessionId: input.sessionId },
+ ctx.serverDB,
+ ctx.userId,
+ ctx.workspaceId ?? undefined,
+ );
+
+ // Scope the search exactly like the topics list (`query`): by agentId
+ // directly (the new agent system stamps every topic with an agentId).
+ // Passing only the resolved sessionId used to miss every agentId-scoped
+ // topic β€” the cause of "no topics match" in the per-agent Topics search.
+ // `containerId` is only the fallback for legacy callers that pass no
+ // agentId/groupId.
+ return ctx.topicModel.queryByKeyword(input.keywords, {
+ agentId: input.agentId,
+ containerId: resolved.sessionId,
+ groupId: input.groupId,
+ });
+ }),
+});
diff --git a/apps/server/src/routers/lambda/topic/remove.ts b/apps/server/src/routers/lambda/topic/remove.ts
new file mode 100644
index 00000000000..3c90eff2098
--- /dev/null
+++ b/apps/server/src/routers/lambda/topic/remove.ts
@@ -0,0 +1,102 @@
+import { z } from 'zod';
+
+import { withScopedPermission } from '@/business/server/trpc-middlewares/rbacPermission';
+import { router } from '@/libs/trpc/lambda';
+
+import {
+ assertWorkspaceRowManageable,
+ shouldRestrictBulkDeleteToCreator,
+} from '../_helpers/assertWorkspaceRowManageable';
+import {
+ assertCanUseConversationTargets,
+ assertCanUseSessionTargets,
+} from '../_helpers/conversationResourceGuard';
+import { resolveContext } from '../_helpers/resolveContext';
+import { guardCtx, topicProcedure } from './procedures';
+
+const topicBulkDeleteScopeSchema = z.enum(['own', 'workspace']).default('own');
+
+export const removeRouter = router({
+ batchDelete: topicProcedure
+ .use(withScopedPermission('topic:delete'))
+ .input(z.object({ ids: z.array(z.string()) }))
+ .mutation(async ({ input, ctx }) => {
+ const rows = await ctx.topicModel.findOwnersByIds(input.ids);
+ for (const userId of new Set(rows.map((row) => row.userId))) {
+ assertWorkspaceRowManageable(ctx, userId, 'topic');
+ }
+
+ await ctx.trashService.trashTopics(input.ids);
+ }),
+ batchDeleteByAgentId: topicProcedure
+ .use(withScopedPermission('topic:delete'))
+ .input(z.object({ agentId: z.string(), scope: topicBulkDeleteScopeSchema }))
+ .mutation(async ({ input, ctx }) => {
+ const restrictToCreator = shouldRestrictBulkDeleteToCreator(ctx, input.scope);
+
+ await ctx.trashService.trashTopicsByAgent(input.agentId, { restrictToCreator });
+ }),
+ batchDeleteByGroupId: topicProcedure
+ .use(withScopedPermission('topic:delete'))
+ .input(z.object({ groupId: z.string(), scope: topicBulkDeleteScopeSchema }))
+ .mutation(async ({ input, ctx }) => {
+ await assertCanUseConversationTargets(guardCtx(ctx), [{ groupId: input.groupId }]);
+ const restrictToCreator = shouldRestrictBulkDeleteToCreator(ctx, input.scope);
+
+ await ctx.trashService.trashTopicsByGroup(input.groupId, { restrictToCreator });
+ }),
+ batchDeleteBySessionId: topicProcedure
+ .use(withScopedPermission('topic:delete'))
+ .input(
+ z.object({
+ agentId: z.string().optional(),
+ id: z.string().nullish(),
+ scope: topicBulkDeleteScopeSchema,
+ }),
+ )
+ .mutation(async ({ input, ctx }) => {
+ const resolved = await resolveContext(
+ { agentId: input.agentId, sessionId: input.id },
+ ctx.serverDB,
+ ctx.userId,
+ ctx.workspaceId ?? undefined,
+ );
+
+ if (input.agentId) {
+ await assertCanUseConversationTargets(guardCtx(ctx), [{ agentId: input.agentId }]);
+ } else if (resolved.sessionId) {
+ await assertCanUseSessionTargets(guardCtx(ctx), [resolved.sessionId]);
+ }
+
+ const restrictToCreator = shouldRestrictBulkDeleteToCreator(ctx, input.scope);
+
+ await ctx.trashService.trashTopicsBySession(resolved.sessionId, { restrictToCreator });
+ }),
+ removeAllTopics: topicProcedure
+ .use(withScopedPermission('topic:delete'))
+ .mutation(async ({ ctx }) => {
+ await ctx.trashService.trashAllTopics();
+ }),
+ /**
+ * Move a topic to the recycle bin. With `removeFiles`, the attachments only
+ * this topic references go along as children and are dropped from storage
+ * when the topic is purged (restore brings them back too).
+ */
+ removeTopic: topicProcedure
+ .use(withScopedPermission('topic:delete'))
+ .input(z.object({ id: z.string(), removeFiles: z.boolean().optional() }))
+ .mutation(async ({ input, ctx }) => {
+ // `findOwnTopicById` (not `findById`): an agent-share visitor topic is
+ // stored under the creator's `userId`, and `TopicModel.delete` refuses to
+ // remove it. Resolving through the visitor-excluding lookup keeps the
+ // file cleanup below from destroying a visitor conversation's attachments
+ // (DB rows + S3 objects) while the topic itself survives.
+ const topic = await ctx.topicModel.findOwnTopicById(input.id);
+ if (topic) assertWorkspaceRowManageable(ctx, topic.userId, 'topic');
+
+ // No creator-visible topic behind this id: nothing to trash.
+ if (!topic) return;
+
+ await ctx.trashService.trashTopics([input.id], { removeFiles: input.removeFiles });
+ }),
+});
diff --git a/apps/server/src/routers/lambda/topic/share.ts b/apps/server/src/routers/lambda/topic/share.ts
new file mode 100644
index 00000000000..585d526805c
--- /dev/null
+++ b/apps/server/src/routers/lambda/topic/share.ts
@@ -0,0 +1,242 @@
+import { PERMISSION_ACTIONS } from '@lobechat/const/rbac';
+import { canPublishAgentTopicLink } from '@lobechat/types';
+import { TRPCError } from '@trpc/server';
+import { z } from 'zod';
+
+import { withScopedPermission } from '@/business/server/trpc-middlewares/rbacPermission';
+import type { AgentModel } from '@/database/models/agent';
+import type { ChatGroupModel } from '@/database/models/chatGroup';
+import { RbacModel } from '@/database/models/rbac';
+import type { TopicModel } from '@/database/models/topic';
+import { WorkspaceAuditLogModel } from '@/database/models/workspaceAuditLog';
+import type { LobeChatDatabase } from '@/database/type';
+import { router } from '@/libs/trpc/lambda';
+
+import { assertCanUseTopicTargets } from '../_helpers/conversationResourceGuard';
+import { resolveAgentIdFromSession } from '../_helpers/resolveContext';
+import { guardCtx, topicProcedure } from './procedures';
+
+interface TopicShareCtx {
+ agentModel: AgentModel;
+ chatGroupModel: ChatGroupModel;
+ serverDB: LobeChatDatabase;
+ topicModel: TopicModel;
+ userId: string;
+ workspaceId?: string | null;
+}
+
+/** Workspace owners hold the `:all` scope; everyone else is capped to `:owner`. */
+const isWorkspaceTopicOwner = (ctx: TopicShareCtx) =>
+ new RbacModel(ctx.serverDB, ctx.userId).hasPermission(`${PERMISSION_ACTIONS.TOPIC_UPDATE}:all`, {
+ workspaceId: ctx.workspaceId!,
+ });
+
+/**
+ * The agent a topic answers to, for policy purposes.
+ *
+ * Group topics resolve through their supervisor first: a group conversation
+ * *is* a conversation with its supervisor, that is the row the group's
+ * Permission page writes, and `createTopic` accepts a `groupId` with no agent
+ * or session at all β€” so reading `agentId` first would leave those rows with
+ * no policy to apply. Agent-native topics then carry `agentId` directly, and
+ * legacy session-only rows predate that column, so resolve through the session
+ * rather than letting them slip past the policy.
+ */
+const resolveTopicShareAgent = async (
+ ctx: TopicShareCtx,
+ topic: { agentId?: string | null; groupId?: string | null; sessionId?: string | null },
+) => {
+ const agentId =
+ (topic.groupId ? await ctx.chatGroupModel.getSupervisorAgentId(topic.groupId) : null) ??
+ topic.agentId ??
+ (topic.sessionId
+ ? await resolveAgentIdFromSession(topic.sessionId, ctx.serverDB, ctx.userId, ctx.workspaceId!)
+ : undefined);
+ if (!agentId) return null;
+
+ return ctx.agentModel.getTopicShareSubject(agentId);
+};
+
+/**
+ * Workspace gate for topic-share management.
+ *
+ * The baseline is the co-editing rule (same gate as `updateTopic`): any member
+ * with `use`-level General access on the topic's conversation may manage its
+ * share β€” view-only members stay read-only. Personal mode needs no extra check
+ * β€” the model's ownership filter already scopes mutations to the caller.
+ *
+ * A topic that backs no conversation at all (legacy rows carrying neither an
+ * agent, a group, nor a resolvable session) resolves to zero targets, so the
+ * guard would pass for every member. Sharing is a wider grant than editing β€”
+ * a link exposes the whole conversation to anyone holding it β€” so those fall
+ * back to the stricter creator-or-workspace-owner rule rather than inheriting
+ * the vacuous pass.
+ *
+ * *Publishing* narrows that further, governed by the owning agent's
+ * `topicSharePolicy`. Under `restricted` only the agent's creator and
+ * workspace owners may publish, which overrides even topic ownership β€” that is
+ * the whole point of the policy. Revoking a link, and the `private`
+ * placeholder the share popover creates when it opens, are never restricted:
+ * pulling a topic out of circulation is always safe, and gating the
+ * placeholder would leave a restricted member with a popover that cannot even
+ * load its state. Pass `targetVisibility: 'link'` when the operation would
+ * publish.
+ */
+const assertCanManageTopicShare = async (
+ ctx: TopicShareCtx,
+ topicId: string,
+ targetVisibility?: 'link' | 'private',
+) => {
+ // `findOwnTopicById`: an agent-share visitor topic is stored under the
+ // creator's userId, and publishing a public link for one would expose the
+ // visitor's conversation. It is never a shareable topic β€” fail closed, and
+ // do so BEFORE the personal-mode short-circuit below: visitor topics exist
+ // in personal mode too, so the exclusion cannot depend on a workspace.
+ const topic = await ctx.topicModel.findOwnTopicById(topicId);
+ if (!topic) {
+ throw new TRPCError({ code: 'NOT_FOUND', message: 'Topic not found' });
+ }
+
+ // Outside a workspace the remaining checks (agent publish policy, workspace
+ // ownership) have no subject β€” personal-mode ownership is the whole story.
+ if (!ctx.workspaceId) return;
+
+ // Publishing under a restricted agent overrides even topic ownership β€”
+ // that is the whole point of the policy. Resolved only on the publish path
+ // so the common case keeps the query count it had.
+ if (targetVisibility === 'link') {
+ const agent = await resolveTopicShareAgent(ctx, topic);
+
+ if (agent && !canPublishAgentTopicLink(agent, { userId: ctx.userId })) {
+ if (await isWorkspaceTopicOwner(ctx)) return;
+
+ throw new TRPCError({
+ cause: { data: { code: 'TopicShareRestrictedByAgent' } },
+ code: 'FORBIDDEN',
+ message: "Only the agent creator or a workspace owner can share this agent's topics",
+ });
+ }
+ }
+
+ if (topic.userId === ctx.userId) return;
+
+ const guardedConversations = await assertCanUseTopicTargets(guardCtx(ctx), [topicId]);
+ if (guardedConversations.length > 0) return;
+
+ const isWorkspaceAdmin = await isWorkspaceTopicOwner(ctx);
+ if (!isWorkspaceAdmin) {
+ throw new TRPCError({
+ code: 'FORBIDDEN',
+ message: 'Only the topic creator or a workspace owner can manage this share',
+ });
+ }
+};
+
+/**
+ * Audit trail for workspace share state changes, mirroring the page-share
+ * `resource.shared` / `resource.unshared` events. Personal mode is not
+ * audited. A share record with 'private' visibility is an unshared
+ * placeholder, so only transitions in/out of 'link' are recorded.
+ */
+const recordTopicShareAudit = async (
+ ctx: TopicShareCtx,
+ params: { currentVisibility: string; previousVisibility: string; topicId: string },
+) => {
+ if (!ctx.workspaceId) return;
+ const { currentVisibility, previousVisibility, topicId } = params;
+ if (currentVisibility === previousVisibility) return;
+ if (currentVisibility !== 'link' && previousVisibility !== 'link') return;
+
+ await new WorkspaceAuditLogModel(ctx.serverDB).create({
+ action: currentVisibility === 'link' ? 'resource.shared' : 'resource.unshared',
+ metadata: { currentVisibility, previousVisibility },
+ resourceId: topicId,
+ resourceType: 'topic',
+ userId: ctx.userId,
+ workspaceId: ctx.workspaceId,
+ });
+};
+
+export const shareRouter = router({
+ /**
+ * Disable sharing for a topic (deletes share record)
+ */
+ disableSharing: topicProcedure
+ .use(withScopedPermission('topic:update'))
+ .input(z.object({ topicId: z.string() }))
+ .mutation(async ({ input, ctx }) => {
+ await assertCanManageTopicShare(ctx, input.topicId);
+
+ const previous = await ctx.topicShareModel.getByTopicId(input.topicId);
+ const result = await ctx.topicShareModel.deleteByTopicId(input.topicId);
+
+ if (previous) {
+ await recordTopicShareAudit(ctx, {
+ currentVisibility: 'private',
+ previousVisibility: previous.visibility,
+ topicId: input.topicId,
+ });
+ }
+
+ return result;
+ }),
+ /**
+ * Enable sharing for a topic (creates share record)
+ */
+ enableSharing: topicProcedure
+ .use(withScopedPermission('topic:update'))
+ .input(
+ z.object({
+ topicId: z.string(),
+ visibility: z.enum(['private', 'link']).optional(),
+ }),
+ )
+ .mutation(async ({ input, ctx }) => {
+ await assertCanManageTopicShare(ctx, input.topicId, input.visibility);
+
+ const previous = await ctx.topicShareModel.getByTopicId(input.topicId);
+ const result = await ctx.topicShareModel.create(input.topicId, input.visibility);
+
+ if (result) {
+ await recordTopicShareAudit(ctx, {
+ currentVisibility: result.visibility,
+ previousVisibility: previous?.visibility ?? 'private',
+ topicId: input.topicId,
+ });
+ }
+
+ return result;
+ }),
+ getShareInfo: topicProcedure
+ .input(z.object({ topicId: z.string() }))
+ .query(async ({ input, ctx }) => {
+ return ctx.topicShareModel.getByTopicId(input.topicId);
+ }),
+ /**
+ * Update share visibility
+ */
+ updateShareVisibility: topicProcedure
+ .use(withScopedPermission('topic:update'))
+ .input(
+ z.object({
+ topicId: z.string(),
+ visibility: z.enum(['private', 'link']),
+ }),
+ )
+ .mutation(async ({ input, ctx }) => {
+ await assertCanManageTopicShare(ctx, input.topicId, input.visibility);
+
+ const previous = await ctx.topicShareModel.getByTopicId(input.topicId);
+ const result = await ctx.topicShareModel.updateVisibility(input.topicId, input.visibility);
+
+ if (result && previous) {
+ await recordTopicShareAudit(ctx, {
+ currentVisibility: result.visibility,
+ previousVisibility: previous.visibility,
+ topicId: input.topicId,
+ });
+ }
+
+ return result;
+ }),
+});
diff --git a/apps/server/src/routers/lambda/topic/update.ts b/apps/server/src/routers/lambda/topic/update.ts
new file mode 100644
index 00000000000..007e58e69e3
--- /dev/null
+++ b/apps/server/src/routers/lambda/topic/update.ts
@@ -0,0 +1,167 @@
+import {
+ chatTopicCreateMetadataSchema,
+ chatTopicMetadataUpdateSchema,
+ chatTopicStatusSchema,
+} from '@lobechat/types';
+import { TRPCError } from '@trpc/server';
+import { z } from 'zod';
+
+import { withScopedPermission } from '@/business/server/trpc-middlewares/rbacPermission';
+import { router } from '@/libs/trpc/lambda';
+
+import { assertWorkspaceRowManageable } from '../_helpers/assertWorkspaceRowManageable';
+import {
+ assertCanUseConversationTargets,
+ assertCanUseTopicTargets,
+} from '../_helpers/conversationResourceGuard';
+import { resolveContext } from '../_helpers/resolveContext';
+import { assertCreatorTopicTargets } from '../_helpers/shareVisitorTargetGuard';
+import { guardCtx, topicProcedure } from './procedures';
+
+export const updateRouter = router({
+ updateTopic: topicProcedure
+ .use(withScopedPermission('topic:update'))
+ .input(
+ z.object({
+ id: z.string(),
+ value: z.object({
+ agentId: z.string().optional(),
+ completedAt: z.date().nullish(),
+ favorite: z.boolean().optional(),
+ historySummary: z.string().optional(),
+ messages: z.array(z.string()).optional(),
+ // The topic's pinned model (top-level columns) β€” written when the user
+ // switches model while the topic is active (see updateTopicModel).
+ // Nullish to match `Partial<ChatTopic>` whose model/provider are `string | null`.
+ model: z.string().nullish(),
+ provider: z.string().nullish(),
+ sessionId: z.string().optional(),
+ status: chatTopicStatusSchema.nullish(),
+ title: z.string().optional(),
+ }),
+ }),
+ )
+ .mutation(async ({ input, ctx }) => {
+ // Intentionally no creator/owner gate: shared topics are co-editable by
+ // members (title/status/metadata); only delete/transfer is creator-scoped.
+ // Co-editing still requires `use`-level General access on the agent β€”
+ // view-only members are read-only.
+ await assertCanUseTopicTargets(guardCtx(ctx), [input.id]);
+ await assertCreatorTopicTargets(guardCtx(ctx), [input.id]);
+ const { agentId, ...restValue } = input.value;
+ if (agentId) await assertCanUseConversationTargets(guardCtx(ctx), [{ agentId }]);
+
+ // If agentId is provided, resolve to sessionId
+ let resolvedSessionId = restValue.sessionId;
+ if (agentId && !resolvedSessionId) {
+ const resolved = await resolveContext(
+ { agentId },
+ ctx.serverDB,
+ ctx.userId,
+ ctx.workspaceId ?? undefined,
+ );
+ resolvedSessionId = resolved.sessionId ?? undefined;
+ }
+
+ return ctx.topicModel.update(input.id, { ...restValue, sessionId: resolvedSessionId });
+ }),
+ /**
+ * Switch the topic's pinned model and its effort pin atomically β€” see
+ * `TopicModel.updateModelPin`. Same co-editing rules as `updateTopic`.
+ */
+ updateTopicModel: topicProcedure
+ .use(withScopedPermission('topic:update'))
+ .input(
+ z.object({
+ id: z.string(),
+ metadata: chatTopicCreateMetadataSchema.optional(),
+ model: z.string(),
+ provider: z.string(),
+ }),
+ )
+ .mutation(async ({ input, ctx }) => {
+ await assertCanUseTopicTargets(guardCtx(ctx), [input.id]);
+ await assertCreatorTopicTargets(guardCtx(ctx), [input.id]);
+
+ const { id, ...value } = input;
+ return ctx.topicModel.updateModelPin(id, value);
+ }),
+ updateTopicMetadata: topicProcedure
+ .use(withScopedPermission('topic:update'))
+ .input(
+ z.object({
+ id: z.string(),
+ metadata: chatTopicMetadataUpdateSchema,
+ }),
+ )
+ .mutation(async ({ input, ctx }) => {
+ // Intentionally no creator/owner gate: metadata follows the same
+ // co-editable path as updateTopic (chat/tool flows write fields like
+ // runningOperation on shared topics); only delete/transfer is gated.
+ // Co-editing still requires `use`-level General access on the agent.
+ await assertCanUseTopicTargets(guardCtx(ctx), [input.id]);
+ await assertCreatorTopicTargets(guardCtx(ctx), [input.id]);
+
+ return ctx.topicModel.updateMetadata(input.id, input.metadata);
+ }),
+ batchMoveTopics: topicProcedure
+ .use(withScopedPermission('topic:update'))
+ .input(
+ z.object({
+ targetAgentId: z.string(),
+ topicIds: z.array(z.string()),
+ }),
+ )
+ .mutation(async ({ input, ctx }) => {
+ const rows = await ctx.topicModel.findOwnersByIds(input.topicIds);
+ for (const userId of new Set(rows.map((row) => row.userId))) {
+ assertWorkspaceRowManageable(ctx, userId, 'topic');
+ }
+ // Moving needs `use` on both the source conversations and the target agent.
+ await assertCanUseTopicTargets(guardCtx(ctx), input.topicIds);
+ await assertCanUseConversationTargets(guardCtx(ctx), [{ agentId: input.targetAgentId }]);
+ // Moving a visitor topic re-parents it off the share and strands the
+ // visitor outside the senderId scope the share depends on β€” see
+ // `assertCreatorTopicTargets` for why this guard sits at the RPC
+ // boundary rather than in the model defaults.
+ await assertCreatorTopicTargets(guardCtx(ctx), input.topicIds);
+
+ return ctx.topicModel.batchMoveToAgent(input.topicIds, input.targetAgentId);
+ }),
+ cancelRateLimitContinuation: topicProcedure
+ .use(withScopedPermission('topic:update'))
+ .input(z.object({ id: z.string() }))
+ .mutation(async ({ input, ctx }) => {
+ await assertCanUseTopicTargets(guardCtx(ctx), [input.id]);
+ await assertCreatorTopicTargets(guardCtx(ctx), [input.id]);
+ const result = await ctx.topicModel.cancelRateLimitContinuation(input.id);
+ if (result.status === 'busy')
+ throw new TRPCError({
+ code: 'CONFLICT',
+ message: 'The source continuation has already been claimed or started.',
+ });
+ if (result.status === 'unchanged') return null;
+ return { metadata: result.metadata };
+ }),
+ settleRunningOperation: topicProcedure
+ .use(withScopedPermission('topic:update'))
+ .input(
+ z.object({
+ id: z.string(),
+ operationId: z.string(),
+ status: chatTopicStatusSchema.optional(),
+ }),
+ )
+ .mutation(async ({ input, ctx }) => {
+ await assertCanUseTopicTargets(guardCtx(ctx), [input.id]);
+ // Same visitor guard as `batchMoveTopics`/`cloneTopic` above.
+ await assertCreatorTopicTargets(guardCtx(ctx), [input.id]);
+
+ // Client-reported end: never clear the marker of a run the server is still
+ // driving (an early / mirrored terminal event would otherwise drop the
+ // supervisor's topic reservation mid group turn).
+ return ctx.topicModel.settleRunningOperation(input.id, input.operationId, input.status, {
+ rejectInFlightOperation: true,
+ });
+ }),
+});