🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
✨ feat(project): replace the coordinator with another main agent (#21483)
Arvin Xu6441e4859e67
diff --git a/apps/server/src/routers/lambda/project.ts b/apps/server/src/routers/lambda/project.tsindex 83f28a89df1..98a0fe80fe6 100644--- a/apps/server/src/routers/lambda/project.ts+++ b/apps/server/src/routers/lambda/project.ts@@ -7,7 +7,8 @@ import {type WorkspaceRole,wsCompatProcedure,} from '@/business/server/trpc-middlewares/workspaceAuth';-import { ProjectModel } from '@/database/models/project';+import { ProjectModel, type ProjectModelOptions } from '@/database/models/project';+import { ProjectCoordinatorRepository } from '@/database/repositories/projectCoordinator';import type { LobeChatDatabase } from '@/database/type';import { router } from '@/libs/trpc/lambda';import { serverDatabase } from '@/libs/trpc/lambda/middleware';@@ -26,12 +27,20 @@ const isWorkspaceViewer = (ctx: { workspaceId?: string | null; workspaceRole?: Wconst projectProcedure = wsCompatProcedure.use(serverDatabase).use(async (opts) => {const { ctx } = opts;+ const workspaceId = ctx.workspaceId ?? undefined;+ const options: ProjectModelOptions = {+ canManageAllMembers: isWorkspaceAdmin(ctx),+ readOnly: isWorkspaceViewer(ctx),+ };return opts.next({ctx: {- projectModel: new ProjectModel(ctx.serverDB, ctx.userId, ctx.workspaceId ?? undefined, {- canManageAllMembers: isWorkspaceAdmin(ctx),- readOnly: isWorkspaceViewer(ctx),- }),+ projectCoordinatorRepo: new ProjectCoordinatorRepository(+ ctx.serverDB,+ ctx.userId,+ workspaceId,+ options,+ ),+ projectModel: new ProjectModel(ctx.serverDB, ctx.userId, workspaceId, options),},});});@@ -204,17 +213,23 @@ export const projectRouter = router({);// TODO(2026-12-31): remove with `ProjectModel.joinTopicAgents`.await ctx.projectModel.joinTopicAgents(project.id);- const [agents, completionReviews, knowledgeBases, tasks, works] = await Promise.all([- ctx.projectModel.listAgents(project.id),- ctx.projectModel.listCompletionReviews(project.id),- ctx.projectModel.listKnowledgeBases(project.id),- ctx.projectModel.listTasks(project.id),- ctx.projectModel.listWorks(project.id),- ]);+ const [agents, completionReviews, knowledgeBases, tasks, works, coordinatorRetires] =+ await Promise.all([+ ctx.projectModel.listAgents(project.id),+ ctx.projectModel.listCompletionReviews(project.id),+ ctx.projectModel.listKnowledgeBases(project.id),+ ctx.projectModel.listTasks(project.id),+ ctx.projectModel.listWorks(project.id),+ ctx.projectModel.isDedicatedCoordinator(project.coordinatorAgentId, {+ exceptProjectId: project.id,+ }),+ ]);return {data: {agents,completionReviews,+ /** Replacing the main agent hands its history over and deletes it. */+ coordinatorRetiresOnReplace: coordinatorRetires,knowledgeBases,permissions: ctx.projectModel.getPermissions(project),project,@@ -314,6 +329,26 @@ export const projectRouter = router({}}),+ replaceCoordinator: projectWriteProcedure+ .input(idInput.extend({ agentId: z.string() }))+ .mutation(async ({ ctx, input }) => {+ try {+ await assertResourceUsable(ctx, 'agent', input.agentId);+ return {+ data: await withMainAgent(+ ctx.projectModel,+ requireResult(+ await ctx.projectCoordinatorRepo.replaceCoordinator(input.id, input.agentId),+ ),+ ),+ message: 'Project main agent replaced',+ success: true,+ };+ } catch (error) {+ mapProjectError(error, 'replaceCoordinator');+ }+ }),+removeKnowledgeBase: projectWriteProcedure.input(idInput.extend({ knowledgeBaseId: z.string() })).mutation(async ({ ctx, input }) => {diff --git a/locales/en-US/project.json b/locales/en-US/project.jsonindex d3eb3b86806..9865b8947f7 100644--- a/locales/en-US/project.json+++ b/locales/en-US/project.json@@ -140,6 +140,13 @@"members.removeConfirmDescription": "Its existing tasks and topics in this project stay as they are.","members.removeConfirmTitle": "Remove {{name}} from this project?","members.removeFailed": "Could not remove the agent",+ "members.replaceCoordinator": "Change main agent",+ "members.replaceCoordinatorDescription": "Topics, tasks and works of {{previous}} move to {{name}}, then {{previous}} is deleted. This cannot be undone.",+ "members.replaceCoordinatorFailed": "Could not change the main agent",+ "members.replaceCoordinatorKeepDescription": "{{previous}} stays in the project as a member.",+ "members.replaceCoordinatorOk": "Make main agent",+ "members.replaceCoordinatorSuccess": "{{name}} is now the main agent",+ "members.replaceCoordinatorTitle": "Make {{name}} the main agent?","members.responsibility": "Responsibility","members.responsibilityPlaceholder": "What this agent owns in the project","members.role": "Role",diff --git a/locales/zh-CN/project.json b/locales/zh-CN/project.jsonindex 08124565c96..ae4f5490916 100644--- a/locales/zh-CN/project.json+++ b/locales/zh-CN/project.json@@ -140,6 +140,13 @@"members.removeConfirmDescription": "它在项目中已有的任务和话题不受影响。","members.removeConfirmTitle": "将「{{name}}」移出项目?","members.removeFailed": "移出 Agent 失败",+ "members.replaceCoordinator": "更换主 Agent",+ "members.replaceCoordinatorDescription": "「{{previous}}」的话题、任务和产出将移交给「{{name}}」,随后删除「{{previous}}」。此操作无法撤销。",+ "members.replaceCoordinatorFailed": "更换主 Agent 失败",+ "members.replaceCoordinatorKeepDescription": "「{{previous}}」将作为普通成员留在项目中。",+ "members.replaceCoordinatorOk": "设为主 Agent",+ "members.replaceCoordinatorSuccess": "「{{name}}」已成为主 Agent",+ "members.replaceCoordinatorTitle": "将「{{name}}」设为主 Agent?","members.responsibility": "职责","members.responsibilityPlaceholder": "这个 Agent 在项目里负责什么","members.role": "角色",diff --git a/packages/database/src/models/__tests__/project.test.ts b/packages/database/src/models/__tests__/project.test.tsindex d675618bf16..83d4c343af8 100644--- a/packages/database/src/models/__tests__/project.test.ts+++ b/packages/database/src/models/__tests__/project.test.ts@@ -114,6 +114,34 @@ describe('ProjectModel', () => {expect(await model.delete(project.id)).toEqual(expect.objectContaining({ id: project.id }));});+ it('tells whether replacing a main agent retires it', async () => {+ const project = await createProject(model, { name: 'Disposition' });+ const inbox = (await new AgentModel(serverDB, userId).getBuiltinAgent(INBOX_SESSION_ID))!;+ const user = await new AgentModel(serverDB, userId).create({ title: 'Planner' });++ // The project's own lead is ignored only when asked about handing it over.+ expect(+ await model.isDedicatedCoordinator(project.coordinatorAgentId, {+ exceptProjectId: project.id,+ }),+ ).toBe(true);+ expect(await model.isDedicatedCoordinator(project.coordinatorAgentId)).toBe(false);+ // A member of another project is still in use there.+ const other = await createProject(model, { name: 'Borrower' });+ await model.addAgent(other.id, { agentId: project.coordinatorAgentId });+ expect(+ await model.isDedicatedCoordinator(project.coordinatorAgentId, {+ exceptProjectId: project.id,+ }),+ ).toBe(false);+ expect(await model.isDedicatedCoordinator(inbox.id, { exceptProjectId: project.id })).toBe(+ false,+ );+ expect(await model.isDedicatedCoordinator(user.id, { exceptProjectId: project.id })).toBe(+ false,+ );+ });+it('creates, lists, updates, and deletes a project in the owner scope', async () => {const project = await createProject(model, { description: 'A large effort', name: 'Apollo' });expect(project.status).toBe('backlog');diff --git a/packages/database/src/models/project.ts b/packages/database/src/models/project.tsindex cbde84fd756..2f9676858af 100644--- a/packages/database/src/models/project.ts+++ b/packages/database/src/models/project.ts@@ -1,9 +1,10 @@import { BUILTIN_AGENT_SLUGS, createProjectCoordinatorAgentConfig } from '@lobechat/builtin-agents';import { INBOX_SESSION_ID } from '@lobechat/const';import type { ProjectStatus, ProjectVisibility } from '@lobechat/types';-import { and, asc, desc, eq, inArray, isNull, max, or, sql } from 'drizzle-orm';+import { and, asc, desc, eq, inArray, isNull, max, ne, or, sql } from 'drizzle-orm';import { agents } from '../schemas/agent';+import { chatGroupsAgents } from '../schemas/chatGroup';import { environments } from '../schemas/environment';import { knowledgeBases } from '../schemas/file';import {@@ -14,6 +15,7 @@ import {} from '../schemas/project';import { projectEnvironments } from '../schemas/projectEnvironment';import { projectWorks } from '../schemas/projectWork';+import { agentsToSessions } from '../schemas/relations';import { tasks } from '../schemas/task';import { topics } from '../schemas/topic';import { works } from '../schemas/work';@@ -210,6 +212,25 @@ export class ProjectModel {* (user agents, LobeAI) stay with their sessions intact.*/private async deleteDedicatedCoordinator(db: LobeChatDatabase, agentId: string) {+ if (!(await this.isDedicatedCoordinator(agentId, { db }))) return;+ await new AgentModel(db, this.userId, this.workspaceId).delete(agentId);+ }++ /**+ * A coordinator provisioned for one project: a virtual, non-builtin agent no+ * other project leads or counts as a member, and no group or session holds.+ */+ async isDedicatedCoordinator(+ agentId: string,+ {+ db = this.db,+ exceptProjectId,+ }: {+ db?: LobeChatDatabase;+ /** Ask before handing this project over: its own lead and membership do not count as "still used". */+ exceptProjectId?: string;+ } = {},+ ) {const [agent] = await db.select({ slug: agents.slug, virtual: agents.virtual }).from(agents)@@ -220,16 +241,46 @@ export class ProjectModel {),).limit(1);- if (!agent?.virtual || (agent.slug && BUILTIN_SLUGS.has(agent.slug))) return;+ if (!agent?.virtual || (agent.slug && BUILTIN_SLUGS.has(agent.slug))) return false;const [stillUsed] = await db.select({ id: projects.id }).from(projects)- .where(eq(projects.coordinatorAgentId, agentId))+ .where(+ and(+ eq(projects.coordinatorAgentId, agentId),+ exceptProjectId ? ne(projects.id, exceptProjectId) : undefined,+ ),+ ).limit(1);- if (stillUsed) return;-- await new AgentModel(db, this.userId, this.workspaceId).delete(agentId);+ if (stillUsed) return false;++ // A group's own members are virtual and slugless as well; they belong to the group.+ // A session link would take the agent's conversations with it on delete, and a+ // member of another project would drop out of it.+ const [linked] = await db+ .select({ agentId: chatGroupsAgents.agentId })+ .from(chatGroupsAgents)+ .where(eq(chatGroupsAgents.agentId, agentId))+ .union(+ db+ .select({ agentId: agentsToSessions.agentId })+ .from(agentsToSessions)+ .where(eq(agentsToSessions.agentId, agentId)),+ )+ .union(+ db+ .select({ agentId: projectAgents.agentId })+ .from(projectAgents)+ .where(+ and(+ eq(projectAgents.agentId, agentId),+ exceptProjectId ? ne(projectAgents.projectId, exceptProjectId) : undefined,+ ),+ ),+ )+ .limit(1);+ return !linked;}/**@@ -479,6 +530,74 @@ export class ProjectModel {return deleted.length > 0;}+ /**+ * Point the project at another main agent and seat it as an enabled member.+ * Returns the predecessor so the caller can retire or keep it; handing over a+ * coordinator's history spans other aggregates and lives in+ * `ProjectCoordinatorRepository`. Call it inside that transaction.+ */+ async assignCoordinator(projectId: string, agentId: string) {+ const [project] = await this.db+ .select()+ .from(projects)+ .where(and(eq(projects.id, projectId), this.membersManageable()))+ .limit(1)+ .for('update');+ if (!project) return null;+ if (project.coordinatorAgentId === agentId) return { previousId: null, project };++ const [agent] = await this.db+ .select({ id: agents.id, visibility: agents.visibility })+ .from(agents)+ .where(+ and(+ eq(agents.id, agentId),+ buildWorkspaceWhere({ userId: this.userId, workspaceId: this.workspaceId }, agents),+ ),+ )+ .limit(1);+ if (!agent) throw new Error('Agent not found');+ this.assertSharedResource(+ project,+ agent.visibility,+ 'A shared project only takes shared agents',+ );++ const [updated] = await this.db+ .update(projects)+ .set({ coordinatorAgentId: agentId, updatedAt: new Date() })+ .where(eq(projects.id, projectId))+ .returning();+ await this.db+ .insert(projectAgents)+ .values({+ addedByUserId: this.userId,+ agentId,+ projectId,+ workspaceId: this.workspaceId ?? null,+ })+ .onConflictDoUpdate({+ set: { enabled: true, updatedAt: new Date() },+ target: [projectAgents.projectId, projectAgents.agentId],+ });++ const previousId = project.coordinatorAgentId;+ if (previousId) {+ // The project role belonged to the main agent; as a member it reads like any other.+ await this.db+ .update(projectAgents)+ .set({ role: null, updatedAt: new Date() })+ .where(+ and(+ eq(projectAgents.projectId, projectId),+ eq(projectAgents.agentId, previousId),+ eq(projectAgents.role, 'coordinator'),+ ),+ );+ }+ return { previousId, project: updated };+ }+async listKnowledgeBases(projectId: string) {if (!(await this.findById(projectId))) return null;return this.dbdiff --git a/packages/database/src/repositories/projectCoordinator/__tests__/index.test.ts b/packages/database/src/repositories/projectCoordinator/__tests__/index.test.tsnew file mode 100644index 00000000000..3ee58a55938--- /dev/null+++ b/packages/database/src/repositories/projectCoordinator/__tests__/index.test.ts@@ -0,0 +1,250 @@+import { eq } from 'drizzle-orm';+import { afterEach, beforeEach, describe, expect, it } from 'vitest';++import { getTestDB } from '../../../core/getTestDB';+import { AgentModel } from '../../../models/agent';+import { ProjectModel } from '../../../models/project';+import { TaskModel } from '../../../models/task';+import { TopicModel } from '../../../models/topic';+import {+ agentDocuments,+ agents,+ briefs,+ chatGroups,+ chatGroupsAgents,+ dashboards,+ documents,+ messages,+ taskComments,+ tasks,+ topics,+ users,+ widgets,+} from '../../../schemas';+import { ProjectCoordinatorRepository } from '../index';++const serverDB = await getTestDB();+const userId = 'project-coordinator-user';+const otherUserId = 'project-coordinator-other-user';+const model = new ProjectModel(serverDB, userId);+const repo = new ProjectCoordinatorRepository(serverDB, userId);+const otherRepo = new ProjectCoordinatorRepository(serverDB, otherUserId);+let identifierSequence = 0;++const createProject = (input: { name: string }) =>+ model.create({ ...input, identifier: `C${String(++identifierSequence).padStart(5, '0')}` });++describe('ProjectCoordinatorRepository.replaceCoordinator', () => {+ beforeEach(async () => {+ await serverDB.delete(users);+ await serverDB.insert(users).values([{ id: userId }, { id: otherUserId }]);+ });++ afterEach(async () => {+ await serverDB.delete(users);+ });++ it('hands a dedicated coordinator history to the new main agent, then deletes it', async () => {+ const project = await createProject({ name: 'Handover' });+ const coordinatorId = project.coordinatorAgentId;+ const lead = await new AgentModel(serverDB, userId).create({ title: 'Lead' });+ const topic = await new TopicModel(serverDB, userId).create({+ agentId: coordinatorId,+ projectId: project.id,+ title: 'Planning',+ });+ const [message] = await serverDB+ .insert(messages)+ .values({+ agentId: coordinatorId,+ content: 'hi',+ role: 'assistant',+ topicId: topic.id,+ userId,+ })+ .returning();+ const [addressed] = await serverDB+ .insert(messages)+ .values({+ content: 'Plan the release',+ role: 'user',+ targetId: coordinatorId,+ topicId: topic.id,+ userId,+ })+ .returning();+ const task = await new TaskModel(serverDB, userId).create({+ assigneeAgentId: coordinatorId,+ createdByAgentId: coordinatorId,+ instruction: 'Ship it',+ projectId: project.id,+ });+ await serverDB.insert(taskComments).values({+ authorAgentId: coordinatorId,+ content: 'Checklist drafted',+ taskId: task.id,+ userId,+ });+ await serverDB.insert(briefs).values({+ agentId: coordinatorId,+ summary: 'Ready',+ taskId: task.id,+ title: 'Result',+ type: 'result',+ userId,+ });+ await serverDB.insert(documents).values({+ content: 'plan',+ fileType: 'text/markdown',+ filename: 'plan.md',+ id: 'doc-handover-plan',+ source: `agent-document://${coordinatorId}/plan.md`,+ sourceType: 'agent',+ title: 'Plan',+ totalCharCount: 4,+ totalLineCount: 1,+ userId,+ });+ await serverDB+ .insert(agentDocuments)+ .values({ agentId: coordinatorId, documentId: 'doc-handover-plan', userId });+ const [widget] = await serverDB+ .insert(widgets)+ .values({ agentId: coordinatorId, projectId: project.id, title: 'Burndown', userId })+ .returning();+ const [board] = await serverDB+ .insert(dashboards)+ .values({ agentId: coordinatorId, projectId: project.id, title: 'Release', userId })+ .returning();++ const updated = await repo.replaceCoordinator(project.id, lead.id);++ expect(updated?.coordinatorAgentId).toBe(lead.id);+ expect(await serverDB.select().from(agents).where(eq(agents.id, coordinatorId))).toEqual([]);+ expect(await serverDB.select().from(topics).where(eq(topics.id, topic.id))).toEqual([+ expect.objectContaining({ agentId: lead.id }),+ ]);+ expect(await serverDB.select().from(messages).where(eq(messages.id, message.id))).toEqual([+ expect.objectContaining({ agentId: lead.id }),+ ]);+ expect(await serverDB.select().from(messages).where(eq(messages.id, addressed.id))).toEqual([+ expect.objectContaining({ targetId: lead.id }),+ ]);+ expect(await serverDB.select().from(tasks).where(eq(tasks.id, task.id))).toEqual([+ expect.objectContaining({ assigneeAgentId: lead.id, createdByAgentId: lead.id }),+ ]);+ expect(+ await serverDB.select().from(taskComments).where(eq(taskComments.taskId, task.id)),+ ).toEqual([expect.objectContaining({ authorAgentId: lead.id })]);+ expect(await serverDB.select().from(briefs).where(eq(briefs.taskId, task.id))).toEqual([+ expect.objectContaining({ agentId: lead.id }),+ ]);+ expect(+ await serverDB+ .select()+ .from(agentDocuments)+ .where(eq(agentDocuments.documentId, 'doc-handover-plan')),+ ).toEqual([expect.objectContaining({ agentId: lead.id })]);+ expect(await model.listAgents(project.id)).toEqual([+ expect.objectContaining({+ agent: expect.objectContaining({ id: lead.id }),+ binding: expect.objectContaining({ enabled: true }),+ }),+ ]);+ expect(await serverDB.select().from(widgets).where(eq(widgets.id, widget.id))).toEqual([+ expect.objectContaining({ agentId: lead.id }),+ ]);+ expect(await serverDB.select().from(dashboards).where(eq(dashboards.id, board.id))).toEqual([+ expect.objectContaining({ agentId: lead.id }),+ ]);+ });++ it('keeps a group member that leads a project when it is replaced', async () => {+ const project = await createProject({ name: 'Group lead' });+ const member = await new AgentModel(serverDB, userId).create({+ title: 'Group member',+ virtual: true,+ });+ await serverDB.insert(chatGroups).values({ id: 'project-lead-group', title: 'G', userId });+ await serverDB+ .insert(chatGroupsAgents)+ .values({ agentId: member.id, chatGroupId: 'project-lead-group', userId });+ const lead = await new AgentModel(serverDB, userId).create({ title: 'Lead' });++ await repo.replaceCoordinator(project.id, member.id);+ await repo.replaceCoordinator(project.id, lead.id);++ expect(await serverDB.select().from(agents).where(eq(agents.id, member.id))).toHaveLength(1);+ });++ it('keeps a coordinator that another project counts as a member when it is replaced', async () => {+ const project = await createProject({ name: 'Origin' });+ const other = await createProject({ name: 'Borrower' });+ const coordinatorId = project.coordinatorAgentId;+ await model.addAgent(other.id, { agentId: coordinatorId, role: 'Advisor' });+ const topic = await new TopicModel(serverDB, userId).create({+ agentId: coordinatorId,+ projectId: other.id,+ title: 'Borrowed work',+ });+ const lead = await new AgentModel(serverDB, userId).create({ title: 'Lead' });++ await repo.replaceCoordinator(project.id, lead.id);++ expect(await serverDB.select().from(agents).where(eq(agents.id, coordinatorId))).toHaveLength(+ 1,+ );+ expect(await serverDB.select().from(topics).where(eq(topics.id, topic.id))).toEqual([+ expect.objectContaining({ agentId: coordinatorId }),+ ]);+ expect(await model.listAgents(other.id)).toContainEqual(+ expect.objectContaining({ agent: expect.objectContaining({ id: coordinatorId }) }),+ );+ });++ it('keeps a reusable main agent as a member when it is replaced', async () => {+ const project = await createProject({ name: 'Rotation' });+ const agentModel = new AgentModel(serverDB, userId);+ const first = await agentModel.create({ title: 'First lead' });+ const second = await agentModel.create({ title: 'Second lead' });+ await model.addAgent(project.id, { agentId: second.id, enabled: false, role: 'Reviewer' });++ await repo.replaceCoordinator(project.id, first.id);+ const updated = await repo.replaceCoordinator(project.id, second.id);++ expect(updated?.coordinatorAgentId).toBe(second.id);+ expect(await serverDB.select().from(agents).where(eq(agents.id, first.id))).toHaveLength(1);+ expect(await model.listAgents(project.id)).toEqual([+ expect.objectContaining({+ agent: expect.objectContaining({ id: second.id }),+ binding: expect.objectContaining({ enabled: true, role: 'Reviewer' }),+ }),+ expect.objectContaining({+ agent: expect.objectContaining({ id: first.id }),+ binding: expect.objectContaining({ role: null }),+ }),+ ]);+ });++ it('gives a project that fell back to LobeAI a main agent of its own', async () => {+ const project = await createProject({ name: 'Orphaned' });+ await new AgentModel(serverDB, userId).delete(project.coordinatorAgentId);+ const lead = await new AgentModel(serverDB, userId).create({ title: 'Lead' });++ const updated = await repo.replaceCoordinator(project.id, lead.id);++ expect(updated?.coordinatorAgentId).toBe(lead.id);+ expect(await model.listAgents(project.id)).toEqual([+ expect.objectContaining({ agent: expect.objectContaining({ id: lead.id }) }),+ ]);+ });++ it('refuses to replace the main agent outside the member-management scope', async () => {+ const project = await createProject({ name: 'Guarded' });+ const agent = await new AgentModel(serverDB, otherUserId).create({ title: 'Outsider' });++ expect(await otherRepo.replaceCoordinator(project.id, agent.id)).toBeNull();+ await expect(repo.replaceCoordinator(project.id, agent.id)).rejects.toThrow('Agent not found');+ expect((await model.findById(project.id))?.coordinatorAgentId).toBe(project.coordinatorAgentId);+ });+});diff --git a/packages/database/src/repositories/projectCoordinator/index.ts b/packages/database/src/repositories/projectCoordinator/index.tsnew file mode 100644index 00000000000..0887f5fc0b7--- /dev/null+++ b/packages/database/src/repositories/projectCoordinator/index.ts@@ -0,0 +1,140 @@+import { and, eq, notExists } from 'drizzle-orm';+import { alias } from 'drizzle-orm/pg-core';++import { AgentModel } from '../../models/agent';+import { ProjectModel, type ProjectModelOptions } from '../../models/project';+import {+ acceptanceComments,+ agentDocuments,+ agentOperations,+ briefs,+ dashboards,+ goalNodeDecisions,+ goalNodes,+ goals,+ messages,+ taskActivities,+ taskComments,+ tasks,+ threads,+ topics,+ widgets,+ widgetVersions,+ works,+ workVersions,+} from '../../schemas';+import type { LobeChatDatabase } from '../../type';++/**+ * Hands a project to another main agent. Retiring a dedicated coordinator moves+ * its record of work to the successor and deletes the agent, which spans the+ * conversation, task, work, goal, widget and document aggregates — so the unit+ * of work lives here and composes {@link ProjectModel} and {@link AgentModel}.+ */+export class ProjectCoordinatorRepository {+ constructor(+ private readonly db: LobeChatDatabase,+ private readonly userId: string,+ private readonly workspaceId?: string,+ private readonly options: ProjectModelOptions = {},+ ) {}++ /**+ * The new main agent joins as a member. A dedicated coordinator passes its+ * history on and is deleted; a reusable predecessor stays a plain member.+ */+ async replaceCoordinator(projectId: string, agentId: string) {+ return this.db.transaction(async (trx) => {+ const tx = trx as LobeChatDatabase;+ const projectModel = new ProjectModel(tx, this.userId, this.workspaceId, this.options);+ const assigned = await projectModel.assignCoordinator(projectId, agentId);+ if (!assigned) return null;++ const { previousId, project } = assigned;+ if (+ previousId &&+ (await projectModel.isDedicatedCoordinator(previousId, { exceptProjectId: projectId }))+ ) {+ await this.transferHistory(tx, previousId, agentId);+ await new AgentModel(tx, this.userId, this.workspaceId).delete(previousId);+ }+ return project;+ });+ }++ /**+ * Everything a deleted agent would take with it (`ON DELETE CASCADE`) or leave+ * unattributed (`SET NULL`) that belongs to the project's record of work.+ */+ private async transferHistory(db: LobeChatDatabase, fromId: string, toId: string) {+ await db.update(topics).set({ agentId: toId }).where(eq(topics.agentId, fromId));+ await db.update(threads).set({ agentId: toId }).where(eq(threads.agentId, fromId));+ await db.update(messages).set({ agentId: toId }).where(eq(messages.agentId, fromId));+ // `target_id` has no foreign key; a user turn addressed to the coordinator+ // would drop out of the successor's thread view if it kept the old id.+ await db.update(messages).set({ targetId: toId }).where(eq(messages.targetId, fromId));+ await db.update(tasks).set({ assigneeAgentId: toId }).where(eq(tasks.assigneeAgentId, fromId));+ await db+ .update(tasks)+ .set({ createdByAgentId: toId })+ .where(eq(tasks.createdByAgentId, fromId));+ await db+ .update(taskComments)+ .set({ authorAgentId: toId })+ .where(eq(taskComments.authorAgentId, fromId));+ await db+ .update(taskActivities)+ .set({ actorAgentId: toId })+ .where(eq(taskActivities.actorAgentId, fromId));+ await db.update(briefs).set({ agentId: toId }).where(eq(briefs.agentId, fromId));+ await db.update(works).set({ originAgentId: toId }).where(eq(works.originAgentId, fromId));+ await db.update(workVersions).set({ agentId: toId }).where(eq(workVersions.agentId, fromId));+ await db.update(goals).set({ agentId: toId }).where(eq(goals.agentId, fromId));+ await db+ .update(goalNodes)+ .set({ createdByAgentId: toId })+ .where(eq(goalNodes.createdByAgentId, fromId));+ await db+ .update(goalNodeDecisions)+ .set({ resolvedByAgentId: toId })+ .where(eq(goalNodeDecisions.resolvedByAgentId, fromId));+ await db.update(widgets).set({ agentId: toId }).where(eq(widgets.agentId, fromId));+ await db+ .update(widgetVersions)+ .set({ sourceAgentId: toId })+ .where(eq(widgetVersions.sourceAgentId, fromId));+ await db.update(dashboards).set({ agentId: toId }).where(eq(dashboards.agentId, fromId));+ await db+ .update(acceptanceComments)+ .set({ authorAgentId: toId })+ .where(eq(acceptanceComments.authorAgentId, fromId));+ await db+ .update(agentOperations)+ .set({ agentId: toId })+ .where(eq(agentOperations.agentId, fromId));++ // The documents its works point at. A document the new agent already holds+ // keeps that binding; the duplicate goes with the coordinator.+ const held = alias(agentDocuments, 'held');+ await db+ .update(agentDocuments)+ .set({ agentId: toId, updatedAt: new Date() })+ .where(+ and(+ eq(agentDocuments.agentId, fromId),+ notExists(+ db+ .select({ id: held.id })+ .from(held)+ .where(+ and(+ eq(held.agentId, toId),+ eq(held.documentId, agentDocuments.documentId),+ eq(held.userId, agentDocuments.userId),+ ),+ ),+ ),+ ),+ );+ }+}diff --git a/packages/locales/src/default/project.ts b/packages/locales/src/default/project.tsindex a8288b5b558..2fc5dcdd01c 100644--- a/packages/locales/src/default/project.ts+++ b/packages/locales/src/default/project.ts@@ -284,6 +284,14 @@ export default {'Its existing tasks and topics in this project stay as they are.','members.removeConfirmTitle': 'Remove {{name}} from this project?','members.removeFailed': 'Could not remove the agent',+ 'members.replaceCoordinator': 'Change main agent',+ 'members.replaceCoordinatorDescription':+ 'Topics, tasks and works of {{previous}} move to {{name}}, then {{previous}} is deleted. This cannot be undone.',+ 'members.replaceCoordinatorFailed': 'Could not change the main agent',+ 'members.replaceCoordinatorKeepDescription': '{{previous}} stays in the project as a member.',+ 'members.replaceCoordinatorOk': 'Make main agent',+ 'members.replaceCoordinatorSuccess': '{{name}} is now the main agent',+ 'members.replaceCoordinatorTitle': 'Make {{name}} the main agent?','members.responsibility': 'Responsibility','members.responsibilityPlaceholder': 'What this agent owns in the project','members.role': 'Role',diff --git a/src/features/Projects/Members/index.tsx b/src/features/Projects/Members/index.tsxindex 0bfc7e3650a..5b2b69dab5b 100644--- a/src/features/Projects/Members/index.tsx+++ b/src/features/Projects/Members/index.tsx@@ -14,16 +14,28 @@ import {toast,Tooltip,} from '@lobehub/ui';-import { MoreHorizontalIcon, PencilLineIcon, Trash2Icon, UserPlusIcon } from 'lucide-react';+import {+ ArrowLeftRightIcon,+ MoreHorizontalIcon,+ PencilLineIcon,+ Trash2Icon,+ UserPlusIcon,+} from 'lucide-react';import { useState } from 'react';import { useTranslation } from 'react-i18next';import Avatar from '@/components/Avatar';import { DEFAULT_AVATAR } from '@/const/meta';import AddAgentMemberModal from '@/features/AddAgentMemberModal';+import AssigneeAgentSelector from '@/features/AgentTasks/features/AssigneeAgentSelector';+import { useAgentStore } from '@/store/agent';+import { builtinAgentSelectors } from '@/store/agent/selectors';+import { useHomeStore } from '@/store/home';+import { homeAgentListSelectors } from '@/store/home/selectors';import type { ProjectDetail } from '@/store/project';import { useProjectStore } from '@/store/project';+import { directoryAgentName } from '../WorkingDirectories/useDirectoryAgent';import { openEditMemberModal } from './EditMemberModal';type ProjectMember = NonNullable<ProjectDetail['agents']>[number];@@ -37,6 +49,7 @@ export function ProjectMemberSettings({ detail }: { detail: ProjectDetail }) {const addProjectAgents = useProjectStore((s) => s.addProjectAgents);const updateProjectAgent = useProjectStore((s) => s.updateProjectAgent);const removeProjectAgent = useProjectStore((s) => s.removeProjectAgent);+ const replaceProjectCoordinator = useProjectStore((s) => s.replaceProjectCoordinator);const projectId = detail.project.id;const canManage = detail.permissions?.canManageMembers ?? false;const members = detail.agents ?? [];@@ -82,6 +95,57 @@ export function ProjectMemberSettings({ detail }: { detail: ProjectDetail }) {}),});+ /** `coordinator` is absent when the project fell back to LobeAI, which has no member row. */+ const replaceCoordinator = (coordinator: ProjectMember | undefined, agentId: string) => {+ const defaultName = t('defaultAgent', { ns: 'common' });+ const previous = coordinator && agentDisplayName(coordinator.agent, defaultName);+ const agent =+ members.find((member) => member.agent.id === agentId)?.agent ??+ homeAgentListSelectors.getAgentById(agentId)(useHomeStore.getState());+ // LobeAI is offered by the picker but not listed on the home sidebar.+ const isInbox = agentId === builtinAgentSelectors.inboxAgentId(useAgentStore.getState());+ const name =+ directoryAgentName(agent, isInbox, t('inbox.title', { ns: 'chat' })) ?? defaultName;+ const values = { name, previous };+ // The server decides: only a coordinator provisioned for this project is retired.+ const dedicated = Boolean(coordinator && detail.coordinatorRetiresOnReplace);+ confirmModal({+ content: !coordinator+ ? undefined+ : dedicated+ ? t('members.replaceCoordinatorDescription', values)+ : t('members.replaceCoordinatorKeepDescription', values),+ okButtonProps: { danger: dedicated },+ okText: t('members.replaceCoordinatorOk'),+ onOk: async () => {+ try {+ await replaceProjectCoordinator(projectId, agentId);+ toast.success(t('members.replaceCoordinatorSuccess', values));+ } catch (error) {+ console.error('Failed to replace project main agent', error);+ toast.error(t('members.replaceCoordinatorFailed'));+ }+ },+ title: t('members.replaceCoordinatorTitle', values),+ });+ };++ const coordinatorMember = members.find(+ (member) => member.agent.id === detail.project.coordinatorAgentId,+ );+ const replaceButton = (coordinator?: ProjectMember) => (+ <AssigneeAgentSelector+ allowUnassigned={false}+ currentAgentId={detail.project.coordinatorAgentId}+ taskVisibility={isShared ? 'public' : null}+ onChange={(agentId) => agentId && replaceCoordinator(coordinator, agentId)}+ >+ <Button icon={ArrowLeftRightIcon} size={coordinator ? 'small' : undefined}>+ {t('members.replaceCoordinator')}+ </Button>+ </AssigneeAgentSelector>+ );+const inviteButton = (<Buttondisabled={!canManage}@@ -103,7 +167,10 @@ export function ProjectMemberSettings({ detail }: { detail: ProjectDetail }) {<Text type="secondary">{t('members.description')}</Text></Flexbox>{canManage ? (- inviteButton+ <Flexbox horizontal gap={8}>+ {!coordinatorMember && replaceButton()}+ {inviteButton}+ </Flexbox>) : (<Tooltip title={t('members.manageForbidden')}><span>{inviteButton}</span>@@ -146,6 +213,7 @@ export function ProjectMemberSettings({ detail }: { detail: ProjectDetail }) {: member.binding.responsibility || t('members.noResponsibility')}</Text></Flexbox>+ {isCoordinator && canManage && replaceButton(member)}{!isCoordinator && canManage && (<><Switchdiff --git a/src/services/project.ts b/src/services/project.tsindex 270535602e7..f347bea0f03 100644--- a/src/services/project.ts+++ b/src/services/project.ts@@ -75,6 +75,9 @@ class ProjectService {removeKnowledgeBase = async (id: string, knowledgeBaseId: string) =>lambdaClient.project.removeKnowledgeBase.mutate({ id, knowledgeBaseId });+ replaceCoordinator = async (id: string, agentId: string) =>+ lambdaClient.project.replaceCoordinator.mutate({ agentId, id });+reopen = async (id: string) => lambdaClient.project.reopen.mutate({ id });requestCompletion = async (id: string) => lambdaClient.project.requestCompletion.mutate({ id });diff --git a/src/store/project/store.test.ts b/src/store/project/store.test.tsindex 4f09828883b..2e25caef760 100644--- a/src/store/project/store.test.ts+++ b/src/store/project/store.test.ts@@ -26,7 +26,16 @@ import {useProjectStore,} from './store';-const mocks = vi.hoisted(() => ({ activeWorkspaceId: null as string | null }));+const mocks = vi.hoisted(() => ({+ activeWorkspaceId: null as string | null,+ refreshProjectTopics: vi.fn(),+}));++vi.mock('@/store/projectWorkingDirectory', () => ({+ useProjectDirectoryStore: {+ getState: () => ({ refreshProjectTopics: mocks.refreshProjectTopics }),+ },+}));vi.mock('@/business/client/hooks/useActiveWorkspaceId', () => ({getActiveWorkspaceId: () => mocks.activeWorkspaceId,@@ -41,6 +50,7 @@ vi.mock('@/services/project', () => ({detail: vi.fn(),listAll: vi.fn(),removeAgent: vi.fn(),+ replaceCoordinator: vi.fn(),update: vi.fn(),updateKnowledgeBase: vi.fn(),},@@ -265,6 +275,25 @@ describe('project store replicas', () => {expect(projectService.detail).toHaveBeenLastCalledWith('launch');});+ it('reloads the page, the list and the conversations once the main agent is replaced', async () => {+ const original = seed();+ await waitSeeded();+ vi.mocked(projectService.replaceCoordinator).mockResolvedValue(ok(original) as any);+ vi.mocked(projectService.detail).mockResolvedValue(+ ok({ ...detailOf(original), project: { ...original, coordinatorAgentId: 'lead' } }) as any,+ );+ vi.mocked(projectService.listAll).mockClear();++ await act(() => useProjectStore.getState().replaceProjectCoordinator('p1', 'lead'));++ expect(projectService.replaceCoordinator).toHaveBeenCalledWith('p1', 'lead');+ expect(useProjectStore.getState().projectDetailMap.launch.project.coordinatorAgentId).toBe(+ 'lead',+ );+ await waitFor(() => expect(projectService.listAll).toHaveBeenCalled());+ expect(mocks.refreshProjectTopics).toHaveBeenCalledWith('p1');+ });+it('restores a knowledge toggle from the server when the update fails', async () => {const original = seed();await waitSeeded();diff --git a/src/store/project/store.ts b/src/store/project/store.tsindex c4f59c5bedd..6f1d800af65 100644--- a/src/store/project/store.ts+++ b/src/store/project/store.ts@@ -19,6 +19,7 @@ import {} from '@/services/project';import { createDevtools } from '@/store/middleware/createDevtools';import { expose } from '@/store/middleware/expose';+import { useProjectDirectoryStore } from '@/store/projectWorkingDirectory';import {PROJECT_LIST_KEY,@@ -54,6 +55,8 @@ interface ProjectStore extends ProjectStoreState {refreshProjectList: () => Promise<void>;removeProjectAgent: (projectId: string, agentId: string) => Promise<void>;removeProjectKnowledgeBase: (projectId: string, knowledgeBaseId: string) => Promise<void>;+ /** Make another agent the main agent; a dedicated coordinator hands over its history and goes. */+ replaceProjectCoordinator: (projectId: string, agentId: string) => Promise<void>;updateProject: (id: string,input: Parameters<typeof projectService.update>[1],@@ -190,6 +193,14 @@ export const useProjectStore = createWithEqualityFn<ProjectStore>()(projectService.removeKnowledgeBase(projectId, knowledgeBaseId),);},+ replaceProjectCoordinator: async (projectId, agentId) => {+ await mutateAndRefresh(projectId, () =>+ projectService.replaceCoordinator(projectId, agentId),+ );+ // The handed-over conversations now group under the new main agent.+ void useProjectDirectoryStore.getState().refreshProjectTopics(projectId);+ void refreshList();+ },updateProjectAgent: async (projectId, agentId, patch) => {patchDetail(projectId, (value) => ({...value,diff --git a/src/store/projectWorkingDirectory/index.test.ts b/src/store/projectWorkingDirectory/index.test.tsindex 0247435f473..a2de619e2fa 100644--- a/src/store/projectWorkingDirectory/index.test.ts+++ b/src/store/projectWorkingDirectory/index.test.ts@@ -170,6 +170,17 @@ describe('projectWorkingDirectory store', () => {// The directory rows themselves did not change.expect(invalidates('projectDirectories', 'project-1')).toBe(false);});++ it('refreshes every projection of a project conversation after its agent changed', async () => {+ await useProjectDirectoryStore.getState().refreshProjectTopics('project-1');++ expect(invalidates('projectTopics', 'project-1')).toBe(true);+ expect(invalidates('projectTopics', 'project-2')).toBe(false);+ // Directory and environment rows denormalize the topic's agent.+ expect(invalidates('directoryTopics', 'directory-1')).toBe(true);+ expect(invalidates('environmentTopics', 'directory-1')).toBe(true);+ expect(invalidates('projectDirectories', 'project-1')).toBe(false);+ });});});diff --git a/src/store/projectWorkingDirectory/index.ts b/src/store/projectWorkingDirectory/index.tsindex ce0ffc95e3a..51223d0dc34 100644--- a/src/store/projectWorkingDirectory/index.ts+++ b/src/store/projectWorkingDirectory/index.ts@@ -101,6 +101,8 @@ interface ProjectDirectoryStore extends ProjectDirectoryStoreState {) => Promise<ServiceData<'createProjectTopic'>>;/** Move a directory conversation to its project's directory on another device. */moveTopic: (...args: ServiceParams<'moveTopic'>) => Promise<ServiceData<'moveTopic'>>;+ /** Refetch a project's conversations after a change made elsewhere, e.g. a new main agent. */+ refreshProjectTopics: (projectId: string) => Promise<void>;/** Create or rename an environment. */saveEnvironment: (...args: ServiceParams<'saveEnvironment'>@@ -221,6 +223,15 @@ export const useProjectDirectoryStore: UseBoundStoreWithEqualityFn<]);return result.data;},+ refreshProjectTopics: async (projectId) => {+ // Directory and environment rows carry the same topics with their agent+ // denormalized, so every projection that lists them is stale too.+ await Promise.all([+ projectTopics.revalidate(projectId),+ directoryTopics.revalidate(),+ environmentTopics.revalidate(),+ ]);+ },saveEnvironment: async (input) => {const result = await projectWorkingDirectoryService.saveEnvironment(input);// One environment is shared by every project that lists it, and its name