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(channel): keep private Agents out of workspace groups (#23565)

Arvin Xu1b89933c8efc
diff --git a/apps/server/src/services/inboundWebhook/verification.test.ts b/apps/server/src/services/inboundWebhook/verification.test.ts
index 13234c7e288..3b89e1eba0f 100644
--- a/apps/server/src/services/inboundWebhook/verification.test.ts
+++ b/apps/server/src/services/inboundWebhook/verification.test.ts
@@ -1,5 +1,5 @@
// @vitest-environment node
-import { describe, expect, it } from 'vitest';
+import { describe, expect, it, vi } from 'vitest';
import { receiverTestSecret, signedWebhookHeaders } from './receiverTestUtils';
import { verifyInboundWebhook } from './verification';
@@ -38,10 +38,17 @@ describe('Standard Webhooks inbound verification', () => {
});
it('rejects expired and future timestamps outside the five-minute window', () => {
- const now = Math.floor(Date.now() / 1000);
- expect(verify(signedWebhookHeaders(body, { timestamp: now - 301 }))).toBe(false);
- expect(verify(signedWebhookHeaders(body, { timestamp: now + 301 }))).toBe(false);
- expect(verify(signedWebhookHeaders(body, { timestamp: now - 290 }))).toBe(true);
+ // Freeze the clock: the verifier reads it again, and a second boundary between the two reads
+ // would put `now + 301` exactly on the window's edge.
+ vi.useFakeTimers({ now: new Date('2026-01-01T00:00:00.500Z'), toFake: ['Date'] });
+ try {
+ const now = Math.floor(Date.now() / 1000);
+ expect(verify(signedWebhookHeaders(body, { timestamp: now - 301 }))).toBe(false);
+ expect(verify(signedWebhookHeaders(body, { timestamp: now + 301 }))).toBe(false);
+ expect(verify(signedWebhookHeaders(body, { timestamp: now - 290 }))).toBe(true);
+ } finally {
+ vi.useRealTimers();
+ }
});
it('rejects the wrong key, absent keys and unsupported verification schemes', () => {
diff --git a/locales/en-US/channel.json b/locales/en-US/channel.json
index f78e56710a5..88438531f46 100644
--- a/locales/en-US/channel.json
+++ b/locales/en-US/channel.json
@@ -92,6 +92,7 @@
"environment.inherited.deviceOffline": "This Agent’s device is offline. Reconnect the device, or remove the Agent.",
"environment.inherited.deviceUnavailable": "This Agent’s device is unavailable in the current space. Change it in the Agent’s settings, or remove the Agent.",
"environment.permissionRequired": "You do not have permission to save these members. Check channel and Agent access.",
+ "environment.privateAgent": "A private Agent cannot join a group. Make it visible to the workspace first, or remove it.",
"environment.remoteHost": "This Agent runs on its own host, so there is no device to choose.",
"environment.resolveRequired": "Resolve the issues shown under the selected Agents first.",
"environment.saveFailed": "Could not save channel members. Your choices are preserved; try again.",
diff --git a/locales/zh-CN/channel.json b/locales/zh-CN/channel.json
index 717c3e95a62..013f544d584 100644
--- a/locales/zh-CN/channel.json
+++ b/locales/zh-CN/channel.json
@@ -92,6 +92,7 @@
"environment.inherited.deviceOffline": "此 Agent 的设备已离线,请重新连接设备,或移除此 Agent。",
"environment.inherited.deviceUnavailable": "当前空间无法使用此 Agent 的设备,请在它的设置里更换设备,或移除此 Agent。",
"environment.permissionRequired": "你无权保存这些成员,请检查频道和 Agent 的访问权限。",
+ "environment.privateAgent": "私有 Agent 不能加入群聊,请先将它设为工作区可见,或移除此 Agent。",
"environment.remoteHost": "这个助手在它自己的主机上运行,无需选择设备。",
"environment.resolveRequired": "请先处理成员下方提示的问题。",
"environment.saveFailed": "未能保存频道成员,已保留你的选择,请重试。",
diff --git a/packages/database/src/repositories/channel/__tests__/agentMember.test.ts b/packages/database/src/repositories/channel/__tests__/agentMember.test.ts
index f4f831c6eae..1faadbd9383 100644
--- a/packages/database/src/repositories/channel/__tests__/agentMember.test.ts
+++ b/packages/database/src/repositories/channel/__tests__/agentMember.test.ts
@@ -65,6 +65,58 @@ describe('adding an Agent to a Channel', () => {
expect(added).toMatchObject({ agentId: agent.id, config: {}, name: 'Current Agent name' });
});
+ describe('the caller’s own private Agent in a workspace', () => {
+ const privateAgent = async (userId = fixture.ownerId) => {
+ const [agent] = await db
+ .insert(agents)
+ .values({ userId, visibility: 'private', workspaceId: fixture.workspaceId })
+ .returning();
+ return agent.id;
+ };
+ const agentMembers = (channelId: string) =>
+ db
+ .select()
+ .from(channelMembers)
+ .where(and(eq(channelMembers.channelId, channelId), eq(channelMembers.actorType, 'agent')));
+
+ it('cannot join a group, where every member would see it', async () => {
+ const team = await fixture.createTeamChannel();
+ const agentId = await privateAgent();
+ await expect(team.asOwner.addAgent(team.channel.id, { agentId })).rejects.toMatchObject({
+ code: 'FORBIDDEN',
+ });
+ expect(await agentMembers(team.channel.id)).toHaveLength(0);
+ });
+
+ it('cannot start a group, from scratch or from its direct conversation', async () => {
+ const agentId = await privateAgent();
+ const repository = new ChannelRepository(db, fixture.ownerId, fixture.workspaceId);
+ await expect(
+ repository.create({ agents: [{ agentId }], title: 'Group' }),
+ ).rejects.toMatchObject({ code: 'FORBIDDEN' });
+ const direct = await repository.create({ agentId, title: 'Direct' });
+ await expect(
+ repository.createGroupFromDirect(direct.channel.id, {
+ title: 'Group',
+ userIds: [fixture.memberId],
+ }),
+ ).rejects.toMatchObject({ code: 'FORBIDDEN' });
+ });
+
+ it('still holds its direct conversation and conversations between the owner’s Agents', async () => {
+ const agentId = await privateAgent();
+ const other = await privateAgent();
+ const repository = new ChannelRepository(db, fixture.ownerId, fixture.workspaceId);
+ const direct = await repository.create({ agentId, title: 'Direct' });
+ expect(await agentMembers(direct.channel.id)).toHaveLength(1);
+ const pair = await repository.openAgentPair({
+ agents: [{ agentId }, { agentId: other }],
+ title: 'Pair',
+ });
+ expect(pair.agents).toHaveLength(2);
+ });
+ });
+
it('labels LobeAI by its product name, not the generic fallback', async () => {
const team = await fixture.createTeamChannel();
const [inbox] = await db
@@ -96,7 +148,8 @@ describe('adding an Agent to a Channel', () => {
).toHaveLength(1);
});
- it('permits an owner’s private Agent but checks the actual requester again at claim', async () => {
+ // Groups no longer take a private Agent, but ones that joined before still hold their members.
+ it('checks the actual requester at claim for a private Agent a group already holds', async () => {
const team = await fixture.createTeamChannel();
const [agent] = await db
.insert(agents)
@@ -106,7 +159,16 @@ describe('adding an Agent to a Channel', () => {
visibility: 'private',
})
.returning();
- const added = await team.asOwner.addAgent(team.channel.id, { agentId: agent.id });
+ const [added] = await db
+ .insert(channelMembers)
+ .values({
+ actorType: 'agent',
+ agentId: agent.id,
+ channelId: team.channel.id,
+ config: {},
+ name: 'Private',
+ })
+ .returning();
const message = await team.asMember.send(team.channel.id, {
content: 'Request',
mentions: [added.id],
diff --git a/packages/database/src/repositories/channel/agent.ts b/packages/database/src/repositories/channel/agent.ts
index a09fe8faf9b..76de7ba2cfc 100644
--- a/packages/database/src/repositories/channel/agent.ts
+++ b/packages/database/src/repositories/channel/agent.ts
@@ -197,20 +197,40 @@ export const requireChannelAgent = async (
options: { allowShared?: boolean } = {},
) => {
const [agent] = await tx
- .select({ name: agents.name, slug: agents.slug, title: agents.title })
+ .select({
+ name: agents.name,
+ slug: agents.slug,
+ title: agents.title,
+ visibility: agents.visibility,
+ })
.from(agents)
.where(agentUsableByWhere(agentId, { userId, workspaceId: workspaceId ?? undefined }))
.for('share');
if (agent)
// LobeAI rows are stored without a title; label it the way the rest of the product does.
- return { name: agent.name, title: normalizeInboxAgentTitle(agent.title, agent) };
+ return {
+ name: agent.name,
+ title: normalizeInboxAgentTitle(agent.title, agent),
+ visibility: agent.visibility,
+ };
const shared = options.allowShared
? await findSharedChannelAgent(tx, userId, agentId)
: undefined;
if (!shared) throw new ChannelError('NOT_FOUND', 'Agent not found');
- return { name: shared.name, title: shared.title };
+ return { name: shared.name, title: shared.title, visibility: null };
};
+/**
+ * Whether a workspace Channel may hold its owner's private Agent. Only the owner can use one, so
+ * only conversations no one else can join take it: the direct conversation with it, and the
+ * conversation between two of the owner's Agents. A group would show it, and its replies, to
+ * every member. The personal space has no private Agents.
+ */
+const acceptsPrivateAgent = (
+ channel: Pick<ChannelItem, 'agentId' | 'agentPairKey' | 'workspaceId'>,
+ agentId: string,
+) => !channel.workspaceId || channel.agentId === agentId || !!channel.agentPairKey;
+
/**
* Called under the Channel lock after the caller's admin role has been checked. `inviter` is the
* caller's own member: its person must be able to use the Agent, and the join line names it.
@@ -240,6 +260,11 @@ export const addAgentMember = async (
const agent = await requireChannelAgent(tx, channel.workspaceId, userId, input.agentId, {
allowShared: acceptsSharedAgent(channel, input.agentId),
});
+ if (agent.visibility === 'private' && !acceptsPrivateAgent(channel, input.agentId))
+ throw new ChannelError(
+ 'FORBIDDEN',
+ 'A private Agent cannot join a workspace Channel; make it visible to the workspace first',
+ );
// Idempotent per Agent: retrying a partly applied batch must not add a second member that
// answers the same requests again.
const [joined] = await tx
diff --git a/packages/locales/src/default/channel.ts b/packages/locales/src/default/channel.ts
index 716886171c1..041759c35c4 100644
--- a/packages/locales/src/default/channel.ts
+++ b/packages/locales/src/default/channel.ts
@@ -78,6 +78,8 @@ export default {
'Choose an online device and working directory for every coding Agent.',
'environment.permissionRequired':
'You do not have permission to save these members. Check channel and Agent access.',
+ 'environment.privateAgent':
+ 'A private Agent cannot join a group. Make it visible to the workspace first, or remove it.',
'environment.resolveRequired': 'Resolve the issues shown under the selected Agents first.',
'environment.saveFailed':
'Could not save channel members. Your choices are preserved; try again.',
diff --git a/src/features/Channels/CreateChannel/saveError.test.ts b/src/features/Channels/CreateChannel/saveError.test.ts
index 4d4048fc88c..0bc5a4a8712 100644
--- a/src/features/Channels/CreateChannel/saveError.test.ts
+++ b/src/features/Channels/CreateChannel/saveError.test.ts
@@ -19,6 +19,10 @@ describe('channel member save feedback', () => {
],
['Unsupported Channel runtime', 'environment.unsupportedRuntime'],
['Agent not found', 'environment.agentUnavailable'],
+ [
+ 'A private Agent cannot join a workspace Channel; make it visible to the workspace first',
+ 'environment.privateAgent',
+ ],
])('translates the actionable domain error %s', (message, key) => {
expect(getChannelSaveErrorKey(new Error(message))).toBe(key);
});
diff --git a/src/features/Channels/CreateChannel/saveError.ts b/src/features/Channels/CreateChannel/saveError.ts
index 4fdbfb65086..d037af0923f 100644
--- a/src/features/Channels/CreateChannel/saveError.ts
+++ b/src/features/Channels/CreateChannel/saveError.ts
@@ -31,6 +31,9 @@ export const getChannelSaveErrorKey = (error: unknown) => {
case 'Agent not found': {
return 'environment.agentUnavailable';
}
+ case 'A private Agent cannot join a workspace Channel; make it visible to the workspace first': {
+ return 'environment.privateAgent';
+ }
default: {
if (status === 401) return 'environment.signInRequired';
if (status === 403) return 'environment.permissionRequired';
diff --git a/src/features/Channels/CreateChannel/useChannelAgentOptions.ts b/src/features/Channels/CreateChannel/useChannelAgentOptions.ts
index b042f53af75..e65087618cb 100644
--- a/src/features/Channels/CreateChannel/useChannelAgentOptions.ts
+++ b/src/features/Channels/CreateChannel/useChannelAgentOptions.ts
@@ -1,6 +1,7 @@
import { INBOX_SESSION_ID, isHeterogeneousAgentModelId } from '@lobechat/const';
import type { SidebarAgentItem } from '@lobechat/types';
+import { useActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspaceId';
import { useHomeStore } from '@/store/home';
import { homeAgentListSelectors } from '@/store/home/selectors';
import { useProjectStore } from '@/store/project';
@@ -42,20 +43,27 @@ const useProjectAgents = (projectId?: string) => {
/**
* 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.
+ * delegation targets, so older Agents stay reachable. Lobe AI cannot join a Channel, nor can a
+ * private Agent in a workspace: a group would show it to every member, so the server refuses it.
* 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 inWorkspace = !!useActiveWorkspaceId();
const sync = useHomeStore((s) => s.useFetchAgentList)(isLogin);
const ready = useHomeStore(homeAgentListSelectors.isAgentListInit);
const items = useHomeStore(homeAgentListSelectors.allAgents);
const project = useProjectAgents(projectId);
const agents: ChannelAgentOption[] | undefined = ready
? items
- .filter((item) => item.type === 'agent' && item.slug !== INBOX_SESSION_ID)
+ .filter(
+ (item) =>
+ item.type === 'agent' &&
+ item.slug !== INBOX_SESSION_ID &&
+ !(inWorkspace && item.visibility === 'private'),
+ )
.map((item) => ({ ...item, runtime: agentRuntime(item) }))
: undefined;
return {