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.

πŸ› fix: guard group rosters against demoted member agents (#17156)

Rdmclin2aa0e43d4e210
diff --git a/apps/server/src/routers/lambda/__tests__/agent.test.ts b/apps/server/src/routers/lambda/__tests__/agent.test.ts
index 7e32f86c2f0..3116989901c 100644
--- a/apps/server/src/routers/lambda/__tests__/agent.test.ts
+++ b/apps/server/src/routers/lambda/__tests__/agent.test.ts
@@ -4,6 +4,7 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';
import { INBOX_SESSION_ID } from '@/const/session';
import { DEFAULT_AGENT_CONFIG } from '@/const/settings';
import { AgentModel } from '@/database/models/agent';
+import { ChatGroupModel } from '@/database/models/chatGroup';
import { FileModel } from '@/database/models/file';
import { KnowledgeBaseModel } from '@/database/models/knowledgeBase';
import { SessionModel } from '@/database/models/session';
@@ -39,6 +40,10 @@ vi.mock('@/database/models/task', () => ({
TaskModel: vi.fn(),
}));
+vi.mock('@/database/models/chatGroup', () => ({
+ ChatGroupModel: vi.fn(),
+}));
+
vi.mock('@/database/models/file', () => ({
FileModel: vi.fn(),
}));
@@ -60,6 +65,7 @@ describe('agentRouter', () => {
let mockCtx: any;
let agentModelMock: any;
let taskModelMock: any;
+ let chatGroupModelMock: any;
let sessionModelMock: any;
let fileModelMock: any;
let knowledgeBaseModelMock: any;
@@ -87,6 +93,11 @@ describe('agentRouter', () => {
};
vi.mocked(TaskModel).mockImplementation(() => taskModelMock);
+ chatGroupModelMock = {
+ countGroupsBlockingAgentDemotion: vi.fn().mockResolvedValue(0),
+ };
+ vi.mocked(ChatGroupModel).mockImplementation(() => chatGroupModelMock);
+
sessionModelMock = {
findByIdOrSlug: vi.fn(),
};
@@ -396,6 +407,22 @@ describe('agentRouter', () => {
expect(agentModelMock.setVisibility).toHaveBeenCalledWith('agent-1', 'private');
});
+ it('rejects demotion while the agent supervises group chats visible to others (LOBE-11772)', async () => {
+ chatGroupModelMock.countGroupsBlockingAgentDemotion.mockResolvedValue(1);
+
+ const caller = agentRouter.createCaller(wsCtx());
+
+ await expect(
+ caller.setAgentVisibility({ id: 'agent-1', visibility: 'private' }),
+ ).rejects.toMatchObject({ code: 'BAD_REQUEST' });
+ // Compared against the agent owner (meta.userId), not just the caller.
+ expect(chatGroupModelMock.countGroupsBlockingAgentDemotion).toHaveBeenCalledWith(
+ 'agent-1',
+ userId,
+ );
+ expect(agentModelMock.setVisibility).not.toHaveBeenCalled();
+ });
+
it('rejects demotion of another member agent even for a workspace owner (LOBE-11760)', async () => {
agentModelMock.getAgentVisibilityMeta.mockResolvedValue({
slug: null,
diff --git a/apps/server/src/routers/lambda/agent.ts b/apps/server/src/routers/lambda/agent.ts
index 90ebd0a7a08..12422c297f0 100644
--- a/apps/server/src/routers/lambda/agent.ts
+++ b/apps/server/src/routers/lambda/agent.ts
@@ -186,6 +186,23 @@ export const agentRouter = router({
'Cannot make this agent private while workspace tasks still depend on it. Reassign those tasks or make them private first.',
});
}
+
+ // Same source-level guard for group chats, but only for the supervisor
+ // role: a private supervisor is unresolvable for every other viewer and
+ // bricks the whole group. Regular members are not blocked β€” roster
+ // reads drop a non-visible member per viewer instead (LOBE-11772).
+ const chatGroupModel = new ChatGroupModel(ctx.serverDB, ctx.userId, ctx.workspaceId);
+ const blockingGroups = await chatGroupModel.countGroupsBlockingAgentDemotion(
+ input.id,
+ meta.userId,
+ );
+ if (blockingGroups > 0) {
+ throw new TRPCError({
+ code: 'BAD_REQUEST',
+ message:
+ 'Cannot make this agent private while it supervises workspace group chats. Remove it as supervisor first.',
+ });
+ }
}
const updated = await ctx.agentModel.setVisibility(input.id, input.visibility);
diff --git a/packages/database/src/models/__tests__/chatGroup.test.ts b/packages/database/src/models/__tests__/chatGroup.test.ts
index 6374d19d18f..92c3d3f8920 100644
--- a/packages/database/src/models/__tests__/chatGroup.test.ts
+++ b/packages/database/src/models/__tests__/chatGroup.test.ts
@@ -401,6 +401,67 @@ describe('ChatGroupModel', () => {
});
});
+ describe('publishToWorkspace', () => {
+ it('publishes the private supervisor agent together with the group', async () => {
+ const ownerModel = new ChatGroupModel(serverDB, userId, workspaceId);
+
+ await serverDB.insert(chatGroups).values({
+ id: 'publish-group',
+ title: 'Publish group',
+ userId,
+ visibility: 'private',
+ workspaceId,
+ });
+ await serverDB.insert(agentsTable).values([
+ {
+ id: 'publish-supervisor',
+ title: 'Supervisor',
+ userId,
+ virtual: true,
+ visibility: 'private',
+ workspaceId,
+ },
+ {
+ id: 'publish-private-member',
+ title: 'Private member',
+ userId,
+ visibility: 'private',
+ workspaceId,
+ },
+ ]);
+ await serverDB.insert(chatGroupsAgents).values([
+ {
+ agentId: 'publish-supervisor',
+ chatGroupId: 'publish-group',
+ order: -1,
+ role: 'supervisor',
+ userId,
+ workspaceId,
+ },
+ {
+ agentId: 'publish-private-member',
+ chatGroupId: 'publish-group',
+ order: 0,
+ role: 'participant',
+ userId,
+ workspaceId,
+ },
+ ]);
+
+ const result = await ownerModel.publishToWorkspace('publish-group');
+ expect(result.visibility).toBe('public');
+
+ const rows = await serverDB
+ .select({ id: agentsTable.id, visibility: agentsTable.visibility })
+ .from(agentsTable);
+ const byId = Object.fromEntries(rows.map((r) => [r.id, r.visibility]));
+ // Supervisor visibility follows the group; a private member agent keeps
+ // its own visibility (its owner demoted/kept it private on purpose).
+ expect(byId['publish-supervisor']).toBe('public');
+ expect(byId['publish-private-member']).toBe('private');
+ });
+ });
+
describe('addAgentToGroup', () => {
it('should add agent to group', async () => {
// Create test data
@@ -1180,4 +1241,175 @@ describe('ChatGroupModel', () => {
expect(result.size).toBe(0);
});
});
+
+ describe('member agent demoted to private (LOBE-11772)', () => {
+ // Public workspace group owned by `userId` with two members: a public agent
+ // and an agent `userId` switched back to private after it joined. Viewer is
+ // `otherUserId` (same workspace) β€” every roster read must drop the private
+ // member for them, while the agent's owner keeps seeing it.
+ const ownerModel = new ChatGroupModel(serverDB, userId, workspaceId);
+
+ beforeEach(async () => {
+ await serverDB.insert(chatGroups).values({
+ id: 'demotion-group',
+ title: 'Demotion group',
+ userId,
+ visibility: 'public',
+ workspaceId,
+ });
+ await serverDB.insert(agentsTable).values([
+ {
+ avatar: '/pub.png',
+ id: 'agt-public-member',
+ title: 'Public member',
+ userId,
+ visibility: 'public',
+ workspaceId,
+ },
+ {
+ avatar: '/priv.png',
+ id: 'agt-demoted-member',
+ title: 'Demoted member',
+ userId,
+ visibility: 'private',
+ workspaceId,
+ },
+ ]);
+ await serverDB.insert(chatGroupsAgents).values([
+ {
+ agentId: 'agt-public-member',
+ chatGroupId: 'demotion-group',
+ enabled: true,
+ order: 0,
+ userId,
+ workspaceId,
+ },
+ {
+ agentId: 'agt-demoted-member',
+ chatGroupId: 'demotion-group',
+ enabled: true,
+ order: 1,
+ userId,
+ workspaceId,
+ },
+ ]);
+ });
+
+ it('drops the private member from every roster read for another member', async () => {
+ const [withDetails] = await workspaceChatGroupModel.queryWithMemberDetails();
+ expect(withDetails.agents.map((a: any) => a.id)).toEqual(['agt-public-member']);
+
+ const found = await workspaceChatGroupModel.findGroupWithAgents('demotion-group');
+ expect(found?.agents.map((a) => a.agentId)).toEqual(['agt-public-member']);
+
+ const groupAgents = await workspaceChatGroupModel.getGroupAgents('demotion-group');
+ expect(groupAgents.map((a) => a.agentId)).toEqual(['agt-public-member']);
+
+ const enabled = await workspaceChatGroupModel.getEnabledGroupAgents('demotion-group');
+ expect(enabled.map((a) => a.agentId)).toEqual(['agt-public-member']);
+
+ const withMeta = await workspaceChatGroupModel.getGroupAgentsWithMeta('demotion-group');
+ expect(withMeta.map((a) => a.agentId)).toEqual(['agt-public-member']);
+
+ const avatars = await workspaceChatGroupModel.getMemberAvatarsByGroupIds(['demotion-group']);
+ expect(avatars.get('demotion-group')).toEqual([
+ { avatar: '/pub.png', backgroundColor: null },
+ ]);
+ });
+
+ it('keeps the private member visible to its own owner', async () => {
+ const found = await ownerModel.findGroupWithAgents('demotion-group');
+ expect(found?.agents.map((a) => a.agentId)).toEqual([
+ 'agt-public-member',
+ 'agt-demoted-member',
+ ]);
+
+ const avatars = await ownerModel.getMemberAvatarsByGroupIds(['demotion-group']);
+ expect(avatars.get('demotion-group')).toHaveLength(2);
+ });
+
+ it('excludes groups reachable only through a non-visible member in getGroupsWithAgents', async () => {
+ const viaDemoted = await workspaceChatGroupModel.getGroupsWithAgents(['agt-demoted-member']);
+ expect(viaDemoted).toHaveLength(0);
+
+ const viaPublic = await workspaceChatGroupModel.getGroupsWithAgents(['agt-public-member']);
+ expect(viaPublic.map((g) => g.id)).toEqual(['demotion-group']);
+ });
+ });
+
+ describe('countGroupsBlockingAgentDemotion', () => {
+ const ownerModel = new ChatGroupModel(serverDB, userId, workspaceId);
+
+ const seedGroup = async (
+ groupId: string,
+ groupOwner: string,
+ visibility: 'private' | 'public',
+ role: string,
+ ) => {
+ await serverDB.insert(chatGroups).values({
+ id: groupId,
+ title: groupId,
+ userId: groupOwner,
+ visibility,
+ workspaceId,
+ });
+ await serverDB.insert(chatGroupsAgents).values({
+ agentId: 'agt-supervisor',
+ chatGroupId: groupId,
+ role,
+ userId: groupOwner,
+ workspaceId,
+ });
+ };
+
+ beforeEach(async () => {
+ await serverDB.insert(agentsTable).values({
+ id: 'agt-supervisor',
+ title: 'Supervisor agent',
+ userId,
+ visibility: 'public',
+ workspaceId,
+ });
+ });
+
+ it('blocks when the agent supervises a public group', async () => {
+ await seedGroup('public-supervised', userId, 'public', 'supervisor');
+
+ await expect(
+ ownerModel.countGroupsBlockingAgentDemotion('agt-supervisor', userId),
+ ).resolves.toBe(1);
+ });
+
+ it("blocks when the agent supervises another member's group, even a private one", async () => {
+ await seedGroup('others-private-supervised', otherUserId, 'private', 'supervisor');
+
+ await expect(
+ ownerModel.countGroupsBlockingAgentDemotion('agt-supervisor', userId),
+ ).resolves.toBe(1);
+ });
+
+ it('does not block for regular membership in a public group', async () => {
+ await seedGroup('public-participant', userId, 'public', 'participant');
+
+ await expect(
+ ownerModel.countGroupsBlockingAgentDemotion('agt-supervisor', userId),
+ ).resolves.toBe(0);
+ });
+
+ it("does not block for the owner's own private group", async () => {
+ await seedGroup('own-private-supervised', userId, 'private', 'supervisor');
+
+ await expect(
+ ownerModel.countGroupsBlockingAgentDemotion('agt-supervisor', userId),
+ ).resolves.toBe(0);
+ });
+
+ it('returns 0 outside a workspace', async () => {
+ await seedGroup('public-supervised-2', userId, 'public', 'supervisor');
+
+ await expect(
+ chatGroupModel.countGroupsBlockingAgentDemotion('agt-supervisor', userId),
+ ).resolves.toBe(0);
+ });
+ });
});
diff --git a/packages/database/src/models/chatGroup.ts b/packages/database/src/models/chatGroup.ts
index 81db3a47df8..acdaf2c7d56 100644
--- a/packages/database/src/models/chatGroup.ts
+++ b/packages/database/src/models/chatGroup.ts
@@ -1,5 +1,5 @@
import { TRPCError } from '@trpc/server';
-import { and, desc, eq, inArray, sql } from 'drizzle-orm';
+import { and, desc, eq, inArray, ne, or, sql } from 'drizzle-orm';
import type {
ChatGroupAgentItem,
@@ -33,6 +33,37 @@ export class ChatGroupModel {
},
);
+ /**
+ * Visibility predicate on the member's `agents` row itself. Group membership
+ * (the junction row) does not grant access to the agent: when a member agent
+ * is switched back to private by its owner, every roster read must drop it
+ * for other members β€” otherwise the join would keep leaking the agent's
+ * config/meta through group surfaces (LOBE-11772).
+ */
+ private memberAgentVisibility = () =>
+ buildWorkspaceWhere(
+ { userId: this.userId, workspaceId: this.workspaceId },
+ {
+ userId: agents.userId,
+ workspaceId: agents.workspaceId,
+ visibility: agents.visibility,
+ },
+ );
+
+ /**
+ * Same guard as an EXISTS subquery, for junction queries that don't join
+ * `agents`. The subquery is spelled with raw identifiers (not drizzle column
+ * refs) because the relational query builder rebinds every referenced column
+ * in `where` to the primary table's alias, which would corrupt the subquery.
+ * Semantics mirror `buildWorkspaceWhere`.
+ */
+ private memberAgentVisibleExists = () => {
+ if (!this.workspaceId) {
+ return sql`EXISTS (SELECT 1 FROM "agents" "ma" WHERE "ma"."id" = ${chatGroupsAgents.agentId} AND "ma"."user_id" = ${this.userId} AND "ma"."workspace_id" IS NULL)`;
+ }
+ return sql`EXISTS (SELECT 1 FROM "agents" "ma" WHERE "ma"."id" = ${chatGroupsAgents.agentId} AND "ma"."workspace_id" = ${this.workspaceId} AND ("ma"."visibility" IS NULL OR "ma"."visibility" = 'public' OR ("ma"."visibility" = 'private' AND "ma"."user_id" = ${this.userId})))`;
+ };
+
/**
* Get member avatar metas (avatar + backgroundColor) grouped by chatGroupId,
* ordered by member order. Inbox members fall back to the default avatar.
@@ -52,7 +83,7 @@ export class ChatGroupModel {
})
.from(chatGroupsAgents)
.innerJoin(agents, eq(chatGroupsAgents.agentId, agents.id))
- .where(inArray(chatGroupsAgents.chatGroupId, groupIds))
+ .where(and(inArray(chatGroupsAgents.chatGroupId, groupIds), this.memberAgentVisibility()))
.orderBy(chatGroupsAgents.order);
for (const { avatar, backgroundColor, chatGroupId, slug } of rows) {
@@ -105,7 +136,11 @@ export class ChatGroupModel {
const groupIds = groups.map((g) => g.id);
const groupAgents = await this.db.query.chatGroupsAgents.findMany({
- where: and(inArray(chatGroupsAgents.chatGroupId, groupIds), this.agentsOwnership()),
+ where: and(
+ inArray(chatGroupsAgents.chatGroupId, groupIds),
+ this.agentsOwnership(),
+ this.memberAgentVisibleExists(),
+ ),
with: { agent: true },
});
@@ -134,7 +169,11 @@ export class ChatGroupModel {
const agents = await this.db.query.chatGroupsAgents.findMany({
orderBy: [chatGroupsAgents.order],
- where: and(eq(chatGroupsAgents.chatGroupId, groupId), this.agentsOwnership()),
+ where: and(
+ eq(chatGroupsAgents.chatGroupId, groupId),
+ this.agentsOwnership(),
+ this.memberAgentVisibleExists(),
+ ),
});
return { agents, group };
@@ -218,6 +257,28 @@ export class ChatGroupModel {
throw new Error('Chat group not found, already published, or access denied');
}
+ // The synthetic supervisor mirrors the group's visibility at creation
+ // (private group β†’ private supervisor). Publish it together with the
+ // group, otherwise other members would receive a `supervisorAgentId`
+ // whose agent row their roster reads filter out.
+ await this.db
+ .update(agents)
+ .set({ updatedAt: new Date(), visibility: 'public' })
+ .where(
+ and(
+ eq(agents.visibility, 'private'),
+ inArray(
+ agents.id,
+ this.db
+ .select({ id: chatGroupsAgents.agentId })
+ .from(chatGroupsAgents)
+ .where(
+ and(eq(chatGroupsAgents.chatGroupId, id), eq(chatGroupsAgents.role, 'supervisor')),
+ ),
+ ),
+ ),
+ );
+
return result;
}
@@ -404,7 +465,11 @@ export class ChatGroupModel {
async getGroupAgents(groupId: string): Promise<ChatGroupAgentItem[]> {
return this.db.query.chatGroupsAgents.findMany({
orderBy: [chatGroupsAgents.order],
- where: and(eq(chatGroupsAgents.chatGroupId, groupId), this.agentsOwnership()),
+ where: and(
+ eq(chatGroupsAgents.chatGroupId, groupId),
+ this.agentsOwnership(),
+ this.memberAgentVisibleExists(),
+ ),
});
}
@@ -443,6 +508,7 @@ export class ChatGroupModel {
eq(chatGroupsAgents.chatGroupId, groupId),
eq(chatGroupsAgents.enabled, true),
this.agentsOwnership(),
+ this.memberAgentVisibility(),
),
)
.orderBy(chatGroupsAgents.order);
@@ -455,10 +521,43 @@ export class ChatGroupModel {
eq(chatGroupsAgents.chatGroupId, groupId),
eq(chatGroupsAgents.enabled, true),
this.agentsOwnership(),
+ this.memberAgentVisibleExists(),
),
});
}
+ /**
+ * Count workspace groups that would break if the given agent were demoted to
+ * private: groups where it is the **supervisor** and the group is visible to
+ * someone else (public, or owned by another member). A private supervisor is
+ * unresolvable for every other viewer, which makes the whole group unusable β€”
+ * so demotion is rejected at the source (mirrors
+ * `countTasksBlockingAgentDemotion`). Regular members are deliberately NOT
+ * counted: roster reads drop a non-visible member per viewer instead.
+ * Deliberately workspace-wide and visibility-blind (NOT `ownership()`):
+ * other members' private groups are invisible to the caller but their
+ * supervisor would still break.
+ */
+ async countGroupsBlockingAgentDemotion(
+ agentId: string,
+ agentOwnerUserId: string,
+ ): Promise<number> {
+ if (!this.workspaceId) return 0;
+ const [row] = await this.db
+ .select({ count: sql<number>`count(*)` })
+ .from(chatGroupsAgents)
+ .innerJoin(chatGroups, eq(chatGroupsAgents.chatGroupId, chatGroups.id))
+ .where(
+ and(
+ eq(chatGroups.workspaceId, this.workspaceId),
+ eq(chatGroupsAgents.agentId, agentId),
+ eq(chatGroupsAgents.role, 'supervisor'),
+ or(eq(chatGroups.visibility, 'public'), ne(chatGroups.userId, agentOwnerUserId)),
+ ),
+ );
+ return Number(row?.count ?? 0);
+ }
+
async getGroupsWithAgents(agentIds?: string[]): Promise<ChatGroupItem[]> {
if (!agentIds || agentIds.length === 0) {
return this.query();
@@ -468,7 +567,13 @@ export class ChatGroupModel {
const groupIds = await this.db
.selectDistinct({ chatGroupId: chatGroupsAgents.chatGroupId })
.from(chatGroupsAgents)
- .where(and(this.agentsOwnership(), inArray(chatGroupsAgents.agentId, agentIds)));
+ .where(
+ and(
+ this.agentsOwnership(),
+ inArray(chatGroupsAgents.agentId, agentIds),
+ this.memberAgentVisibleExists(),
+ ),
+ );
if (groupIds.length === 0) return [];
diff --git a/packages/database/src/repositories/agentGroup/index.test.ts b/packages/database/src/repositories/agentGroup/index.test.ts
index d869a1450c8..2cbb62192a0 100644
--- a/packages/database/src/repositories/agentGroup/index.test.ts
+++ b/packages/database/src/repositories/agentGroup/index.test.ts
@@ -1,5 +1,6 @@
// @vitest-environment node
import { BUILTIN_AGENT_SLUGS } from '@lobechat/builtin-agents';
+import { eq } from 'drizzle-orm';
import { beforeEach, describe, expect, it } from 'vitest';
import { getTestDB } from '../../core/getTestDB';
@@ -352,6 +353,123 @@ describe('AgentGroupRepository', () => {
]);
});
+ describe('member agent demoted to private (LOBE-11772)', () => {
+ const workspaceId = 'agent-group-demotion-ws';
+
+ beforeEach(async () => {
+ await serverDB.insert(workspaces).values({
+ id: workspaceId,
+ name: 'Demotion WS',
+ primaryOwnerId: userId,
+ slug: workspaceId,
+ });
+ await serverDB.insert(chatGroups).values({
+ id: 'ws-demotion-group',
+ title: 'WS demotion group',
+ userId,
+ visibility: 'public',
+ workspaceId,
+ });
+ await serverDB.insert(agents).values([
+ {
+ id: 'ws-supervisor',
+ title: 'Supervisor',
+ userId,
+ virtual: true,
+ visibility: 'public',
+ workspaceId,
+ },
+ {
+ id: 'ws-public-member',
+ title: 'Public member',
+ userId,
+ visibility: 'public',
+ workspaceId,
+ },
+ {
+ id: 'ws-demoted-member',
+ systemRole: 'secret prompt',
+ title: 'Demoted member',
+ userId,
+ visibility: 'private',
+ workspaceId,
+ },
+ ]);
+ await serverDB.insert(chatGroupsAgents).values([
+ {
+ agentId: 'ws-supervisor',
+ chatGroupId: 'ws-demotion-group',
+ order: -1,
+ role: 'supervisor',
+ userId,
+ workspaceId,
+ },
+ {
+ agentId: 'ws-public-member',
+ chatGroupId: 'ws-demotion-group',
+ order: 0,
+ role: 'participant',
+ userId,
+ workspaceId,
+ },
+ {
+ agentId: 'ws-demoted-member',
+ chatGroupId: 'ws-demotion-group',
+ order: 1,
+ role: 'participant',
+ userId,
+ workspaceId,
+ },
+ ]);
+ });
+
+ it('hides the private member config from another workspace member', async () => {
+ const viewerRepo = new AgentGroupRepository(serverDB, otherUserId, workspaceId);
+
+ const result = await viewerRepo.findByIdWithAgents('ws-demotion-group');
+
+ expect(result!.agents.map((a) => a.id)).toEqual(['ws-supervisor', 'ws-public-member']);
+ expect(JSON.stringify(result)).not.toContain('secret prompt');
+ expect(result!.supervisorAgentId).toBe('ws-supervisor');
+ });
+
+ it('keeps the private member visible to its owner', async () => {
+ const ownerRepo = new AgentGroupRepository(serverDB, userId, workspaceId);
+
+ const result = await ownerRepo.findByIdWithAgents('ws-demotion-group');
+
+ expect(result!.agents.map((a) => a.id)).toEqual([
+ 'ws-supervisor',
+ 'ws-public-member',
+ 'ws-demoted-member',
+ ]);
+ });
+
+ it('does not auto-create a duplicate supervisor when the supervisor row is not visible', async () => {
+ // Out-of-sync legacy data: a group published while its supervisor row
+ // stayed private (publishToWorkspace now keeps them in sync).
+ await serverDB
+ .update(agents)
+ .set({ visibility: 'private' })
+ .where(eq(agents.id, 'ws-supervisor'));
+
+ const viewerRepo = new AgentGroupRepository(serverDB, otherUserId, workspaceId);
+ const result = await viewerRepo.findByIdWithAgents('ws-demotion-group');
+
+ // Supervisor existence is judged on raw rows: no duplicate is created,
+ // and the group-owned supervisor stays in the roster so that
+ // `supervisorAgentId` always resolves to a member entry.
+ expect(result!.supervisorAgentId).toBe('ws-supervisor');
+ expect(result!.agents.map((a) => a.id)).toEqual(['ws-supervisor', 'ws-public-member']);
+
+ const supervisorRows = await serverDB
+ .select()
+ .from(chatGroupsAgents)
+ .where(eq(chatGroupsAgents.chatGroupId, 'ws-demotion-group'));
+ expect(supervisorRows.filter((r) => r.role === 'supervisor')).toHaveLength(1);
+ });
+ });
+
it('should inject group-supervisor slug for supervisor agent', async () => {
// Create group
await serverDB.insert(chatGroups).values({
diff --git a/packages/database/src/repositories/agentGroup/index.ts b/packages/database/src/repositories/agentGroup/index.ts
index 693acc35522..9ca27fc7a14 100644
--- a/packages/database/src/repositories/agentGroup/index.ts
+++ b/packages/database/src/repositories/agentGroup/index.ts
@@ -1,7 +1,7 @@
import { BUILTIN_AGENT_SLUGS } from '@lobechat/builtin-agents';
import type { AgentGroupDetail, AgentGroupMember, AgentPluginEntry } from '@lobechat/types';
import { cleanObject } from '@lobechat/utils';
-import { and, eq, inArray, not } from 'drizzle-orm';
+import { and, eq, inArray, not, sql } from 'drizzle-orm';
import type {
AgentItem,
@@ -322,12 +322,18 @@ export class AgentGroupRepository {
if (!group) return null;
- // 2. Find all agents associated with this group (including role info)
+ // 2. Find all agents associated with this group (including role info). The
+ // roster is fetched raw (no visibility filter) with a per-row `visible`
+ // flag: supervisor existence must be judged on the raw rows β€” otherwise a
+ // viewer who can't see the supervisor would auto-create a duplicate one
+ // below β€” while a member agent switched back to private must not leak its
+ // config to other members (LOBE-11772), so only visible rows are returned.
const groupAgentsWithDetails = await this.db
.select({
agent: agents,
order: chatGroupsAgents.order,
role: chatGroupsAgents.role,
+ visible: sql<boolean>`(${this.agentOwnership()})`,
})
.from(chatGroupsAgents)
.innerJoin(agents, eq(chatGroupsAgents.agentId, agents.id))
@@ -340,6 +346,14 @@ export class AgentGroupRepository {
for (const row of groupAgentsWithDetails) {
const isSupervisor = row.role === 'supervisor';
+ if (isSupervisor) {
+ supervisorAgentId = row.agent.id;
+ }
+ // The supervisor is a group-owned synthetic agent: anyone who can read
+ // the group needs it to run group chat, and `publishToWorkspace` keeps
+ // its visibility in sync with the group. Skipping an out-of-sync legacy
+ // row would strand `supervisorAgentId` without a matching agent entry.
+ if (!row.visible && !isSupervisor) continue;
agentItems.push(
cleanObject({
...row.agent,
@@ -348,9 +362,6 @@ export class AgentGroupRepository {
slug: isSupervisor ? BUILTIN_AGENT_SLUGS.groupSupervisor : row.agent.slug,
}) as AgentGroupMember,
);
- if (isSupervisor) {
- supervisorAgentId = row.agent.id;
- }
}
// 4. If no supervisor exists, create a virtual supervisor agent