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(channel): one member model — project Channels open to the project, project Agents first, remove and leave (#23107)

Arvin Xu995c0f1c0898
diff --git a/apps/server/src/routers/lambda/__tests__/project.removeAgent.test.ts b/apps/server/src/routers/lambda/__tests__/project.removeAgent.test.ts
new file mode 100644
index 00000000000..2951ae8e1df
--- /dev/null
+++ b/apps/server/src/routers/lambda/__tests__/project.removeAgent.test.ts
@@ -0,0 +1,62 @@
+// @vitest-environment node
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+const mocks = vi.hoisted(() => ({
+ leaveProjectChannels: vi.fn(),
+ removeAgent: vi.fn(),
+}));
+
+vi.mock('@/database/core/db-adaptor', () => ({
+ getServerDB: vi.fn(function () {
+ return {};
+ }),
+}));
+
+vi.mock('@/business/server/trpc-middlewares/rbacPermission', () => ({
+ withScopedPermission: vi.fn(function () {
+ return (opts: any) => opts.next({ ctx: opts.ctx });
+ }),
+}));
+
+vi.mock('@/database/models/project', () => ({
+ ProjectIdentifierTakenError: class extends Error {},
+ ProjectModel: vi.fn(function () {
+ return { removeAgent: mocks.removeAgent };
+ }),
+}));
+
+vi.mock('@/database/repositories/projectCoordinator', () => ({
+ ProjectCoordinatorRepository: vi.fn(function () {
+ return {};
+ }),
+}));
+
+vi.mock('@/server/services/channel/projectMembership', () => ({
+ leaveProjectChannels: mocks.leaveProjectChannels,
+}));
+
+const { projectRouter } = await import('../project');
+
+const caller = () => projectRouter.createCaller({ userId: 'member', workspaceId: 'ws-1' } as never);
+
+describe('project.removeAgent', () => {
+ beforeEach(() => vi.clearAllMocks());
+
+ it('takes the Agent out of the project’s Channels too', async () => {
+ mocks.removeAgent.mockResolvedValue(true);
+
+ await caller().removeAgent({ agentId: 'agent-2', id: 'project-1' });
+
+ expect(mocks.removeAgent).toHaveBeenCalledWith('project-1', 'agent-2');
+ expect(mocks.leaveProjectChannels).toHaveBeenCalledWith({}, 'project-1', 'agent-2');
+ });
+
+ it('leaves Channels alone when the caller could not remove it from the project', async () => {
+ mocks.removeAgent.mockResolvedValue(false);
+
+ await expect(
+ caller().removeAgent({ agentId: 'agent-2', id: 'project-1' }),
+ ).rejects.toMatchObject({ code: 'NOT_FOUND' });
+ expect(mocks.leaveProjectChannels).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/server/src/routers/lambda/_helpers/projectRights.ts b/apps/server/src/routers/lambda/_helpers/projectRights.ts
new file mode 100644
index 00000000000..38122b79ef5
--- /dev/null
+++ b/apps/server/src/routers/lambda/_helpers/projectRights.ts
@@ -0,0 +1,16 @@
+import type { WorkspaceRole } from '@/business/server/trpc-middlewares/workspaceAuth';
+import type { ProjectModelOptions } from '@/database/models/project';
+
+/**
+ * The caller's project rights from their workspace role. Reads `workspaceRole` as an optional
+ * context field: the cloud workspace-auth override injects it, while the OSS stub leaves it absent.
+ * Workspace owners and admins manage every readable project's members; viewers hold no
+ * `agent:update` grant, so they only read.
+ */
+export const projectModelOptions = (ctx: {
+ workspaceId?: string | null;
+ workspaceRole?: WorkspaceRole;
+}): ProjectModelOptions => ({
+ canManageAllMembers: ctx.workspaceRole === 'owner' || ctx.workspaceRole === 'admin',
+ readOnly: !!ctx.workspaceId && ctx.workspaceRole === 'viewer',
+});
diff --git a/apps/server/src/routers/lambda/channel.ts b/apps/server/src/routers/lambda/channel.ts
index 2b27197cf79..6932e47a47d 100644
--- a/apps/server/src/routers/lambda/channel.ts
+++ b/apps/server/src/routers/lambda/channel.ts
@@ -17,6 +17,7 @@ import {
import { WakeConfigInputSchema } from '@/server/services/conversationWake/config';
import { pickWakeJudgeScore } from '@/server/services/conversationWake/judgeScore';
+import { projectModelOptions } from './_helpers/projectRights';
import { channelHistoryProcedures } from './channelHistory';
const channelId = z.string().regex(/^chn_[\dA-Za-z]{12}$/);
@@ -36,7 +37,12 @@ const channelProcedure = wsCompatProcedure.use(serverDatabase).use(async ({ ctx,
});
const result = await next({
ctx: {
- channelService: new ChannelService(ctx.serverDB, ctx.userId, ctx.workspaceId ?? undefined),
+ channelService: new ChannelService(
+ ctx.serverDB,
+ ctx.userId,
+ ctx.workspaceId ?? undefined,
+ projectModelOptions(ctx),
+ ),
},
});
if (!result.ok && result.error.cause instanceof ChannelError) {
@@ -67,10 +73,13 @@ export const channelRouter = router({
await ctx.channelService.archiveThread(input.channelId, input.threadId);
return { success: true };
}),
+ /** In a project Channel, `joinProject` seats an Agent from outside in the project first. */
addAgent: channelProcedure
- .input(z.object({ channelId, agent: agentSelection }))
+ .input(z.object({ channelId, agent: agentSelection, joinProject: z.boolean().optional() }))
.mutation(async ({ ctx, input }) => ({
- data: await ctx.channelService.addAgent(input.channelId, input.agent),
+ data: await ctx.channelService.addAgent(input.channelId, input.agent, {
+ joinProject: input.joinProject,
+ }),
success: true,
})),
agentEnvironment: channelProcedure
@@ -184,6 +193,7 @@ export const channelRouter = router({
.input(
z.object({
agents: z.array(agentSelection).max(20).default([]),
+ joinProject: z.boolean().optional(),
projectId: z.string().min(1).optional(),
title: z.string().trim().min(1).max(CHANNEL_LIMITS.titleLength),
userIds: z.array(z.string().min(1)).max(100).default([]),
@@ -252,10 +262,16 @@ export const channelRouter = router({
.query(async ({ ctx, input }) => ({
data: await ctx.channelService.repository.listJoinable(input?.search),
})),
+ /** Joins an open project Channel or a public one the caller can join. */
join: channelProcedure.input(z.object({ channelId })).mutation(async ({ ctx, input }) => {
const { channel } = await ctx.channelService.join(input.channelId);
return { data: channel, success: true };
}),
+ /** The caller leaves a group Channel; its owner cannot. */
+ leave: channelProcedure.input(z.object({ channelId })).mutation(async ({ ctx, input }) => {
+ const { readable } = await ctx.channelService.leave(input.channelId);
+ return { readable, success: true };
+ }),
list: channelProcedure.query(async ({ ctx }) => ({
data: await ctx.channelService.repository.list(),
success: true,
@@ -288,6 +304,13 @@ export const channelRouter = router({
data: await ctx.channelService.editMessage(input.channelId, input.messageId, input.content),
success: true,
})),
+ /** An admin removes a person or an Agent from a group Channel. */
+ removeMember: channelProcedure
+ .input(z.object({ channelId, memberId: z.uuid() }))
+ .mutation(async ({ ctx, input }) => {
+ await ctx.channelService.removeMember(input.channelId, input.memberId);
+ return { success: true };
+ }),
rename: channelProcedure
.input(z.object({ channelId, title: z.string().trim().min(1).max(CHANNEL_LIMITS.titleLength) }))
.mutation(async ({ ctx, input }) => ({
diff --git a/apps/server/src/routers/lambda/project.ts b/apps/server/src/routers/lambda/project.ts
index 98eef15e0b8..6976656999a 100644
--- a/apps/server/src/routers/lambda/project.ts
+++ b/apps/server/src/routers/lambda/project.ts
@@ -10,15 +10,8 @@ import { TRPCError } from '@trpc/server';
import { z } from 'zod';
import { withScopedPermission } from '@/business/server/trpc-middlewares/rbacPermission';
-import {
- type WorkspaceRole,
- wsCompatProcedure,
-} from '@/business/server/trpc-middlewares/workspaceAuth';
-import {
- ProjectIdentifierTakenError,
- ProjectModel,
- type ProjectModelOptions,
-} from '@/database/models/project';
+import { wsCompatProcedure } from '@/business/server/trpc-middlewares/workspaceAuth';
+import { ProjectIdentifierTakenError, ProjectModel } from '@/database/models/project';
import { ProjectRepository } from '@/database/repositories/project';
import { ProjectCoordinatorRepository } from '@/database/repositories/projectCoordinator';
import { ProjectOverviewRepository } from '@/database/repositories/projectOverview';
@@ -26,29 +19,17 @@ import type { LobeChatDatabase } from '@/database/type';
import { router } from '@/libs/trpc/lambda';
import { serverDatabase } from '@/libs/trpc/lambda/middleware';
import { createDefaultChannel } from '@/server/services/channel/defaultChannel';
+import { leaveProjectChannels } from '@/server/services/channel/projectMembership';
import { GoalService } from '@/server/services/goal';
import { assertCanPerformResourceAction } from '@/server/services/resourcePermission';
import { rethrowDuplicateProjectField } from './_helpers/projectConstraintErrors';
-
-/**
- * Reads `workspaceRole` as an optional context field: the cloud workspace-auth
- * override injects it, while the OSS stub leaves it absent.
- */
-const isWorkspaceAdmin = (ctx: { userId: string; workspaceRole?: WorkspaceRole }) =>
- ctx.workspaceRole === 'owner' || ctx.workspaceRole === 'admin';
-
-/** Viewers hold no `agent:update` grant, so `projectWriteProcedure` rejects them. */
-const isWorkspaceViewer = (ctx: { workspaceId?: string | null; workspaceRole?: WorkspaceRole }) =>
- !!ctx.workspaceId && ctx.workspaceRole === 'viewer';
+import { projectModelOptions } from './_helpers/projectRights';
const projectProcedure = wsCompatProcedure.use(serverDatabase).use(async (opts) => {
const { ctx } = opts;
const workspaceId = ctx.workspaceId ?? undefined;
- const options: ProjectModelOptions = {
- canManageAllMembers: isWorkspaceAdmin(ctx),
- readOnly: isWorkspaceViewer(ctx),
- };
+ const options = projectModelOptions(ctx);
return opts.next({
ctx: {
projectCoordinatorRepo: new ProjectCoordinatorRepository(
@@ -59,7 +40,7 @@ const projectProcedure = wsCompatProcedure.use(serverDatabase).use(async (opts)
),
projectModel: new ProjectModel(ctx.serverDB, ctx.userId, workspaceId, options),
projectOverviewRepo: new ProjectOverviewRepository(ctx.serverDB, ctx.userId, workspaceId),
- projectRepo: new ProjectRepository(ctx.serverDB, ctx.userId, workspaceId),
+ projectRepo: new ProjectRepository(ctx.serverDB, ctx.userId, workspaceId, options),
},
});
});
@@ -141,7 +122,7 @@ export const projectRouter = router({
try {
return {
data: requireResult(
- await ctx.projectModel.reviewCompletion(input.id, 'accepted', input.comment),
+ await ctx.projectRepo.reviewCompletion(input.id, 'accepted', input.comment),
),
message: 'Project completion accepted',
success: true,
@@ -250,7 +231,7 @@ export const projectRouter = router({
delete: projectWriteProcedure.input(idInput).mutation(async ({ ctx, input }) => {
try {
return {
- data: requireResult(await ctx.projectModel.delete(input.id)),
+ data: requireResult(await ctx.projectRepo.delete(input.id)),
message: 'Project deleted',
success: true,
};
@@ -370,7 +351,7 @@ export const projectRouter = router({
try {
return {
data: requireResult(
- await ctx.projectModel.reviewCompletion(input.id, 'rejected', input.comment),
+ await ctx.projectRepo.reviewCompletion(input.id, 'rejected', input.comment),
),
message: 'Project completion rejected',
success: true,
@@ -386,6 +367,7 @@ export const projectRouter = router({
try {
const removed = await ctx.projectModel.removeAgent(input.id, input.agentId);
if (!removed) throw new TRPCError({ code: 'NOT_FOUND', message: 'Binding not found' });
+ await leaveProjectChannels(ctx.serverDB, input.id, input.agentId);
return { message: 'Agent removed from project', success: true };
} catch (error) {
mapProjectError(error, 'removeAgent');
diff --git a/apps/server/src/services/channel/ChannelService.project.test.ts b/apps/server/src/services/channel/ChannelService.project.test.ts
index 6d57ecea31e..d029cdc13d5 100644
--- a/apps/server/src/services/channel/ChannelService.project.test.ts
+++ b/apps/server/src/services/channel/ChannelService.project.test.ts
@@ -3,20 +3,29 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';
import { ChannelService } from './ChannelService';
-const { create, findProject, getAgent } = vi.hoisted(() => ({
- create: vi.fn(),
- findProject: vi.fn(),
- getAgent: vi.fn(),
-}));
+const { addAgent, addProjectAgent, create, findAccess, findProject, getAgent, hasAgent } =
+ vi.hoisted(() => ({
+ addAgent: vi.fn(),
+ addProjectAgent: vi.fn(),
+ create: vi.fn(),
+ findAccess: vi.fn(),
+ findProject: vi.fn(),
+ getAgent: vi.fn(),
+ hasAgent: vi.fn(),
+ }));
vi.mock('@/database/repositories/channel', async (original) => ({
...(await original<object>()),
ChannelRepository: class {
+ addAgent = addAgent;
create = create;
+ findAccess = findAccess;
},
}));
vi.mock('@/database/models/project', () => ({
ProjectModel: class {
+ addAgent = addProjectAgent;
findById = findProject;
+ hasAgent = hasAgent;
},
}));
vi.mock('@/database/models/device', () => ({ DeviceModel: class {} }));
@@ -35,6 +44,7 @@ describe('creating a Channel inside a project', () => {
vi.resetAllMocks();
create.mockResolvedValue({ channel: { id: 'chn_1' } });
getAgent.mockResolvedValue({ model: 'gpt-5' });
+ hasAgent.mockResolvedValue(true);
});
const service = () => new ChannelService({} as never, 'owner', 'workspace');
const agents = [{ agentId: 'agt_1' }];
@@ -63,3 +73,84 @@ describe('creating a Channel inside a project', () => {
expect(create).toHaveBeenCalledWith(expect.objectContaining({ projectId: undefined }));
});
});
+
+describe('seating Agents in a project Channel', () => {
+ beforeEach(() => {
+ vi.resetAllMocks();
+ create.mockResolvedValue({ channel: { id: 'chn_1' } });
+ getAgent.mockResolvedValue({ model: 'gpt-5' });
+ findProject.mockResolvedValue({ id: 'pro_1' });
+ findAccess.mockResolvedValue({
+ channel: { id: 'chn_1', projectId: 'pro_1' },
+ member: { role: 'owner' },
+ });
+ addAgent.mockResolvedValue({ id: 'member_1' });
+ });
+ const service = (options = {}) => new ChannelService({} as never, 'owner', 'workspace', options);
+
+ it('adds a project member Agent without touching the project', async () => {
+ hasAgent.mockResolvedValue(true);
+ await service().addAgent('chn_1', { agentId: 'agt_1' });
+ expect(addProjectAgent).not.toHaveBeenCalled();
+ expect(addAgent).toHaveBeenCalledWith('chn_1', expect.objectContaining({ agentId: 'agt_1' }));
+ });
+
+ it('asks for the project first when an outside Agent comes without consent', async () => {
+ hasAgent.mockResolvedValue(false);
+ await expect(service().addAgent('chn_1', { agentId: 'agt_2' })).rejects.toMatchObject({
+ code: 'CONFLICT',
+ });
+ expect(addProjectAgent).not.toHaveBeenCalled();
+ expect(addAgent).not.toHaveBeenCalled();
+ });
+
+ it('seats an outside Agent in the project first, then the Channel', async () => {
+ hasAgent.mockResolvedValue(false);
+ addProjectAgent.mockResolvedValue({ id: 'binding_1' });
+ await service().addAgent('chn_1', { agentId: 'agt_2' }, { joinProject: true });
+ expect(addProjectAgent).toHaveBeenCalledWith('pro_1', { agentId: 'agt_2' });
+ expect(addAgent).toHaveBeenCalled();
+ expect(addProjectAgent.mock.invocationCallOrder[0]).toBeLessThan(
+ addAgent.mock.invocationCallOrder[0],
+ );
+ });
+
+ it('refuses when the caller cannot manage the project’s members', async () => {
+ hasAgent.mockResolvedValue(false);
+ addProjectAgent.mockResolvedValue(null);
+ await expect(
+ service().addAgent('chn_1', { agentId: 'agt_2' }, { joinProject: true }),
+ ).rejects.toMatchObject({ code: 'FORBIDDEN' });
+ expect(addAgent).not.toHaveBeenCalled();
+
+ await expect(
+ service({ readOnly: true }).addAgent('chn_1', { agentId: 'agt_2' }, { joinProject: true }),
+ ).rejects.toMatchObject({ code: 'FORBIDDEN' });
+ });
+
+ it('does not let a plain Channel member seat an Agent in the project', async () => {
+ findAccess.mockResolvedValue({
+ channel: { id: 'chn_1', projectId: 'pro_1' },
+ member: { role: 'member' },
+ });
+ hasAgent.mockResolvedValue(false);
+ await expect(
+ service().addAgent('chn_1', { agentId: 'agt_2' }, { joinProject: true }),
+ ).rejects.toMatchObject({ code: 'FORBIDDEN' });
+ expect(addProjectAgent).not.toHaveBeenCalled();
+ });
+
+ it('seats outside Agents of a new project Channel before creating it', async () => {
+ hasAgent.mockImplementation(async (_projectId: string, agentId: string) => agentId === 'agt_1');
+ addProjectAgent.mockResolvedValue({ id: 'binding_2' });
+ await service().create({
+ agents: [{ agentId: 'agt_1' }, { agentId: 'agt_2' }],
+ joinProject: true,
+ projectId: 'pro_1',
+ title: 'Launch',
+ });
+ expect(addProjectAgent).toHaveBeenCalledTimes(1);
+ expect(addProjectAgent).toHaveBeenCalledWith('pro_1', { agentId: 'agt_2' });
+ expect(create).toHaveBeenCalled();
+ });
+});
diff --git a/apps/server/src/services/channel/ChannelService.ts b/apps/server/src/services/channel/ChannelService.ts
index 8eb7c89cf10..2bd5272030e 100644
--- a/apps/server/src/services/channel/ChannelService.ts
+++ b/apps/server/src/services/channel/ChannelService.ts
@@ -14,6 +14,7 @@ import pMap from 'p-map';
import { AgentShareModel } from '@/database/models/agentShare';
import { ContactModel, parseContactHandle } from '@/database/models/contact';
import { DeviceModel } from '@/database/models/device';
+import type { ProjectModelOptions } from '@/database/models/project';
import { ProjectModel } from '@/database/models/project';
import type {
ChannelAddAgentInput,
@@ -59,11 +60,13 @@ export class ChannelService {
private readonly db: LobeChatDatabase,
private readonly userId: string,
private readonly workspaceId?: string,
+ /** The caller's project rights, for seating a new Agent in a project Channel's project. */
+ private readonly projectOptions: ProjectModelOptions = {},
) {
this.repository = new ChannelRepository(db, userId, workspaceId);
this.agentService = new AgentService(db, userId, workspaceId);
this.deviceModel = new DeviceModel(db, userId, workspaceId);
- this.projectModel = new ProjectModel(db, userId, workspaceId);
+ this.projectModel = new ProjectModel(db, userId, workspaceId, projectOptions);
}
private async resolveAgent(
@@ -133,9 +136,38 @@ export class ChannelService {
return { agentId: input.agentId, config, description: input.description, name: input.name };
}
+ /**
+ * A project Channel seats only the project's own Agents. With `joinProject`, an Agent from
+ * outside joins the project first, which takes the right to manage the project's members;
+ * without it, the caller is told to add the Agent to the project.
+ */
+ private async seatAgentsInProject(projectId: string, agentIds: string[], joinProject?: boolean) {
+ const missing: string[] = [];
+ for (const agentId of new Set(agentIds))
+ if (!(await this.projectModel.hasAgent(projectId, agentId))) missing.push(agentId);
+ if (!missing.length) return;
+ if (!joinProject) throw new ChannelError('CONFLICT', 'Add the Agent to the project first');
+ const forbidden = new ChannelError(
+ 'FORBIDDEN',
+ 'Only the project creator or a workspace admin can add an Agent to the project',
+ );
+ if (this.projectOptions.readOnly) throw forbidden;
+ for (const agentId of missing) {
+ let binding: Awaited<ReturnType<ProjectModel['addAgent']>>;
+ try {
+ binding = await this.projectModel.addAgent(projectId, { agentId });
+ } catch (error) {
+ throw new ChannelError('BAD_REQUEST', (error as Error).message);
+ }
+ if (!binding) throw forbidden;
+ }
+ }
+
/** A group starts with Agents, workspace people, both, or only its creator. */
create = async (input: {
agents: ChannelAgentSelection[];
+ /** Seats Agents from outside the project in the project first. */
+ joinProject?: boolean;
projectId?: string;
title: string;
userIds?: string[];
@@ -149,6 +181,12 @@ export class ChannelService {
const agents = await pMap(input.agents, (agent) => this.resolveAgent(agent), {
concurrency: 5,
});
+ if (input.projectId)
+ await this.seatAgentsInProject(
+ input.projectId,
+ agents.map(({ agentId }) => agentId),
+ input.joinProject,
+ );
const access = await this.repository.create({
agents,
projectId: input.projectId,
@@ -301,11 +339,26 @@ export class ChannelService {
return inbox.id;
}
- addAgent = async (channelId: string, input: ChannelAgentSelection) => {
+ addAgent = async (
+ channelId: string,
+ input: ChannelAgentSelection,
+ options: { joinProject?: boolean } = {},
+ ) => {
// Check membership before probing a device; the write rechecks the current admin role.
- if (!(await this.repository.findAccess(channelId)))
- throw new ChannelError('NOT_FOUND', 'Channel not found');
- const member = await this.repository.addAgent(channelId, await this.resolveAgent(input));
+ const access = await this.repository.findAccess(channelId);
+ if (!access) throw new ChannelError('NOT_FOUND', 'Channel not found');
+ const agent = await this.resolveAgent(input);
+ if (access.channel.projectId) {
+ // Only an admin may add, so no one else can seat an Agent in the project through here.
+ if (access.member.role === 'member')
+ throw new ChannelError('FORBIDDEN', 'Requires the admin role in this channel');
+ await this.seatAgentsInProject(
+ access.channel.projectId,
+ [agent.agentId],
+ options.joinProject,
+ );
+ }
+ const member = await this.repository.addAgent(channelId, agent);
await this.changed(channelId);
return member;
};
@@ -348,7 +401,23 @@ export class ChannelService {
return channel;
};
- /** Members already in the Channel see the newcomer without waiting for their next poll. */
+ /** The coordinator physically stops a removed Agent's runs. */
+ removeMember = async (channelId: string, memberId: string) => {
+ const writers = await this.repository.removeMember(channelId, memberId);
+ await new ChannelCoordinator(this.db).stopWriters(writers);
+ await Promise.all([wakeChannel(channelId), this.changed(channelId)]);
+ };
+
+ leave = async (channelId: string) => {
+ const result = await this.repository.leave(channelId);
+ await this.changed(channelId);
+ return result;
+ };
+
+ /**
+ * Joins an open project Channel or a public one of the workspace. Members already in it see the
+ * newcomer without waiting for their next poll.
+ */
join = async (channelId: string) => {
const access = await this.repository.join(channelId);
await this.changed(channelId);
diff --git a/apps/server/src/services/channel/projectMembership.ts b/apps/server/src/services/channel/projectMembership.ts
new file mode 100644
index 00000000000..7f3c7d0a0ca
--- /dev/null
+++ b/apps/server/src/services/channel/projectMembership.ts
@@ -0,0 +1,26 @@
+import type { LobeChatDatabase } from '@lobechat/database';
+import pMap from 'p-map';
+
+import { removeAgentFromProjectChannels } from '@/database/repositories/channel';
+
+import { ChannelCoordinator } from './ChannelCoordinator';
+import { notifyChannel } from './notify';
+import { wakeChannel } from './queue';
+
+/**
+ * An Agent removed from a project leaves the project's Channels: they seat only its own Agents.
+ * The caller has already checked the right to manage the project's members.
+ */
+export const leaveProjectChannels = async (
+ db: LobeChatDatabase,
+ projectId: string,
+ agentId: string,
+) => {
+ const { channelIds, writers } = await removeAgentFromProjectChannels(db, projectId, agentId);
+ await new ChannelCoordinator(db).stopWriters(writers);
+ await pMap(
+ channelIds,
+ (channelId) => Promise.all([wakeChannel(channelId), notifyChannel(db, channelId)]),
+ { concurrency: 5 },
+ );
+};
diff --git a/locales/en-US/channel.json b/locales/en-US/channel.json
index 5af85218d4a..0c3d9540c02 100644
--- a/locales/en-US/channel.json
+++ b/locales/en-US/channel.json
@@ -46,6 +46,7 @@
"composer": "Message #{{name}}",
"composer.actions": "More actions",
"composer.mention": "Mention someone",
+ "composerToJoin": "Message #{{name}} to join",
"conversationEmpty": "Start the conversation",
"copyId": "Copy ID",
"copyIdSuccess": "Channel ID copied",
@@ -111,25 +112,47 @@
"failure.title": "Failed replies · {{count}}",
"followers": "Replies from: {{names}}",
"invite.directHint": "Inviting here starts a new channel with {{name}} and the members you choose. This conversation with {{name}} stays as it is.",
+ "invite.joinProjectNotice": "{{names}} will join the project “{{project}}” first, then this channel.",
+ "invite.joinProjectNoticeUnnamed": "{{names}} will join this project first, then this channel.",
"invite.noAgentMatches": "No matching Agents",
"invite.noAgents": "All available Agents have joined",
"invite.noSelected": "No one selected yet",
+ "invite.outsideProject": "Other Agents · they join the project too",
+ "invite.outsideProjectLocked": "Only the project creator or a workspace admin can add another Agent to this project",
"invite.people": "Workspace members",
"invite.search": "Search members and Agents",
"invite.submit": "Invite",
"invite.title": "Invite members",
"latestMessages": "Latest messages",
+ "leave": "Leave channel",
+ "leaveConfirm": "You will no longer see this channel unless someone invites you again.",
+ "leaveConfirmProject": "You can join again from the project at any time.",
+ "leaveConfirmTitle": "Leave “{{title}}”?",
+ "leaveFailed": "Couldn't leave the channel. Try again.",
+ "leaveSuccess": "You left the channel",
"main": "Channel conversation",
"memberActionsNamed": "Actions for {{name}}",
"members.agents": "Agents · {{count}}",
+ "member.remove": "Remove from channel",
+ "member.removeConfirmAgent": "Its replies in progress here stop. It stays in the project and can be invited again.",
+ "member.removeConfirmAgentStandalone": "Its replies in progress here stop. You can invite it again later.",
+ "member.removeConfirmPerson": "They will no longer see this channel unless an admin invites them again.",
+ "member.removeConfirmTitle": "Remove {{name}} from the channel?",
+ "member.removeFailed": "Couldn't remove {{name}}. Try again.",
+ "member.removeNamed": "Remove {{name}} from the channel",
"members.hide": "Hide member list",
"members.show": "Show member list",
"membersCount": "Members · {{count}}",
"membersTitle": "Members",
"mentionHint": "Mention Agents to choose who replies. Without a mention, every Agent here replies.",
+ "mentionInvite.confirmAgent": "It will read this channel and can reply here.",
+ "mentionInvite.confirmAgentProject": "It is not in the project “{{project}}” yet: it joins the project first, then this channel.",
+ "mentionInvite.confirmOk": "Invite and mention",
+ "mentionInvite.confirmPerson": "They will see the whole conversation in this channel.",
+ "mentionInvite.confirmTitle": "Invite {{name}} to this channel?",
"mentionInvite.failed": "Couldn't add {{name}} to the channel. Try again.",
"mentionInvite.failedReason": "Couldn't add {{name}} to the channel: {{reason}}",
- "mentionInvite.section": "Not in this channel · mention to add",
+ "mentionInvite.section": "Not in this channel · mention to invite",
"message.collapse": "Collapse message",
"message.copied": "Copied",
"message.copy": "Copy text",
@@ -163,7 +186,7 @@
"profile.show": "Show Agent profile",
"profile.title": "Agent profile",
"profile.view": "View profile",
- "projectAgents": "Project members",
+ "projectAgents": "Project Agents",
"receipt.errorReason": "Failure reason",
"receipt.errorUnavailable": "No detailed reason was recorded. Check the Agent’s model and device settings before sending again.",
"receipt.failedHint": "Mention it again to retry.",
diff --git a/locales/en-US/project.json b/locales/en-US/project.json
index 9d6cb27708e..b3e62f240c1 100644
--- a/locales/en-US/project.json
+++ b/locales/en-US/project.json
@@ -203,7 +203,7 @@
"members.more": "More",
"members.noResponsibility": "No responsibility set yet",
"members.remove": "Remove from project",
- "members.removeConfirmDescription": "Its existing tasks and topics in this project stay as they are.",
+ "members.removeConfirmDescription": "Its existing tasks and topics in the project are not affected. It also leaves the project’s channels.",
"members.removeConfirmTitle": "Remove {{name}} from this project?",
"members.removeFailed": "Could not remove the agent",
"members.replaceCoordinator": "Change main agent",
diff --git a/locales/zh-CN/channel.json b/locales/zh-CN/channel.json
index 33f7cb564ac..54a2bc3d429 100644
--- a/locales/zh-CN/channel.json
+++ b/locales/zh-CN/channel.json
@@ -46,6 +46,7 @@
"composer": "发消息到 #{{name}}",
"composer.actions": "更多操作",
"composer.mention": "提及成员或 Agent",
+ "composerToJoin": "发消息即可加入 #{{name}}",
"conversationEmpty": "开始一起讨论吧",
"copyId": "复制 ID",
"copyIdSuccess": "已复制频道 ID",
@@ -111,25 +112,47 @@
"failure.title": "回复失败 · {{count}}",
"followers": "参与回复:{{names}}",
"invite.directHint": "邀请后会新建一个频道,包含 {{name}} 和你选择的成员;你和 {{name}} 的这个对话保持不变。",
+ "invite.joinProjectNotice": "{{names}} 会先加入项目「{{project}}」,再加入频道。",
+ "invite.joinProjectNoticeUnnamed": "{{names}} 会先加入这个项目,再加入频道。",
"invite.noAgentMatches": "没有匹配的 Agent",
"invite.noAgents": "可用的 Agent 都已加入",
"invite.noSelected": "还没有选择成员",
+ "invite.outsideProject": "其他 Agent · 选中后会一起加入项目",
+ "invite.outsideProjectLocked": "只有项目创建者或工作区管理员能把新的 Agent 加进这个项目",
"invite.people": "工作区成员",
"invite.search": "搜索成员和 Agent",
"invite.submit": "邀请",
"invite.title": "邀请成员",
"latestMessages": "最新消息",
+ "leave": "退出频道",
+ "leaveConfirm": "退出后你将看不到这个频道,除非有人再次邀请你。",
+ "leaveConfirmProject": "之后随时可以在项目里重新加入。",
+ "leaveConfirmTitle": "退出「{{title}}」?",
+ "leaveFailed": "退出频道失败,请重试",
+ "leaveSuccess": "已退出频道",
"main": "频道对话",
"memberActionsNamed": "{{name}} 的操作",
"members.agents": "Agent · {{count}}",
+ "member.remove": "移出频道",
+ "member.removeConfirmAgent": "它在这里正在进行的回复会停止。它仍在项目中,之后可以再邀请。",
+ "member.removeConfirmAgentStandalone": "它在这里正在进行的回复会停止,之后可以再邀请。",
+ "member.removeConfirmPerson": "对方将看不到这个频道,除非管理员再次邀请。",
+ "member.removeConfirmTitle": "将「{{name}}」移出频道?",
+ "member.removeFailed": "移出「{{name}}」失败,请重试",
+ "member.removeNamed": "将 {{name}} 移出频道",
"members.hide": "收起成员列表",
"members.show": "展开成员列表",
"membersCount": "成员 · {{count}}",
"membersTitle": "成员",
"mentionHint": "@ Agent 可指定谁来回复;不 @ 时,频道里的所有 Agent 都会回复。",
+ "mentionInvite.confirmAgent": "它加入后会读取这个频道,并在这里回复。",
+ "mentionInvite.confirmAgentProject": "它还不在项目「{{project}}」中,会先加入项目,再加入频道。",
+ "mentionInvite.confirmOk": "邀请并 @",
+ "mentionInvite.confirmPerson": "对方加入后能看到这个频道的全部消息。",
+ "mentionInvite.confirmTitle": "邀请「{{name}}」加入频道?",
"mentionInvite.failed": "未能将 {{name}} 加入频道,请重试。",
"mentionInvite.failedReason": "未能将 {{name}} 加入频道:{{reason}}",
- "mentionInvite.section": "不在频道中 · @ 后将加入",
+ "mentionInvite.section": "不在频道中 · @ 时会询问是否邀请",
"message.collapse": "收起消息",
"message.copied": "已复制",
"message.copy": "复制文本",
@@ -163,7 +186,7 @@
"profile.show": "展开 Agent 资料",
"profile.title": "Agent 资料",
"profile.view": "查看资料",
- "projectAgents": "项目成员",
+ "projectAgents": "项目 Agent",
"receipt.errorReason": "失败原因",
"receipt.errorUnavailable": "未记录具体原因,请检查 Agent 的模型与设备设置后重新发送。",
"receipt.failedHint": "再次 @ 它即可重试。",
diff --git a/locales/zh-CN/project.json b/locales/zh-CN/project.json
index 63a482941a4..46d420d1070 100644
--- a/locales/zh-CN/project.json
+++ b/locales/zh-CN/project.json
@@ -203,7 +203,7 @@
"members.more": "更多",
"members.noResponsibility": "还没有设置职责",
"members.remove": "移出项目",
- "members.removeConfirmDescription": "它在项目中已有的任务和话题不受影响。",
+ "members.removeConfirmDescription": "它在项目中已有的任务和话题不受影响,同时会退出项目里的频道。",
"members.removeConfirmTitle": "将「{{name}}」移出项目?",
"members.removeFailed": "移出 Agent 失败",
"members.replaceCoordinator": "更换主 Agent",
diff --git a/packages/database/src/models/__tests__/project.coverage.test.ts b/packages/database/src/models/__tests__/project.coverage.test.ts
index f5c4c6b29b6..379295d7a61 100644
--- a/packages/database/src/models/__tests__/project.coverage.test.ts
+++ b/packages/database/src/models/__tests__/project.coverage.test.ts
@@ -50,7 +50,7 @@ describe('ProjectModel coverage', () => {
),
);
- expect(await model.delete('t863-proj-race')).toBeNull();
+ expect(await repo.delete('t863-proj-race')).toBeNull();
});
});
@@ -145,6 +145,24 @@ describe('ProjectModel coverage', () => {
});
});
+ describe('hasAgent', () => {
+ it('counts the main agent and bound members of a readable project, nothing else', async () => {
+ const project = await repo.create({ name: 'Crew' });
+ await serverDB.insert(agents).values([
+ { id: 't863-proj-member', userId },
+ { id: 't863-proj-outsider', userId },
+ ]);
+ await model.addAgent(project.id, { agentId: 't863-proj-member' });
+ const stranger = new ProjectModel(serverDB, otherUserId);
+
+ expect(await model.hasAgent(project.id, project.coordinatorAgentId!)).toBe(true);
+ expect(await model.hasAgent(project.id, 't863-proj-member')).toBe(true);
+ expect(await model.hasAgent(project.id, 't863-proj-outsider')).toBe(false);
+ expect(await model.hasAgent('t863-proj-missing', 't863-proj-member')).toBe(false);
+ expect(await stranger.hasAgent(project.id, 't863-proj-member')).toBe(false);
+ });
+ });
+
describe('listTasks', () => {
it("lists a visible project's tasks", async () => {
const project = await repo.create({ name: 'With tasks' });
@@ -177,7 +195,7 @@ describe('ProjectModel coverage', () => {
name: 'Legacy project',
});
- await model.delete(project.id);
+ await repo.delete(project.id);
expect(await serverDB.select().from(agents).where(eq(agents.id, legacy.id))).toEqual([]);
});
@@ -190,7 +208,7 @@ describe('ProjectModel coverage', () => {
name: 'Picked project',
});
- await model.delete(project.id);
+ await repo.delete(project.id);
expect(await serverDB.select().from(agents).where(eq(agents.id, picked.id))).toHaveLength(1);
});
diff --git a/packages/database/src/models/__tests__/project.test.ts b/packages/database/src/models/__tests__/project.test.ts
index 7fe40a787cc..351471d358a 100644
--- a/packages/database/src/models/__tests__/project.test.ts
+++ b/packages/database/src/models/__tests__/project.test.ts
@@ -174,7 +174,7 @@ describe('ProjectModel', () => {
.set({ coordinatorAgentId: shared.id })
.where(eq(projects.userId, userId));
- await model.delete(first.id);
+ await repo.delete(first.id);
expect(await serverDB.select().from(agents).where(eq(agents.id, shared.id))).toHaveLength(1);
expect((await model.findById(second.id))?.coordinatorAgentId).toBe(shared.id);
@@ -188,7 +188,7 @@ describe('ProjectModel', () => {
.set({ coordinatorAgentId: inbox.id })
.where(eq(projects.id, project.id));
- expect(await model.delete(project.id)).toEqual(expect.objectContaining({ id: project.id }));
+ expect(await repo.delete(project.id)).toEqual(expect.objectContaining({ id: project.id }));
expect(await serverDB.select().from(agents).where(eq(agents.id, inbox.id))).toHaveLength(1);
});
@@ -209,7 +209,7 @@ describe('ProjectModel', () => {
expect(await model.resolveCoordinatorAgents([cleared])).toEqual([
expect.objectContaining({ coordinatorAgentId: inbox?.id, id: project.id }),
]);
- expect(await model.delete(project.id)).toEqual(expect.objectContaining({ id: project.id }));
+ expect(await repo.delete(project.id)).toEqual(expect.objectContaining({ id: project.id }));
});
it('tells whether replacing a main agent retires it', async () => {
@@ -273,7 +273,7 @@ describe('ProjectModel', () => {
.where(eq(projectAgents.projectId, project.id)),
).toEqual([{ role: 'coordinator' }]);
- await model.delete(project.id);
+ await repo.delete(project.id);
expect(await serverDB.select().from(agents).where(eq(agents.id, picked.id))).toHaveLength(1);
});
@@ -320,7 +320,7 @@ describe('ProjectModel', () => {
const updated = await model.update(project.id, { name: 'Apollo 2' });
expect(updated?.name).toBe('Apollo 2');
- expect(await model.delete(project.id)).toEqual(expect.objectContaining({ id: project.id }));
+ expect(await repo.delete(project.id)).toEqual(expect.objectContaining({ id: project.id }));
expect(await model.findById(project.id)).toBeNull();
// The main agent is an ordinary agent and stays with the user.
expect(
@@ -435,7 +435,7 @@ describe('ProjectModel', () => {
const project = await createProject(otherRepo, { name: 'Private effort' });
expect(await model.findById(project.id)).toBeNull();
expect(await model.update(project.id, { name: 'Hacked' })).toBeNull();
- expect(await model.delete(project.id)).toBeNull();
+ expect(await repo.delete(project.id)).toBeNull();
expect(await model.findManageableById(project.id)).toBeNull();
});
@@ -876,12 +876,12 @@ describe('ProjectModel', () => {
await model.updateStatus(project.id, 'active');
await model.requestCompletion(project.id);
- const rejected = await model.reviewCompletion(project.id, 'rejected', 'Needs evidence');
+ const rejected = await repo.reviewCompletion(project.id, 'rejected', 'Needs evidence');
expect(rejected?.project.status).toBe('active');
expect(rejected?.review.round).toBe(1);
await model.requestCompletion(project.id);
- const accepted = await model.reviewCompletion(project.id, 'accepted', 'Approved');
+ const accepted = await repo.reviewCompletion(project.id, 'accepted', 'Approved');
expect(accepted?.project.status).toBe('completed');
expect(accepted?.project.completedReviewId).toBe(accepted?.review.id);
expect(accepted?.review.round).toBe(2);
@@ -910,7 +910,7 @@ describe('ProjectModel', () => {
const project = await createProject(repo, { name: 'Archived completion' });
await model.updateStatus(project.id, 'active');
await model.requestCompletion(project.id);
- await model.reviewCompletion(project.id, 'accepted');
+ await repo.reviewCompletion(project.id, 'accepted');
await model.updateStatus(project.id, 'archived');
await expect(model.updateStatus(project.id, 'active')).rejects.toThrow(
@@ -939,11 +939,11 @@ describe('ProjectModel', () => {
await expect(model.updateStatus(project.id, 'paused')).rejects.toThrow(
'A project awaiting review must be accepted or rejected',
);
- await expect(model.reviewCompletion('missing', 'accepted')).resolves.toBeNull();
- await expect(model.reviewCompletion(project.id, 'rejected')).resolves.toEqual(
+ await expect(repo.reviewCompletion('missing', 'accepted')).resolves.toBeNull();
+ await expect(repo.reviewCompletion(project.id, 'rejected')).resolves.toEqual(
expect.objectContaining({ project: expect.objectContaining({ status: 'active' }) }),
);
- await expect(model.reviewCompletion(project.id, 'accepted')).rejects.toThrow(
+ await expect(repo.reviewCompletion(project.id, 'accepted')).rejects.toThrow(
'Project is not awaiting review',
);
expect(await model.reopen(project.id)).toBeNull();
@@ -953,7 +953,7 @@ describe('ProjectModel', () => {
const completed = await createProject(repo, { name: 'Completed' });
await model.updateStatus(completed.id, 'active');
await model.requestCompletion(completed.id);
- await model.reviewCompletion(completed.id, 'accepted');
+ await repo.reviewCompletion(completed.id, 'accepted');
await expect(model.updateStatus(completed.id, 'active')).rejects.toThrow(
'A completed project must be reopened',
);
diff --git a/packages/database/src/models/project/agents.ts b/packages/database/src/models/project/agents.ts
new file mode 100644
index 00000000000..eaa91c96fc5
--- /dev/null
+++ b/packages/database/src/models/project/agents.ts
@@ -0,0 +1,109 @@
+import { and, eq } from 'drizzle-orm';
+
+import { projectAgents } from '../../schemas/project';
+import type { LobeChatDatabase } from '../../type';
+
+export interface ProjectAgentInput {
+ agentId: string;
+ enabled?: boolean;
+ responsibility?: string | null;
+ role?: string | null;
+ sortOrder?: number;
+}
+
+export type ProjectAgentPatch = Partial<Omit<ProjectAgentInput, 'agentId'>>;
+
+/** Who adds a binding and the scope it lives in; the caller has already checked the project. */
+interface BindingScope {
+ addedByUserId: string;
+ projectId: string;
+ workspaceId: string | null;
+}
+
+const bindingOf = (projectId: string, agentId: string) =>
+ and(eq(projectAgents.projectId, projectId), eq(projectAgents.agentId, agentId));
+
+export const hasProjectAgentBinding = async (
+ db: LobeChatDatabase,
+ projectId: string,
+ agentId: string,
+) => {
+ const [binding] = await db
+ .select({ id: projectAgents.id })
+ .from(projectAgents)
+ .where(bindingOf(projectId, agentId))
+ .limit(1);
+ return !!binding;
+};
+
+/** Binds an Agent to a project, or updates its existing binding in place. */
+export const upsertProjectAgent = async (
+ db: LobeChatDatabase,
+ scope: BindingScope,
+ input: ProjectAgentInput,
+) => {
+ const [binding] = await db
+ .insert(projectAgents)
+ .values({ ...input, ...scope })
+ .onConflictDoUpdate({
+ set: {
+ enabled: input.enabled,
+ responsibility: input.responsibility,
+ role: input.role,
+ sortOrder: input.sortOrder,
+ updatedAt: new Date(),
+ },
+ target: [projectAgents.projectId, projectAgents.agentId],
+ })
+ .returning();
+ return binding;
+};
+
+export const updateProjectAgent = async (
+ db: LobeChatDatabase,
+ projectId: string,
+ agentId: string,
+ patch: ProjectAgentPatch,
+) => {
+ const [binding] = await db
+ .update(projectAgents)
+ .set({ ...patch, updatedAt: new Date() })
+ .where(bindingOf(projectId, agentId))
+ .returning();
+ return binding ?? null;
+};
+
+export const deleteProjectAgent = async (
+ db: LobeChatDatabase,
+ projectId: string,
+ agentId: string,
+) => {
+ const deleted = await db
+ .delete(projectAgents)
+ .where(bindingOf(projectId, agentId))
+ .returning({ id: projectAgents.id });
+ return deleted.length > 0;
+};
+
+/**
+ * Seats a new main agent as an enabled member. The project role belonged to the main agent, so
+ * the predecessor stays on as a member that reads like any other.
+ */
+export const seatCoordinator = async (
+ db: LobeChatDatabase,
+ scope: BindingScope & { agentId: string; previousId: string | null },
+) => {
+ const { agentId, previousId, ...binding } = scope;
+ await db
+ .insert(projectAgents)
+ .values({ ...binding, agentId })
+ .onConflictDoUpdate({
+ set: { enabled: true, updatedAt: new Date() },
+ target: [projectAgents.projectId, projectAgents.agentId],
+ });
+ if (!previousId) return;
+ await db
+ .update(projectAgents)
+ .set({ role: null, updatedAt: new Date() })
+ .where(and(bindingOf(binding.projectId, previousId), eq(projectAgents.role, 'coordinator')));
+};
diff --git a/packages/database/src/models/project.ts b/packages/database/src/models/project/index.ts
similarity index 85%
rename from packages/database/src/models/project.ts
rename to packages/database/src/models/project/index.ts
index 7b0a493295e..21c49ccfd9e 100644
--- a/packages/database/src/models/project.ts
+++ b/packages/database/src/models/project/index.ts
@@ -1,45 +1,54 @@
import { BUILTIN_AGENT_SLUGS } 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, ne, or, sql } from 'drizzle-orm';
+import { and, asc, desc, eq, inArray, isNull, ne, or, sql } from 'drizzle-orm';
-import { agents } from '../schemas/agent';
-import { channelMembers } from '../schemas/channel';
-import { chatGroupsAgents } from '../schemas/chatGroup';
-import { environments } from '../schemas/environment';
-import { knowledgeBases } from '../schemas/file';
+import { agents } from '../../schemas/agent';
+import { channelMembers } from '../../schemas/channel';
+import { chatGroupsAgents } from '../../schemas/chatGroup';
+import { environments } from '../../schemas/environment';
+import { knowledgeBases } from '../../schemas/file';
import {
projectAgents,
projectCompletionReviews,
projectKnowledgeBases,
projects,
-} 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';
-import type { LobeChatDatabase } from '../type';
-import { isUserKnowledgeBase } from '../utils/knowledgeBaseType';
-import { joinTopicAgentsToProjects } from '../utils/projectTopicAgents';
-import { topicRunStartedAtColumn } from '../utils/topicRunStartedAt';
-import { notChannelTopic } from '../utils/topicVisibility';
+} 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';
+import type { LobeChatDatabase } from '../../type';
+import { isUserKnowledgeBase } from '../../utils/knowledgeBaseType';
+import { joinTopicAgentsToProjects } from '../../utils/projectTopicAgents';
+import { topicRunStartedAtColumn } from '../../utils/topicRunStartedAt';
+import { notChannelTopic } from '../../utils/topicVisibility';
import {
buildWorkspacePayload,
buildWorkspaceWhere,
normalizeWorkspaceId,
-} from '../utils/workspace';
-import { AgentModel } from './agent';
-import { EnvironmentModel } from './environment';
+} from '../../utils/workspace';
+import { AgentModel } from '../agent';
+import { EnvironmentModel } from '../environment';
import {
isProjectIdentifierConflict,
normalizeProjectIdentifier,
ProjectIdentifierTakenError,
-} from './projectIdentifier';
-import { topicHasGoal } from './topicGoal';
+} from '../projectIdentifier';
+import { topicHasGoal } from '../topicGoal';
+import type { ProjectAgentInput, ProjectAgentPatch } from './agents';
+import {
+ deleteProjectAgent,
+ hasProjectAgentBinding,
+ seatCoordinator,
+ updateProjectAgent,
+ upsertProjectAgent,
+} from './agents';
-export { normalizeProjectIdentifier, ProjectIdentifierTakenError } from './projectIdentifier';
+export { normalizeProjectIdentifier, ProjectIdentifierTakenError } from '../projectIdentifier';
+export type { ProjectAgentInput, ProjectAgentPatch } from './agents';
export interface CreateProjectInput {
avatar?: string;
@@ -81,16 +90,6 @@ export interface UpdateProjectInput {
visibility?: ProjectVisibility;
}
-export interface ProjectAgentInput {
- agentId: string;
- enabled?: boolean;
- responsibility?: string | null;
- role?: string | null;
- sortOrder?: number;
-}
-
-export type ProjectAgentPatch = Partial<Omit<ProjectAgentInput, 'agentId'>>;
-
export interface ProjectKnowledgeBaseInput {
enabled?: boolean;
knowledgeBaseId: string;
@@ -246,34 +245,16 @@ export class ProjectModel {
}
}
- async delete(id: string) {
- return this.db.transaction(async (tx) => {
- const [project] = await tx
- .select({ coordinatorAgentId: projects.coordinatorAgentId })
- .from(projects)
- .where(and(eq(projects.id, id), this.manageable()))
- .limit(1);
- if (!project) return null;
-
- const [deleted] = await tx
- .delete(projects)
- .where(and(eq(projects.id, id), this.manageable()))
- .returning();
- if (project.coordinatorAgentId) {
- await this.deleteDedicatedCoordinator(tx as LobeChatDatabase, project.coordinatorAgentId);
- }
- return deleted ?? null;
- });
- }
-
/**
- * Remove a coordinator only when it was provisioned for this project: a
- * virtual, non-builtin agent no other project still uses. Reusable agents
- * (user agents, LobeAI) stay with their sessions intact.
+ * Deletes the project row only. `ProjectRepository.delete` also retires a
+ * coordinator provisioned for it, which belongs to another aggregate.
*/
- private async deleteDedicatedCoordinator(db: LobeChatDatabase, agentId: string) {
- if (!(await this.isDedicatedCoordinator(agentId, { db }))) return;
- await new AgentModel(db, this.userId, this.workspaceId).delete(agentId);
+ async delete(id: string) {
+ const [deleted] = await this.db
+ .delete(projects)
+ .where(and(eq(projects.id, id), this.manageable()))
+ .returning();
+ return deleted ?? null;
}
/**
@@ -611,6 +592,14 @@ export class ProjectModel {
return agent ?? null;
}
+ /** Whether an Agent belongs to a readable project: its main Agent or a bound member. */
+ async hasAgent(projectId: string, agentId: string) {
+ const project = await this.findById(projectId);
+ if (!project) return false;
+ if (project.coordinatorAgentId === agentId) return true;
+ return hasProjectAgentBinding(this.db, projectId, agentId);
+ }
+
async addAgent(projectId: string, input: ProjectAgentInput) {
const project = await this.findMembersManageableById(projectId);
if (!project) return null;
@@ -625,26 +614,11 @@ export class ProjectModel {
'A shared project only takes shared agents',
);
- const [binding] = await this.db
- .insert(projectAgents)
- .values({
- ...input,
- addedByUserId: this.userId,
- projectId,
- workspaceId: this.workspaceId ?? null,
- })
- .onConflictDoUpdate({
- set: {
- enabled: input.enabled,
- responsibility: input.responsibility,
- role: input.role,
- sortOrder: input.sortOrder,
- updatedAt: new Date(),
- },
- target: [projectAgents.projectId, projectAgents.agentId],
- })
- .returning();
- return binding;
+ return upsertProjectAgent(this.db, this.bindingScope(projectId), input);
+ }
+
+ private bindingScope(projectId: string) {
+ return { addedByUserId: this.userId, projectId, workspaceId: this.workspaceId ?? null };
}
async updateAgent(projectId: string, agentId: string, patch: ProjectAgentPatch) {
@@ -653,12 +627,7 @@ export class ProjectModel {
if (project.coordinatorAgentId === agentId) {
throw new Error('The project coordinator is managed by the project');
}
- const [binding] = await this.db
- .update(projectAgents)
- .set({ ...patch, updatedAt: new Date() })
- .where(and(eq(projectAgents.projectId, projectId), eq(projectAgents.agentId, agentId)))
- .returning();
- return binding ?? null;
+ return updateProjectAgent(this.db, projectId, agentId, patch);
}
async removeAgent(projectId: string, agentId: string) {
@@ -667,11 +636,7 @@ export class ProjectModel {
if (project.coordinatorAgentId === agentId) {
throw new Error('The project coordinator cannot be removed');
}
- const deleted = await this.db
- .delete(projectAgents)
- .where(and(eq(projectAgents.projectId, projectId), eq(projectAgents.agentId, agentId)))
- .returning({ id: projectAgents.id });
- return deleted.length > 0;
+ return deleteProjectAgent(this.db, projectId, agentId);
}
/**
@@ -690,16 +655,7 @@ export class ProjectModel {
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);
+ const agent = await this.findAccessibleAgent(this.db, agentId);
if (!agent) throw new Error('Agent not found');
this.assertSharedResource(
project,
@@ -712,33 +668,8 @@ export class ProjectModel {
.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'),
- ),
- );
- }
+ await seatCoordinator(this.db, { ...this.bindingScope(projectId), agentId, previousId });
return { previousId, project: updated };
}
@@ -967,49 +898,23 @@ export class ProjectModel {
return this.setStatus(id, 'reviewing', project.startedAt);
}
- async reviewCompletion(id: string, decision: 'accepted' | 'rejected', comment?: string) {
- return this.db.transaction(async (tx) => {
- const [project] = await tx
- .select()
- .from(projects)
- .where(and(eq(projects.id, id), this.manageable()))
- .for('update')
- .limit(1);
- if (!project) return null;
- if (project.status !== 'reviewing') throw new Error('Project is not awaiting review');
-
- const [{ value: lastRound }] = await tx
- .select({ value: max(projectCompletionReviews.round) })
- .from(projectCompletionReviews)
- .where(eq(projectCompletionReviews.projectId, id));
- const [review] = await tx
- .insert(projectCompletionReviews)
- .values({
- comment,
- decision,
- projectId: id,
- reviewerUserId: this.userId,
- round: (lastRound ?? 0) + 1,
- workspaceId: this.workspaceId ?? null,
- })
- .returning();
- const now = new Date();
- const [updated] = await tx
- .update(projects)
- .set(
- decision === 'accepted'
- ? {
- completedAt: now,
- completedReviewId: review.id,
- status: 'completed',
- updatedAt: now,
- }
- : { completedAt: null, completedReviewId: null, status: 'active', updatedAt: now },
- )
- .where(eq(projects.id, id))
- .returning();
- return { project: updated, review };
- });
+ /**
+ * Settles a completion review on the project row: an accepted review completes
+ * it, a rejected one sends it back to active. `ProjectRepository.reviewCompletion`
+ * locks the row and records the review in the same transaction.
+ */
+ async applyCompletionReview(id: string, decision: 'accepted' | 'rejected', reviewId: string) {
+ const now = new Date();
+ const [updated] = await this.db
+ .update(projects)
+ .set(
+ decision === 'accepted'
+ ? { completedAt: now, completedReviewId: reviewId, status: 'completed', updatedAt: now }
+ : { completedAt: null, completedReviewId: null, status: 'active', updatedAt: now },
+ )
+ .where(eq(projects.id, id))
+ .returning();
+ return updated;
}
async listCompletionReviews(projectId: string) {
@@ -1037,12 +942,13 @@ export class ProjectModel {
return project ?? null;
}
- async findManageableById(id: string) {
- const [project] = await this.db
+ async findManageableById(id: string, { lock = false }: { lock?: boolean } = {}) {
+ const query = this.db
.select()
.from(projects)
.where(and(eq(projects.id, id), this.manageable()))
.limit(1);
+ const [project] = lock ? await query.for('update') : await query;
return project ?? null;
}
diff --git a/packages/database/src/repositories/channel/__tests__/membership.test.ts b/packages/database/src/repositories/channel/__tests__/membership.test.ts
new file mode 100644
index 00000000000..a220bd4cf98
--- /dev/null
+++ b/packages/database/src/repositories/channel/__tests__/membership.test.ts
@@ -0,0 +1,183 @@
+// @vitest-environment node
+import { and, eq } from 'drizzle-orm';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+
+import { getTestDB } from '../../../core/getTestDB';
+import {
+ agents,
+ channelAudit,
+ channelJobs,
+ channelMembers,
+ projects,
+ workspaceMembers,
+} from '../../../schemas';
+import { ChannelRepository, removeAgentFromProjectChannels } from '..';
+import { createChannelFixture } from './testUtils';
+
+const db = await getTestDB();
+const fixture = createChannelFixture(db, 'channel-membership');
+beforeEach(async () => {
+ await fixture.setup();
+ await db.insert(workspaceMembers).values([
+ { workspaceId: fixture.workspaceId, userId: fixture.ownerId, role: 'owner' },
+ { workspaceId: fixture.workspaceId, userId: fixture.memberId },
+ ]);
+});
+afterEach(async () => {
+ await db.delete(projects).where(eq(projects.workspaceId, fixture.workspaceId));
+ await fixture.cleanup();
+});
+
+const statusOf = async (memberId: string) => {
+ const [row] = await db
+ .select({ status: channelMembers.status })
+ .from(channelMembers)
+ .where(eq(channelMembers.id, memberId));
+ return row?.status;
+};
+
+describe('removing Channel members', () => {
+ it('lets an admin remove a person, who then loses access', async () => {
+ const { asMember, asOwner, channel, member } = await fixture.createTeamChannel();
+ await asOwner.removeMember(channel.id, member.id);
+
+ expect(await statusOf(member.id)).toBe('removed');
+ expect(await asMember.findAccess(channel.id)).toBeUndefined();
+ expect(await asMember.list()).toEqual([]);
+ const [entry] = await db
+ .select()
+ .from(channelAudit)
+ .where(and(eq(channelAudit.channelId, channel.id), eq(channelAudit.event, 'member_removed')));
+ expect(entry).toMatchObject({ targetId: member.id, details: { actorType: 'user' } });
+ });
+
+ it('removes an Agent and cancels its open replies', async () => {
+ const { asOwner, channel } = await fixture.createTeamChannel();
+ const agent = await fixture.addAgent(channel.id, 'Helper');
+ const message = await asOwner.send(channel.id, {
+ content: 'Please help',
+ mentions: [agent.id],
+ requestKey: 'help',
+ });
+ const [queued] = await db
+ .select()
+ .from(channelJobs)
+ .where(eq(channelJobs.messageId, message.id));
+ expect(queued.status).toBe('queued');
+
+ await asOwner.removeMember(channel.id, agent.id);
+
+ expect(await statusOf(agent.id)).toBe('removed');
+ const [job] = await db.select().from(channelJobs).where(eq(channelJobs.id, queued.id));
+ expect(job.status).not.toBe('queued');
+ });
+
+ it('keeps the owner and the caller, and leaves other admins to the owner', async () => {
+ const { asMember, asOwner, channel, member, owner } = await fixture.createTeamChannel();
+ await expect(asOwner.removeMember(channel.id, owner.id)).rejects.toMatchObject({
+ code: 'BAD_REQUEST',
+ });
+ await expect(asMember.removeMember(channel.id, owner.id)).rejects.toMatchObject({
+ code: 'FORBIDDEN',
+ });
+
+ await db.update(channelMembers).set({ role: 'admin' }).where(eq(channelMembers.id, member.id));
+ await expect(asMember.removeMember(channel.id, owner.id)).rejects.toMatchObject({
+ code: 'FORBIDDEN',
+ });
+ await asOwner.removeMember(channel.id, member.id);
+ expect(await statusOf(member.id)).toBe('removed');
+ });
+
+ it('refuses a direct conversation, which keeps its two sides', async () => {
+ const [agent] = await db
+ .insert(agents)
+ .values({ userId: fixture.ownerId, workspaceId: fixture.workspaceId })
+ .returning();
+ const owner = new ChannelRepository(db, fixture.ownerId, fixture.workspaceId);
+ const { channel } = await owner.create({ agentId: agent.id, title: 'Direct' });
+ const [seat] = await db
+ .select()
+ .from(channelMembers)
+ .where(and(eq(channelMembers.channelId, channel.id), eq(channelMembers.actorType, 'agent')));
+
+ await expect(owner.removeMember(channel.id, seat.id)).rejects.toMatchObject({
+ code: 'BAD_REQUEST',
+ });
+ });
+});
+
+describe('leaving a Channel', () => {
+ it('lets a member leave and keeps the owner', async () => {
+ const { asMember, asOwner, channel, member } = await fixture.createTeamChannel();
+ expect(await asMember.leave(channel.id)).toEqual({ readable: false });
+
+ expect(await statusOf(member.id)).toBe('left');
+ expect(await asMember.list()).toEqual([]);
+ await expect(asOwner.leave(channel.id)).rejects.toMatchObject({ code: 'CONFLICT' });
+ });
+
+ it('lists the caller’s own role', async () => {
+ const { asMember, asOwner } = await fixture.createTeamChannel();
+ expect((await asOwner.list())[0].memberRole).toBe('owner');
+ expect((await asMember.list())[0].memberRole).toBe('member');
+ });
+
+ it('lets someone who left an open project Channel join again, but not someone removed', async () => {
+ const [project] = await db
+ .insert(projects)
+ .values({ name: 'Apollo', userId: fixture.ownerId, workspaceId: fixture.workspaceId })
+ .returning();
+ const owner = new ChannelRepository(db, fixture.ownerId, fixture.workspaceId);
+ const teammate = new ChannelRepository(db, fixture.memberId, fixture.workspaceId);
+ const { channel } = await owner.create({ projectId: project.id, title: 'General' });
+
+ const joined = await teammate.join(channel.id);
+ expect(await teammate.leave(channel.id)).toEqual({ readable: true });
+ expect(await teammate.list()).toEqual([
+ expect.objectContaining({ id: channel.id, joined: false, memberRole: null }),
+ ]);
+ await teammate.join(channel.id);
+ expect(await statusOf(joined.member.id)).toBe('active');
+
+ await owner.removeMember(channel.id, joined.member.id);
+ await expect(teammate.join(channel.id)).rejects.toMatchObject({ code: 'NOT_FOUND' });
+ });
+
+ it('reports an archived project Channel as no longer readable once left', async () => {
+ const [project] = await db
+ .insert(projects)
+ .values({ name: 'Apollo', userId: fixture.ownerId, workspaceId: fixture.workspaceId })
+ .returning();
+ const owner = new ChannelRepository(db, fixture.ownerId, fixture.workspaceId);
+ const teammate = new ChannelRepository(db, fixture.memberId, fixture.workspaceId);
+ const { channel } = await owner.create({ projectId: project.id, title: 'General' });
+ await teammate.join(channel.id);
+ await owner.archive(channel.id);
+
+ expect(await teammate.leave(channel.id)).toEqual({ readable: false });
+ });
+});
+
+describe('an Agent leaving a project', () => {
+ it('leaves every Channel of that project and no other', async () => {
+ const [project] = await db
+ .insert(projects)
+ .values({ name: 'Apollo', userId: fixture.ownerId, workspaceId: fixture.workspaceId })
+ .returning();
+ const owner = new ChannelRepository(db, fixture.ownerId, fixture.workspaceId);
+ const { channel: general } = await owner.create({ projectId: project.id, title: 'General' });
+ const { channel: design } = await owner.create({ projectId: project.id, title: 'Design' });
+ const { channel: outside } = await owner.create({ title: 'Outside' });
+ const seat = await fixture.addAgent(general.id, 'Helper');
+ const second = await owner.addAgent(design.id, { agentId: seat.agentId! });
+ const kept = await owner.addAgent(outside.id, { agentId: seat.agentId! });
+
+ const { channelIds } = await removeAgentFromProjectChannels(db, project.id, seat.agentId!);
+
+ expect(channelIds.sort()).toEqual([general.id, design.id].sort());
+ expect(await statusOf(seat.id)).toBe('removed');
+ expect(await statusOf(second.id)).toBe('removed');
+ expect(await statusOf(kept.id)).toBe('active');
+ });
+});
diff --git a/packages/database/src/repositories/channel/__tests__/projectAccess.test.ts b/packages/database/src/repositories/channel/__tests__/projectAccess.test.ts
new file mode 100644
index 00000000000..5397eecfaa0
--- /dev/null
+++ b/packages/database/src/repositories/channel/__tests__/projectAccess.test.ts
@@ -0,0 +1,199 @@
+// @vitest-environment node
+import { and, eq } from 'drizzle-orm';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+
+import { getTestDB } from '../../../core/getTestDB';
+import { channelMembers, projects, workspaceMembers } from '../../../schemas';
+import { ChannelExecutionRepository, ChannelRepository } from '..';
+import { createChannelFixture, jobsOf, lease } from './testUtils';
+
+const db = await getTestDB();
+const fixture = createChannelFixture(db, 'channel-project-access');
+beforeEach(async () => {
+ await fixture.setup();
+ await db.insert(workspaceMembers).values([
+ { workspaceId: fixture.workspaceId, userId: fixture.ownerId, role: 'owner' },
+ { workspaceId: fixture.workspaceId, userId: fixture.memberId },
+ ]);
+});
+afterEach(async () => {
+ await db.delete(projects).where(eq(projects.workspaceId, fixture.workspaceId));
+ await fixture.cleanup();
+});
+
+/** A project of the owner's with one Channel and one message, which the teammate did not join. */
+const projectChannel = async (visibility: 'private' | 'public' = 'public') => {
+ const [project] = await db
+ .insert(projects)
+ .values({
+ name: 'Apollo',
+ userId: fixture.ownerId,
+ visibility,
+ workspaceId: fixture.workspaceId,
+ })
+ .returning();
+ const owner = new ChannelRepository(db, fixture.ownerId, fixture.workspaceId);
+ const { channel } = await owner.create({ projectId: project.id, title: 'General' });
+ await owner.send(channel.id, { content: 'Kickoff', requestKey: 'kickoff', routing: 'fallback' });
+ const teammate = new ChannelRepository(db, fixture.memberId, fixture.workspaceId);
+ return { channel, owner, project, teammate };
+};
+
+const membershipOf = (channelId: string) =>
+ db
+ .select()
+ .from(channelMembers)
+ .where(
+ and(eq(channelMembers.channelId, channelId), eq(channelMembers.userId, fixture.memberId)),
+ );
+
+describe('open project Channels', () => {
+ it("lists a readable project's Channels to a teammate as not joined, with nothing unread", async () => {
+ const { channel, teammate } = await projectChannel();
+
+ expect(await teammate.list()).toEqual([
+ expect.objectContaining({
+ canDelete: false,
+ id: channel.id,
+ joined: false,
+ lastMessage: expect.objectContaining({ content: 'Kickoff' }),
+ unreadCount: 0,
+ }),
+ ]);
+ });
+
+ it('lets a teammate read without joining, with no member actions', async () => {
+ const { channel, teammate } = await projectChannel();
+
+ const detail = await teammate.detail(channel.id);
+
+ expect(detail).toMatchObject({ channel: { canDelete: false }, joined: false });
+ expect(detail.messages.map((message) => message.content)).toEqual(['Kickoff']);
+ expect(await membershipOf(channel.id)).toEqual([]);
+ await expect(teammate.markRead(channel.id, 1)).rejects.toMatchObject({ code: 'NOT_FOUND' });
+ await expect(teammate.rename(channel.id, 'Mine')).rejects.toMatchObject({
+ code: 'NOT_FOUND',
+ });
+ });
+
+ it("keeps another person's reply topic out of what a teammate reads without joining", async () => {
+ const { channel, owner, teammate } = await projectChannel();
+ const agent = await fixture.addAgent(channel.id, 'Researcher');
+ const request = await owner.send(channel.id, {
+ content: 'Look into it',
+ mentions: [agent.id],
+ requestKey: 'look',
+ routing: 'fallback',
+ });
+ const [job] = await jobsOf(db, request.id);
+ await new ChannelExecutionRepository(db).claim(channel.id, job.id, lease);
+
+ const { jobs } = await teammate.detail(channel.id);
+
+ expect(jobs).toEqual([expect.objectContaining({ canStop: false, id: job.id })]);
+ expect(jobs[0]).not.toHaveProperty('topicId');
+ expect(jobs[0]).not.toHaveProperty('topicOwnerId');
+ });
+
+ it('joins a teammate on their first message, starting from what they already saw', async () => {
+ const { channel, owner, teammate } = await projectChannel();
+
+ await teammate.send(channel.id, { content: 'Hi', requestKey: 'hi', routing: 'fallback' });
+
+ expect(await membershipOf(channel.id)).toEqual([
+ expect.objectContaining({ lastReadSequence: 1, role: 'member', status: 'active' }),
+ ]);
+ expect(await teammate.list()).toEqual([
+ expect.objectContaining({ id: channel.id, joined: true, unreadCount: 1 }),
+ ]);
+ expect((await teammate.detail(channel.id)).joined).toBe(true);
+ expect((await owner.detail(channel.id)).messages.map((message) => message.content)).toEqual([
+ 'Kickoff',
+ 'Hi',
+ ]);
+ });
+
+ it('joins explicitly, once', async () => {
+ const { channel, teammate } = await projectChannel();
+
+ const first = await teammate.join(channel.id);
+ const again = await teammate.join(channel.id);
+
+ expect(again.member.id).toBe(first.member.id);
+ expect(await membershipOf(channel.id)).toHaveLength(1);
+ });
+
+ it("keeps a private project's Channels with their members", async () => {
+ const { channel, teammate } = await projectChannel('private');
+
+ expect(await teammate.list()).toEqual([]);
+ await expect(teammate.detail(channel.id)).rejects.toMatchObject({ code: 'NOT_FOUND' });
+ await expect(
+ teammate.send(channel.id, { content: 'Hi', requestKey: 'hi', routing: 'fallback' }),
+ ).rejects.toMatchObject({ code: 'NOT_FOUND' });
+ });
+
+ it('stays closed to people outside the workspace, other scopes and removed members', async () => {
+ const { channel, teammate } = await projectChannel();
+
+ // Personal scope sees no workspace Channel.
+ const personal = new ChannelRepository(db, fixture.memberId);
+ expect(await personal.list()).toEqual([]);
+ await expect(personal.join(channel.id)).rejects.toMatchObject({ code: 'NOT_FOUND' });
+
+ // Removed by an admin: neither listed nor readable, and cannot rejoin.
+ await db.insert(channelMembers).values({
+ actorType: 'user',
+ channelId: channel.id,
+ role: 'member',
+ status: 'removed',
+ userId: fixture.memberId,
+ });
+ expect(await teammate.list()).toEqual([]);
+ await expect(teammate.detail(channel.id)).rejects.toMatchObject({ code: 'NOT_FOUND' });
+ await expect(teammate.join(channel.id)).rejects.toMatchObject({ code: 'NOT_FOUND' });
+ });
+
+ it('closes the Channels to someone who left the workspace, or never belonged', async () => {
+ const { channel, teammate } = await projectChannel();
+ await db
+ .update(workspaceMembers)
+ .set({ deletedAt: new Date() })
+ .where(
+ and(
+ eq(workspaceMembers.workspaceId, fixture.workspaceId),
+ eq(workspaceMembers.userId, fixture.memberId),
+ ),
+ );
+
+ expect(await teammate.list()).toEqual([]);
+ await expect(teammate.detail(channel.id)).rejects.toMatchObject({ code: 'NOT_FOUND' });
+ await expect(teammate.join(channel.id)).rejects.toMatchObject({ code: 'NOT_FOUND' });
+ expect(await membershipOf(channel.id)).toEqual([]);
+
+ // An outsider naming the workspace gets nothing either.
+ const outsider = new ChannelRepository(
+ db,
+ 'channel-project-access-outsider',
+ fixture.workspaceId,
+ );
+ expect(await outsider.list()).toEqual([]);
+ await expect(outsider.detail(channel.id)).rejects.toMatchObject({ code: 'NOT_FOUND' });
+ });
+
+ it('opens neither archived nor trashed Channels to newcomers', async () => {
+ const { channel, owner, teammate } = await projectChannel();
+ await owner.archive(channel.id);
+
+ expect(await teammate.list()).toEqual([]);
+ await expect(teammate.detail(channel.id)).rejects.toMatchObject({ code: 'NOT_FOUND' });
+ await expect(teammate.join(channel.id)).rejects.toMatchObject({ code: 'NOT_FOUND' });
+ // Its members still read it.
+ expect((await owner.detail(channel.id)).joined).toBe(true);
+
+ await owner.unarchive(channel.id);
+ await owner.remove(channel.id);
+ expect(await teammate.list()).toEqual([]);
+ await expect(teammate.detail(channel.id)).rejects.toMatchObject({ code: 'NOT_FOUND' });
+ });
+});
diff --git a/packages/database/src/repositories/channel/index.ts b/packages/database/src/repositories/channel/index.ts
index 08e3ae57928..e0fb9af5ce0 100644
--- a/packages/database/src/repositories/channel/index.ts
+++ b/packages/database/src/repositories/channel/index.ts
@@ -7,7 +7,7 @@ import type {
ChannelVisibility,
} from '@lobechat/types';
import { agentDisplayName } from '@lobechat/types';
-import { and, desc, eq, inArray, isNotNull, isNull, notExists, or, sql } from 'drizzle-orm';
+import { and, desc, eq, inArray, isNotNull, isNull, or, sql } from 'drizzle-orm';
import { TrashModel } from '../../models/trash';
import type { ChannelItem, ChannelJobItem, ChannelMessageItem } from '../../schemas';
@@ -22,7 +22,6 @@ import {
workspaceMembers,
} from '../../schemas';
import type { LobeChatDatabase, Transaction } from '../../type';
-import { ilikeContains } from '../../utils/like';
import { notTrashed, trashStamp } from '../../utils/softDelete';
import { normalizeWorkspaceId } from '../../utils/workspace';
import type { ChannelAddAgentInput } from './agent';
@@ -38,16 +37,19 @@ import { findThread } from './delivery';
import { editMessage } from './edit';
import { ChannelError } from './error';
import { channelLastMessages } from './lastMessage';
+import { leaveChannel, removeChannelMember } from './membership';
import { setMemberMuted } from './mute';
import { findPeer, lockPeerPair, peerOf, requirePeerRelation } from './peer';
-import {
- addChannelUser,
- channelUserCandidates,
- newChannelUserCandidates,
- requireWorkspaceMember,
-} from './people';
+import { addChannelUser, channelUserCandidates, newChannelUserCandidates } from './people';
import type { ChannelAgentPostInput } from './post';
import { postAgentMessage } from './post';
+import {
+ findOpenChannel,
+ joinOpenChannel,
+ listUnjoinedOpenChannels,
+ readOpenChannel,
+} from './projectAccess';
+import { joinPublicChannel, listJoinableChannels } from './publicAccess';
import { retryJob } from './retry';
import { retryRouting } from './routing';
import type { ChannelSendInput } from './send';
@@ -74,6 +76,7 @@ export type { ChannelErrorCode } from './error';
export { ChannelError } from './error';
export { ChannelExecutionRepository } from './execution';
export { ChannelHistoryRepository } from './history';
+export { removeAgentFromProjectChannels } from './membership';
export type { ChannelOpeningCandidate, ChannelOpeningDecision } from './opening';
export type { ChannelAgentPostInput } from './post';
export type { AppliedChannelRouting, ChannelRoutingDecision } from './routing';
@@ -416,113 +419,48 @@ export class ChannelRepository {
);
/** Public group Channels in this workspace the caller has not joined, newest first. */
- listJoinable = async (search?: string) => {
- const { workspaceId } = this;
- if (!workspaceId) return [];
- const query = search?.trim();
- return this.db.transaction(async (tx) => {
- await requireWorkspaceMember(tx, workspaceId, this.userId);
- return tx
- .select({
- createdAt: channels.createdAt,
- id: channels.id,
- // Qualified by hand: a single-table select renders columns without their table.
- memberCount: sql<number>`(
- SELECT count(*)::int FROM channel_members m
- WHERE m.channel_id = "channels"."id" AND m.actor_type = 'user' AND m.status = 'active'
- )`,
- projectId: channels.projectId,
- title: channels.title,
- })
- .from(channels)
- .where(
- and(
- eq(channels.workspaceId, workspaceId),
- eq(channels.visibility, 'public'),
- eq(channels.status, 'active'),
- isNull(channels.agentId),
- isNull(channels.peerUserId),
- notTrashed(channels.isDeleted),
- query ? ilikeContains(channels.title, query) : undefined,
- notExists(
- tx
- .select({ id: channelMembers.id })
- .from(channelMembers)
- .where(
- and(
- eq(channelMembers.channelId, channels.id),
- eq(channelMembers.userId, this.userId),
- eq(channelMembers.status, 'active'),
- ),
- ),
- ),
- ),
- )
- .orderBy(desc(channels.createdAt))
- .limit(100);
- });
- };
+ listJoinable = async (search?: string) =>
+ listJoinableChannels(this.db, this.userId, this.workspaceId, search);
/**
- * Joins a public group Channel of this workspace as a plain member. A person who left or was
- * removed can come back, the same as being added again.
+ * Joins a group Channel the caller can see without belonging to it, or returns their membership
+ * when they already belong: an open project Channel (see {@link joinOpenChannel}), else a public
+ * one of this workspace.
*/
join = async (channelId: string): Promise<ChannelAccess> => {
- const { workspaceId } = this;
- if (!workspaceId) throw new ChannelError('NOT_FOUND', 'Channel not found');
- return this.db.transaction(async (tx) => {
- await lockChannel(tx, channelId);
- const [channel] = await tx
- .select()
- .from(channels)
- .where(
- and(
- eq(channels.id, channelId),
- eq(channels.workspaceId, workspaceId),
- eq(channels.visibility, 'public'),
- isNull(channels.agentId),
- isNull(channels.peerUserId),
- notTrashed(channels.isDeleted),
- ),
- )
- .limit(1);
- // A private channel answers the same as a missing one, so its existence does not leak.
- if (!channel) throw new ChannelError('NOT_FOUND', 'Channel not found');
- if (channel.status === 'archived') throw new ChannelError('CONFLICT', 'Channel is archived');
- await requireWorkspaceMember(tx, workspaceId, this.userId);
-
- const [existing] = await tx
- .select()
- .from(channelMembers)
- .where(
- and(eq(channelMembers.channelId, channelId), eq(channelMembers.userId, this.userId)),
- );
- if (existing?.status === 'active') return { channel, member: existing };
- // History is there to read, but it is not unread: a joiner starts caught up.
- const [member] = existing
- ? await tx
- .update(channelMembers)
- .set({ lastReadSequence: channel.sequence, role: 'member', status: 'active' })
- .where(eq(channelMembers.id, existing.id))
- .returning()
- : await tx
- .insert(channelMembers)
- .values({
- actorType: 'user',
- channelId,
- lastReadSequence: channel.sequence,
- role: 'member',
- userId: this.userId,
- })
- .returning();
- await audit(tx, channelId, 'member_joined', member.id, { userId: this.userId });
- return { channel, member };
- });
+ try {
+ return await this.write(channelId, async (_tx, access) => access, { joinOpen: true });
+ } catch (error) {
+ if (!(error instanceof ChannelError) || error.code !== 'NOT_FOUND') throw error;
+ }
+ return joinPublicChannel(this.db, this.userId, this.workspaceId, channelId);
};
addUser = async (channelId: string, userId: string) =>
this.write(channelId, (tx, access) => addChannelUser(tx, access, userId), { minRole: 'admin' });
+ /** Removes a person or an Agent; returns the writers still to stop. See {@link removeChannelMember}. */
+ removeMember = async (channelId: string, memberId: string): Promise<ChannelJobItem[]> =>
+ this.write(channelId, (tx, access) => removeChannelMember(tx, access, memberId), {
+ allowArchived: true,
+ minRole: 'admin',
+ });
+
+ /**
+ * The caller leaves a group Channel. See {@link leaveChannel}. `readable` says whether they can
+ * still open it: only an active open project Channel stays readable without a seat.
+ */
+ leave = async (channelId: string): Promise<{ readable: boolean }> =>
+ this.write(
+ channelId,
+ async (tx, access) => {
+ await leaveChannel(tx, access);
+ const open = await findOpenChannel(tx, this.userId, this.workspaceId, channelId);
+ return { readable: !!open };
+ },
+ { allowArchived: true },
+ );
+
/** People a new Channel in this workspace can start with. */
newChannelUserCandidates = async (search?: string) => {
const { workspaceId } = this;
@@ -538,8 +476,10 @@ export class ChannelRepository {
minRole: 'admin',
});
- detail = async (channelId: string, options?: Parameters<typeof readChannelView>[2]) =>
- this.write(
+ detail = async (channelId: string, options?: Parameters<typeof readChannelView>[2]) => {
+ if (!(await this.findAccess(channelId)))
+ return readOpenChannel(this.db, this.userId, this.workspaceId, channelId, options);
+ return this.write(
channelId,
async (tx, access) => {
if (access.channel.isDeleted) throw new ChannelError('NOT_FOUND', 'Channel not found');
@@ -547,6 +487,7 @@ export class ChannelRepository {
const view = await readChannelView(tx, channelId, options, this.userId);
return {
channel: { ...access.channel, canDelete: admin },
+ joined: true,
...view,
jobs: view.jobs.map(({ requesterMemberId, topicId, topicOwnerId, ...job }) => ({
...job,
@@ -560,9 +501,10 @@ export class ChannelRepository {
},
{ allowArchived: true, allowTrashed: true },
);
+ };
createThread = async (channelId: string, input: Parameters<typeof createChannelThread>[2]) =>
- this.write(channelId, (tx) => createChannelThread(tx, channelId, input));
+ this.write(channelId, (tx) => createChannelThread(tx, channelId, input), { joinOpen: true });
markRead = async (channelId: string, sequence: number) =>
this.write(
@@ -583,15 +525,19 @@ export class ChannelRepository {
/**
* Channels the caller belongs to in the current scope, newest first. Archived ones are
- * included with their `status`, so they stay readable outside the active list.
+ * included with their `status`, so they stay readable outside the active list. Active open
+ * project Channels the caller has not joined follow with `joined: false`.
*/
list = async (): Promise<
Array<
ChannelItem & {
agentIds: string[];
canDelete: boolean;
+ /** False for an open project Channel the caller can read but has not joined. */
+ joined: boolean;
lastMessage: ChannelLastMessage | null;
memberAvatars: ChannelAvatarMember[];
+ memberRole: ChannelMemberRole | null;
mentionCount: number;
replyJobs: ChannelReplyJob[];
sharedAgentHandle: string | null;
@@ -617,11 +563,10 @@ export class ChannelRepository {
.leftJoin(agentShares, eq(agentShares.agentId, channels.agentId))
.where(and(this.membershipWhere(), notTrashed(channels.isDeleted)))
.orderBy(desc(channels.createdAt));
+ const open = await listUnjoinedOpenChannels(this.db, this.userId, this.workspaceId);
+ const previewIds = [...rows.map(({ channel }) => channel.id), ...open.map(({ id }) => id)];
- const lastMessageOf = await channelLastMessages(
- this.db,
- rows.map(({ channel }) => channel.id),
- );
+ const lastMessageOf = await channelLastMessages(this.db, previewIds);
// Main-conversation replies the list row shows as in progress: ones that can still publish,
// and stopped ones whose writer has not exited yet.
@@ -689,24 +634,17 @@ export class ChannelRepository {
// A group Channel's list avatar pictures its first members; a direct one, its Agent or the
// other person, which also pictures a shared Agent the caller has no sidebar row for.
- const avatarsOf = await channelAvatarMembers(
- this.db,
- rows.map(({ channel }) => channel.id),
- this.userId,
- );
+ const avatarsOf = await channelAvatarMembers(this.db, previewIds, this.userId);
// Every active Agent member, so a page about one Agent can list the Channels it takes part in;
// the avatars above are capped and leave later members out.
- const agentMembers = rows.length
+ const agentMembers = previewIds.length
? await this.db
.select({ agentId: channelMembers.agentId, channelId: channelMembers.channelId })
.from(channelMembers)
.where(
and(
- inArray(
- channelMembers.channelId,
- rows.map(({ channel }) => channel.id),
- ),
+ inArray(channelMembers.channelId, previewIds),
eq(channelMembers.actorType, 'agent'),
eq(channelMembers.status, 'active'),
isNotNull(channelMembers.agentId),
@@ -721,7 +659,7 @@ export class ChannelRepository {
agentIdsOf.set(channelId, ids);
}
- return rows.map(({ channel, lastReadSequence, role, shareId, shareSlug, ...agent }) => {
+ const joined = rows.map(({ channel, lastReadSequence, role, shareId, shareSlug, ...agent }) => {
const sharedAgent = isSharedAgentChannel(channel, agent, this.userId);
return {
...channel,
@@ -730,14 +668,35 @@ export class ChannelRepository {
// Its visitor page (`/a/<handle>`) is where the caller can see this Agent; it has no other.
sharedAgentHandle: sharedAgent ? (shareSlug ?? shareId) : null,
canDelete: hasRole(role, 'admin'),
+ joined: true,
lastMessage: lastMessageOf.get(channel.id) ?? null,
memberAvatars: avatarsOf.get(channel.id) ?? [],
+ memberRole: role,
mentionCount: mentionCountOf.get(channel.id) ?? 0,
peerUserId: peerOf(channel, this.userId),
replyJobs: replyJobsOf.get(channel.id) ?? [],
unreadCount: Math.max(0, channel.sequence - (lastReadSequence ?? 0)),
};
});
+ return [
+ ...joined,
+ // Not joined: nothing is unread or pending for the caller yet.
+ ...open.map((channel) => ({
+ ...channel,
+ agentIds: agentIdsOf.get(channel.id) ?? [],
+ sharedAgent: false,
+ sharedAgentHandle: null,
+ canDelete: false,
+ joined: false,
+ lastMessage: lastMessageOf.get(channel.id) ?? null,
+ memberAvatars: avatarsOf.get(channel.id) ?? [],
+ memberRole: null,
+ mentionCount: 0,
+ peerUserId: peerOf(channel, this.userId),
+ replyJobs: [],
+ unreadCount: 0,
+ })),
+ ].sort((a, b) => b.createdAt.getTime() - a.createdAt.getTime());
};
/**
@@ -885,11 +844,16 @@ export class ChannelRepository {
.innerJoin(channelMembers, eq(channelMembers.channelId, channels.id))
.where(and(eq(channels.id, channelId), this.membershipWhere()))
.limit(1);
- if (!row) throw new ChannelError('NOT_FOUND', 'Channel not found');
- const access: ChannelAccess = {
+ let access: ChannelAccess | undefined = row && {
channel: row.channel,
member: { ...row.member, role: row.role },
};
+ if (!access && options.joinOpen) {
+ // Joining is itself a write, so a trashed or archived Channel stays closed to newcomers.
+ const open = await findOpenChannel(tx, this.userId, this.workspaceId, channelId);
+ if (open) access = await joinOpenChannel(tx, open, this.userId);
+ }
+ if (!access) throw new ChannelError('NOT_FOUND', 'Channel not found');
const minRole = options.minRole ?? 'member';
if (!hasRole(access.member.role, minRole))
@@ -913,8 +877,9 @@ export class ChannelRepository {
this.write(channelId, (tx) => postAgentMessage(tx, channelId, input));
/** Posts a message as the caller. See {@link sendMessage} for routing. */
+ /** Sending into an open project Channel joins it first. */
send = async (channelId: string, input: ChannelSendInput): Promise<ChannelMessageItem> =>
- this.write(channelId, (tx, access) => sendMessage(tx, access, input));
+ this.write(channelId, (tx, access) => sendMessage(tx, access, input), { joinOpen: true });
/**
* Stops one job (its requester or an admin) or a branch: everything for admins, only the
diff --git a/packages/database/src/repositories/channel/membership.ts b/packages/database/src/repositories/channel/membership.ts
new file mode 100644
index 00000000000..d3935b0c5f0
--- /dev/null
+++ b/packages/database/src/repositories/channel/membership.ts
@@ -0,0 +1,133 @@
+import { and, eq, inArray } from 'drizzle-orm';
+
+import type { ChannelJobItem } from '../../schemas';
+import { channelJobs, channelMembers, channels } from '../../schemas';
+import type { LobeChatDatabase, Transaction } from '../../type';
+import { ChannelError } from './error';
+import { stopScope } from './stop';
+import { audit, lockChannel } from './transaction';
+import type { ChannelAccess } from './types';
+import { OPEN_JOB_STATUSES } from './writer';
+
+/** A direct or person-to-person conversation is defined by its two sides, so no one leaves it. */
+const requireGroup = ({ channel }: ChannelAccess) => {
+ if (channel.agentId || channel.peerUserId)
+ throw new ChannelError('BAD_REQUEST', 'A direct conversation keeps its members');
+};
+
+/** Cancels an Agent member's open jobs; returns the writers the caller must still stop. */
+const stopMemberJobs = async (tx: Transaction, channelId: string, memberId: string) => {
+ const open = await tx
+ .select({ id: channelJobs.id })
+ .from(channelJobs)
+ .where(
+ and(
+ eq(channelJobs.channelId, channelId),
+ eq(channelJobs.memberId, memberId),
+ inArray(channelJobs.status, [...OPEN_JOB_STATUSES]),
+ ),
+ );
+ const writers: ChannelJobItem[] = [];
+ for (const { id } of open) writers.push(...(await stopScope(tx, channelId, { jobId: id })));
+ return writers;
+};
+
+/**
+ * Removes a person or an Agent from a group Channel, under the lock after the caller's admin
+ * role was checked. The owner stays, and only the owner removes another admin. A removed person
+ * does not come back through an open project Channel; an admin can add them again.
+ */
+export const removeChannelMember = async (
+ tx: Transaction,
+ access: ChannelAccess,
+ memberId: string,
+): Promise<ChannelJobItem[]> => {
+ requireGroup(access);
+ const [target] = await tx
+ .select()
+ .from(channelMembers)
+ .where(
+ and(
+ eq(channelMembers.channelId, access.channel.id),
+ eq(channelMembers.id, memberId),
+ eq(channelMembers.status, 'active'),
+ ),
+ );
+ if (!target) throw new ChannelError('NOT_FOUND', 'Member not found');
+ if (target.id === access.member.id)
+ throw new ChannelError('BAD_REQUEST', 'Leave the Channel instead of removing yourself');
+ if (target.role === 'owner') throw new ChannelError('FORBIDDEN', 'The owner cannot be removed');
+ if (target.role === 'admin' && access.member.role !== 'owner')
+ throw new ChannelError('FORBIDDEN', 'Only the owner can remove an admin');
+
+ const writers =
+ target.actorType === 'agent' ? await stopMemberJobs(tx, access.channel.id, target.id) : [];
+ await tx
+ .update(channelMembers)
+ .set({ status: 'removed' })
+ .where(eq(channelMembers.id, target.id));
+ await audit(tx, access.channel.id, 'member_removed', target.id, {
+ actorType: target.actorType,
+ ...(target.agentId ? { agentId: target.agentId } : { userId: target.userId }),
+ });
+ return writers;
+};
+
+/**
+ * The caller leaves a group Channel. The owner hands the Channel on by deleting it, so they stay.
+ * Someone who left an open project Channel can join it again.
+ */
+export const leaveChannel = async (tx: Transaction, access: ChannelAccess): Promise<void> => {
+ requireGroup(access);
+ if (access.member.role === 'owner')
+ throw new ChannelError('CONFLICT', 'The owner cannot leave the Channel');
+ await tx
+ .update(channelMembers)
+ .set({ status: 'left' })
+ .where(eq(channelMembers.id, access.member.id));
+ await audit(tx, access.channel.id, 'member_left', access.member.id, {
+ actorType: 'user',
+ userId: access.member.userId,
+ });
+};
+
+/**
+ * An Agent that leaves a project leaves its Channels too: a project Channel only seats the
+ * project's own Agents. Called by project member management after its own permission check.
+ * Returns the Channels it left and the writers still to stop.
+ */
+export const removeAgentFromProjectChannels = (
+ db: LobeChatDatabase,
+ projectId: string,
+ agentId: string,
+): Promise<{ channelIds: string[]; writers: ChannelJobItem[] }> =>
+ db.transaction(async (tx) => {
+ const seats = await tx
+ .select({ channelId: channelMembers.channelId, id: channelMembers.id })
+ .from(channelMembers)
+ .innerJoin(channels, eq(channels.id, channelMembers.channelId))
+ .where(
+ and(
+ eq(channels.projectId, projectId),
+ eq(channelMembers.actorType, 'agent'),
+ eq(channelMembers.agentId, agentId),
+ eq(channelMembers.status, 'active'),
+ ),
+ );
+ const writers: ChannelJobItem[] = [];
+ for (const seat of seats) {
+ // The same lock every Channel write holds, so a reply cannot claim the seat meanwhile.
+ await lockChannel(tx, seat.channelId);
+ writers.push(...(await stopMemberJobs(tx, seat.channelId, seat.id)));
+ await tx
+ .update(channelMembers)
+ .set({ status: 'removed' })
+ .where(eq(channelMembers.id, seat.id));
+ await audit(tx, seat.channelId, 'member_removed', seat.id, {
+ actorType: 'agent',
+ agentId,
+ reason: 'left_project',
+ });
+ }
+ return { channelIds: [...new Set(seats.map(({ channelId }) => channelId))], writers };
+ });
diff --git a/packages/database/src/repositories/channel/projectAccess.ts b/packages/database/src/repositories/channel/projectAccess.ts
new file mode 100644
index 00000000000..ad5a6210da4
--- /dev/null
+++ b/packages/database/src/repositories/channel/projectAccess.ts
@@ -0,0 +1,197 @@
+import { and, eq, exists, isNotNull, isNull, notExists, sql } from 'drizzle-orm';
+
+import type { ChannelItem } from '../../schemas';
+import { channelMembers, channels, projects, workspaceMembers } from '../../schemas';
+import type { LobeChatDatabase, Transaction } from '../../type';
+import { notTrashed } from '../../utils/softDelete';
+import { buildWorkspaceWhere } from '../../utils/workspace';
+import { ChannelError } from './error';
+import { requireWorkspaceMember } from './people';
+import { audit } from './transaction';
+import type { ChannelAccess } from './types';
+import { readChannelView } from './view';
+
+/**
+ * A workspace project's group Channels are open to everyone who can read the project: they find
+ * them in the project, read them, and become a member by joining or by sending. A private project
+ * is readable by its creator only, so its Channels stay with their members. Personal scope has
+ * no one else to open them to, so nothing is open there. Only active workspace members qualify:
+ * the workspace header alone is not proof of membership in every runtime.
+ */
+export const openProjectChannelWhere = (
+ db: LobeChatDatabase | Transaction,
+ userId: string,
+ workspaceId: string | null,
+) =>
+ workspaceId
+ ? and(
+ isNotNull(channels.projectId),
+ isNull(channels.agentId),
+ eq(channels.workspaceId, workspaceId),
+ exists(
+ db
+ .select({ userId: workspaceMembers.userId })
+ .from(workspaceMembers)
+ .where(
+ and(
+ eq(workspaceMembers.workspaceId, workspaceId),
+ eq(workspaceMembers.userId, userId),
+ isNull(workspaceMembers.deletedAt),
+ ),
+ ),
+ ),
+ exists(
+ db
+ .select({ id: projects.id })
+ .from(projects)
+ .where(
+ and(
+ eq(projects.id, channels.projectId),
+ buildWorkspaceWhere({ userId, workspaceId }, projects),
+ ),
+ ),
+ ),
+ )
+ : undefined;
+
+/** Open project Channels of this scope, minus the ones an admin removed the caller from. */
+export const openChannelWhere = (
+ db: LobeChatDatabase | Transaction,
+ userId: string,
+ workspaceId: string | null,
+) => {
+ const open = openProjectChannelWhere(db, userId, workspaceId);
+ if (!open) return sql`false`;
+ return and(
+ open,
+ notExists(
+ db
+ .select({ id: channelMembers.id })
+ .from(channelMembers)
+ .where(
+ and(
+ eq(channelMembers.channelId, channels.id),
+ eq(channelMembers.userId, userId),
+ eq(channelMembers.status, 'removed'),
+ ),
+ ),
+ ),
+ );
+};
+
+/** Trashed and archived open Channels stay with their members: newcomers neither read nor join. */
+const activeOpenWhere = (
+ db: LobeChatDatabase | Transaction,
+ userId: string,
+ workspaceId: string | null,
+) =>
+ and(
+ openChannelWhere(db, userId, workspaceId),
+ notTrashed(channels.isDeleted),
+ eq(channels.status, 'active'),
+ );
+
+export const findOpenChannel = async (
+ tx: Transaction,
+ userId: string,
+ workspaceId: string | null,
+ channelId: string,
+) => {
+ const [channel] = await tx
+ .select()
+ .from(channels)
+ .where(and(eq(channels.id, channelId), activeOpenWhere(tx, userId, workspaceId)))
+ .limit(1);
+ return channel;
+};
+
+/** Active open project Channels the caller has not joined, so the project can list them. */
+export const listUnjoinedOpenChannels = async (
+ db: LobeChatDatabase,
+ userId: string,
+ workspaceId: string | null,
+) =>
+ workspaceId
+ ? db
+ .select()
+ .from(channels)
+ .where(
+ and(
+ activeOpenWhere(db, userId, workspaceId),
+ notExists(
+ db
+ .select({ id: channelMembers.id })
+ .from(channelMembers)
+ .where(
+ and(
+ eq(channelMembers.channelId, channels.id),
+ eq(channelMembers.userId, userId),
+ eq(channelMembers.status, 'active'),
+ ),
+ ),
+ ),
+ ),
+ )
+ : [];
+
+/**
+ * An active open project Channel read by someone who has not joined: read-only, no member
+ * actions.
+ */
+export const readOpenChannel = async (
+ db: LobeChatDatabase,
+ userId: string,
+ workspaceId: string | null,
+ channelId: string,
+ options?: Parameters<typeof readChannelView>[2],
+) =>
+ db.transaction(async (tx) => {
+ const channel = await findOpenChannel(tx, userId, workspaceId, channelId);
+ if (!channel) throw new ChannelError('NOT_FOUND', 'Channel not found');
+ const view = await readChannelView(tx, channelId, options, userId);
+ return {
+ channel: { ...channel, canDelete: false },
+ joined: false,
+ ...view,
+ jobs: view.jobs.map(({ requesterMemberId: _, topicId, topicOwnerId, ...job }) => ({
+ ...job,
+ canStop: false,
+ ...(topicId && topicOwnerId === userId ? { topicId } : {}),
+ })),
+ };
+ });
+
+/**
+ * Makes the caller an active member of an open project Channel. They have seen it before joining,
+ * so it starts read; a member who left comes back, one removed by an admin does not.
+ */
+export const joinOpenChannel = async (
+ tx: Transaction,
+ channel: ChannelItem,
+ userId: string,
+): Promise<ChannelAccess> => {
+ await requireWorkspaceMember(tx, channel.workspaceId!, userId);
+ const [existing] = await tx
+ .select()
+ .from(channelMembers)
+ .where(and(eq(channelMembers.channelId, channel.id), eq(channelMembers.userId, userId)));
+ if (existing?.status === 'removed') throw new ChannelError('NOT_FOUND', 'Channel not found');
+ const [member] = existing
+ ? await tx
+ .update(channelMembers)
+ .set({ lastReadSequence: channel.sequence, role: 'member', status: 'active' })
+ .where(eq(channelMembers.id, existing.id))
+ .returning()
+ : await tx
+ .insert(channelMembers)
+ .values({
+ actorType: 'user',
+ channelId: channel.id,
+ lastReadSequence: channel.sequence,
+ role: 'member',
+ userId,
+ })
+ .returning();
+ await audit(tx, channel.id, 'member_joined', member.id, { actorType: 'user', userId });
+ return { channel, member };
+};
diff --git a/packages/database/src/repositories/channel/publicAccess.ts b/packages/database/src/repositories/channel/publicAccess.ts
new file mode 100644
index 00000000000..928c71f3750
--- /dev/null
+++ b/packages/database/src/repositories/channel/publicAccess.ts
@@ -0,0 +1,121 @@
+import { and, desc, eq, isNull, notExists, sql } from 'drizzle-orm';
+
+import { channelMembers, channels } from '../../schemas';
+import type { LobeChatDatabase } from '../../type';
+import { ilikeContains } from '../../utils/like';
+import { notTrashed } from '../../utils/softDelete';
+import { ChannelError } from './error';
+import { requireWorkspaceMember } from './people';
+import { audit, lockChannel } from './transaction';
+import type { ChannelAccess } from './types';
+
+/** Public group Channels in this workspace the caller has not joined, newest first. */
+export const listJoinableChannels = async (
+ db: LobeChatDatabase,
+ userId: string,
+ workspaceId: string | null,
+ search?: string,
+) => {
+ if (!workspaceId) return [];
+ const query = search?.trim();
+ return db.transaction(async (tx) => {
+ await requireWorkspaceMember(tx, workspaceId, userId);
+ return tx
+ .select({
+ createdAt: channels.createdAt,
+ id: channels.id,
+ // Qualified by hand: a single-table select renders columns without their table.
+ memberCount: sql<number>`(
+ SELECT count(*)::int FROM channel_members m
+ WHERE m.channel_id = "channels"."id" AND m.actor_type = 'user' AND m.status = 'active'
+ )`,
+ projectId: channels.projectId,
+ title: channels.title,
+ })
+ .from(channels)
+ .where(
+ and(
+ eq(channels.workspaceId, workspaceId),
+ eq(channels.visibility, 'public'),
+ eq(channels.status, 'active'),
+ isNull(channels.agentId),
+ isNull(channels.peerUserId),
+ notTrashed(channels.isDeleted),
+ query ? ilikeContains(channels.title, query) : undefined,
+ notExists(
+ tx
+ .select({ id: channelMembers.id })
+ .from(channelMembers)
+ .where(
+ and(
+ eq(channelMembers.channelId, channels.id),
+ eq(channelMembers.userId, userId),
+ eq(channelMembers.status, 'active'),
+ ),
+ ),
+ ),
+ ),
+ )
+ .orderBy(desc(channels.createdAt))
+ .limit(100);
+ });
+};
+
+/**
+ * Joins a public group Channel of this workspace as a plain member. A person who left or was
+ * removed can come back, the same as being added again.
+ */
+export const joinPublicChannel = async (
+ db: LobeChatDatabase,
+ userId: string,
+ workspaceId: string | null,
+ channelId: string,
+): Promise<ChannelAccess> => {
+ if (!workspaceId) throw new ChannelError('NOT_FOUND', 'Channel not found');
+ return db.transaction(async (tx) => {
+ await lockChannel(tx, channelId);
+ const [channel] = await tx
+ .select()
+ .from(channels)
+ .where(
+ and(
+ eq(channels.id, channelId),
+ eq(channels.workspaceId, workspaceId),
+ eq(channels.visibility, 'public'),
+ isNull(channels.agentId),
+ isNull(channels.peerUserId),
+ notTrashed(channels.isDeleted),
+ ),
+ )
+ .limit(1);
+ // A private channel answers the same as a missing one, so its existence does not leak.
+ if (!channel) throw new ChannelError('NOT_FOUND', 'Channel not found');
+ if (channel.status === 'archived') throw new ChannelError('CONFLICT', 'Channel is archived');
+ await requireWorkspaceMember(tx, workspaceId, userId);
+
+ const [existing] = await tx
+ .select()
+ .from(channelMembers)
+ .where(and(eq(channelMembers.channelId, channelId), eq(channelMembers.userId, userId)));
+ if (existing?.status === 'active') return { channel, member: existing };
+ // History is there to read, but it is not unread: a joiner starts caught up.
+ const [member] = existing
+ ? await tx
+ .update(channelMembers)
+ .set({ lastReadSequence: channel.sequence, role: 'member', status: 'active' })
+ .where(eq(channelMembers.id, existing.id))
+ .returning()
+ : await tx
+ .insert(channelMembers)
+ .values({
+ actorType: 'user',
+ channelId,
+ lastReadSequence: channel.sequence,
+ role: 'member',
+ userId,
+ })
+ .returning();
+ await audit(tx, channelId, 'member_joined', member.id, { userId });
+ return { channel, member };
+ });
+};
diff --git a/packages/database/src/repositories/channel/types.ts b/packages/database/src/repositories/channel/types.ts
index e9d013c82bf..94ff51c278e 100644
--- a/packages/database/src/repositories/channel/types.ts
+++ b/packages/database/src/repositories/channel/types.ts
@@ -13,5 +13,7 @@ export interface ChannelWriteOptions {
allowArchived?: boolean;
/** Lets owners and admins act on a channel that sits in the recycle bin. */
allowTrashed?: boolean;
+ /** A caller who is not a member yet joins an open project Channel first (see `projectAccess`). */
+ joinOpen?: boolean;
minRole?: ChannelMemberRole;
}
diff --git a/packages/database/src/repositories/project/index.ts b/packages/database/src/repositories/project/index.ts
index 9505cf48661..c3402778878 100644
--- a/packages/database/src/repositories/project/index.ts
+++ b/packages/database/src/repositories/project/index.ts
@@ -1,12 +1,15 @@
+import { eq, max } from 'drizzle-orm';
+
+import { AgentModel } from '../../models/agent';
import { EnvironmentModel } from '../../models/environment';
-import type { CreateProjectInput } from '../../models/project';
+import type { CreateProjectInput, ProjectModelOptions } from '../../models/project';
import {
normalizeProjectIdentifier,
ProjectIdentifierTakenError,
ProjectModel,
} from '../../models/project';
import { createProjectMainAgent } from '../../models/projectMainAgent';
-import { projectAgents } from '../../schemas/project';
+import { projectAgents, projectCompletionReviews } from '../../schemas/project';
import { projectEnvironments } from '../../schemas/projectEnvironment';
import type { LobeChatDatabase } from '../../type';
@@ -22,8 +25,13 @@ export class ProjectRepository {
private readonly db: LobeChatDatabase,
private readonly userId: string,
private readonly workspaceId?: string,
+ private readonly options: ProjectModelOptions = {},
) {}
+ private model(db: LobeChatDatabase) {
+ return new ProjectModel(db, this.userId, this.workspaceId, this.options);
+ }
+
async create({ dedicatedAgentId, repository, ...input }: CreateProjectInput) {
const identifier = normalizeProjectIdentifier(input.identifier);
@@ -99,6 +107,60 @@ export class ProjectRepository {
});
}
+ /**
+ * Deletes a project and retires a coordinator provisioned for it: a virtual,
+ * non-builtin agent no other project still uses. Reusable agents (user agents,
+ * LobeAI) stay with their sessions intact.
+ */
+ async delete(id: string) {
+ return this.db.transaction(async (tx) => {
+ const db = tx as LobeChatDatabase;
+ const projectModel = this.model(db);
+ const project = await projectModel.findManageableById(id);
+ if (!project) return null;
+
+ const deleted = await projectModel.delete(id);
+ // Asked after the delete, so this project no longer counts as one still using it.
+ const agentId = project.coordinatorAgentId;
+ if (agentId && (await projectModel.isDedicatedCoordinator(agentId, { db }))) {
+ await new AgentModel(db, this.userId, this.workspaceId).delete(agentId);
+ }
+ return deleted;
+ });
+ }
+
+ /**
+ * Records the next round of a completion review and settles the project by it,
+ * holding the project row so concurrent reviews number their rounds in turn.
+ */
+ async reviewCompletion(id: string, decision: 'accepted' | 'rejected', comment?: string) {
+ return this.db.transaction(async (tx) => {
+ const db = tx as LobeChatDatabase;
+ const projectModel = this.model(db);
+ const project = await projectModel.findManageableById(id, { lock: true });
+ if (!project) return null;
+ if (project.status !== 'reviewing') throw new Error('Project is not awaiting review');
+
+ const [{ value: lastRound }] = await db
+ .select({ value: max(projectCompletionReviews.round) })
+ .from(projectCompletionReviews)
+ .where(eq(projectCompletionReviews.projectId, id));
+ const [review] = await db
+ .insert(projectCompletionReviews)
+ .values({
+ comment,
+ decision,
+ projectId: id,
+ reviewerUserId: this.userId,
+ round: (lastRound ?? 0) + 1,
+ workspaceId: this.workspaceId ?? null,
+ })
+ .returning();
+ const updated = await projectModel.applyCompletionReview(id, decision, review.id);
+ return { project: updated, review };
+ });
+ }
+
/**
* Seat the main agent on the project it leads. The link lives in the project
* aggregate but points at a row another aggregate owns, so it is written here
diff --git a/packages/locales/src/default/channel.ts b/packages/locales/src/default/channel.ts
index 62fe32e21b4..a99cb653a4b 100644
--- a/packages/locales/src/default/channel.ts
+++ b/packages/locales/src/default/channel.ts
@@ -25,7 +25,7 @@ export default {
'create.onlyYou': 'Only you for now. Create it and invite members whenever you like.',
'agents': 'Agents',
'otherAgents': 'Other Agents',
- 'projectAgents': 'Project members',
+ 'projectAgents': 'Project Agents',
'searchAgents': 'Search Agents',
'unnamedAgent': 'Unnamed Agent',
'person': 'Person',
@@ -115,6 +115,7 @@ export default {
'outgoing.retry': 'Retry',
'outgoing.sending': 'Sending…',
'composer': 'Message #{{name}}',
+ 'composerToJoin': 'Message #{{name}} to join',
'directComposer': 'Message {{name}}',
'threadComposer': 'Reply in thread',
'composer.actions': 'More actions',
@@ -138,7 +139,7 @@ export default {
'Mention Agents to choose who replies. Without a mention, every Agent here replies.',
'mentionInvite.failed': "Couldn't add {{name}} to the channel. Try again.",
'mentionInvite.failedReason': "Couldn't add {{name}} to the channel: {{reason}}",
- 'mentionInvite.section': 'Not in this channel · mention to add',
+ 'mentionInvite.section': 'Not in this channel · mention to invite',
'attachments.upload': 'Attach files',
'date.yesterday': 'Yesterday',
'attachments.failed': 'Upload failed. Try again.',
@@ -310,4 +311,32 @@ export default {
'settings.visibility.title': 'Public channel',
'visibilityFailed': 'Could not change who can see the channel. Try again.',
'visibilityForbidden': 'Only the channel owner or an administrator can change who can see it.',
+ 'invite.outsideProject': 'Other Agents · they join the project too',
+ 'invite.outsideProjectLocked':
+ 'Only the project creator or a workspace admin can add another Agent to this project',
+ 'invite.joinProjectNotice':
+ '{{names}} will join the project “{{project}}” first, then this channel.',
+ 'invite.joinProjectNoticeUnnamed': '{{names}} will join this project first, then this channel.',
+ 'member.remove': 'Remove from channel',
+ 'member.removeNamed': 'Remove {{name}} from the channel',
+ 'member.removeConfirmTitle': 'Remove {{name}} from the channel?',
+ 'member.removeConfirmPerson':
+ 'They will no longer see this channel unless an admin invites them again.',
+ 'member.removeConfirmAgent':
+ 'Its replies in progress here stop. It stays in the project and can be invited again.',
+ 'member.removeConfirmAgentStandalone':
+ 'Its replies in progress here stop. You can invite it again later.',
+ 'member.removeFailed': "Couldn't remove {{name}}. Try again.",
+ 'leave': 'Leave channel',
+ 'leaveConfirmTitle': 'Leave “{{title}}”?',
+ 'leaveConfirm': 'You will no longer see this channel unless someone invites you again.',
+ 'leaveConfirmProject': 'You can join again from the project at any time.',
+ 'leaveFailed': "Couldn't leave the channel. Try again.",
+ 'leaveSuccess': 'You left the channel',
+ 'mentionInvite.confirmTitle': 'Invite {{name}} to this channel?',
+ 'mentionInvite.confirmPerson': 'They will see the whole conversation in this channel.',
+ 'mentionInvite.confirmAgent': 'It will read this channel and can reply here.',
+ 'mentionInvite.confirmAgentProject':
+ 'It is not in the project “{{project}}” yet: it joins the project first, then this channel.',
+ 'mentionInvite.confirmOk': 'Invite and mention',
};
diff --git a/packages/locales/src/default/project.ts b/packages/locales/src/default/project.ts
index 3f1e2b75013..a82ce7b6869 100644
--- a/packages/locales/src/default/project.ts
+++ b/packages/locales/src/default/project.ts
@@ -463,7 +463,7 @@ export default {
'members.noResponsibility': 'No responsibility set yet',
'members.remove': 'Remove from project',
'members.removeConfirmDescription':
- 'Its existing tasks and topics in this project stay as they are.',
+ 'Its existing tasks and topics in the project are not affected. It also leaves the project’s channels.',
'members.removeConfirmTitle': 'Remove {{name}} from this project?',
'members.removeFailed': 'Could not remove the agent',
'members.replaceCoordinator': 'Change main agent',
diff --git a/packages/types/src/channel.ts b/packages/types/src/channel.ts
index 68d8913a2d8..9b46e17bf80 100644
--- a/packages/types/src/channel.ts
+++ b/packages/types/src/channel.ts
@@ -496,6 +496,11 @@ export interface ChannelListItem {
canDelete: boolean;
createdAt: Date;
id: string;
+ /**
+ * False for a project Channel the caller can read through the project but has not joined; it
+ * belongs in that project's list only. Absent means joined.
+ */
+ joined?: boolean;
/** The newest message, Threads included, cut for a preview; set by the Channel list. */
lastMessage?: ChannelLastMessage | null;
/**
@@ -503,6 +508,11 @@ export interface ChannelListItem {
* set by the Channel list.
*/
memberAvatars?: ChannelAvatarMember[];
+ /**
+ * The caller's own role here; null for an open project Channel they have not joined. Set by the
+ * Channel list. Everyone but the owner may leave a group Channel.
+ */
+ memberRole?: ChannelMemberRole | null;
/** Unread messages, Threads included, that @mention the caller; set by the Channel list. */
mentionCount?: number;
/**
@@ -658,6 +668,8 @@ export interface ChannelDetail {
* running, or holding the writer); filter by `threadId` for one conversation's own.
*/
jobs: ChannelPublicJob[];
+ /** False while the caller reads an open project Channel without being a member; sending joins. */
+ joined?: boolean;
members: ChannelPublicMember[];
messages: ChannelPublicMessage[];
rootMessage: ChannelPublicMessage | null;
diff --git a/src/features/Channels/ChannelConversation.tsx b/src/features/Channels/ChannelConversation.tsx
index f862a9065d4..9863168d15f 100644
--- a/src/features/Channels/ChannelConversation.tsx
+++ b/src/features/Channels/ChannelConversation.tsx
@@ -22,7 +22,7 @@ import { ChannelMessage, ThreadRootMessage } from './ChannelMessage';
import { Composer } from './Composer';
import { hasReplyActivity } from './jobStatus';
import { JoinEventLine } from './JoinEventLine';
-import { channelJoinEvents, channelTimeline } from './joinEvents';
+import { channelJoinEvents, channelTimeline, isSelfJoinable } from './joinEvents';
import { isCurrentUserMember } from './memberName';
import { channelTimeFormatters, presentChannelTimeline } from './messagePresentation';
import { presentOutgoingMessage, timelineTail } from './outgoing';
@@ -108,12 +108,14 @@ const Timeline = ({
if (feed && followLatest.current && before === undefined) feed.scrollTop = feed.scrollHeight;
}, [feedTail, before]);
+ // Someone reading an open project Channel without joining has no read position to move.
+ const joined = detail?.joined !== false;
useEffect(() => {
- if (threadId || sequence === undefined || before !== undefined) return;
+ if (!joined || threadId || sequence === undefined || before !== undefined) return;
void channelActions
.markRead(channelId, sequence)
.catch((error: unknown) => console.error('Failed to mark Channel read', error));
- }, [channelId, threadId, sequence, before]);
+ }, [channelId, joined, threadId, sequence, before]);
const activeMembers = detail?.members.filter((member) => member.status === 'active') ?? [];
const thread = threadId ? detail?.threads.find((entry) => entry.id === threadId) : undefined;
@@ -127,7 +129,9 @@ const Timeline = ({
outgoing.length
? [...detail.messages, ...outgoing.map((item) => item.message)]
: detail.messages,
- threadId || direct ? [] : channelJoinEvents(detail.members),
+ threadId || direct
+ ? []
+ : channelJoinEvents(detail.members, { selfJoinable: isSelfJoinable(detail.channel) }),
!detail.hasMore && before === undefined,
)
: [];
@@ -278,7 +282,9 @@ const Timeline = ({
placeholder={
threadId
? t('threadComposer')
- : t(direct ? 'directComposer' : 'composer', { name: detail.channel.title })
+ : t(direct ? 'directComposer' : joined ? 'composer' : 'composerToJoin', {
+ name: detail.channel.title,
+ })
}
onCancelReply={() => reply.clear()}
onQueue={(message) => {
diff --git a/src/features/Channels/ChannelList.tsx b/src/features/Channels/ChannelList.tsx
index 76fd4247adc..03c211f316b 100644
--- a/src/features/Channels/ChannelList.tsx
+++ b/src/features/Channels/ChannelList.tsx
@@ -263,22 +263,32 @@ const EnabledChannelSection = ({ itemKey = 'channels', projectId }: ChannelSecti
// The open Channel is being read; its count clears once the read receipt lands.
const unread = !open && (channel.unreadCount ?? 0) > 0;
const mentions = open ? 0 : (channel.mentionCount ?? 0);
+ // A project Channel the caller can read but has not joined: dimmed, with no member actions.
+ const joined = channel.joined !== false;
return (
<Flexbox key={channel.id} {...stylex.props(styles.channel)}>
{unread && <span aria-hidden {...stylex.props(styles.unreadPill)} />}
<NavItem
active={open && !activeThreadId}
aria-current={open && !activeThreadId ? 'page' : undefined}
- contextMenuItems={() => menuItems(channel)}
+ contextMenuItems={joined ? () => menuItems(channel) : undefined}
data-channel-id={channel.id}
href={buildWorkspaceAwarePath(path, slug)}
title={channel.title}
- titleColor={unread ? cssVar.colorText : undefined}
- actions={() => (
- <DropdownMenu items={menuItems(channel)}>
- <ActionIcon icon={MoreHorizontal} size="small" title={t('more', { ns: 'common' })} />
- </DropdownMenu>
- )}
+ titleColor={unread ? cssVar.colorText : joined ? undefined : cssVar.colorTextTertiary}
+ actions={
+ joined
+ ? () => (
+ <DropdownMenu items={menuItems(channel)}>
+ <ActionIcon
+ icon={MoreHorizontal}
+ size="small"
+ title={t('more', { ns: 'common' })}
+ />
+ </DropdownMenu>
+ )
+ : undefined
+ }
extra={
mentions > 0 ? (
<span
diff --git a/src/features/Channels/Composer.tsx b/src/features/Channels/Composer.tsx
index 795973b60b2..8cf6854ca77 100644
--- a/src/features/Channels/Composer.tsx
+++ b/src/features/Channels/Composer.tsx
@@ -357,7 +357,7 @@ export function Composer({
label: String(option.label),
metadata: option.metadata,
});
- // Choosing someone outside the Channel brings them in right away.
+ // Choosing someone outside the Channel asks, then brings them in right away.
if (option.metadata?.type === 'channel-invite')
invites.invite(option.metadata as ChannelMentionInvite);
// Leave the decorator's cursor node before the next @ is typed.
diff --git a/src/features/Channels/CreateChannel/MemberSelection.tsx b/src/features/Channels/CreateChannel/MemberSelection.tsx
index 454ab2f2d60..88d0fc0446c 100644
--- a/src/features/Channels/CreateChannel/MemberSelection.tsx
+++ b/src/features/Channels/CreateChannel/MemberSelection.tsx
@@ -41,16 +41,18 @@ const SectionTitle = ({ children }: { children: string }) => (
const AgentOptionRow = ({
agent,
checked,
+ disabled,
fallback,
onToggle,
}: {
agent: ChannelAgentOption;
checked: boolean;
+ disabled?: boolean;
fallback: string;
onToggle: () => void;
}) => (
- <label {...stylex.props(styles.row)}>
- <Checkbox checked={checked} onChange={onToggle} />
+ <label {...stylex.props(styles.row)} aria-disabled={disabled || undefined}>
+ <Checkbox checked={checked} disabled={disabled} onChange={onToggle} />
<AgentAvatar
agentId={agent.id}
avatar={typeof agent.avatar === 'string' ? agent.avatar : undefined}
@@ -85,7 +87,7 @@ export const MemberSelection = ({
value: ChannelAgentDraft[];
}) => {
const { t } = useTranslation(['channel', 'device', 'chat', 'common']);
- const { agents, projectAgentIds = [] } = options;
+ const { agents, project, projectAgentIds = [] } = options;
const [search, setSearch] = useState('');
const available = (agents ?? []).filter((agent) => !exclude.includes(agent.id));
const filtered = available.filter((agent) =>
@@ -94,17 +96,32 @@ export const MemberSelection = ({
.includes(search.trim().toLocaleLowerCase()),
);
// Inside a project its own team comes first, so a project Channel starts from the project.
- const { others, priority } = splitByPriority(filtered, projectAgentIds);
+ // A project Channel seats only the project's Agents; anyone else joins the project too, which
+ // takes the right to manage its members, so without it they are listed but cannot be picked.
+ const { others, priority } = splitByPriority(
+ filtered,
+ project ? project.memberIds : projectAgentIds,
+ );
+ const outsideLocked = !!project && !project.canAddAgents;
+ const showOthersTitle = project
+ ? others.length > 0
+ : !!people || (priority.length > 0 && others.length > 0);
+ const othersTitle = project
+ ? 'invite.outsideProject'
+ : priority.length
+ ? 'otherAgents'
+ : 'agents';
const toggle = (agentId: string) =>
onChange((current) =>
current.some((item) => item.agentId === agentId)
? current.filter((item) => item.agentId !== agentId)
: [...current, { agentId, initialized: false, issue: 'configurationLoading' }],
);
- const renderAgent = (agent: ChannelAgentOption) => (
+ const renderAgent = (agent: ChannelAgentOption, disabled?: boolean) => (
<AgentOptionRow
agent={agent}
checked={value.some((item) => item.agentId === agent.id)}
+ disabled={disabled}
fallback={t('unnamedAgent')}
key={agent.id}
onToggle={() => toggle(agent.id)}
@@ -139,15 +156,18 @@ export const MemberSelection = ({
{priority.length > 0 && (
<Flexbox gap={2}>
<SectionTitle>{t('projectAgents')}</SectionTitle>
- {priority.map(renderAgent)}
+ {priority.map((agent) => renderAgent(agent))}
</Flexbox>
)}
<Flexbox gap={2}>
- {(people || (priority.length > 0 && others.length > 0)) && (
- <SectionTitle>{t(priority.length ? 'otherAgents' : 'agents')}</SectionTitle>
+ {showOthersTitle && <SectionTitle>{t(othersTitle)}</SectionTitle>}
+ {outsideLocked && others.length > 0 && (
+ <Text fontSize={12} type="secondary" {...stylex.props(styles.section)}>
+ {t('invite.outsideProjectLocked')}
+ </Text>
)}
{others.length ? (
- others.map(renderAgent)
+ others.map((agent) => renderAgent(agent, outsideLocked))
) : priority.length ? null : people?.channelId ? (
<Text fontSize={12} type="secondary" {...stylex.props(styles.section)}>
{t(search.trim() ? 'invite.noAgentMatches' : 'invite.noAgents')}
diff --git a/src/features/Channels/CreateChannel/index.tsx b/src/features/Channels/CreateChannel/index.tsx
index 25cab6c4650..d654fd76ed9 100644
--- a/src/features/Channels/CreateChannel/index.tsx
+++ b/src/features/Channels/CreateChannel/index.tsx
@@ -27,6 +27,8 @@ interface ExistingChannel {
*/
directAgentName?: string;
id: string;
+ /** The project a project Channel belongs to: it seats only that project's Agents. */
+ projectId: string | null;
/** People can be invited only into workspace Channels. */
workspaceId: string | null;
}
@@ -67,7 +69,7 @@ function CreateChannel({ existing, onCreated, projectId }: CreateChannelProps) {
const [people, setPeople] = useState<ChannelPersonOption[]>([]);
const [busy, setBusy] = useState(false);
const [error, setError] = useState<unknown>();
- const options = useChannelAgentOptions(existing ? undefined : projectId);
+ const options = useChannelAgentOptions((existing ? existing.projectId : projectId) ?? undefined);
const direct = existing?.directAgentName !== undefined;
const nameOf = usePersonName();
const activeWorkspaceId = useActiveWorkspaceId();
@@ -98,6 +100,10 @@ function CreateChannel({ existing, onCreated, projectId }: CreateChannelProps) {
},
CHANNEL_LIMITS.titleLength,
) || t('autoTitle.empty');
+ // Agents from outside the project join it first; say so before anyone submits.
+ const joiningProject = options.project
+ ? agentNames.filter((_, index) => !options.project!.memberIds.includes(agents[index].agentId))
+ : [];
const canSubmit = canSubmitChannelMembers(agents, {
creating: !existing,
people: people.length,
@@ -127,6 +133,8 @@ function CreateChannel({ existing, onCreated, projectId }: CreateChannelProps) {
} else {
const id = await channelActions.create({
agents: selections,
+ // The notice above the buttons names who joins the project.
+ joinProject: true,
projectId,
title: title.trim() || autoTitle,
userIds: people.map((person) => person.userId),
@@ -179,6 +187,18 @@ function CreateChannel({ existing, onCreated, projectId }: CreateChannelProps) {
/>
</Flexbox>
)}
+ {joiningProject.length > 0 && (
+ <Text fontSize={12} type="secondary">
+ {options.project?.name
+ ? t('invite.joinProjectNotice', {
+ names: joiningProject.join(t('autoTitle.separator')),
+ project: options.project.name,
+ })
+ : t('invite.joinProjectNoticeUnnamed', {
+ names: joiningProject.join(t('autoTitle.separator')),
+ })}
+ </Text>
+ )}
{error !== undefined && (
<AsyncError error={error} title={t(getChannelSaveErrorKey(error))} variant="inline" />
)}
diff --git a/src/features/Channels/CreateChannel/projectAgentOrder.ts b/src/features/Channels/CreateChannel/projectAgentOrder.ts
index 9bb8e29f373..bf245ba8cf2 100644
--- a/src/features/Channels/CreateChannel/projectAgentOrder.ts
+++ b/src/features/Channels/CreateChannel/projectAgentOrder.ts
@@ -14,6 +14,19 @@ export const projectAgentIds = (detail?: Pick<ProjectDetail, 'agents' | 'project
return mainAgentId ? [mainAgentId, ...members] : members;
};
+/**
+ * Every Agent that already belongs to the project, enabled or not: a project Channel seats only
+ * these, and anyone else joins the project first.
+ */
+export const projectMemberAgentIds = (
+ detail?: Pick<ProjectDetail, 'agents' | 'project'>,
+): string[] => {
+ if (!detail) return [];
+ const mainAgentId = detail.project.coordinatorAgentId;
+ const members = (detail.agents ?? []).map(({ agent }) => agent.id);
+ return mainAgentId ? [mainAgentId, ...members.filter((id) => id !== mainAgentId)] : members;
+};
+
/**
* Splits picker candidates into the project's Agents (in `priorityIds` order) and everyone
* else (in their original order), so a project Channel starts from its own team.
diff --git a/src/features/Channels/CreateChannel/useChannelAgentOptions.ts b/src/features/Channels/CreateChannel/useChannelAgentOptions.ts
index 953cd955d2b..b042f53af75 100644
--- a/src/features/Channels/CreateChannel/useChannelAgentOptions.ts
+++ b/src/features/Channels/CreateChannel/useChannelAgentOptions.ts
@@ -7,7 +7,7 @@ import { useProjectStore } from '@/store/project';
import { useUserStore } from '@/store/user';
import { authSelectors } from '@/store/user/selectors';
-import { projectAgentIds } from './projectAgentOrder';
+import { projectAgentIds, projectMemberAgentIds } from './projectAgentOrder';
export interface ChannelAgentOption extends SidebarAgentItem {
/** External runtime label source; `undefined` for a Native Agent. */
@@ -21,30 +21,38 @@ const agentRuntime = (agent: SidebarAgentItem) =>
undefined;
/**
- * The project's own Agents, ranked for the picker. The project sidebar has usually loaded the
- * detail under its route slug already, so reuse it by id before fetching.
+ * The project's own Agents: ranked for the picker, all of its members, and whether the caller may
+ * add another one. The project sidebar has usually loaded the detail under its route slug
+ * already, so reuse it by id before fetching.
*/
-const useProjectAgentIds = (projectId?: string) => {
+const useProjectAgents = (projectId?: string) => {
const detail = useProjectStore((s) =>
projectId
? Object.values(s.projectDetailMap).find((item) => item?.project.id === projectId)
: undefined,
);
useProjectStore((s) => s.useFetchProjectDetail)(projectId && !detail ? projectId : undefined);
- return projectAgentIds(detail);
+ return {
+ canAddToProject: detail?.permissions?.canManageMembers ?? false,
+ memberIds: projectMemberAgentIds(detail),
+ priorityIds: projectAgentIds(detail),
+ projectName: detail?.project.name,
+ };
};
/**
* Every Agent the user can add, from the full sidebar list rather than the recent
* delegation targets, so older Agents stay reachable. Lobe AI cannot join a Channel.
- * Inside a project, `projectAgentIds` names the project's Agents to list first.
+ * Inside a project, `projectAgentIds` names the project's Agents to list first, and `project`
+ * says which Agents are already its members: a project Channel seats only those, so picking
+ * anyone else adds them to the project too.
*/
export const useChannelAgentOptions = (projectId?: string) => {
const isLogin = useUserStore(authSelectors.isLogin);
const sync = useHomeStore((s) => s.useFetchAgentList)(isLogin);
const ready = useHomeStore(homeAgentListSelectors.isAgentListInit);
const items = useHomeStore(homeAgentListSelectors.allAgents);
- const priorityIds = useProjectAgentIds(projectId);
+ const project = useProjectAgents(projectId);
const agents: ChannelAgentOption[] | undefined = ready
? items
.filter((item) => item.type === 'agent' && item.slug !== INBOX_SESSION_ID)
@@ -53,7 +61,14 @@ export const useChannelAgentOptions = (projectId?: string) => {
return {
agents,
error: sync.error,
- projectAgentIds: priorityIds,
+ project: projectId
+ ? {
+ canAddAgents: project.canAddToProject,
+ memberIds: project.memberIds,
+ name: project.projectName,
+ }
+ : undefined,
+ projectAgentIds: project.priorityIds,
retry: () => void sync.revalidate(),
};
};
diff --git a/src/features/Channels/MemberList.tsx b/src/features/Channels/MemberList.tsx
index a431b458018..b910ba79198 100644
--- a/src/features/Channels/MemberList.tsx
+++ b/src/features/Channels/MemberList.tsx
@@ -2,19 +2,23 @@ import type { ChannelDetail, ChannelPublicMember } from '@lobechat/types';
import type { DropdownItem } from '@lobehub/ui';
import { ActionIcon, DropdownMenu, Flexbox, Icon, Spin, Text } from '@lobehub/ui';
import * as stylex from '@stylexjs/stylex';
-import { ExternalLink, FolderCog, MoreHorizontal } from 'lucide-react';
+import { ExternalLink, FolderCog, MoreHorizontal, UserMinus } from 'lucide-react';
import { useTranslation } from 'react-i18next';
import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
+import { useUserStore } from '@/store/user';
+import { userProfileSelectors } from '@/store/user/selectors';
import { openChannelAgentEnvironment } from './AgentEnvironment';
import { ChannelStatus } from './ChannelStatus';
import type { ChannelStatusTone } from './jobStatus';
import { channelJobTone, memberCurrentJob, memberJobStatus } from './jobStatus';
import { MemberAvatar } from './MemberAvatar';
-import { memberName } from './memberName';
+import { callerMemberRole, canRemoveMember } from './memberManagement';
+import { isCurrentUserMember, memberName } from './memberName';
import { MemberProfileTrigger } from './MemberProfileTrigger';
import { statusStyles, styles, toneStyles } from './styles';
+import { useRemoveMember } from './useMemberActions';
import { getVisibleStatusMembers, groupMembersByActor } from './visibleMembers';
interface MemberEntry {
@@ -77,10 +81,20 @@ interface MemberRowProps {
entry: MemberEntry;
manageable: boolean;
onAction?: () => void;
+ onRemove: () => void;
+ removable: boolean;
showDescription?: boolean;
}
-const MemberRow = ({ channelId, entry, manageable, onAction, showDescription }: MemberRowProps) => {
+const MemberRow = ({
+ channelId,
+ entry,
+ manageable,
+ onAction,
+ onRemove,
+ removable,
+ showDescription,
+}: MemberRowProps) => {
const { t } = useTranslation('channel');
const navigate = useWorkspaceAwareNavigate();
const isAgent = entry.member.actorType === 'agent';
@@ -106,6 +120,17 @@ const MemberRow = ({ channelId, entry, manageable, onAction, showDescription }:
navigate(`/agent/${agentId}`);
},
});
+ if (removable)
+ menuItems.push({
+ danger: true,
+ icon: <Icon icon={UserMinus} />,
+ key: 'remove',
+ label: t('member.remove'),
+ onClick: () => {
+ onAction?.();
+ onRemove();
+ },
+ });
return (
<Flexbox
@@ -168,6 +193,9 @@ export function MemberList({
const entries = useMemberEntries(detail);
const { channel } = detail;
const manageable = channel.canDelete && channel.status !== 'archived';
+ const userId = useUserStore(userProfileSelectors.userId);
+ const selfRole = callerMemberRole(detail.members, userId);
+ const removeMember = useRemoveMember();
const { agents, people } = groupMembersByActor(entries);
const renderRow = (entry: MemberEntry) => (
<MemberRow
@@ -176,7 +204,12 @@ export function MemberList({
key={entry.member.id}
manageable={manageable}
showDescription={showDescription}
+ removable={canRemoveMember(channel, entry.member, {
+ isSelf: isCurrentUserMember(entry.member, userId),
+ selfRole,
+ })}
onAction={onAction}
+ onRemove={() => removeMember(channel, entry.member, entry.name)}
/>
);
diff --git a/src/features/Channels/MemberStatus.tsx b/src/features/Channels/MemberStatus.tsx
index e04c49a6b0b..cb1b5151b05 100644
--- a/src/features/Channels/MemberStatus.tsx
+++ b/src/features/Channels/MemberStatus.tsx
@@ -186,6 +186,7 @@ export function MemberStatus({
),
directAgentName: channel.agentId ? (directAgent?.name ?? '') : undefined,
id: channel.id,
+ projectId: channel.projectId,
workspaceId: channel.workspaceId,
},
// Inviting from a direct conversation opens the group it starts.
diff --git a/src/features/Channels/Settings/MembersSection.tsx b/src/features/Channels/Settings/MembersSection.tsx
index a73042ad2e6..96747fc7cd5 100644
--- a/src/features/Channels/Settings/MembersSection.tsx
+++ b/src/features/Channels/Settings/MembersSection.tsx
@@ -28,6 +28,7 @@ export function MembersSection({ detail }: { detail: ChannelDetail }) {
member.status === 'active' && member.agentId ? [member.agentId] : [],
),
id: channel.id,
+ projectId: channel.projectId,
workspaceId: channel.workspaceId,
})
}
diff --git a/src/features/Channels/confirmInvite.test.ts b/src/features/Channels/confirmInvite.test.ts
new file mode 100644
index 00000000000..82091b39ea2
--- /dev/null
+++ b/src/features/Channels/confirmInvite.test.ts
@@ -0,0 +1,42 @@
+import { createModal } from '@lobehub/ui';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { confirmInvite } from './confirmInvite';
+
+vi.mock('@lobehub/ui', () => ({ createModal: vi.fn() }));
+
+type ModalOptions = {
+ content: { props: { onConfirm: () => void } };
+ onOpenChange?: (open: boolean) => void;
+ onOpenChangeComplete?: (open: boolean) => void;
+};
+
+const options = { cancelText: 'Cancel', content: 'Body', okText: 'Invite', title: 'Invite A?' };
+const lastModal = () => vi.mocked(createModal).mock.calls.at(-1)![0] as unknown as ModalOptions;
+
+describe('confirmInvite', () => {
+ beforeEach(() => {
+ vi.mocked(createModal).mockClear();
+ });
+
+ it('resolves true when confirmed, even after the dialog finishes closing', async () => {
+ const answer = confirmInvite(options);
+ const modal = lastModal();
+ modal.content.props.onConfirm();
+ modal.onOpenChangeComplete?.(false);
+ await expect(answer).resolves.toBe(true);
+ });
+
+ // Cancel closes through the modal context, which reports only the close completing.
+ it('resolves false once a dialog closed by Cancel finishes closing', async () => {
+ const answer = confirmInvite(options);
+ lastModal().onOpenChangeComplete?.(false);
+ await expect(Promise.race([answer, Promise.resolve('pending')])).resolves.toBe(false);
+ });
+
+ it('resolves false when dismissed with ✕, Esc or the mask', async () => {
+ const answer = confirmInvite(options);
+ lastModal().onOpenChange?.(false);
+ await expect(answer).resolves.toBe(false);
+ });
+});
diff --git a/src/features/Channels/confirmInvite.tsx b/src/features/Channels/confirmInvite.tsx
new file mode 100644
index 00000000000..1d2bc839dc3
--- /dev/null
+++ b/src/features/Channels/confirmInvite.tsx
@@ -0,0 +1,64 @@
+import { Button, createModal, Flexbox, Text, useModalContext } from '@lobehub/ui';
+import type { ReactNode } from 'react';
+
+interface ConfirmInviteOptions {
+ cancelText: string;
+ content: ReactNode;
+ okText: string;
+ title: string;
+}
+
+const ConfirmBody = ({
+ cancelText,
+ content,
+ okText,
+ onConfirm,
+}: Omit<ConfirmInviteOptions, 'title'> & { onConfirm: () => void }) => {
+ const { close } = useModalContext();
+ return (
+ <Flexbox gap={16}>
+ <Text type="secondary">{content}</Text>
+ <Flexbox horizontal gap={8} justify="flex-end">
+ <Button onClick={close}>{cancelText}</Button>
+ <Button
+ autoFocus
+ type="primary"
+ onClick={() => {
+ onConfirm();
+ close();
+ }}
+ >
+ {okText}
+ </Button>
+ </Flexbox>
+ </Flexbox>
+ );
+};
+
+/**
+ * Asks before someone outside the Channel is brought in. Resolves false however the dialog
+ * closes without confirming (Cancel, ✕, Esc or the mask), so a waiting send never hangs. Cancel
+ * closes through the modal context, which does not report `onOpenChange`; the close completing
+ * does, whatever closed it.
+ */
+export const confirmInvite = ({ title, ...body }: ConfirmInviteOptions) =>
+ new Promise<boolean>((resolve) => {
+ let settled = false;
+ const settle = (confirmed: boolean) => {
+ if (settled) return;
+ settled = true;
+ resolve(confirmed);
+ };
+ createModal({
+ content: <ConfirmBody {...body} onConfirm={() => settle(true)} />,
+ footer: null,
+ title,
+ width: 420,
+ onOpenChange: (open) => {
+ if (!open) settle(false);
+ },
+ onOpenChangeComplete: (open) => {
+ if (!open) settle(false);
+ },
+ });
+ });
diff --git a/src/features/Channels/joinEvents.test.ts b/src/features/Channels/joinEvents.test.ts
index 69fa7f1f7d3..54bb535fe47 100644
--- a/src/features/Channels/joinEvents.test.ts
+++ b/src/features/Channels/joinEvents.test.ts
@@ -1,7 +1,7 @@
import type { ChannelPublicMember, ChannelPublicMessage } from '@lobechat/types';
import { describe, expect, it } from 'vitest';
-import { channelJoinEvents, channelTimeline } from './joinEvents';
+import { channelJoinEvents, channelTimeline, isSelfJoinable } from './joinEvents';
const member = (id: string, joinedAt: number, patch: Partial<ChannelPublicMember> = {}) =>
({
@@ -30,6 +30,22 @@ describe('channelJoinEvents', () => {
expect(events.every((event) => event.inviter === owner)).toBe(true);
});
+ it('names no inviter where people join by themselves', () => {
+ const [event] = channelJoinEvents([owner, member('a', 60_000, { actorType: 'user' })], {
+ selfJoinable: true,
+ });
+ expect(event.inviter).toBeUndefined();
+ });
+
+ it.each([
+ [{ projectId: 'prj_1', visibility: 'private', workspaceId: 'ws' }, true],
+ [{ projectId: null, visibility: 'public', workspaceId: 'ws' }, true],
+ [{ projectId: null, visibility: 'private', workspaceId: 'ws' }, false],
+ [{ projectId: 'prj_1', visibility: 'private', workspaceId: null }, false],
+ ] as const)('tells which Channels take self-joins: %o → %s', (channel, expected) => {
+ expect(isSelfJoinable(channel)).toBe(expected);
+ });
+
it('does not guess the inviter when an admin could have added members', () => {
const [event] = channelJoinEvents([
owner,
diff --git a/src/features/Channels/joinEvents.ts b/src/features/Channels/joinEvents.ts
index ece8a8f76cf..4d1245af3b0 100644
--- a/src/features/Channels/joinEvents.ts
+++ b/src/features/Channels/joinEvents.ts
@@ -1,4 +1,4 @@
-import type { ChannelPublicMember, ChannelPublicMessage } from '@lobechat/types';
+import type { ChannelListItem, ChannelPublicMember, ChannelPublicMessage } from '@lobechat/types';
/** Members added by one action land within this window and read as one line. */
const BATCH_MS = 5000;
@@ -8,7 +8,8 @@ export interface ChannelJoinEvent {
id: string;
/**
* Only owners and admins add members. With no admin besides the owner, the owner added
- * everyone else; otherwise the adder is unknown and the line says who joined.
+ * everyone else; otherwise the adder is unknown and the line says who joined. A Channel people
+ * can join on their own (see {@link isSelfJoinable}) never names an inviter.
*/
inviter?: ChannelPublicMember;
members: ChannelPublicMember[];
@@ -16,9 +17,18 @@ export interface ChannelJoinEvent {
const time = (value: Date | string) => new Date(value).getTime();
-export const channelJoinEvents = (members: ChannelPublicMember[]): ChannelJoinEvent[] => {
+/** A workspace project's Channels and public Channels take members who join by themselves. */
+export const isSelfJoinable = (
+ channel: Pick<ChannelListItem, 'projectId' | 'visibility' | 'workspaceId'>,
+) => !!channel.workspaceId && (!!channel.projectId || channel.visibility === 'public');
+
+export const channelJoinEvents = (
+ members: ChannelPublicMember[],
+ { selfJoinable = false }: { selfJoinable?: boolean } = {},
+): ChannelJoinEvent[] => {
const owner = members.find((member) => member.role === 'owner');
- const inviter = members.some((member) => member.role === 'admin') ? undefined : owner;
+ const inviter =
+ selfJoinable || members.some((member) => member.role === 'admin') ? undefined : owner;
const joined = members
.filter((member) => member !== owner)
.sort((a, b) => time(a.joinedAt) - time(b.joinedAt));
diff --git a/src/features/Channels/memberManagement.test.ts b/src/features/Channels/memberManagement.test.ts
new file mode 100644
index 00000000000..0c00d1ea9f2
--- /dev/null
+++ b/src/features/Channels/memberManagement.test.ts
@@ -0,0 +1,77 @@
+import { describe, expect, it } from 'vitest';
+
+import { callerMemberRole, canLeaveChannel, canRemoveMember } from './memberManagement';
+
+const group = {
+ agentId: null,
+ canDelete: true,
+ joined: true,
+ memberRole: 'admin' as const,
+ peerUserId: null,
+ status: 'active' as const,
+};
+const agent = { role: null, status: 'active' as const };
+
+describe('canRemoveMember', () => {
+ it('lets an admin remove an Agent or a member of a group Channel', () => {
+ expect(canRemoveMember(group, agent, { isSelf: false, selfRole: 'admin' })).toBe(true);
+ expect(
+ canRemoveMember(
+ group,
+ { role: 'member', status: 'active' },
+ { isSelf: false, selfRole: 'admin' },
+ ),
+ ).toBe(true);
+ });
+
+ it('never removes the owner, the caller, or someone already gone', () => {
+ const options = { isSelf: false, selfRole: 'owner' as const };
+ expect(canRemoveMember(group, { role: 'owner', status: 'active' }, options)).toBe(false);
+ expect(canRemoveMember(group, { role: 'member', status: 'left' }, options)).toBe(false);
+ expect(
+ canRemoveMember(group, { role: 'member', status: 'active' }, { ...options, isSelf: true }),
+ ).toBe(false);
+ });
+
+ it('leaves another admin to the owner', () => {
+ const admin = { role: 'admin' as const, status: 'active' as const };
+ expect(canRemoveMember(group, admin, { isSelf: false, selfRole: 'admin' })).toBe(false);
+ expect(canRemoveMember(group, admin, { isSelf: false, selfRole: 'owner' })).toBe(true);
+ });
+
+ it('keeps direct conversations and non-admins out', () => {
+ const options = { isSelf: false, selfRole: 'admin' as const };
+ expect(canRemoveMember({ ...group, agentId: 'agt_1' }, agent, options)).toBe(false);
+ expect(canRemoveMember({ ...group, peerUserId: 'user_2' }, agent, options)).toBe(false);
+ expect(canRemoveMember({ ...group, canDelete: false }, agent, options)).toBe(false);
+ });
+});
+
+describe('canLeaveChannel', () => {
+ it('lets anyone but the owner leave a group Channel they joined', () => {
+ expect(canLeaveChannel(group)).toBe(true);
+ expect(canLeaveChannel({ ...group, memberRole: 'member', status: 'archived' })).toBe(true);
+ expect(canLeaveChannel({ ...group, memberRole: 'owner' })).toBe(false);
+ expect(canLeaveChannel({ ...group, joined: false, memberRole: null })).toBe(false);
+ expect(canLeaveChannel({ ...group, agentId: 'agt_1' })).toBe(false);
+ });
+});
+
+describe('callerMemberRole', () => {
+ const members = [
+ { actorType: 'user' as const, role: 'owner' as const, userId: 'u1' },
+ { actorType: 'agent' as const, role: null, userId: null },
+ { actorType: 'user' as const, role: 'member' as const, userId: 'u2' },
+ ];
+
+ it("finds the caller's role among the people in the Channel", () => {
+ expect(callerMemberRole(members, 'u2')).toBe('member');
+ expect(callerMemberRole(members, 'u1')).toBe('owner');
+ });
+
+ it('is undefined for a non-member, no user, or no member list', () => {
+ expect(callerMemberRole(members, 'u3')).toBeUndefined();
+ expect(callerMemberRole(members, undefined)).toBeUndefined();
+ expect(callerMemberRole(undefined, 'u1')).toBeUndefined();
+ });
+});
diff --git a/src/features/Channels/memberManagement.ts b/src/features/Channels/memberManagement.ts
new file mode 100644
index 00000000000..e89c92c9de5
--- /dev/null
+++ b/src/features/Channels/memberManagement.ts
@@ -0,0 +1,40 @@
+import type { ChannelListItem, ChannelMemberRole, ChannelPublicMember } from '@lobechat/types';
+
+import { isCurrentUserMember } from './memberName';
+
+type GroupChannel = Pick<
+ ChannelListItem,
+ 'agentId' | 'canDelete' | 'joined' | 'memberRole' | 'peerUserId' | 'status'
+>;
+
+/** A direct or person-to-person conversation is defined by its two sides; no one joins or leaves. */
+const isGroup = (channel: GroupChannel) => !channel.agentId && !channel.peerUserId;
+
+/**
+ * Whether the caller may remove `member`: an admin of a group Channel, never the owner or
+ * themselves, and only the owner removes another admin. The server enforces the same rule.
+ */
+export const canRemoveMember = (
+ channel: GroupChannel,
+ member: Pick<ChannelPublicMember, 'role' | 'status'>,
+ options: { isSelf: boolean; selfRole: ChannelMemberRole | null | undefined },
+) =>
+ isGroup(channel) &&
+ channel.canDelete &&
+ member.status === 'active' &&
+ !options.isSelf &&
+ member.role !== 'owner' &&
+ (member.role !== 'admin' || options.selfRole === 'owner');
+
+/** Everyone in a group Channel but its owner may leave it, archived or not. */
+export const canLeaveChannel = (channel: GroupChannel) =>
+ isGroup(channel) &&
+ channel.joined !== false &&
+ !!channel.memberRole &&
+ channel.memberRole !== 'owner';
+
+/** The caller's role among a Channel's members; undefined when they are not one of them. */
+export const callerMemberRole = (
+ members: Pick<ChannelPublicMember, 'actorType' | 'role' | 'userId'>[] | undefined,
+ userId: string | undefined,
+) => members?.find((member) => isCurrentUserMember(member, userId))?.role;
diff --git a/src/features/Channels/useChannelMenu.ts b/src/features/Channels/useChannelMenu.ts
index 610a5b1226f..c2fe2f6eddd 100644
--- a/src/features/Channels/useChannelMenu.ts
+++ b/src/features/Channels/useChannelMenu.ts
@@ -1,21 +1,26 @@
import type { ChannelListItem } from '@lobechat/types';
import { CHANNEL_LIMITS } from '@lobechat/types';
import { copyToClipboard, toast } from '@lobehub/ui';
-import { Archive, ArchiveRestore, Copy, PencilLine, Trash } from 'lucide-react';
+import { Archive, ArchiveRestore, Copy, LogOut, PencilLine, Trash } from 'lucide-react';
import { useTranslation } from 'react-i18next';
import { openRenameModal } from '@/components/RenameModal';
import { channelActions } from '@/store/channel';
import { isTrpcErrorCode } from '@/utils/trpcError';
+import { canLeaveChannel } from './memberManagement';
import { useChannelArchive } from './useChannelArchive';
+import { useLeaveChannel } from './useMemberActions';
import { useRemoveChannel } from './useRemoveChannel';
-/** A Channel's menu wherever it is listed: rename, copy id, archive, and move to the trash. */
+/**
+ * A Channel's menu wherever it is listed: rename, copy id, archive, leave, and move to the trash.
+ */
export const useChannelMenu = () => {
const { t } = useTranslation('channel');
const remove = useRemoveChannel();
const { archive, unarchive } = useChannelArchive();
+ const leave = useLeaveChannel();
const rename = (channel: ChannelListItem) =>
openRenameModal({
@@ -51,6 +56,12 @@ export const useChannelMenu = () => {
}
},
},
+ ...(canLeaveChannel(channel)
+ ? [
+ { type: 'divider' as const },
+ { icon: LogOut, key: 'leave', label: t('leave'), onClick: () => leave(channel) },
+ ]
+ : []),
...(channel.canDelete
? [
channel.status === 'archived'
diff --git a/src/features/Channels/useMemberActions.ts b/src/features/Channels/useMemberActions.ts
new file mode 100644
index 00000000000..3b11e9b4f1d
--- /dev/null
+++ b/src/features/Channels/useMemberActions.ts
@@ -0,0 +1,88 @@
+import type { ChannelListItem, ChannelPublicMember } from '@lobechat/types';
+import { confirmModal, toast } from '@lobehub/ui';
+import { useLatest } from 'ahooks';
+import { useTranslation } from 'react-i18next';
+
+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
+import { useActiveLocation } from '@/hooks/useActiveLocation';
+import { cacheScope } from '@/libs/replica';
+import { channelActions } from '@/store/channel';
+
+import { matchChannel } from './paths';
+
+/** Confirms, then removes a person or an Agent from a group Channel. */
+export const useRemoveMember = () => {
+ const { t } = useTranslation('channel');
+ return (
+ channel: Pick<ChannelListItem, 'id' | 'projectId'>,
+ member: ChannelPublicMember,
+ name: string,
+ ) => {
+ const scope = cacheScope.get();
+ return confirmModal({
+ cancelText: t('cancel'),
+ content: t(
+ member.actorType === 'user'
+ ? 'member.removeConfirmPerson'
+ : channel.projectId
+ ? 'member.removeConfirmAgent'
+ : 'member.removeConfirmAgentStandalone',
+ ),
+ okButtonProps: { danger: true },
+ okText: t('member.remove'),
+ title: t('member.removeConfirmTitle', { name }),
+ onOk: async () => {
+ try {
+ // A confirmation belongs to the identity that opened it.
+ if (cacheScope.get() !== scope) throw new Error('Channel scope changed');
+ await channelActions.removeMember(channel.id, member.id);
+ } catch (error) {
+ console.error('Failed to remove a Channel member', error);
+ toast.error(t('member.removeFailed', { name }));
+ throw error; // Keep the confirmation open so the user can retry or cancel.
+ }
+ },
+ });
+ };
+};
+
+/**
+ * Confirms, then leaves a group Channel. A Channel the caller can no longer read (outside a
+ * project, archived, or in a project they cannot see) returns its page home; an active open
+ * project Channel stays readable through its project.
+ */
+export const useLeaveChannel = () => {
+ const { t } = useTranslation('channel');
+ const location = useActiveLocation();
+ const navigate = useWorkspaceAwareNavigate();
+ const latest = useLatest({ location, navigate });
+
+ return (channel: Pick<ChannelListItem, 'id' | 'projectId' | 'status' | 'title'>) => {
+ const scope = cacheScope.get();
+ return confirmModal({
+ cancelText: t('cancel'),
+ // An archived project Channel takes no newcomers, so leaving it is final too.
+ content: t(
+ channel.projectId && channel.status === 'active' ? 'leaveConfirmProject' : 'leaveConfirm',
+ ),
+ okButtonProps: { danger: true },
+ okText: t('leave'),
+ title: t('leaveConfirmTitle', { title: channel.title }),
+ onOk: async () => {
+ let readable: boolean;
+ try {
+ if (cacheScope.get() !== scope) throw new Error('Channel scope changed');
+ readable = await channelActions.leave(channel);
+ } catch (error) {
+ console.error('Failed to leave Channel', error);
+ toast.error(t('leaveFailed'));
+ throw error;
+ }
+ if (cacheScope.get() !== scope) return;
+ if (!readable && matchChannel(latest.current.location.pathname) === channel.id)
+ latest.current.navigate('/', { replace: true });
+ toast.success(t('leaveSuccess'));
+ },
+ });
+ };
+};
diff --git a/src/features/Channels/useMentionInvites.test.ts b/src/features/Channels/useMentionInvites.test.ts
index 7f5fdebd512..7b0803f4f62 100644
--- a/src/features/Channels/useMentionInvites.test.ts
+++ b/src/features/Channels/useMentionInvites.test.ts
@@ -9,9 +9,15 @@ import { channelActions } from '@/store/channel';
import type { ChannelMentionInvite } from './mentions';
import { useMentionInvites } from './useMentionInvites';
-const { agentDraft } = vi.hoisted(() => ({
+const { agentDraft, agentOptions, confirmInvite } = vi.hoisted(() => ({
agentDraft: { issue: undefined as string | undefined },
+ agentOptions: {
+ project: undefined as
+ undefined | { canAddAgents: boolean; memberIds: string[]; name: string | undefined },
+ },
+ confirmInvite: vi.fn(),
}));
+vi.mock('./confirmInvite', () => ({ confirmInvite }));
vi.mock('react-i18next', () => ({
useTranslation: () => ({
t: (key: string, options?: Record<string, string>) =>
@@ -28,6 +34,7 @@ vi.mock('./CreateChannel/useChannelAgentOptions', () => ({
{ id: 'agt_project', title: 'Project writer' },
{ id: 'agt_joined', title: 'Joined writer' },
],
+ project: agentOptions.project,
projectAgentIds: ['agt_project'],
}),
}));
@@ -78,6 +85,8 @@ const setup = (current: ChannelListItem = channel, members = [joinedAgent]) => {
describe('@mentions that invite people and Agents from outside the Channel', () => {
beforeEach(() => {
agentDraft.issue = undefined;
+ agentOptions.project = undefined;
+ confirmInvite.mockResolvedValue(true);
vi.spyOn(console, 'error').mockImplementation(() => {});
vi.spyOn(channelService, 'userCandidates').mockResolvedValue([
{ avatar: null, fullName: 'Writer Lin', userId: 'user_lin', username: 'lin' },
@@ -179,7 +188,8 @@ describe('@mentions that invite people and Agents from outside the Channel', ()
it("adds an Agent with the invite dialog's environment defaults", async () => {
const { result, rerenderDrafts } = setup();
let resolved: Promise<string[] | undefined>;
- act(() => {
+ // The question is answered before the Agent's environment starts resolving.
+ await act(async () => {
resolved = result.current.resolve([target('agent', 'agt_writer')]);
});
rerenderDrafts();
@@ -193,7 +203,8 @@ describe('@mentions that invite people and Agents from outside the Channel', ()
agentDraft.issue = 'deviceOffline';
const { result, rerenderDrafts } = setup();
let resolved: Promise<string[] | undefined>;
- act(() => {
+ // The question is answered before the Agent's environment starts resolving.
+ await act(async () => {
resolved = result.current.resolve([target('agent', 'agt_writer')]);
});
rerenderDrafts();
@@ -210,7 +221,7 @@ describe('@mentions that invite people and Agents from outside the Channel', ()
agentDraft.issue = 'devicesLoading';
const { result, rerenderDrafts } = setup();
let resolved: Promise<string[] | undefined>;
- act(() => {
+ await act(async () => {
resolved = result.current.resolve([target('agent', 'agt_writer')]);
});
rerenderDrafts();
@@ -233,4 +244,58 @@ describe('@mentions that invite people and Agents from outside the Channel', ()
]);
expect(channelActions.addMember).toHaveBeenCalledTimes(2);
});
+
+ it('asks before bringing someone in, once per person', async () => {
+ const { result } = setup();
+ act(() => {
+ result.current.invite(target('user', 'user_lin'));
+ });
+ await expect(result.current.resolve([target('user', 'user_lin')])).resolves.toEqual([
+ 'mem_user_lin',
+ ]);
+ expect(confirmInvite).toHaveBeenCalledOnce();
+ expect(confirmInvite).toHaveBeenCalledWith(
+ expect.objectContaining({ content: 'mentionInvite.confirmPerson' }),
+ );
+ });
+
+ it('mentions someone the user declined to invite by name only, without adding them', async () => {
+ confirmInvite.mockResolvedValue(false);
+ const { result } = setup();
+ act(() => {
+ result.current.invite(target('user', 'user_lin'));
+ });
+ await expect(
+ result.current.resolve([target('user', 'user_lin'), target('agent', 'agt_joined')]),
+ ).resolves.toEqual(['mem_joined']);
+ // Sending does not ask again; only choosing them from the menu again does.
+ expect(confirmInvite).toHaveBeenCalledOnce();
+ expect(channelActions.addMember).not.toHaveBeenCalled();
+ expect(result.current.error).toBe('');
+ });
+
+ it('says an Agent from outside joins the project first', async () => {
+ agentOptions.project = { canAddAgents: true, memberIds: ['agt_project'], name: 'Apollo' };
+ const { result, rerenderDrafts } = setup({ ...channel, projectId: 'pro_1' });
+ let resolved: Promise<string[] | undefined>;
+ await act(async () => {
+ resolved = result.current.resolve([target('agent', 'agt_writer')]);
+ });
+ rerenderDrafts();
+ await expect(resolved!).resolves.toEqual(['mem_agt_writer']);
+ expect(confirmInvite).toHaveBeenCalledWith(
+ expect.objectContaining({
+ content: `mentionInvite.confirmAgentProject ${JSON.stringify({ project: 'Apollo' })}`,
+ }),
+ );
+ });
+
+ it('offers only the project’s Agents to someone who cannot add Agents to the project', async () => {
+ agentOptions.project = { canAddAgents: false, memberIds: ['agt_project'], name: 'Apollo' };
+ const { result } = setup({ ...channel, projectId: 'pro_1' });
+ const options = await result.current.options('writer');
+ expect(
+ options.filter((option) => option.metadata.actorType === 'agent').map((o) => o.metadata.id),
+ ).toEqual(['agt_project']);
+ });
});
diff --git a/src/features/Channels/useMentionInvites.tsx b/src/features/Channels/useMentionInvites.tsx
index b7adb6e4cd7..e7135c55c2b 100644
--- a/src/features/Channels/useMentionInvites.tsx
+++ b/src/features/Channels/useMentionInvites.tsx
@@ -17,6 +17,7 @@ import type { DeviceListResult } from '@/store/device/useDeviceList';
import { useDeviceList } from '@/store/device/useDeviceList';
import { canInviteMembers } from './channelAccess';
+import { confirmInvite } from './confirmInvite';
import type { ChannelAgentDraft, ChannelAgentIssue } from './CreateChannel/agentEnvironment';
import { channelAgentIssueKey, toChannelAgentSelection } from './CreateChannel/agentEnvironment';
import { getChannelSaveErrorKey } from './CreateChannel/saveError';
@@ -40,6 +41,9 @@ class AgentIssueError extends Error {
}
}
+/** The user chose not to bring someone in; their mention stays plain text. */
+class InviteDeclinedError extends Error {}
+
const inviteKey = ({ actorType, id }: Pick<ChannelMentionInvite, 'actorType' | 'id'>) =>
`${actorType}:${id}`;
@@ -104,6 +108,8 @@ export const useMentionInvites = (
// The editor keeps the mention callbacks it was first given, so they read the latest render.
const latest = useLatest({ agentOptions, channel, enabled, members });
const running = useSingleton(() => new Map<string, Promise<string | undefined>>());
+ // Sending does not ask again about someone the user already answered for from the menu.
+ const answers = useSingleton(() => new Map<string, Promise<boolean>>());
const people = useSingleton(() => new Map<string, Promise<ChannelPersonOption[]>>());
const latestQuery = useRef('');
const agentWaiters = useSingleton(
@@ -175,7 +181,13 @@ export const useMentionInvites = (
const { agentOptions, channel, enabled, members } = latest.current;
const search = query.trim();
if (!enabled || !channel || !search) return [];
- const agents = matchInviteAgents(agentOptions.agents ?? [], {
+ // Without the right to add Agents to the project, only its own Agents can be brought in.
+ const project = agentOptions.project;
+ const candidates =
+ project && !project.canAddAgents
+ ? (agentOptions.agents ?? []).filter((agent) => project.memberIds.includes(agent.id))
+ : (agentOptions.agents ?? []);
+ const agents = matchInviteAgents(candidates, {
exclude: members.flatMap((member) => (member.agentId ? [member.agentId] : [])),
nameOf: (agent) => agentDisplayName(agent, t('unnamedAgent')),
priorityIds: agentOptions.projectAgentIds,
@@ -238,6 +250,32 @@ export const useMentionInvites = (
];
};
+ /**
+ * Confirms bringing `target` in. An Agent from outside a project Channel's project joins the
+ * project first, and the question says so.
+ */
+ const ask = (target: ChannelMentionInvite) => {
+ const key = inviteKey(target);
+ const asked = answers.get(key);
+ if (asked) return asked;
+ const { agentOptions } = latest.current;
+ const project = agentOptions.project;
+ const content =
+ target.actorType === 'user'
+ ? t('mentionInvite.confirmPerson')
+ : project && !project.memberIds.includes(target.id)
+ ? t('mentionInvite.confirmAgentProject', { project: project.name ?? '' })
+ : t('mentionInvite.confirmAgent');
+ const answer = confirmInvite({
+ cancelText: t('cancel'),
+ content,
+ okText: t('mentionInvite.confirmOk'),
+ title: t('mentionInvite.confirmTitle', { name: target.name }),
+ });
+ answers.set(key, answer);
+ return answer;
+ };
+
/**
* The member `target` already is, or adds them once however often they are mentioned.
* Undefined where no one can be invited, such as a chip pasted into a direct conversation:
@@ -256,17 +294,22 @@ export const useMentionInvites = (
const pending = running.get(key);
if (pending) return pending;
setError('');
- const added = (
- target.actorType === 'user'
- ? channelActions.addMember(channel.id, { userId: target.id })
- : resolveAgent(target.id).then((agent) => channelActions.addMember(channel.id, { agent }))
- )
+ const added = ask(target)
+ .then((confirmed) => {
+ if (!confirmed) throw new InviteDeclinedError();
+ return target.actorType === 'user'
+ ? channelActions.addMember(channel.id, { userId: target.id })
+ : resolveAgent(target.id).then((agent) =>
+ channelActions.addMember(channel.id, { agent }),
+ );
+ })
.then((memberId) => {
// Searches cached before the invite would still list them as outside.
people.clear();
return memberId;
})
.catch((cause: unknown) => {
+ if (cause instanceof InviteDeclinedError) throw cause;
console.error('Failed to invite a mentioned member', cause);
const reasonKey =
cause instanceof AgentIssueError
@@ -286,12 +329,15 @@ export const useMentionInvites = (
/**
* Member ids for the outsiders a message mentions, waiting for invites still in flight and
- * retrying failed ones. Undefined when someone could not join; the error says who.
+ * retrying failed ones; someone the user declined to invite is left out. Undefined when
+ * someone could not join; the error says who.
*/
const resolve = async (targets: ChannelMentionInvite[]) => {
const results = await Promise.allSettled(targets.map(invite));
const ids: string[] = [];
for (const result of results) {
+ // Someone the user chose not to invite is mentioned by name only.
+ if (result.status === 'rejected' && result.reason instanceof InviteDeclinedError) continue;
if (result.status === 'rejected') return;
if (result.value) ids.push(result.value);
}
@@ -306,7 +352,11 @@ export const useMentionInvites = (
clearError: () => setError(''),
enabled,
error,
- invite: (target: ChannelMentionInvite) => void invite(target).catch(() => {}),
+ /** Choosing someone from the menu again is a new question, even after a no. */
+ invite: (target: ChannelMentionInvite) => {
+ answers.delete(inviteKey(target));
+ void invite(target).catch(() => {});
+ },
options,
resolve,
};
diff --git a/src/services/channel.ts b/src/services/channel.ts
index 43ae506e976..0bda62fc8cf 100644
--- a/src/services/channel.ts
+++ b/src/services/channel.ts
@@ -62,10 +62,15 @@ class ChannelService {
/** Without a Channel, the people a new Channel in the active workspace can start with. */
userCandidates = async (channelId: string | undefined, search: string) =>
(await lambdaClient.channel.userCandidates.query({ channelId, search })).data;
- addAgent = (channelId: string, agent: ChannelAgentSelection) =>
- lambdaClient.channel.addAgent.mutate({ agent, channelId });
+ /** In a project Channel, `joinProject` adds an Agent from outside to the project first. */
+ addAgent = (channelId: string, agent: ChannelAgentSelection, joinProject?: boolean) =>
+ lambdaClient.channel.addAgent.mutate({ agent, channelId, joinProject });
+ removeMember = (channelId: string, memberId: string) =>
+ lambdaClient.channel.removeMember.mutate({ channelId, memberId });
+ leave = (channelId: string) => lambdaClient.channel.leave.mutate({ channelId });
create = (input: {
agents: ChannelAgentSelection[];
+ joinProject?: boolean;
projectId?: string;
title: string;
userIds?: string[];
diff --git a/src/store/channel/action.test.ts b/src/store/channel/action.test.ts
index 53355622b2a..dff72f116e2 100644
--- a/src/store/channel/action.test.ts
+++ b/src/store/channel/action.test.ts
@@ -89,9 +89,12 @@ describe('channelActions after a committed write', () => {
channelActions.addMember('chn_000000000001', { agent: { agentId: 'agt_a' } }),
).resolves.toBe('mem_agent');
expect(channelService.addUser).toHaveBeenCalledExactlyOnceWith('chn_000000000001', 'user_b');
- expect(channelService.addAgent).toHaveBeenCalledExactlyOnceWith('chn_000000000001', {
- agentId: 'agt_a',
- });
+ // The mention confirmation already said whether the Agent joins the project.
+ expect(channelService.addAgent).toHaveBeenCalledExactlyOnceWith(
+ 'chn_000000000001',
+ { agentId: 'agt_a' },
+ true,
+ );
});
// One invite adds people and Agents together; people go first so a failing Agent
diff --git a/src/store/channel/action.ts b/src/store/channel/action.ts
index 51fa362352c..042c673e84e 100644
--- a/src/store/channel/action.ts
+++ b/src/store/channel/action.ts
@@ -1,4 +1,5 @@
import type {
+ ChannelListItem,
ChannelPublicThread,
ChannelStatus,
ChannelThreadStatus,
@@ -136,6 +137,32 @@ class ChannelActionImpl {
);
this.#private.entity.remove(channelId, { scope });
};
+ /**
+ * Leaves a group Channel. An active open project Channel stays readable through its project, so
+ * it only refreshes; any other Channel is gone for the caller, like a removed one. Resolves to
+ * whether the caller can still read it.
+ */
+ leave = async (channel: Pick<ChannelListItem, 'id'>) => {
+ const scope = cacheScope.get();
+ const { readable } = await channelService.leave(channel.id);
+ if (readable) {
+ await this.#refreshAfterWrite(() =>
+ Promise.all([this.refreshList(), this.refreshDetail({ channelId: channel.id })]),
+ );
+ return true;
+ }
+ await this.#refreshAfterWrite(this.refreshList);
+ this.#private.entity.remove(channel.id, { scope });
+ return false;
+ };
+ /** Removes a person or an Agent; an Agent's unfinished replies stop. */
+ removeMember = async (channelId: string, memberId: string) => {
+ try {
+ await channelService.removeMember(channelId, memberId);
+ } finally {
+ await this.#refreshAfterWrite(() => this.refreshDetail({ channelId }));
+ }
+ };
removeThread = async (channelId: string, threadId: string) => {
const scope = cacheScope.get();
// Optimistically hide sidebar references, retaining the open view until confirmed.
@@ -245,7 +272,8 @@ class ChannelActionImpl {
) => {
try {
for (const userId of userIds) await channelService.addUser(channelId, userId);
- for (const agent of agents) await channelService.addAgent(channelId, agent);
+ // The dialog shows which Agents also join the project, so choosing them is the consent.
+ for (const agent of agents) await channelService.addAgent(channelId, agent, true);
} finally {
// A partial failure still shows the members that did join.
await this.#refreshAfterWrite(() => this.refreshDetail({ channelId }));
@@ -262,7 +290,7 @@ class ChannelActionImpl {
const { data } =
'userId' in member
? await channelService.addUser(channelId, member.userId)
- : await channelService.addAgent(channelId, member.agent);
+ : await channelService.addAgent(channelId, member.agent, true);
await this.#refreshAfterWrite(() => this.refreshDetail({ channelId }));
return data.id;
};