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(bot): let everyone in listed channels use the owner's devices (#23544)

Rdmclin2f69ecef28404
diff --git a/apps/server/src/services/aiAgent/deviceAccessPolicy.test.ts b/apps/server/src/services/aiAgent/deviceAccessPolicy.test.ts
index d92a20616ab..5dc49f0e575 100644
--- a/apps/server/src/services/aiAgent/deviceAccessPolicy.test.ts
+++ b/apps/server/src/services/aiAgent/deviceAccessPolicy.test.ts
@@ -88,6 +88,33 @@ describe('resolveDeviceAccessPolicy', () => {
});
});
+ describe('device channel grant', () => {
+ it('grants a channel member in a granted channel', () => {
+ expect(
+ resolveDeviceAccessPolicy({
+ botContext: baseBotContext({ isDeviceChannelGranted: true }),
+ }),
+ ).toEqual({ canUseDevice: true, reason: 'bot-channel-granted' });
+ });
+
+ it('keeps the owner decision ahead of the channel grant', () => {
+ expect(
+ resolveDeviceAccessPolicy({
+ botContext: baseBotContext({ isDeviceChannelGranted: true, isOwner: true }),
+ }),
+ ).toEqual({ canUseDevice: true, reason: 'bot-owner' });
+ });
+
+ it('still denies a granted channel member in a shared-agent visitor run', () => {
+ expect(
+ resolveDeviceAccessPolicy({
+ botContext: baseBotContext({ isDeviceChannelGranted: true }),
+ shareVisitor: { canUseDevice: false },
+ }),
+ ).toEqual({ canUseDevice: false, reason: 'share-visitor' });
+ });
+ });
+
describe('device channel scope', () => {
it('denies the owner in a channel outside the device channel list', () => {
expect(
diff --git a/apps/server/src/services/aiAgent/deviceAccessPolicy.ts b/apps/server/src/services/aiAgent/deviceAccessPolicy.ts
index d9b249c45b1..a0a66bcd96d 100644
--- a/apps/server/src/services/aiAgent/deviceAccessPolicy.ts
+++ b/apps/server/src/services/aiAgent/deviceAccessPolicy.ts
@@ -21,6 +21,12 @@ export type DeviceAccessReason =
* 'allowlist'`), carried as `botContext.isDeviceTrusted`.
*/
| 'bot-trusted'
+ /**
+ * Bot caller in a channel whose members may all use the owner's devices
+ * (`settings.devicePolicy = 'channel'`), carried as
+ * `botContext.isDeviceChannelGranted`.
+ */
+ | 'bot-channel-granted'
/**
* Bot caller in a channel outside the owner's device channel list
* (`settings.deviceChannelPolicy = 'allowlist'`), carried as
@@ -140,6 +146,10 @@ export const resolveDeviceAccessPolicy = (
return { canUseDevice: true, reason: 'bot-trusted' };
}
+ if (botContext.isDeviceChannelGranted) {
+ return { canUseDevice: true, reason: 'bot-channel-granted' };
+ }
+
if (!botContext.senderExternalUserId) {
return { canUseDevice: false, reason: 'bot-owner-not-configured' };
}
diff --git a/apps/server/src/services/bot/BotMessageRouter/catchAll.ts b/apps/server/src/services/bot/BotMessageRouter/catchAll.ts
index e51da385d37..07de954d3eb 100644
--- a/apps/server/src/services/bot/BotMessageRouter/catchAll.ts
+++ b/apps/server/src/services/bot/BotMessageRouter/catchAll.ts
@@ -31,6 +31,7 @@ export const registerCatchAllHandler = (bot: Chat<any>, ctx: BotHandlerContext):
commands,
detectReplyLocale,
deviceAllowlist,
+ isDeviceChannelGrantedFor,
isDeviceChannelRestrictedFor,
displayToolCalls,
dmSettings,
@@ -281,6 +282,7 @@ export const registerCatchAllHandler = (bot: Chat<any>, ctx: BotHandlerContext):
applicationId,
authorUserId: merged.author?.userId,
deviceAllowlist,
+ deviceChannelGranted: isDeviceChannelGrantedFor(thread),
deviceChannelRestricted: isDeviceChannelRestrictedFor(thread),
operatorUserId,
platform,
diff --git a/apps/server/src/services/bot/BotMessageRouter/handlers.ts b/apps/server/src/services/bot/BotMessageRouter/handlers.ts
index 9c7caaf8c72..9db45c5a8f9 100644
--- a/apps/server/src/services/bot/BotMessageRouter/handlers.ts
+++ b/apps/server/src/services/bot/BotMessageRouter/handlers.ts
@@ -37,6 +37,8 @@ import {
import {
extractDeviceAllowlist,
extractDeviceChannelAllowlist,
+ extractDeviceChannelGrantlist,
+ isDeviceChannelGranted,
isDeviceChannelRestricted,
} from '../platforms/deviceAccess';
import { renderThrownAgentError } from '../renderThrownError';
@@ -187,6 +189,18 @@ export function registerHandlers(
channelAllowlist: deviceChannelAllowlist,
isDM: thread.isDM === true,
});
+ /** Channels whose members may all use the devices (`devicePolicy: 'channel'`). */
+ const deviceChannelGrantlist = extractDeviceChannelGrantlist(info.settings);
+ /** Whether a thread sits in one of those channels; same candidate IDs as above. */
+ const isDeviceChannelGrantedFor = (thread: { id: string; isDM?: boolean }): boolean =>
+ isDeviceChannelGranted({
+ candidateChannelIds: [
+ client.extractChatId(thread.id),
+ ...(client.extraGroupAllowlistChannels?.(thread.id) ?? []),
+ ],
+ channelGrantlist: deviceChannelGrantlist,
+ isDM: thread.isDM === true,
+ });
const fallbackReplyLocale: BotReplyLocale = getBotReplyLocale(platform);
/**
@@ -576,6 +590,7 @@ export function registerHandlers(
applicationId,
authorUserId: merged.author?.userId,
deviceAllowlist,
+ deviceChannelGranted: isDeviceChannelGrantedFor(thread),
deviceChannelRestricted: isDeviceChannelRestrictedFor(thread),
operatorUserId,
platform,
@@ -860,6 +875,7 @@ export function registerHandlers(
applicationId,
authorUserId: merged.author?.userId,
deviceAllowlist,
+ deviceChannelGranted: isDeviceChannelGrantedFor(thread),
deviceChannelRestricted: isDeviceChannelRestrictedFor(thread),
operatorUserId,
platform,
@@ -916,6 +932,7 @@ export function registerHandlers(
registerCatchAllHandler(bot, {
deviceAllowlist,
+ isDeviceChannelGrantedFor,
isDeviceChannelRestrictedFor,
agentId,
applicationId,
diff --git a/apps/server/src/services/bot/BotMessageRouter/index.policy.test.ts b/apps/server/src/services/bot/BotMessageRouter/index.policy.test.ts
index 15881e7f896..700282e5e2f 100644
--- a/apps/server/src/services/bot/BotMessageRouter/index.policy.test.ts
+++ b/apps/server/src/services/bot/BotMessageRouter/index.policy.test.ts
@@ -236,6 +236,69 @@ describe('BotMessageRouter', () => {
});
});
+ describe('device channel grant', () => {
+ const channelGranted = {
+ // The "Where" choice does not apply under the grant: the list grants, it never restricts.
+ deviceChannelAllowFrom: [{ id: 'dev-channel', name: '#dev' }],
+ deviceChannelPolicy: 'allowlist',
+ devicePolicy: 'channel',
+ dmPolicy: 'open',
+ userId: 'owner-platform-id',
+ };
+ const mentionAs = async (
+ settings: Record<string, unknown>,
+ thread: Record<string, unknown>,
+ userId: string,
+ ) => {
+ const handler = await loadMentionHandler(settings);
+ await handler(
+ { post: vi.fn().mockResolvedValue(undefined), ...thread },
+ { author: { isBot: false, userId, userName: userId }, isMention: true, text: '@bot run' },
+ );
+ expect(mockHandleMention).toHaveBeenCalledTimes(1);
+ return mockHandleMention.mock.calls[0][2].botContext;
+ };
+
+ it('grants a channel member in a listed channel', async () => {
+ const botContext = await mentionAs(
+ channelGranted,
+ { id: 'telegram:dev-channel', isDM: false },
+ 'team-mate',
+ );
+ expect(botContext.isOwner).toBe(false);
+ expect(botContext.isDeviceChannelGranted).toBe(true);
+ expect(botContext.isDeviceChannelRestricted).toBeUndefined();
+ });
+
+ it('does not grant a member in any other channel', async () => {
+ const botContext = await mentionAs(
+ channelGranted,
+ { id: 'telegram:random', isDM: false },
+ 'team-mate',
+ );
+ expect(botContext.isDeviceChannelGranted).toBeUndefined();
+ });
+
+ it('leaves the owner unrestricted outside the listed channels', async () => {
+ const botContext = await mentionAs(
+ channelGranted,
+ { id: 'telegram:random', isDM: false },
+ 'owner-platform-id',
+ );
+ expect(botContext.isOwner).toBe(true);
+ expect(botContext.isDeviceChannelRestricted).toBeUndefined();
+ });
+
+ it('never grants a DM', async () => {
+ const botContext = await mentionAs(
+ channelGranted,
+ { id: 'telegram:dev-channel', isDM: true },
+ 'team-mate',
+ );
+ expect(botContext.isDeviceChannelGranted).toBeUndefined();
+ });
+ });
+
it('should fall back to isOwner=false when settings.userId is missing (fail-closed)', async () => {
// No `userId` configured on the bot — even a sender who happens to
// share an ID with the operator can't claim owner status.
diff --git a/apps/server/src/services/bot/BotMessageRouter/types.ts b/apps/server/src/services/bot/BotMessageRouter/types.ts
index 94d9befefd4..4a1e141839b 100644
--- a/apps/server/src/services/bot/BotMessageRouter/types.ts
+++ b/apps/server/src/services/bot/BotMessageRouter/types.ts
@@ -158,6 +158,8 @@ export interface BotHandlerContext {
thread: { id: string },
threadSubscribed?: boolean,
) => Promise<WakeInitiation | undefined>;
+ /** Whether everyone in a thread may use the devices because its channel is granted. */
+ isDeviceChannelGrantedFor: (thread: { id: string; isDM?: boolean }) => boolean;
/** Whether a thread is outside the channels the owner limited device use to. */
isDeviceChannelRestrictedFor: (thread: { id: string; isDM?: boolean }) => boolean;
isMessageMonitoringAllowed: (caller: string, threadId: string) => Promise<boolean>;
diff --git a/apps/server/src/services/bot/buildBotContext.test.ts b/apps/server/src/services/bot/buildBotContext.test.ts
index edf32e4d65d..ac76bbd17d6 100644
--- a/apps/server/src/services/bot/buildBotContext.test.ts
+++ b/apps/server/src/services/bot/buildBotContext.test.ts
@@ -143,4 +143,38 @@ describe('buildBotContext', () => {
expect(buildBotContext(baseParams)).not.toHaveProperty('isDeviceChannelRestricted');
});
});
+
+ describe('device channel grant', () => {
+ it('grants a sender who is not the owner in a granted channel', () => {
+ const ctx = buildBotContext({
+ ...baseParams,
+ authorUserId: 'team-mate',
+ deviceChannelGranted: true,
+ operatorUserId: 'owner-1',
+ });
+ expect(ctx.isOwner).toBe(false);
+ expect(ctx.isDeviceChannelGranted).toBe(true);
+ });
+
+ it('does not grant an unknown sender', () => {
+ const ctx = buildBotContext({
+ ...baseParams,
+ authorUserId: undefined,
+ deviceChannelGranted: true,
+ operatorUserId: 'owner-1',
+ });
+ expect(ctx).not.toHaveProperty('isDeviceChannelGranted');
+ });
+
+ it('leaves the owner marked as owner only', () => {
+ const ctx = buildBotContext({
+ ...baseParams,
+ authorUserId: 'owner-1',
+ deviceChannelGranted: true,
+ operatorUserId: 'owner-1',
+ });
+ expect(ctx.isOwner).toBe(true);
+ expect(ctx).not.toHaveProperty('isDeviceChannelGranted');
+ });
+ });
});
diff --git a/apps/server/src/services/bot/buildBotContext.ts b/apps/server/src/services/bot/buildBotContext.ts
index 721844e4252..13c62cce320 100644
--- a/apps/server/src/services/bot/buildBotContext.ts
+++ b/apps/server/src/services/bot/buildBotContext.ts
@@ -9,6 +9,11 @@ export interface BuildBotContextParams {
* (`extractDeviceAllowlist(settings)`). Omitted or empty: owner only.
*/
deviceAllowlist?: string[];
+ /**
+ * Whether this conversation sits in a channel whose members may all use the
+ * owner's devices (`isDeviceChannelGranted`). Omitted: no channel grant.
+ */
+ deviceChannelGranted?: boolean;
/**
* Whether this conversation is outside the channels the owner limited device
* use to (`isDeviceChannelRestricted`). Omitted: no channel restriction.
@@ -44,9 +49,12 @@ export const buildBotContext = (params: BuildBotContextParams): ChatTopicBotCont
// Same fail-closed rule as `isOwner`: an unknown sender is never trusted.
const isDeviceTrusted =
!isOwner && !!senderExternalUserId && !!params.deviceAllowlist?.includes(senderExternalUserId);
+ const isDeviceChannelGranted =
+ !isOwner && !!senderExternalUserId && params.deviceChannelGranted === true;
return {
applicationId: params.applicationId,
isOwner,
+ ...(isDeviceChannelGranted && { isDeviceChannelGranted }),
...(params.deviceChannelRestricted && { isDeviceChannelRestricted: true }),
...(isDeviceTrusted && { isDeviceTrusted }),
platform: params.platform,
diff --git a/apps/server/src/services/bot/platforms/deviceAccess.test.ts b/apps/server/src/services/bot/platforms/deviceAccess.test.ts
index 90df55b4265..161ee672981 100644
--- a/apps/server/src/services/bot/platforms/deviceAccess.test.ts
+++ b/apps/server/src/services/bot/platforms/deviceAccess.test.ts
@@ -3,6 +3,8 @@ import { describe, expect, it } from 'vitest';
import {
extractDeviceAllowlist,
extractDeviceChannelAllowlist,
+ extractDeviceChannelGrantlist,
+ isDeviceChannelGranted,
isDeviceChannelRestricted,
} from './deviceAccess';
@@ -105,3 +107,60 @@ describe('isDeviceChannelRestricted', () => {
).toBe(true);
});
});
+
+describe('device channel grant', () => {
+ const granted = {
+ deviceChannelAllowFrom: [{ id: ' c1 ', name: '#dev' }, { id: '' }, { id: 'c2' }],
+ deviceChannelPolicy: 'allowlist',
+ devicePolicy: 'channel',
+ };
+
+ it('returns the listed channel IDs as the grant list under the channel policy', () => {
+ expect(extractDeviceChannelGrantlist(granted)).toEqual(['c1', 'c2']);
+ });
+
+ it('has no grant list under any other policy', () => {
+ expect(
+ extractDeviceChannelGrantlist({ ...granted, devicePolicy: 'allowlist' }),
+ ).toBeUndefined();
+ expect(extractDeviceChannelGrantlist({ ...granted, devicePolicy: 'owner' })).toBeUndefined();
+ expect(extractDeviceChannelGrantlist(undefined)).toBeUndefined();
+ });
+
+ it('turns off the channel restriction under the channel policy', () => {
+ expect(extractDeviceChannelAllowlist(granted)).toBeUndefined();
+ });
+
+ it('grants a conversation in a listed channel, including a reply thread of it', () => {
+ expect(
+ isDeviceChannelGranted({
+ candidateChannelIds: ['thread-1', 'c2'],
+ channelGrantlist: ['c1', 'c2'],
+ isDM: false,
+ }),
+ ).toBe(true);
+ });
+
+ it('does not grant other channels, DMs, an empty list or a missing list', () => {
+ expect(
+ isDeviceChannelGranted({
+ candidateChannelIds: ['c3'],
+ channelGrantlist: ['c1'],
+ isDM: false,
+ }),
+ ).toBe(false);
+ expect(
+ isDeviceChannelGranted({ candidateChannelIds: ['c1'], channelGrantlist: ['c1'], isDM: true }),
+ ).toBe(false);
+ expect(
+ isDeviceChannelGranted({ candidateChannelIds: ['c1'], channelGrantlist: [], isDM: false }),
+ ).toBe(false);
+ expect(
+ isDeviceChannelGranted({
+ candidateChannelIds: ['c1'],
+ channelGrantlist: undefined,
+ isDM: false,
+ }),
+ ).toBe(false);
+ });
+});
diff --git a/apps/server/src/services/bot/platforms/deviceAccess.ts b/apps/server/src/services/bot/platforms/deviceAccess.ts
index c730855f09b..28d406dc614 100644
--- a/apps/server/src/services/bot/platforms/deviceAccess.ts
+++ b/apps/server/src/services/bot/platforms/deviceAccess.ts
@@ -6,17 +6,19 @@ import type { FieldSchema } from './types';
*
* - `owner` (default): only the sender whose ID equals `settings.userId`.
* - `allowlist`: the owner, plus the user IDs in `deviceAllowFrom`.
+ * - `channel`: the owner anywhere, plus everyone in the channels listed in
+ * `deviceChannelAllowFrom`. Only platforms with group chat offer it.
*
* Kept apart from `allowFrom`: being allowed to talk to the bot is not being
* trusted with the owner's machine, so neither list implies the other.
*/
-export type DevicePolicy = 'allowlist' | 'owner';
+export type DevicePolicy = 'allowlist' | 'channel' | 'owner';
export const devicePolicyField: FieldSchema = {
key: 'devicePolicy',
default: 'owner',
description: 'channel.devicePolicyHint',
- enum: ['owner', 'allowlist'],
+ enum: ['owner', 'allowlist', 'channel'],
label: 'channel.devicePolicy',
type: 'string',
};
@@ -126,14 +128,46 @@ export const extractDeviceAllowlist = (
* unrestricted, so bots saved before this setting existed keep their behavior.
* An `allowlist` with no entries restricts every channel (fail-closed, like
* `groupAllowFrom`).
+ *
+ * Under `devicePolicy: 'channel'` the list grants access instead of limiting
+ * it (`extractDeviceChannelGrantlist`), so no restriction applies.
*/
export const extractDeviceChannelAllowlist = (
settings: Record<string, unknown> | null | undefined,
): string[] | undefined => {
+ if (settings?.devicePolicy === 'channel') return undefined;
if (settings?.deviceChannelPolicy !== 'allowlist') return undefined;
return parseIdList(settings.deviceChannelAllowFrom);
};
+/**
+ * The channel IDs whose members may all use the owner's devices
+ * (`devicePolicy: 'channel'`), or `undefined` under any other policy. An empty
+ * list grants nobody, leaving only the owner.
+ */
+export const extractDeviceChannelGrantlist = (
+ settings: Record<string, unknown> | null | undefined,
+): string[] | undefined => {
+ if (settings?.devicePolicy !== 'channel') return undefined;
+ return parseIdList(settings.deviceChannelAllowFrom);
+};
+
+/**
+ * Whether a conversation sits in one of `channelList`. DMs never match: a DM is
+ * not a channel. `candidateChannelIds` are the same raw IDs the group policy
+ * matches (`extractChatId` plus `extraGroupAllowlistChannels`), so a Discord
+ * reply thread counts as its parent channel.
+ */
+const isInDeviceChannels = (params: {
+ candidateChannelIds: ReadonlyArray<string | undefined>;
+ channelList: string[];
+ isDM: boolean;
+}): boolean => {
+ const { candidateChannelIds, channelList, isDM } = params;
+ if (isDM) return false;
+ return candidateChannelIds.some((id) => !!id && channelList.includes(id));
+};
+
/**
* Whether the conversation sits outside the channels the owner's devices are
* limited to. DMs are never restricted: a DM is not a channel, and who may use
@@ -150,5 +184,20 @@ export const isDeviceChannelRestricted = (params: {
}): boolean => {
const { candidateChannelIds, channelAllowlist, isDM } = params;
if (!channelAllowlist || isDM) return false;
- return !candidateChannelIds.some((id) => !!id && channelAllowlist.includes(id));
+ return !isInDeviceChannels({ candidateChannelIds, channelList: channelAllowlist, isDM });
+};
+
+/**
+ * Whether everyone in the conversation may use the owner's devices because it
+ * sits in a channel the owner granted (`devicePolicy: 'channel'`). DMs are
+ * never granted; there only the owner may use the devices.
+ */
+export const isDeviceChannelGranted = (params: {
+ candidateChannelIds: ReadonlyArray<string | undefined>;
+ channelGrantlist: string[] | undefined;
+ isDM: boolean;
+}): boolean => {
+ const { candidateChannelIds, channelGrantlist, isDM } = params;
+ if (!channelGrantlist) return false;
+ return isInDeviceChannels({ candidateChannelIds, channelList: channelGrantlist, isDM });
};
diff --git a/locales/en-US/agent.json b/locales/en-US/agent.json
index df7e7899a1f..19342ae4e83 100644
--- a/locales/en-US/agent.json
+++ b/locales/en-US/agent.json
@@ -9,6 +9,14 @@
"channel.access.device.channel.list": "Channels for devices",
"channel.access.device.channel.listEmpty": "No channels added yet, so devices cannot be used in any channel.",
"channel.access.device.channel.listHint": "Use the same channel / group / chat IDs as Allowed Channels for conversations.",
+ "channel.access.device.channelMembers": "Anyone in the listed channels",
+ "channel.access.device.channelMembersDesc": "You anywhere, plus everyone in the channels listed below. In other channels and in direct messages, only you.",
+ "channel.access.device.channelMembersRisk": "Anyone in these channels can have the bot read and write files and run commands on your devices. List only channels whose members you all trust.",
+ "channel.access.device.grant.listEmpty": "No channels added yet, so only you can use your devices.",
+ "channel.access.device.grant.listHint": "Everyone in these channels can use your devices. Use the same channel / group / chat IDs as Allowed Channels for conversations.",
+ "channel.access.device.grantConfirmContent": "{{count}} channel(s) are already on the device channel list. They will now grant access: everyone in them can have the bot operate your devices.",
+ "channel.access.device.grantConfirmOk": "Grant access",
+ "channel.access.device.grantConfirmTitle": "Grant these channels?",
"channel.access.device.label": "Who can use your devices",
"channel.access.device.list": "Authorized people",
"channel.access.device.listEmpty": "No one is authorized yet, so only you can use your devices.",
@@ -16,6 +24,7 @@
"channel.access.device.owner": "Only me",
"channel.access.device.ownerDesc": "Only you can have the bot operate your devices. Others can still talk to it.",
"channel.access.device.ownerMissing": "Add your platform user ID under Owner identity first. Until then the bot cannot recognize you, and no one can use your devices.",
+ "channel.access.device.ownerMissingChannel": "Add your platform user ID under Owner identity first. Until then the bot cannot recognize you, so only members of the listed channels can use your devices, and only in those channels.",
"channel.access.dm.approval": "Strangers need my approval",
"channel.access.dm.approvalDesc": "A stranger gets a pairing code, and you run /approve to let them in.",
"channel.access.dm.closed": "No direct messages",
diff --git a/locales/zh-CN/agent.json b/locales/zh-CN/agent.json
index 30a2c1be331..a6d0ed5b7e2 100644
--- a/locales/zh-CN/agent.json
+++ b/locales/zh-CN/agent.json
@@ -9,6 +9,14 @@
"channel.access.device.channel.list": "可使用设备的频道",
"channel.access.device.channel.listEmpty": "尚未添加频道,目前任何频道都无法使用设备。",
"channel.access.device.channel.listHint": "填写与对话「允许的频道」相同的频道 / 群组 / 会话 ID。",
+ "channel.access.device.channelMembers": "列出频道里的所有人",
+ "channel.access.device.channelMembersDesc": "你在任何地方都能用;下方列出的频道里,所有成员也都能用。其他频道和私信里只有你能用。",
+ "channel.access.device.channelMembersRisk": "这些频道里的任何人都能让机器人在你的设备上读写文件、执行命令。只列出成员都可信的频道。",
+ "channel.access.device.grant.listEmpty": "尚未添加频道,目前仅你本人可以使用设备。",
+ "channel.access.device.grant.listHint": "这些频道里的所有成员都能使用你的设备。填写与对话「允许的频道」相同的频道 / 群组 / 会话 ID。",
+ "channel.access.device.grantConfirmContent": "设备频道名单里已有 {{count}} 个频道。切换后它们将改为授权:这些频道里的所有人都能让机器人操作你的设备。",
+ "channel.access.device.grantConfirmOk": "授权",
+ "channel.access.device.grantConfirmTitle": "授权这些频道?",
"channel.access.device.label": "谁可以使用你的设备",
"channel.access.device.list": "授权成员",
"channel.access.device.listEmpty": "尚未授权任何成员,目前仅你本人可以使用设备。",
@@ -16,6 +24,7 @@
"channel.access.device.owner": "仅限本人",
"channel.access.device.ownerDesc": "只有你本人可以让机器人操作你的设备,其他人仍可正常对话。",
"channel.access.device.ownerMissing": "请先在「所有者身份」中填写你的平台用户 ID。未填写时,机器人无法识别你,任何人都无法使用你的设备。",
+ "channel.access.device.ownerMissingChannel": "请先在「所有者身份」中填写你的平台用户 ID。未填写时,机器人无法识别你,只有列出频道里的成员能在这些频道中使用你的设备。",
"channel.access.dm.approval": "陌生人需要我批准",
"channel.access.dm.approvalDesc": "陌生人会收到配对码,你用 /approve 批准后才能使用。",
"channel.access.dm.closed": "不接受私聊",
diff --git a/packages/locales/src/default/agent.ts b/packages/locales/src/default/agent.ts
index 42c6c3c0491..3298ee53e76 100644
--- a/packages/locales/src/default/agent.ts
+++ b/packages/locales/src/default/agent.ts
@@ -713,8 +713,23 @@ export default {
'Use the same channel / group / chat IDs as Allowed Channels for conversations.',
'channel.access.device.channel.listEmpty':
'No channels added yet, so devices cannot be used in any channel.',
+ 'channel.access.device.channelMembers': 'Anyone in the listed channels',
+ 'channel.access.device.channelMembersDesc':
+ 'You anywhere, plus everyone in the channels listed below. In other channels and in direct messages, only you.',
+ 'channel.access.device.channelMembersRisk':
+ 'Anyone in these channels can have the bot read and write files and run commands on your devices. List only channels whose members you all trust.',
+ 'channel.access.device.grant.listEmpty':
+ 'No channels added yet, so only you can use your devices.',
+ 'channel.access.device.grant.listHint':
+ 'Everyone in these channels can use your devices. Use the same channel / group / chat IDs as Allowed Channels for conversations.',
+ 'channel.access.device.grantConfirmTitle': 'Grant these channels?',
+ 'channel.access.device.grantConfirmContent':
+ '{{count}} channel(s) are already on the device channel list. They will now grant access: everyone in them can have the bot operate your devices.',
+ 'channel.access.device.grantConfirmOk': 'Grant access',
'channel.access.device.ownerMissing':
'Add your platform user ID under Owner identity first. Until then the bot cannot recognize you, and no one can use your devices.',
+ 'channel.access.device.ownerMissingChannel':
+ 'Add your platform user ID under Owner identity first. Until then the bot cannot recognize you, so only members of the listed channels can use your devices, and only in those channels.',
'channel.devicePolicy': 'Device Access',
'channel.devicePolicyHint': 'Who may operate your devices through the bot.',
'channel.deviceAllowFrom': 'Authorized People',
diff --git a/packages/types/src/topic/topic.ts b/packages/types/src/topic/topic.ts
index ad1ac16825d..30b8a0b0ca9 100644
--- a/packages/types/src/topic/topic.ts
+++ b/packages/types/src/topic/topic.ts
@@ -70,6 +70,12 @@ export interface ChatTopicWebhookContext {
export interface ChatTopicBotContext {
applicationId: string;
+ /**
+ * Whether the sender, not being the owner, sits in a channel whose members
+ * may all use the owner's devices (`settings.devicePolicy = 'channel'` +
+ * `settings.deviceChannelAllowFrom`). Absent means no channel grant.
+ */
+ isDeviceChannelGranted?: boolean;
/**
* Whether the conversation is outside the channels the owner limited device
* use to (`settings.deviceChannelPolicy = 'allowlist'` +
diff --git a/src/features/AgentChannel/PlatformDetail/AccessSection.tsx b/src/features/AgentChannel/PlatformDetail/AccessSection.tsx
index 67ebdf9e80e..6290280da0d 100644
--- a/src/features/AgentChannel/PlatformDetail/AccessSection.tsx
+++ b/src/features/AgentChannel/PlatformDetail/AccessSection.tsx
@@ -1,6 +1,6 @@
'use client';
-import { confirmModal, Text } from '@lobehub/ui';
+import { confirmModal, Flexbox, Text } from '@lobehub/ui';
import { Form, type FormInstance, useWatch } from '@lobehub/ui/form';
import { memo, type ReactNode, useCallback, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
@@ -21,7 +21,7 @@ import { SchemaField } from './SchemaField';
import type { AccessSectionKey } from './settingsGroups';
type GroupPolicy = 'allowlist' | 'disabled' | 'open';
-type DevicePolicy = 'allowlist' | 'owner';
+type DevicePolicy = 'allowlist' | 'channel' | 'owner';
type DeviceChannelPolicy = 'allowlist' | 'any';
interface AccessSectionProps {
@@ -44,8 +44,9 @@ interface AccessSectionProps {
* (`allowFrom`), a group policy and a group list. This section lets a person
* choose one stance per surface and only then shows what that choice needs: the
* list for "approval" and "listed", the owner's ID for approving. Devices are
- * the owner's alone unless they name people in `deviceAllowFrom`, and can be
- * limited to the channels in `deviceChannelAllowFrom`. A list stays mounted
+ * the owner's alone unless they name people in `deviceAllowFrom` or grant whole
+ * channels (`devicePolicy: 'channel'`), and can otherwise be limited to the
+ * channels in `deviceChannelAllowFrom`. A list stays mounted
* when hidden so a saved list is never dropped by a save.
*/
export const AccessSection = memo<AccessSectionProps>(
@@ -59,8 +60,15 @@ export const AccessSection = memo<AccessSectionProps>(
const stance = deriveDmStance(settings);
const groupPolicy = (settings.groupPolicy as GroupPolicy | undefined) ?? 'open';
+ // Granting whole channels needs the channel list, which only platforms with
+ // group chat declare; elsewhere the option is not offered.
+ const canGrantChannels = byKey.has('deviceChannelAllowFrom');
const devicePolicy: DevicePolicy =
- settings.devicePolicy === 'allowlist' ? 'allowlist' : 'owner';
+ settings.devicePolicy === 'allowlist' ||
+ (settings.devicePolicy === 'channel' && canGrantChannels)
+ ? settings.devicePolicy
+ : 'owner';
+ const channelGrant = devicePolicy === 'channel';
const deviceChannelPolicy: DeviceChannelPolicy =
settings.deviceChannelPolicy === 'allowlist' ? 'allowlist' : 'any';
const hasPeopleList = countListed(settings.allowFrom) > 0;
@@ -100,6 +108,28 @@ export const AccessSection = memo<AccessSectionProps>(
[settings, stance, t, write],
);
+ const handleDevicePolicy = useCallback(
+ (next: DevicePolicy) => {
+ if (next === devicePolicy) return;
+ // Channels already saved on the list, whether they limited device use or
+ // sat hidden after "Any channel", would start granting every member of
+ // those channels. Say so before they change meaning.
+ const savedChannels = countListed(settings.deviceChannelAllowFrom);
+ if (next === 'channel' && savedChannels > 0) {
+ confirmModal({
+ content: t('channel.access.device.grantConfirmContent', { count: savedChannels }),
+ okText: t('channel.access.device.grantConfirmOk'),
+ onOk: () => write({ devicePolicy: next }),
+ title: t('channel.access.device.grantConfirmTitle'),
+ });
+ return;
+ }
+
+ write({ devicePolicy: next });
+ },
+ [devicePolicy, settings, t, write],
+ );
+
// Each option states what it does, so the choice is made by reading the
// options rather than by opening one.
const dmOptions: ChoiceOption<DmStance>[] = (
@@ -110,14 +140,19 @@ export const AccessSection = memo<AccessSectionProps>(
recommendedLabel: value === 'approval' ? t('channel.access.recommended') : undefined,
value,
}));
- const deviceOptions: ChoiceOption<DevicePolicy>[] = (['owner', 'allowlist'] as const).map(
- (value) => ({
- desc: t(`channel.access.device.${value}Desc`),
- label: t(`channel.access.device.${value}`),
+ const deviceValues: DevicePolicy[] = canGrantChannels
+ ? ['owner', 'allowlist', 'channel']
+ : ['owner', 'allowlist'];
+ const deviceOptions: ChoiceOption<DevicePolicy>[] = deviceValues.map((value) => {
+ // `channel.access.device.channel.*` already names the "where" block.
+ const key = value === 'channel' ? 'channelMembers' : value;
+ return {
+ desc: t(`channel.access.device.${key}Desc`),
+ label: t(`channel.access.device.${key}`),
recommendedLabel: value === 'owner' ? t('channel.access.recommended') : undefined,
value,
- }),
- );
+ };
+ });
const deviceChannelOptions: ChoiceOption<DeviceChannelPolicy>[] = (
['any', 'allowlist'] as const
).map((value) => ({
@@ -191,18 +226,29 @@ export const AccessSection = memo<AccessSectionProps>(
desc={
ownerMissing ? (
<Text fontSize={12} type={'warning'}>
- {t('channel.access.device.ownerMissing')}
+ {t(
+ channelGrant
+ ? 'channel.access.device.ownerMissingChannel'
+ : 'channel.access.device.ownerMissing',
+ )}
</Text>
) : undefined
}
>
- <ChoiceList
- aria-label={t('channel.access.device.label')}
- disabled={disabled}
- options={deviceOptions}
- value={devicePolicy}
- onChange={(next) => write({ devicePolicy: next })}
- />
+ <Flexbox gap={8}>
+ <ChoiceList
+ aria-label={t('channel.access.device.label')}
+ disabled={disabled}
+ options={deviceOptions}
+ value={devicePolicy}
+ onChange={handleDevicePolicy}
+ />
+ {channelGrant && (
+ <Text fontSize={12} type={'warning'}>
+ {t('channel.access.device.channelMembersRisk')}
+ </Text>
+ )}
+ </Flexbox>
</Form.Field>
)}
{deviceAllowFrom && (
@@ -217,7 +263,7 @@ export const AccessSection = memo<AccessSectionProps>(
parentKey="settings"
/>
)}
- {byKey.has('deviceChannelPolicy') && (
+ {byKey.has('deviceChannelPolicy') && !channelGrant && (
<Form.Field divider label={t('channel.access.device.channel.label')} layout="vertical">
<ChoiceList
aria-label={t('channel.access.device.channel.label')}
@@ -231,13 +277,21 @@ export const AccessSection = memo<AccessSectionProps>(
{deviceChannelAllowFrom && (
<SchemaField
divider
- descOverride={t('channel.access.device.channel.listHint')}
disabled={disabled}
- emptyOverride={t('channel.access.device.channel.listEmpty')}
field={deviceChannelAllowFrom}
- hidden={deviceChannelPolicy !== 'allowlist'}
+ hidden={!channelGrant && deviceChannelPolicy !== 'allowlist'}
labelOverride={t('channel.access.device.channel.list')}
parentKey="settings"
+ descOverride={t(
+ channelGrant
+ ? 'channel.access.device.grant.listHint'
+ : 'channel.access.device.channel.listHint',
+ )}
+ emptyOverride={t(
+ channelGrant
+ ? 'channel.access.device.grant.listEmpty'
+ : 'channel.access.device.channel.listEmpty',
+ )}
/>
)}
</>
diff --git a/src/features/AgentChannel/PlatformDetail/Body.access.test.tsx b/src/features/AgentChannel/PlatformDetail/Body.access.test.tsx
index eb3ef7bcf73..b19ed4ce8a7 100644
--- a/src/features/AgentChannel/PlatformDetail/Body.access.test.tsx
+++ b/src/features/AgentChannel/PlatformDetail/Body.access.test.tsx
@@ -1,6 +1,7 @@
/**
* @vitest-environment happy-dom
*/
+import { confirmModal } from '@lobehub/ui';
import { useForm } from '@lobehub/ui/form';
import { fireEvent, render, screen, within } from '@testing-library/react';
import { useEffect } from 'react';
@@ -26,6 +27,11 @@ vi.mock('react-i18next', () => ({
useTranslation: () => ({ t: (key: string) => state.copy[key] ?? key }),
}));
+vi.mock('@lobehub/ui', async (importOriginal) => ({
+ ...(await importOriginal<Record<string, unknown>>()),
+ confirmModal: vi.fn(),
+}));
+
vi.mock('@/store/serverConfig', () => ({
useServerConfigStore: (selector: (s: { featureFlags: Record<string, unknown> }) => unknown) =>
selector({ featureFlags: state.featureFlags }),
@@ -211,6 +217,101 @@ describe('channel settings form: access tab', () => {
expect(onSave).toHaveBeenCalledWith('access-device');
});
+ it('grants everyone in the listed channels, with a risk warning and no channel limit choice', () => {
+ state.copy = zh;
+
+ render(
+ <Harness
+ settings={{
+ deviceChannelAllowFrom: [{ id: 'dev-channel', name: '#dev' }],
+ devicePolicy: 'channel',
+ userId: 'owner-1',
+ }}
+ />,
+ );
+
+ const who = screen.getByRole('radiogroup', { name: zh['channel.access.device.label'] });
+ expect(
+ within(who).getByRole('radio', {
+ name: new RegExp(zh['channel.access.device.channelMembers']),
+ }),
+ ).toHaveAttribute('aria-checked', 'true');
+ expect(screen.getByText(zh['channel.access.device.channelMembersRisk'])).toBeVisible();
+ // The list grants here, so "where devices can be used" would contradict it.
+ expect(
+ screen.queryByRole('radiogroup', { name: zh['channel.access.device.channel.label'] }),
+ ).not.toBeInTheDocument();
+ expect(screen.getByText(zh['channel.access.device.grant.listHint'])).toBeVisible();
+ expect(screen.getByDisplayValue('dev-channel')).toBeInTheDocument();
+ });
+
+ it('shows the channel list as soon as channels are granted', () => {
+ state.copy = en;
+
+ render(<Harness settings={{ userId: 'owner-1' }} />);
+
+ expect(screen.queryByText(en['channel.access.device.channelMembersRisk'])).toBeNull();
+ const who = screen.getByRole('radiogroup', { name: en['channel.access.device.label'] });
+ fireEvent.click(
+ within(who).getByRole('radio', {
+ name: new RegExp(en['channel.access.device.channelMembers']),
+ }),
+ );
+
+ expect(screen.getByText(en['channel.access.device.channelMembersRisk'])).toBeVisible();
+ expect(screen.getByText(en['channel.access.device.grant.listEmpty'])).toBeVisible();
+ });
+
+ it('asks before a channel list that limits devices starts granting them', () => {
+ state.copy = en;
+
+ render(
+ <Harness
+ settings={{
+ deviceChannelAllowFrom: [{ id: 'ops', name: '#ops' }],
+ deviceChannelPolicy: 'allowlist',
+ userId: 'owner-1',
+ }}
+ />,
+ );
+
+ const who = screen.getByRole('radiogroup', { name: en['channel.access.device.label'] });
+ fireEvent.click(
+ within(who).getByRole('radio', {
+ name: new RegExp(en['channel.access.device.channelMembers']),
+ }),
+ );
+
+ expect(confirmModal).toHaveBeenCalledTimes(1);
+ expect(
+ within(who).getByRole('radio', { name: new RegExp(en['channel.access.device.owner']) }),
+ ).toHaveAttribute('aria-checked', 'true');
+ });
+
+ it('also asks when the saved channel list was hidden under "Any channel"', () => {
+ state.copy = en;
+ vi.mocked(confirmModal).mockClear();
+
+ render(
+ <Harness
+ settings={{
+ deviceChannelAllowFrom: [{ id: 'ops', name: '#ops' }],
+ deviceChannelPolicy: 'any',
+ userId: 'owner-1',
+ }}
+ />,
+ );
+
+ const who = screen.getByRole('radiogroup', { name: en['channel.access.device.label'] });
+ fireEvent.click(
+ within(who).getByRole('radio', {
+ name: new RegExp(en['channel.access.device.channelMembers']),
+ }),
+ );
+
+ expect(confirmModal).toHaveBeenCalledTimes(1);
+ });
+
it('warns that nobody can use the devices until the owner ID is filled', () => {
state.copy = en;
diff --git a/src/features/AgentChannel/PlatformDetail/accessStance.test.ts b/src/features/AgentChannel/PlatformDetail/accessStance.test.ts
index bcf09e42416..e818106072e 100644
--- a/src/features/AgentChannel/PlatformDetail/accessStance.test.ts
+++ b/src/features/AgentChannel/PlatformDetail/accessStance.test.ts
@@ -118,6 +118,16 @@ describe('dropHiddenIncompleteRows', () => {
).toEqual({});
});
+ it('keeps an incomplete device channel row while channels are granted', () => {
+ expect(
+ dropHiddenIncompleteRows({
+ deviceChannelAllowFrom: [{ id: '' }],
+ deviceChannelPolicy: 'any',
+ devicePolicy: 'channel',
+ }),
+ ).toEqual({});
+ });
+
it('drops a half-added group row once groups are no longer limited to a list', () => {
expect(
dropHiddenIncompleteRows({
diff --git a/src/features/AgentChannel/PlatformDetail/accessStance.ts b/src/features/AgentChannel/PlatformDetail/accessStance.ts
index 44c0a5fb6f7..3a1a7c8b5d5 100644
--- a/src/features/AgentChannel/PlatformDetail/accessStance.ts
+++ b/src/features/AgentChannel/PlatformDetail/accessStance.ts
@@ -131,7 +131,9 @@ export const dropHiddenIncompleteRows = (
if (!peopleListShown) prune('allowFrom');
if (settings.groupPolicy !== 'allowlist') prune('groupAllowFrom');
if (settings.devicePolicy !== 'allowlist') prune('deviceAllowFrom');
- if (settings.deviceChannelPolicy !== 'allowlist') prune('deviceChannelAllowFrom');
+ // The channel list shows both to grant channels and to limit device use to them.
+ if (settings.devicePolicy !== 'channel' && settings.deviceChannelPolicy !== 'allowlist')
+ prune('deviceChannelAllowFrom');
return patch;
};