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.

✨ feat: add agents with project topics to project members (#21467)

Arvin Xu11c0d4c2d39d
diff --git a/apps/server/src/routers/lambda/project.ts b/apps/server/src/routers/lambda/project.ts
index 693a0740d3a..83f28a89df1 100644
--- a/apps/server/src/routers/lambda/project.ts
+++ b/apps/server/src/routers/lambda/project.ts
@@ -202,6 +202,8 @@ export const projectRouter = router({
ctx.projectModel,
requireResult(await ctx.projectModel.findByReference(input.id)),
);
+ // 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),
diff --git a/packages/database/src/models/__tests__/project.topicAgents.test.ts b/packages/database/src/models/__tests__/project.topicAgents.test.ts
new file mode 100644
index 00000000000..38ac39c8eff
--- /dev/null
+++ b/packages/database/src/models/__tests__/project.topicAgents.test.ts
@@ -0,0 +1,161 @@
+import { INBOX_SESSION_ID } from '@lobechat/const';
+import { eq } from 'drizzle-orm';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+
+import { getTestDB } from '../../core/getTestDB';
+import { agents, projectAgents, projects, topics, users, workspaces } from '../../schemas';
+import type { LobeChatDatabase } from '../../type';
+import { AgentModel } from '../agent';
+import type { CreateProjectInput } from '../project';
+import { ProjectModel } from '../project';
+import { TopicModel } from '../topic';
+
+const serverDB: LobeChatDatabase = await getTestDB();
+const userId = 'project-topic-agents-user';
+let projectIdentifierSequence = 0;
+
+const createProject = (projectModel: ProjectModel, input: Omit<CreateProjectInput, 'identifier'>) =>
+ projectModel.create({
+ ...input,
+ identifier: `T${String(++projectIdentifierSequence).padStart(5, '0')}`,
+ });
+
+const memberIds = async (model: ProjectModel, projectId: string) =>
+ ((await model.listAgents(projectId)) ?? []).map((member) => member.agent.id);
+
+describe('project members from project topics', () => {
+ const model = new ProjectModel(serverDB, userId);
+ const topicModel = new TopicModel(serverDB, userId);
+
+ beforeEach(async () => {
+ await serverDB.delete(users);
+ await serverDB.insert(users).values({ id: userId });
+ });
+
+ afterEach(async () => {
+ await serverDB.delete(users);
+ });
+
+ it('adds the agent of a topic created in the project', async () => {
+ const project = await createProject(model, { name: 'Build' });
+ const agent = await new AgentModel(serverDB, userId).create({ title: 'Codex' });
+
+ await topicModel.create({ agentId: agent.id, projectId: project.id, title: 'Plan' });
+
+ expect(await memberIds(model, project.id)).toContain(agent.id);
+ });
+
+ it('adds the agent when an existing topic moves into the project', async () => {
+ const project = await createProject(model, { name: 'Build' });
+ const agent = await new AgentModel(serverDB, userId).create({ title: 'Claude Code' });
+ const topic = await topicModel.create({ agentId: agent.id, title: 'Loose' });
+ expect(await memberIds(model, project.id)).not.toContain(agent.id);
+
+ await topicModel.update(topic.id, { projectId: project.id });
+
+ expect(await memberIds(model, project.id)).toContain(agent.id);
+ });
+
+ it('keeps an existing member binding untouched', async () => {
+ const project = await createProject(model, { name: 'Build' });
+ const agent = await new AgentModel(serverDB, userId).create({ title: 'Reviewer' });
+ await model.addAgent(project.id, { agentId: agent.id, enabled: false, role: 'reviewer' });
+
+ await topicModel.create({ agentId: agent.id, projectId: project.id, title: 'Review' });
+
+ const [binding] = await serverDB
+ .select()
+ .from(projectAgents)
+ .where(eq(projectAgents.agentId, agent.id));
+ expect(binding).toEqual(expect.objectContaining({ enabled: false, role: 'reviewer' }));
+ });
+
+ it('never adds the project coordinator as a regular member', async () => {
+ const project = await createProject(model, { name: 'Build' });
+ const before = await serverDB
+ .select()
+ .from(projectAgents)
+ .where(eq(projectAgents.projectId, project.id));
+
+ await topicModel.create({
+ agentId: project.coordinatorAgentId,
+ projectId: project.id,
+ title: 'Coordinate',
+ });
+
+ expect(
+ await serverDB.select().from(projectAgents).where(eq(projectAgents.projectId, project.id)),
+ ).toHaveLength(before.length);
+ });
+
+ /** @example Review: a project whose main agent was cleared is led by LobeAI. */
+ it('never adds LobeAI as a member when it leads a project with a cleared main agent', async () => {
+ const project = await createProject(model, { name: 'Cleared' });
+ await serverDB
+ .update(projects)
+ .set({ coordinatorAgentId: null })
+ .where(eq(projects.id, project.id));
+ const inbox = (await new AgentModel(serverDB, userId).getBuiltinAgent(INBOX_SESSION_ID))!;
+ const agent = await new AgentModel(serverDB, userId).create({ title: 'Codex' });
+
+ await topicModel.create({ agentId: inbox.id, projectId: project.id, title: 'Ask LobeAI' });
+ await topicModel.create({ agentId: agent.id, projectId: project.id, title: 'Build' });
+
+ const members = await memberIds(model, project.id);
+ expect(members).not.toContain(inbox.id);
+ expect(members).toContain(agent.id);
+ });
+
+ it('keeps private agents out of a shared workspace project', async () => {
+ const workspaceId = 'project-topic-agents-workspace';
+ await serverDB.insert(workspaces).values({
+ id: workspaceId,
+ name: 'Topic Agents Workspace',
+ primaryOwnerId: userId,
+ slug: workspaceId,
+ });
+ const creator = new ProjectModel(serverDB, userId, workspaceId);
+ const sharedProject = await createProject(creator, { name: 'Shared' });
+ const [privateAgent] = await serverDB
+ .insert(agents)
+ .values({ title: 'Private agent', userId, visibility: 'private', workspaceId })
+ .returning();
+
+ await new TopicModel(serverDB, userId, workspaceId).create({
+ agentId: privateAgent.id,
+ projectId: sharedProject.id,
+ title: 'Private work',
+ });
+
+ expect(await memberIds(creator, sharedProject.id)).not.toContain(privateAgent.id);
+ });
+
+ // TODO(2026-12-31): remove with `ProjectModel.joinTopicAgents`.
+ it('backfills agents of topics filed before members were added on write', async () => {
+ const project = await createProject(model, { name: 'Legacy' });
+ const agent = await new AgentModel(serverDB, userId).create({ title: 'Architect' });
+ await serverDB
+ .insert(topics)
+ .values({ agentId: agent.id, id: 'tpc_legacy', projectId: project.id, userId });
+ expect(await memberIds(model, project.id)).not.toContain(agent.id);
+
+ await model.joinTopicAgents(project.id);
+
+ expect(await memberIds(model, project.id)).toContain(agent.id);
+ });
+
+ // TODO(2026-12-31): remove with `ProjectModel.joinTopicAgents`.
+ it('leaves members alone when a read-only viewer opens the project', async () => {
+ const project = await createProject(model, { name: 'Legacy' });
+ const agent = await new AgentModel(serverDB, userId).create({ title: 'Architect' });
+ await serverDB
+ .insert(topics)
+ .values({ agentId: agent.id, id: 'tpc_legacy_viewer', projectId: project.id, userId });
+
+ await new ProjectModel(serverDB, userId, undefined, { readOnly: true }).joinTopicAgents(
+ project.id,
+ );
+
+ expect(await memberIds(model, project.id)).not.toContain(agent.id);
+ });
+});
diff --git a/packages/database/src/models/project.ts b/packages/database/src/models/project.ts
index 54c05f8d60a..cbde84fd756 100644
--- a/packages/database/src/models/project.ts
+++ b/packages/database/src/models/project.ts
@@ -18,6 +18,7 @@ import { tasks } from '../schemas/task';
import { topics } from '../schemas/topic';
import { works } from '../schemas/work';
import type { LobeChatDatabase } from '../type';
+import { joinTopicAgentsToProjects } from '../utils/projectTopicAgents';
import { buildWorkspacePayload, buildWorkspaceWhere } from '../utils/workspace';
import { AgentModel } from './agent';
import { EnvironmentModel } from './environment';
@@ -395,6 +396,17 @@ export class ProjectModel {
.orderBy(...coordinatorFirst, asc(projectAgents.sortOrder), asc(projectAgents.createdAt));
}
+ /**
+ * TODO(2026-12-31): remove this runtime backfill. Topics filed before their
+ * agents joined the project on write still leave those agents out of the
+ * members; opening the member list brings them in. Read-only viewers only
+ * look, so their visit changes nothing.
+ */
+ async joinTopicAgents(projectId: string) {
+ if (this.options.readOnly || !(await this.findById(projectId))) return;
+ await joinTopicAgentsToProjects(this.db, { projectId });
+ }
+
async addAgent(projectId: string, input: ProjectAgentInput) {
const project = await this.findMembersManageableById(projectId);
if (!project) return null;
diff --git a/packages/database/src/models/topic/create.ts b/packages/database/src/models/topic/create.ts
index 57c175eeafc..2f3348ca7b7 100644
--- a/packages/database/src/models/topic/create.ts
+++ b/packages/database/src/models/topic/create.ts
@@ -1,6 +1,7 @@
import { runTimedSinkStage as runTimedStage } from '@lobechat/utils';
import { type TopicItem, topics } from '../../schemas';
+import { joinTopicAgentsToProjects } from '../../utils/projectTopicAgents';
import { buildWorkspacePayload } from '../../utils/workspace';
import type { TopicModelContext } from './context';
import type { CreateTopicParams, ModelTimingContext } from './types';
@@ -48,6 +49,9 @@ export const create = async (
},
);
+ if (topic?.projectId && topic.agentId)
+ await joinTopicAgentsToProjects(ctx.db, { topicIds: [topic.id] });
+
return topic;
};
diff --git a/packages/database/src/models/topic/update.ts b/packages/database/src/models/topic/update.ts
index 57e6ca07817..80da6b3a931 100644
--- a/packages/database/src/models/topic/update.ts
+++ b/packages/database/src/models/topic/update.ts
@@ -2,6 +2,7 @@ import type { ChatTopicMetadata } from '@lobechat/types';
import { and, eq, or, sql } from 'drizzle-orm';
import { type TopicItem, topics } from '../../schemas';
+import { joinTopicAgentsToProjects } from '../../utils/projectTopicAgents';
import { recomputeTopicUsage } from '../topicUsage';
import type { TopicModelContext } from './context';
import type { TopicMetadataPatch } from './types';
@@ -46,11 +47,18 @@ export const update = async (ctx: TopicModelContext, id: string, data: Partial<T
? persistedMetadata
: undefined;
- return ctx.db
+ const updated = await ctx.db
.update(topics)
.set({ ...data, metadata, updatedAt: new Date() })
.where(and(eq(topics.id, id), ctx.ownership()))
.returning();
+
+ // Moving a topic into a project, or handing it to another agent, makes that
+ // agent a project member.
+ if ((data.projectId || data.agentId) && updated.some((topic) => topic.projectId && topic.agentId))
+ await joinTopicAgentsToProjects(ctx.db, { topicIds: updated.map((topic) => topic.id) });
+
+ return updated;
};
/**
diff --git a/packages/database/src/repositories/projectDirectory/index.ts b/packages/database/src/repositories/projectDirectory/index.ts
index a5afc35f2af..9f88a77625e 100644
--- a/packages/database/src/repositories/projectDirectory/index.ts
+++ b/packages/database/src/repositories/projectDirectory/index.ts
@@ -12,6 +12,7 @@ import {
import { hasLiveTaskCallbackReservation } from '../../models/topic';
import { agents, devices, projectEnvironments, topics } from '../../schemas';
import type { LobeChatDatabase } from '../../type';
+import { joinTopicAgentsToProjects } from '../../utils/projectTopicAgents';
import { buildWorkspaceWhere } from '../../utils/workspace';
/**
@@ -210,6 +211,7 @@ export class ProjectDirectoryRepository {
const found = new Set(selected.map((topic) => topic.id));
for (const id of topicIds)
if (!found.has(id)) skippedTopics.push({ id, reason: 'notFound' });
+ const filedTopicIds: string[] = [];
// Filing is a convenience on top of the binding: one conversation that
// cannot move must not cost the directory or the others, so it is
// skipped and reported instead of failing the whole bind.
@@ -241,7 +243,9 @@ export class ProjectDirectoryRepository {
metadata: { ...metadata, boundDeviceId: device.deviceId },
})
.where(eq(topics.id, topic.id));
+ filedTopicIds.push(topic.id);
}
+ await joinTopicAgentsToProjects(db, { topicIds: filedTopicIds });
}
return { ...directory, skippedTopics };
});
@@ -326,6 +330,7 @@ export class ProjectDirectoryRepository {
})
.where(eq(topics.id, topicId))
.returning();
+ await joinTopicAgentsToProjects(db, { topicIds: [topicId] });
return updated;
});
}
diff --git a/packages/database/src/repositories/topic/move.ts b/packages/database/src/repositories/topic/move.ts
index ccccfb54de6..6f13edbf0cb 100644
--- a/packages/database/src/repositories/topic/move.ts
+++ b/packages/database/src/repositories/topic/move.ts
@@ -1,6 +1,7 @@
import { and, eq, inArray } from 'drizzle-orm';
import { agents, messages, threads, topics } from '../../schemas';
+import { joinTopicAgentsToProjects } from '../../utils/projectTopicAgents';
import { buildWorkspaceWhere } from '../../utils/workspace';
import { messageOwnership, topicOwnership, type TopicRepositoryScope } from './scope';
@@ -50,10 +51,13 @@ export const batchMoveToAgent = async (
throw new Error(`Target agent ${targetAgentId} not found or not accessible`);
}
- await tx
+ const moved = await tx
.update(topics)
.set({ agentId: targetAgentId, sessionId: null, updatedAt: new Date() })
- .where(and(inArray(topics.id, topicIds), topicOwnership(scope)));
+ .where(and(inArray(topics.id, topicIds), topicOwnership(scope)))
+ .returning({ id: topics.id });
+ // A project topic handed to another agent brings that agent into the project.
+ await joinTopicAgentsToProjects(tx, { topicIds: moved.map((topic) => topic.id) });
await tx
.update(messages)
diff --git a/packages/database/src/utils/projectTopicAgents.ts b/packages/database/src/utils/projectTopicAgents.ts
new file mode 100644
index 00000000000..f058001216c
--- /dev/null
+++ b/packages/database/src/utils/projectTopicAgents.ts
@@ -0,0 +1,77 @@
+import { INBOX_SESSION_ID } from '@lobechat/const';
+import { and, eq, inArray, isNotNull, isNull, ne, or, sql } from 'drizzle-orm';
+
+import { agents } from '../schemas/agent';
+import { projectAgents, projects } from '../schemas/project';
+import { topics } from '../schemas/topic';
+import type { LobeChatDatabase, Transaction } from '../type';
+
+export type ProjectTopicAgentsFilter = { projectId: string } | { topicIds: string[] };
+
+/**
+ * An agent that works on a project topic is a member of that project: add the
+ * agent of every matching topic to its project's members. Existing members keep
+ * their role, responsibility and enabled state.
+ *
+ * The coordinator is managed by the project, and a shared workspace project only
+ * takes shared agents, so neither ever joins this way. A project whose main
+ * agent was cleared is led by LobeAI (see `resolveCoordinatorAgents`), so LobeAI
+ * counts as its coordinator here.
+ *
+ * Best effort: membership is a side effect of the topic write, so a failure is
+ * logged instead of failing it. The work runs in its own savepoint, so a failed
+ * statement does not abort the caller's transaction either.
+ */
+export const joinTopicAgentsToProjects = async (
+ db: LobeChatDatabase | Transaction,
+ filter: ProjectTopicAgentsFilter,
+) => {
+ if ('topicIds' in filter && filter.topicIds.length === 0) return;
+
+ try {
+ await db.transaction(async (tx) => {
+ const candidates = await tx
+ .selectDistinct({
+ agentId: agents.id,
+ projectId: projects.id,
+ workspaceId: projects.workspaceId,
+ })
+ .from(topics)
+ .innerJoin(projects, eq(projects.id, topics.projectId))
+ .innerJoin(agents, eq(agents.id, topics.agentId))
+ .where(
+ and(
+ 'topicIds' in filter
+ ? inArray(topics.id, filter.topicIds)
+ : eq(topics.projectId, filter.projectId),
+ isNotNull(topics.agentId),
+ isNull(topics.deletedAt),
+ or(
+ and(
+ isNotNull(projects.coordinatorAgentId),
+ ne(agents.id, projects.coordinatorAgentId),
+ ),
+ and(
+ isNull(projects.coordinatorAgentId),
+ sql`${agents.slug} is distinct from ${INBOX_SESSION_ID}`,
+ ),
+ ),
+ sql`${agents.workspaceId} is not distinct from ${projects.workspaceId}`,
+ or(
+ isNull(projects.workspaceId),
+ ne(projects.visibility, 'public'),
+ eq(agents.visibility, 'public'),
+ ),
+ ),
+ );
+ if (candidates.length === 0) return;
+
+ await tx
+ .insert(projectAgents)
+ .values(candidates)
+ .onConflictDoNothing({ target: [projectAgents.projectId, projectAgents.agentId] });
+ });
+ } catch (error) {
+ console.error('[joinTopicAgentsToProjects] failed to add topic agents to projects', error);
+ }
+};