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 owners share device access, and split the access tab into identity, conversation and device (#21754)

Arvin Xuc13601022053
diff --git a/apps/server/src/services/aiAgent/deviceAccessPolicy.test.ts b/apps/server/src/services/aiAgent/deviceAccessPolicy.test.ts
index a910a4609fd..4c2a59f2762 100644
--- a/apps/server/src/services/aiAgent/deviceAccessPolicy.test.ts
+++ b/apps/server/src/services/aiAgent/deviceAccessPolicy.test.ts
@@ -53,15 +53,28 @@ describe('resolveDeviceAccessPolicy', () => {
});
});
- it('never returns canUseDevice=true for a non-owner bot sender, even with a trusted-looking ID', () => {
- // Future-proofing: until the trusted list lands, every non-owner bot
- // sender must be denied. This guards against accidentally reintroducing
- // a permissive default while wiring the future `bot-trusted` branch.
+ it('denies a non-owner bot sender who is not on the device list', () => {
const result = resolveDeviceAccessPolicy({
botContext: baseBotContext({ isOwner: false, senderExternalUserId: 'team-mate' }),
});
- expect(result.canUseDevice).toBe(false);
- expect(result.reason).not.toBe('bot-trusted');
+ expect(result).toEqual({ canUseDevice: false, reason: 'bot-external-sender' });
+ });
+
+ it('grants device access to a sender the owner put on the device list', () => {
+ expect(
+ resolveDeviceAccessPolicy({
+ botContext: baseBotContext({ isDeviceTrusted: true, senderExternalUserId: 'team-mate' }),
+ }),
+ ).toEqual({ canUseDevice: true, reason: 'bot-trusted' });
+ });
+
+ it('keeps a trusted sender away from devices in a shared-agent visitor run', () => {
+ expect(
+ resolveDeviceAccessPolicy({
+ botContext: baseBotContext({ isDeviceTrusted: true }),
+ shareVisitor: true,
+ }),
+ ).toEqual({ canUseDevice: false, reason: 'share-visitor' });
});
describe('personal-scope bot platforms', () => {
diff --git a/apps/server/src/services/aiAgent/deviceAccessPolicy.ts b/apps/server/src/services/aiAgent/deviceAccessPolicy.ts
index 445f62711d8..316492b961a 100644
--- a/apps/server/src/services/aiAgent/deviceAccessPolicy.ts
+++ b/apps/server/src/services/aiAgent/deviceAccessPolicy.ts
@@ -17,10 +17,8 @@ export type DeviceAccessReason =
*/
| 'bot-personal-platform'
/**
- * Bot caller, sender is on the operator's trusted external list. Reserved —
- * the resolver never returns this value yet; future work will plumb the
- * trusted list through `DeviceAccessPolicyInput` and add the branch here
- * without touching `AgentToolsEngine`.
+ * Bot caller, sender is on the owner's device list (`settings.devicePolicy =
+ * 'allowlist'`), carried as `botContext.isDeviceTrusted`.
*/
| 'bot-trusted'
/** Bot caller, sender is identifiable but not the owner — DENY device tools. */
@@ -111,9 +109,9 @@ export const resolveDeviceAccessPolicy = (
return { canUseDevice: true, reason: 'bot-personal-platform' };
}
- // Future: bot-trusted branch (operator-curated allowlist of external
- // senders). Falls through to the deny branch until the trusted list is
- // wired into `DeviceAccessPolicyInput`.
+ if (botContext.isDeviceTrusted) {
+ return { canUseDevice: true, reason: 'bot-trusted' };
+ }
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 c765a682fbe..788e9fe68cd 100644
--- a/apps/server/src/services/bot/BotMessageRouter/catchAll.ts
+++ b/apps/server/src/services/bot/BotMessageRouter/catchAll.ts
@@ -28,6 +28,7 @@ export const registerCatchAllHandler = (bot: Chat<any>, ctx: BotHandlerContext):
client,
commands,
detectReplyLocale,
+ deviceAllowlist,
displayToolCalls,
dmSettings,
gateFollowup,
@@ -279,6 +280,7 @@ export const registerCatchAllHandler = (bot: Chat<any>, ctx: BotHandlerContext):
botContext: buildBotContext({
applicationId,
authorUserId: merged.author?.userId,
+ deviceAllowlist,
operatorUserId,
platform,
platformThreadId: thread.id,
diff --git a/apps/server/src/services/bot/BotMessageRouter/handlers.ts b/apps/server/src/services/bot/BotMessageRouter/handlers.ts
index d21c00989fb..aaf9643c17c 100644
--- a/apps/server/src/services/bot/BotMessageRouter/handlers.ts
+++ b/apps/server/src/services/bot/BotMessageRouter/handlers.ts
@@ -31,6 +31,7 @@ import {
resolveReplyStyle,
type UserAllowlist,
} from '../platforms';
+import { extractDeviceAllowlist } from '../platforms/deviceAccess';
import { renderThrownAgentError } from '../renderThrownError';
import { createWakeClassify } from '../wake/classify';
import { createWakeDutyJudge } from '../wake/dutyJudge';
@@ -169,6 +170,8 @@ export function registerHandlers(
typeof info.settings?.userId === 'string'
? (info.settings.userId as string).trim() || undefined
: undefined;
+ /** Who besides the owner may use the owner's devices; read once per bot. */
+ const deviceAllowlist = extractDeviceAllowlist(info.settings);
const fallbackReplyLocale: BotReplyLocale = getBotReplyLocale(platform);
/**
@@ -541,6 +544,7 @@ export function registerHandlers(
botContext: buildBotContext({
applicationId,
authorUserId: merged.author?.userId,
+ deviceAllowlist,
operatorUserId,
platform,
platformThreadId: thread.id,
@@ -844,6 +848,7 @@ export function registerHandlers(
botContext: buildBotContext({
applicationId,
authorUserId: merged.author?.userId,
+ deviceAllowlist,
operatorUserId,
platform,
platformThreadId: thread.id,
@@ -892,6 +897,7 @@ export function registerHandlers(
);
registerCatchAllHandler(bot, {
+ deviceAllowlist,
agentId,
applicationId,
botWakeEnabled: isBotWakeEnabled(parseBotWakeSettings(info.settings).config),
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 e50253aaa6d..61b997ac35a 100644
--- a/apps/server/src/services/bot/BotMessageRouter/index.policy.test.ts
+++ b/apps/server/src/services/bot/BotMessageRouter/index.policy.test.ts
@@ -144,6 +144,33 @@ describe('BotMessageRouter', () => {
const opts = mockHandleMention.mock.calls[0][2];
expect(opts.botContext.senderExternalUserId).toBe('random-user-id');
expect(opts.botContext.isOwner).toBe(false);
+ expect(opts.botContext.isDeviceTrusted).toBeUndefined();
+ });
+
+ it('should mark a sender on the device list as device-trusted on botContext', async () => {
+ const handler = await loadMentionHandler({
+ deviceAllowFrom: [{ id: 'friend-id', name: 'Ada' }],
+ devicePolicy: 'allowlist',
+ dmPolicy: 'open',
+ userId: 'owner-platform-id',
+ });
+ const thread = {
+ id: 'telegram:group-1',
+ isDM: false,
+ post: vi.fn().mockResolvedValue(undefined),
+ };
+ const message = {
+ author: { isBot: false, userId: 'friend-id', userName: 'ada' },
+ isMention: true,
+ text: '@bot check my build',
+ };
+
+ await handler(thread, message);
+
+ expect(mockHandleMention).toHaveBeenCalledTimes(1);
+ const opts = mockHandleMention.mock.calls[0][2];
+ expect(opts.botContext.isOwner).toBe(false);
+ expect(opts.botContext.isDeviceTrusted).toBe(true);
});
it('should fall back to isOwner=false when settings.userId is missing (fail-closed)', async () => {
diff --git a/apps/server/src/services/bot/BotMessageRouter/types.ts b/apps/server/src/services/bot/BotMessageRouter/types.ts
index f13c1225246..d650f98c255 100644
--- a/apps/server/src/services/bot/BotMessageRouter/types.ts
+++ b/apps/server/src/services/bot/BotMessageRouter/types.ts
@@ -134,6 +134,8 @@ export interface BotHandlerContext {
client: PlatformClient;
commands: BotCommand[];
detectReplyLocale: (message: { author?: unknown }) => BotReplyLocale;
+ /** User IDs, besides the owner, trusted with the owner's devices. */
+ deviceAllowlist: string[];
displayToolCalls: boolean;
dmSettings: DmSettings;
/** Last check before a follow-up wake (watch keyword) runs: enforced policies, then the scheduler. */
diff --git a/apps/server/src/services/bot/buildBotContext.test.ts b/apps/server/src/services/bot/buildBotContext.test.ts
index 4bc5962307d..f6e1581777b 100644
--- a/apps/server/src/services/bot/buildBotContext.test.ts
+++ b/apps/server/src/services/bot/buildBotContext.test.ts
@@ -85,4 +85,48 @@ describe('buildBotContext', () => {
platformThreadId: 'thread-x',
});
});
+
+ describe('device list', () => {
+ it('trusts a listed sender who is not the owner', () => {
+ const ctx = buildBotContext({
+ ...baseParams,
+ authorUserId: 'friend-1',
+ deviceAllowlist: ['friend-1'],
+ operatorUserId: 'owner-1',
+ });
+ expect(ctx.isOwner).toBe(false);
+ expect(ctx.isDeviceTrusted).toBe(true);
+ });
+
+ it('does not trust a sender missing from the list', () => {
+ const ctx = buildBotContext({
+ ...baseParams,
+ authorUserId: 'stranger',
+ deviceAllowlist: ['friend-1'],
+ operatorUserId: 'owner-1',
+ });
+ expect(ctx.isDeviceTrusted).toBeUndefined();
+ });
+
+ it('does not trust an unknown sender, even with an empty ID on the list', () => {
+ const ctx = buildBotContext({
+ ...baseParams,
+ authorUserId: undefined,
+ deviceAllowlist: [''],
+ operatorUserId: 'owner-1',
+ });
+ expect(ctx.isDeviceTrusted).toBeUndefined();
+ });
+
+ it('leaves the owner marked as owner only', () => {
+ const ctx = buildBotContext({
+ ...baseParams,
+ authorUserId: 'owner-1',
+ deviceAllowlist: ['owner-1'],
+ operatorUserId: 'owner-1',
+ });
+ expect(ctx.isOwner).toBe(true);
+ expect(ctx.isDeviceTrusted).toBeUndefined();
+ });
+ });
});
diff --git a/apps/server/src/services/bot/buildBotContext.ts b/apps/server/src/services/bot/buildBotContext.ts
index f3fe0afabe6..85e5a6e5a37 100644
--- a/apps/server/src/services/bot/buildBotContext.ts
+++ b/apps/server/src/services/bot/buildBotContext.ts
@@ -4,6 +4,11 @@ export interface BuildBotContextParams {
applicationId: string;
/** Platform-assigned ID of the inbound message author (e.g. Discord/Slack `user.id`). */
authorUserId: string | undefined;
+ /**
+ * User IDs, besides the owner, the owner trusts with their devices
+ * (`extractDeviceAllowlist(settings)`). Omitted or empty: owner only.
+ */
+ deviceAllowlist?: string[];
/**
* Configured owner ID for this bot install (e.g. `agent_bot_providers.settings.userId`
* or messenger link's `platformUserId`). Owner identity is decided by
@@ -31,9 +36,13 @@ export interface BuildBotContextParams {
export const buildBotContext = (params: BuildBotContextParams): ChatTopicBotContext => {
const senderExternalUserId = params.authorUserId ?? '';
const isOwner = !!params.operatorUserId && senderExternalUserId === params.operatorUserId;
+ // Same fail-closed rule as `isOwner`: an unknown sender is never trusted.
+ const isDeviceTrusted =
+ !isOwner && !!senderExternalUserId && !!params.deviceAllowlist?.includes(senderExternalUserId);
return {
applicationId: params.applicationId,
isOwner,
+ ...(isDeviceTrusted && { isDeviceTrusted }),
platform: params.platform,
platformThreadId: params.platformThreadId,
senderExternalUserId,
diff --git a/apps/server/src/services/bot/platforms/const.ts b/apps/server/src/services/bot/platforms/const.ts
index c4e65a4ae5d..dd3561a1e7b 100644
--- a/apps/server/src/services/bot/platforms/const.ts
+++ b/apps/server/src/services/bot/platforms/const.ts
@@ -639,7 +639,7 @@ const findFirstMatchingKeyword = (
* never sees the names — those exist purely so the operator can recognise
* each entry on the settings page.
*/
-function parseIdList(raw: unknown): string[] {
+export function parseIdList(raw: unknown): string[] {
if (typeof raw === 'string') {
return raw
.split(/[\s,]+/)
diff --git a/apps/server/src/services/bot/platforms/deviceAccess.test.ts b/apps/server/src/services/bot/platforms/deviceAccess.test.ts
new file mode 100644
index 00000000000..bb43aa8368e
--- /dev/null
+++ b/apps/server/src/services/bot/platforms/deviceAccess.test.ts
@@ -0,0 +1,26 @@
+import { describe, expect, it } from 'vitest';
+
+import { extractDeviceAllowlist } from './deviceAccess';
+
+describe('extractDeviceAllowlist', () => {
+ it('returns the listed IDs under the allowlist policy', () => {
+ expect(
+ extractDeviceAllowlist({
+ deviceAllowFrom: [{ id: ' u1 ', name: 'Ada' }, { id: '' }, { id: 'u2' }],
+ devicePolicy: 'allowlist',
+ }),
+ ).toEqual(['u1', 'u2']);
+ });
+
+ it('ignores a kept list while the policy is owner only', () => {
+ expect(
+ extractDeviceAllowlist({ deviceAllowFrom: [{ id: 'u1' }], devicePolicy: 'owner' }),
+ ).toEqual([]);
+ });
+
+ it('fails closed for missing or malformed settings', () => {
+ expect(extractDeviceAllowlist(undefined)).toEqual([]);
+ expect(extractDeviceAllowlist({ deviceAllowFrom: [{ id: 'u1' }] })).toEqual([]);
+ expect(extractDeviceAllowlist({ deviceAllowFrom: 'u1', devicePolicy: 'everyone' })).toEqual([]);
+ });
+});
diff --git a/apps/server/src/services/bot/platforms/deviceAccess.ts b/apps/server/src/services/bot/platforms/deviceAccess.ts
new file mode 100644
index 00000000000..591a0027376
--- /dev/null
+++ b/apps/server/src/services/bot/platforms/deviceAccess.ts
@@ -0,0 +1,65 @@
+import { parseIdList } from './const';
+import type { FieldSchema } from './types';
+
+/**
+ * Who on a bot may use the owner's devices (local system, remote device).
+ *
+ * - `owner` (default): only the sender whose ID equals `settings.userId`.
+ * - `allowlist`: the owner, plus the user IDs in `deviceAllowFrom`.
+ *
+ * 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 const devicePolicyField: FieldSchema = {
+ key: 'devicePolicy',
+ default: 'owner',
+ description: 'channel.devicePolicyHint',
+ enum: ['owner', 'allowlist'],
+ label: 'channel.devicePolicy',
+ type: 'string',
+};
+
+/** Same `{ id, name? }` rows as `allowFrom`, so the page renders and parses it the same way. */
+export const deviceAllowFromField: FieldSchema = {
+ key: 'deviceAllowFrom',
+ default: [],
+ description: 'channel.deviceAllowFromHint',
+ items: {
+ key: 'item',
+ label: '',
+ properties: [
+ {
+ key: 'id',
+ label: 'channel.allowFromIdLabel',
+ placeholder: 'channel.allowFromIdPlaceholder',
+ required: true,
+ type: 'string',
+ },
+ {
+ key: 'name',
+ label: 'channel.allowFromNameLabel',
+ placeholder: 'channel.allowFromNamePlaceholder',
+ type: 'string',
+ },
+ ],
+ type: 'object',
+ },
+ label: 'channel.deviceAllowFrom',
+ type: 'array',
+};
+
+export const deviceAccessFields: FieldSchema[] = [devicePolicyField, deviceAllowFromField];
+
+/**
+ * The user IDs, besides the owner, who may use the owner's devices. Anything
+ * but an explicit `allowlist` policy yields an empty list, so a missing or
+ * malformed setting fails closed to "owner only".
+ */
+export const extractDeviceAllowlist = (
+ settings: Record<string, unknown> | null | undefined,
+): string[] => {
+ if (settings?.devicePolicy !== 'allowlist') return [];
+ return parseIdList(settings.deviceAllowFrom);
+};
diff --git a/apps/server/src/services/bot/platforms/discord/schema.ts b/apps/server/src/services/bot/platforms/discord/schema.ts
index f39c653ba27..6dac6df1ca2 100644
--- a/apps/server/src/services/bot/platforms/discord/schema.ts
+++ b/apps/server/src/services/bot/platforms/discord/schema.ts
@@ -17,6 +17,7 @@ import {
replyPlacementField,
watchKeywordsField,
} from '../const';
+import { deviceAccessFields } from '../deviceAccess';
import { replyStyleFields } from '../replyStyle';
import type { FieldSchema } from '../types';
import {
@@ -69,6 +70,7 @@ export const schema: FieldSchema[] = [
label: 'channel.settings',
properties: [
makeUserIdField('discord'),
+ ...deviceAccessFields,
makeServerIdField('discord'),
{
key: 'charLimit',
diff --git a/apps/server/src/services/bot/platforms/feishu/definitions/schema.ts b/apps/server/src/services/bot/platforms/feishu/definitions/schema.ts
index 34bda1799cb..566fbfd3bbf 100644
--- a/apps/server/src/services/bot/platforms/feishu/definitions/schema.ts
+++ b/apps/server/src/services/bot/platforms/feishu/definitions/schema.ts
@@ -14,6 +14,7 @@ import {
reactionModeField,
watchKeywordsField,
} from '../../const';
+import { deviceAccessFields } from '../../deviceAccess';
import { replyStyleFields } from '../../replyStyle';
import type { FieldSchema } from '../../types';
import { DEFAULT_FEISHU_CONNECTION_MODE, MAX_FEISHU_HISTORY_LIMIT } from '../const';
@@ -59,6 +60,7 @@ export const sharedSchema: FieldSchema[] = [
label: 'channel.settings',
properties: [
makeUserIdField('feishu'),
+ ...deviceAccessFields,
{
key: 'connectionMode',
default: DEFAULT_FEISHU_CONNECTION_MODE,
diff --git a/apps/server/src/services/bot/platforms/imessage/schema.ts b/apps/server/src/services/bot/platforms/imessage/schema.ts
index 2c91a56ee6d..06b233bff4c 100644
--- a/apps/server/src/services/bot/platforms/imessage/schema.ts
+++ b/apps/server/src/services/bot/platforms/imessage/schema.ts
@@ -1,6 +1,7 @@
import { DEFAULT_BOT_DEBOUNCE_MS, MAX_BOT_DEBOUNCE_MS } from '@lobechat/const';
import { displayToolCallsField, makeUserIdField, watchKeywordsField } from '../const';
+import { deviceAccessFields } from '../deviceAccess';
import { replyStyleFields } from '../replyStyle';
import type { FieldSchema } from '../types';
@@ -21,6 +22,7 @@ export const schema: FieldSchema[] = [
label: 'channel.settings',
properties: [
makeUserIdField('imessage'),
+ ...deviceAccessFields,
{
key: 'charLimit',
default: 5000,
diff --git a/apps/server/src/services/bot/platforms/line/schema.ts b/apps/server/src/services/bot/platforms/line/schema.ts
index 4f06a3a44d6..4ca06e53e97 100644
--- a/apps/server/src/services/bot/platforms/line/schema.ts
+++ b/apps/server/src/services/bot/platforms/line/schema.ts
@@ -1,6 +1,7 @@
import { DEFAULT_BOT_DEBOUNCE_MS, MAX_BOT_DEBOUNCE_MS } from '@lobechat/const';
import { displayToolCallsField, makeUserIdField, watchKeywordsField } from '../const';
+import { deviceAccessFields } from '../deviceAccess';
import { replyStyleFields } from '../replyStyle';
import type { FieldSchema } from '../types';
@@ -39,6 +40,7 @@ export const schema: FieldSchema[] = [
label: 'channel.settings',
properties: [
makeUserIdField('line'),
+ ...deviceAccessFields,
{
key: 'charLimit',
default: 5000,
diff --git a/apps/server/src/services/bot/platforms/qq/schema.ts b/apps/server/src/services/bot/platforms/qq/schema.ts
index d8826ab5827..ddcdccf7054 100644
--- a/apps/server/src/services/bot/platforms/qq/schema.ts
+++ b/apps/server/src/services/bot/platforms/qq/schema.ts
@@ -8,6 +8,7 @@ import {
makeUserIdField,
watchKeywordsField,
} from '../const';
+import { deviceAccessFields } from '../deviceAccess';
import { replyStyleFields } from '../replyStyle';
import type { FieldSchema } from '../types';
import { DEFAULT_QQ_CONNECTION_MODE } from './const';
@@ -39,6 +40,7 @@ export const schema: FieldSchema[] = [
label: 'channel.settings',
properties: [
makeUserIdField('qq'),
+ ...deviceAccessFields,
{
key: 'connectionMode',
default: DEFAULT_QQ_CONNECTION_MODE,
diff --git a/apps/server/src/services/bot/platforms/slack/schema.ts b/apps/server/src/services/bot/platforms/slack/schema.ts
index f40e6a45b82..0640928b964 100644
--- a/apps/server/src/services/bot/platforms/slack/schema.ts
+++ b/apps/server/src/services/bot/platforms/slack/schema.ts
@@ -16,6 +16,7 @@ import {
replyPlacementField,
watchKeywordsField,
} from '../const';
+import { deviceAccessFields } from '../deviceAccess';
import { replyStyleFields } from '../replyStyle';
import type { FieldSchema } from '../types';
import { DEFAULT_SLACK_CONNECTION_MODE, MAX_SLACK_HISTORY_LIMIT } from './const';
@@ -61,6 +62,7 @@ export const schema: FieldSchema[] = [
label: 'channel.settings',
properties: [
makeUserIdField('slack'),
+ ...deviceAccessFields,
makeServerIdField('slack'),
{
key: 'connectionMode',
diff --git a/apps/server/src/services/bot/platforms/telegram/schema.ts b/apps/server/src/services/bot/platforms/telegram/schema.ts
index 0ff2d513386..1404a1bc78b 100644
--- a/apps/server/src/services/bot/platforms/telegram/schema.ts
+++ b/apps/server/src/services/bot/platforms/telegram/schema.ts
@@ -10,6 +10,7 @@ import {
reactionModeField,
watchKeywordsField,
} from '../const';
+import { deviceAccessFields } from '../deviceAccess';
import { replyStyleFields } from '../replyStyle';
import type { FieldSchema } from '../types';
@@ -48,6 +49,7 @@ export const schema: FieldSchema[] = [
label: 'channel.settings',
properties: [
makeUserIdField('telegram'),
+ ...deviceAccessFields,
{
key: 'charLimit',
default: 4000,
diff --git a/locales/en-US/agent.json b/locales/en-US/agent.json
index 6e2fea8b9fe..0c84501c859 100644
--- a/locales/en-US/agent.json
+++ b/locales/en-US/agent.json
@@ -1,4 +1,13 @@
{
+ "channel.access.device.allowlist": "Me and authorized people",
+ "channel.access.device.allowlistDesc": "You and the people listed below can have the bot operate your devices.",
+ "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.",
+ "channel.access.device.listHint": "Listed people can read and write files and run commands on your devices through the bot. Add only people you trust.",
+ "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.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",
@@ -28,6 +37,11 @@
"channel.access.list.hint": "The list applies everywhere: only these people can use the bot, in DMs and in groups.",
"channel.access.list.listed": "People on the list",
"channel.access.recommended": "Recommended",
+ "channel.access.section.conversation": "Conversation access",
+ "channel.access.section.conversationDesc": "Determines who may talk to the bot in direct messages, and in which groups and channels it responds.",
+ "channel.access.section.device": "Device access",
+ "channel.access.section.deviceDesc": "Determines who may operate your devices through the bot, such as reading files or running commands. Conversation access does not include device access.",
+ "channel.access.section.identity": "Owner identity",
"channel.allowFrom": "Allowed Users",
"channel.allowFromAdd": "Add user",
"channel.allowFromEmpty": "No users added yet — anyone can interact with the bot.",
@@ -162,6 +176,12 @@
"channel.deleteConfirmDesc": "This action will permanently remove this bot and its configuration. This cannot be undone.",
"channel.devWebhookProxyUrl": "HTTPS Tunnel URL",
"channel.devWebhookProxyUrlHint": "Optional. HTTPS tunnel URL for forwarding webhook requests to local dev server.",
+ "channel.deviceAllowFrom": "Authorized People",
+ "channel.deviceAllowFromAdd": "Add person",
+ "channel.deviceAllowFromEmpty": "No one is authorized yet, so only you can use your devices.",
+ "channel.deviceAllowFromHint": "Listed people can read and write files and run commands on your devices through the bot.",
+ "channel.devicePolicy": "Device Access",
+ "channel.devicePolicyHint": "Who may operate your devices through the bot.",
"channel.discard": "Discard",
"channel.discord.description": "Connect this agent to Discord server for channel chat and direct messages.",
"channel.displayToolCalls": "Display Tool Calls",
diff --git a/locales/zh-CN/agent.json b/locales/zh-CN/agent.json
index 6b843dab408..b6d7fc45474 100644
--- a/locales/zh-CN/agent.json
+++ b/locales/zh-CN/agent.json
@@ -1,4 +1,13 @@
{
+ "channel.access.device.allowlist": "本人及授权成员",
+ "channel.access.device.allowlistDesc": "你和下方名单中的成员可以让机器人操作你的设备。",
+ "channel.access.device.label": "谁可以使用你的设备",
+ "channel.access.device.list": "授权成员",
+ "channel.access.device.listEmpty": "尚未授权任何成员,目前仅你本人可以使用设备。",
+ "channel.access.device.listHint": "名单中的成员可以通过机器人在你的设备上读写文件、执行命令。请仅添加你信任的人。",
+ "channel.access.device.owner": "仅限本人",
+ "channel.access.device.ownerDesc": "只有你本人可以让机器人操作你的设备,其他人仍可正常对话。",
+ "channel.access.device.ownerMissing": "请先在「所有者身份」中填写你的平台用户 ID。未填写时,机器人无法识别你,任何人都无法使用你的设备。",
"channel.access.dm.approval": "陌生人需要我批准",
"channel.access.dm.approvalDesc": "陌生人会收到配对码,你用 /approve 批准后才能使用。",
"channel.access.dm.closed": "不接受私聊",
@@ -28,6 +37,11 @@
"channel.access.list.hint": "名单在私聊和群聊里都生效:只有名单里的人能使用它。",
"channel.access.list.listed": "名单内的人",
"channel.access.recommended": "推荐",
+ "channel.access.section.conversation": "对话权限",
+ "channel.access.section.conversationDesc": "设定哪些人可以私聊机器人,以及机器人在哪些群聊和频道中响应。",
+ "channel.access.section.device": "设备权限",
+ "channel.access.section.deviceDesc": "设定哪些人可以通过机器人操作你的设备,例如读取文件、执行命令。对话权限不包含设备权限。",
+ "channel.access.section.identity": "所有者身份",
"channel.allowFrom": "允许的用户",
"channel.allowFromAdd": "添加用户",
"channel.allowFromEmpty": "尚未添加任何用户——任何人都可以与机器人交互。",
@@ -162,6 +176,12 @@
"channel.deleteConfirmDesc": "此操作将永久移除该 Bot 及其配置,且无法撤销。",
"channel.devWebhookProxyUrl": "HTTPS 隧道地址",
"channel.devWebhookProxyUrlHint": "可选。用于将 webhook 请求转发到本地开发服务器的 HTTPS 隧道 URL。",
+ "channel.deviceAllowFrom": "授权成员",
+ "channel.deviceAllowFromAdd": "添加成员",
+ "channel.deviceAllowFromEmpty": "尚未授权任何成员,目前仅你本人可以使用设备。",
+ "channel.deviceAllowFromHint": "名单中的成员可以通过机器人在你的设备上读写文件、执行命令。",
+ "channel.devicePolicy": "设备权限",
+ "channel.devicePolicyHint": "谁可以通过机器人操作你的设备。",
"channel.discard": "放弃更改",
"channel.discord.description": "将助手连接到 Discord 服务器,支持频道聊天和私信。",
"channel.displayToolCalls": "展示工具调用",
diff --git a/packages/locales/src/default/agent.ts b/packages/locales/src/default/agent.ts
index 87a72403a2b..6715fa94f13 100644
--- a/packages/locales/src/default/agent.ts
+++ b/packages/locales/src/default/agent.ts
@@ -614,6 +614,33 @@ export default {
'channel.access.identity.required': 'Required to approve strangers',
'channel.access.identity.approverMissing':
'To approve strangers, add your own ID first, or nobody can run /approve.',
+ 'channel.access.section.identity': 'Owner identity',
+ 'channel.access.section.conversation': 'Conversation access',
+ 'channel.access.section.conversationDesc':
+ 'Determines who may talk to the bot in direct messages, and in which groups and channels it responds.',
+ 'channel.access.section.device': 'Device access',
+ 'channel.access.section.deviceDesc':
+ 'Determines who may operate your devices through the bot, such as reading files or running commands. Conversation access does not include device access.',
+ 'channel.access.device.label': 'Who can use your devices',
+ '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.allowlist': 'Me and authorized people',
+ 'channel.access.device.allowlistDesc':
+ 'You and the people listed below can have the bot operate your devices.',
+ 'channel.access.device.list': 'Authorized people',
+ 'channel.access.device.listHint':
+ 'Listed people can read and write files and run commands on your devices through the bot. Add only people you trust.',
+ 'channel.access.device.listEmpty': 'No one is authorized yet, so only you can use your devices.',
+ '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.devicePolicy': 'Device Access',
+ 'channel.devicePolicyHint': 'Who may operate your devices through the bot.',
+ 'channel.deviceAllowFrom': 'Authorized People',
+ 'channel.deviceAllowFromAdd': 'Add person',
+ 'channel.deviceAllowFromEmpty': 'No one is authorized yet, so only you can use your devices.',
+ 'channel.deviceAllowFromHint':
+ 'Listed people can read and write files and run commands on your devices through the bot.',
'channel.hero.title': '{{name}} bot',
'channel.hero.connected': '{{agent}} · app ID {{id}}',
'channel.hero.new': 'Once connected, {{agent}} can work in {{name}}.',
diff --git a/packages/types/src/topic/topic.ts b/packages/types/src/topic/topic.ts
index e4623681c2f..5b6e3906008 100644
--- a/packages/types/src/topic/topic.ts
+++ b/packages/types/src/topic/topic.ts
@@ -50,6 +50,12 @@ export interface TopicUserMemoryExtractRunState {
export interface ChatTopicBotContext {
applicationId: string;
+ /**
+ * Whether the sender, not being the owner, is on the owner's device list
+ * (`settings.devicePolicy = 'allowlist'` + `settings.deviceAllowFrom`).
+ * Computed with `isOwner` in `buildBotContext`; absent means not trusted.
+ */
+ isDeviceTrusted?: boolean;
/**
* Whether the message sender is the bot owner. Computed at the bot
* router/dispatcher entry point as
diff --git a/src/features/AgentChannel/PlatformDetail/AccessSection.tsx b/src/features/AgentChannel/PlatformDetail/AccessSection.tsx
index 8b63f34bb5f..0d003854026 100644
--- a/src/features/AgentChannel/PlatformDetail/AccessSection.tsx
+++ b/src/features/AgentChannel/PlatformDetail/AccessSection.tsx
@@ -18,8 +18,10 @@ import {
import { ChoiceList, type ChoiceOption } from './ChoiceList';
import type { ChannelFormValues } from './index';
import { SchemaField } from './SchemaField';
+import type { AccessSectionKey } from './settingsGroups';
type GroupPolicy = 'allowlist' | 'disabled' | 'open';
+type DevicePolicy = 'allowlist' | 'owner';
interface AccessSectionProps {
disabled?: boolean;
@@ -27,21 +29,25 @@ interface AccessSectionProps {
fields: FieldSchema[];
form: FormInstance<ChannelFormValues>;
onValuesChange?: (values: ChannelFormValues) => void;
+ /** Which block of the access tab to render. */
+ section: AccessSectionKey;
/** Platform helper rendered right under the owner ID field (e.g. Feishu's lookup). */
userIdExtras?: ReactNode;
}
/**
- * "Who can use it", asked as decisions instead of settings.
+ * "Who can use it", asked as decisions instead of settings, one block at a time:
+ * who the owner is, who may talk to the bot, and who may use the owner's devices.
*
- * The runtime decides access with `dmPolicy`, a global people list (`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. The list stays mounted
- * when hidden so a saved list is never dropped by a save.
+ * The runtime decides conversation access with `dmPolicy`, a global people list
+ * (`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`. A list stays
+ * mounted when hidden so a saved list is never dropped by a save.
*/
export const AccessSection = memo<AccessSectionProps>(
- ({ disabled, fields, form, onValuesChange, userIdExtras }) => {
+ ({ disabled, fields, form, onValuesChange, section, userIdExtras }) => {
const { t: _t } = useTranslation('agent');
const t = _t as (key: string, options?: Record<string, unknown>) => string;
@@ -51,6 +57,8 @@ export const AccessSection = memo<AccessSectionProps>(
const stance = deriveDmStance(settings);
const groupPolicy = (settings.groupPolicy as GroupPolicy | undefined) ?? 'open';
+ const devicePolicy: DevicePolicy =
+ settings.devicePolicy === 'allowlist' ? 'allowlist' : 'owner';
const hasPeopleList = countListed(settings.allowFrom) > 0;
const write = useCallback(
@@ -98,6 +106,14 @@ 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}`),
+ recommendedLabel: value === 'owner' ? t('channel.access.recommended') : undefined,
+ value,
+ }),
+ );
const groupOptions: ChoiceOption<GroupPolicy>[] = (
['open', 'allowlist', 'disabled'] as const
).map((value) => ({
@@ -111,47 +127,91 @@ export const AccessSection = memo<AccessSectionProps>(
const allowFrom = byKey.get('allowFrom');
const guestPolicy = byKey.get('guestPolicy');
const groupAllowFrom = byKey.get('groupAllowFrom');
+ const deviceAllowFrom = byKey.get('deviceAllowFrom');
- const approverMissing =
- settings.dmPolicy === 'pairing' &&
- !(typeof settings.userId === 'string' && settings.userId.trim());
+ const ownerMissing = !(typeof settings.userId === 'string' && settings.userId.trim());
+ const approverMissing = settings.dmPolicy === 'pairing' && ownerMissing;
// A filled list limits everyone in every surface, so it stays visible (and
// clearable) whatever the DM stance is.
const listVisible = stance === 'approval' || stance === 'listed' || hasPeopleList;
- return (
- <>
- {userId && (
- <SchemaField
- disabled={disabled}
- field={userId}
- parentKey="settings"
- descOverride={
- <>
- {t('channel.access.identity.desc')}
- {approverMissing && (
- <Text fontSize={12} style={{ display: 'block' }} type={'warning'}>
- {t('channel.access.identity.approverMissing')}
+ if (section === 'identity')
+ return (
+ <>
+ {userId && (
+ <SchemaField
+ disabled={disabled}
+ field={userId}
+ parentKey="settings"
+ descOverride={
+ <>
+ {t('channel.access.identity.desc')}
+ {approverMissing && (
+ <Text fontSize={12} style={{ display: 'block' }} type={'warning'}>
+ {t('channel.access.identity.approverMissing')}
+ </Text>
+ )}
+ </>
+ }
+ validateOverride={() =>
+ form.getValue('settings.dmPolicy') === 'pairing' &&
+ !String(form.getValue('settings.userId') ?? '').trim()
+ ? t('channel.access.identity.required')
+ : undefined
+ }
+ />
+ )}
+ {userIdExtras}
+ {/* Your server sits with your own ID: both say what is yours, not who may talk. */}
+ {serverId && (
+ <SchemaField divider disabled={disabled} field={serverId} parentKey="settings" />
+ )}
+ </>
+ );
+
+ if (section === 'device')
+ return (
+ <>
+ {byKey.has('devicePolicy') && (
+ <Form.Field
+ label={t('channel.access.device.label')}
+ layout="vertical"
+ desc={
+ ownerMissing ? (
+ <Text fontSize={12} type={'warning'}>
+ {t('channel.access.device.ownerMissing')}
</Text>
- )}
- </>
- }
- validateOverride={() =>
- form.getValue('settings.dmPolicy') === 'pairing' &&
- !String(form.getValue('settings.userId') ?? '').trim()
- ? t('channel.access.identity.required')
- : undefined
- }
- />
- )}
- {userIdExtras}
- {/* Your server sits with your own ID: both say what is yours, not who may talk. */}
- {serverId && (
- <SchemaField divider disabled={disabled} field={serverId} parentKey="settings" />
- )}
+ ) : undefined
+ }
+ >
+ <ChoiceList
+ aria-label={t('channel.access.device.label')}
+ disabled={disabled}
+ options={deviceOptions}
+ value={devicePolicy}
+ onChange={(next) => write({ devicePolicy: next })}
+ />
+ </Form.Field>
+ )}
+ {deviceAllowFrom && (
+ <SchemaField
+ divider
+ descOverride={t('channel.access.device.listHint')}
+ disabled={disabled}
+ emptyOverride={t('channel.access.device.listEmpty')}
+ field={deviceAllowFrom}
+ hidden={devicePolicy !== 'allowlist'}
+ labelOverride={t('channel.access.device.list')}
+ parentKey="settings"
+ />
+ )}
+ </>
+ );
+ return (
+ <>
{byKey.has('dmPolicy') && (
- <Form.Field divider label={t('channel.access.dm.label')} layout="vertical">
+ <Form.Field label={t('channel.access.dm.label')} layout="vertical">
<ChoiceList
aria-label={t('channel.access.dm.label')}
disabled={disabled}
diff --git a/src/features/AgentChannel/PlatformDetail/Body.access.test.tsx b/src/features/AgentChannel/PlatformDetail/Body.access.test.tsx
new file mode 100644
index 00000000000..cbd2c8b3b7b
--- /dev/null
+++ b/src/features/AgentChannel/PlatformDetail/Body.access.test.tsx
@@ -0,0 +1,167 @@
+/**
+ * @vitest-environment happy-dom
+ */
+import { useForm } from '@lobehub/ui/form';
+import { fireEvent, render, screen, within } from '@testing-library/react';
+import { useEffect } from 'react';
+import { describe, expect, it, vi } from 'vitest';
+
+import { schema as discordSchema } from '@/server/services/bot/platforms/discord/schema';
+import type { SerializedPlatformDefinition } from '@/server/services/bot/platforms/types';
+
+import agentZh from '../../../../locales/zh-CN/agent.json';
+import agentEn from '../../../../packages/locales/src/default/agent';
+import Body, { type ModuleControls } from './Body';
+import { getChannelFormValues, mergeSettingsWithDefaults } from './formState';
+import type { ChannelFormValues } from './index';
+
+const state = vi.hoisted(() => ({
+ copy: {} as Record<string, string>,
+ featureFlags: {} as Record<string, unknown>,
+}));
+
+// Resolve real copy instead of echoing keys, so the test sees what a user would read.
+vi.mock('react-i18next', () => ({
+ Trans: ({ i18nKey }: { i18nKey: string }) => <span>{i18nKey}</span>,
+ useTranslation: () => ({ t: (key: string) => state.copy[key] ?? key }),
+}));
+
+vi.mock('@/store/serverConfig', () => ({
+ useServerConfigStore: (selector: (s: { featureFlags: Record<string, unknown> }) => unknown) =>
+ selector({ featureFlags: state.featureFlags }),
+}));
+
+vi.mock('@/components/FormInput', () => ({
+ FormInput: (props: React.InputHTMLAttributes<HTMLInputElement>) => <input {...props} />,
+ FormTextArea: (props: React.TextareaHTMLAttributes<HTMLTextAreaElement>) => (
+ <textarea {...props} />
+ ),
+ FormPassword: (props: React.InputHTMLAttributes<HTMLInputElement>) => <input {...props} />,
+}));
+
+vi.mock('@/components/InfoTooltip', () => ({
+ default: ({ title }: { title?: string }) => <span aria-hidden="true" title={title} />,
+}));
+
+vi.mock('@/features/AgentChannel/const', () => ({ getPlatformIcon: () => null }));
+
+vi.mock('@/services/agentBotProvider', () => ({
+ agentBotProviderService: { wechatGetQrCode: vi.fn(), wechatPollQrStatus: vi.fn() },
+}));
+
+vi.mock('@/hooks/useAppOrigin', () => ({ useAppOrigin: () => 'https://example.test' }));
+
+const platformDef = {
+ documentation: {},
+ id: 'discord',
+ name: 'Discord',
+ schema: discordSchema,
+} as unknown as SerializedPlatformDefinition;
+
+const ACCESS_IDS = ['access-identity', 'access-conversation', 'access-device'] as const;
+
+/** Mounts the access tab the way the channel page does: a saved bot, merged with the defaults. */
+const Harness = ({
+ moduleControls,
+ settings,
+}: {
+ moduleControls?: ModuleControls;
+ settings?: Record<string, unknown>;
+}) => {
+ const form = useForm<ChannelFormValues>();
+ const saved = mergeSettingsWithDefaults(discordSchema, settings ?? {});
+
+ useEffect(() => {
+ form.setValues(
+ getChannelFormValues({ applicationId: '1', credentials: {}, settings: saved }) as never,
+ );
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, []);
+
+ return (
+ <Body
+ hasConfig
+ activeTab="access"
+ currentConfig={{ applicationId: '1', credentials: {}, settings: saved }}
+ form={form}
+ moduleControls={moduleControls}
+ platformDef={platformDef}
+ />
+ );
+};
+
+const en = agentEn as Record<string, string>;
+const zh = agentZh as Record<string, string>;
+
+const controls = (overrides: Partial<ModuleControls> = {}): ModuleControls => ({
+ dirty: [],
+ ids: ACCESS_IDS,
+ onDiscard: vi.fn(),
+ onSave: vi.fn(),
+ ...overrides,
+});
+
+describe('channel settings form: access tab', () => {
+ it('splits access into owner identity, conversation and device blocks, each with a Save', () => {
+ state.copy = zh;
+
+ render(<Harness moduleControls={controls()} />);
+
+ const titles = [
+ zh['channel.access.section.identity'],
+ zh['channel.access.section.conversation'],
+ zh['channel.access.section.device'],
+ ];
+ for (const title of titles) expect(screen.getByText(title)).toBeInTheDocument();
+ expect(screen.getAllByRole('button', { name: zh['channel.module.save'] })).toHaveLength(3);
+ });
+
+ it('keeps devices to the owner by default and hides the authorized list', () => {
+ state.copy = en;
+
+ render(<Harness />);
+
+ const device = screen.getByRole('radiogroup', { name: en['channel.access.device.label'] });
+ expect(within(device).getByRole('radio', { name: /Only me/ })).toHaveAttribute(
+ 'aria-checked',
+ 'true',
+ );
+ expect(screen.queryByText(en['channel.access.device.list'])).not.toBeVisible();
+ });
+
+ it('shows the authorized list once devices are shared, and saves only the device block', () => {
+ state.copy = en;
+ const onSave = vi.fn();
+
+ render(
+ <Harness
+ moduleControls={controls({ dirty: ['access-device'], onSave })}
+ settings={{
+ deviceAllowFrom: [{ id: 'friend-1', name: 'Ada' }],
+ devicePolicy: 'allowlist',
+ userId: 'owner-1',
+ }}
+ />,
+ );
+
+ expect(screen.getByText(en['channel.access.device.list'])).toBeVisible();
+ // The list's add button derives its copy from the field label: a missing key shows raw.
+ expect(screen.getByRole('button', { name: 'Add person' })).toBeVisible();
+ expect(screen.getByDisplayValue('friend-1')).toBeInTheDocument();
+
+ const enabled = screen
+ .getAllByRole('button', { name: en['channel.module.save'] })
+ .filter((button) => !(button as HTMLButtonElement).disabled);
+ expect(enabled).toHaveLength(1);
+ fireEvent.click(enabled[0]);
+ expect(onSave).toHaveBeenCalledWith('access-device');
+ });
+
+ it('warns that nobody can use the devices until the owner ID is filled', () => {
+ state.copy = en;
+
+ render(<Harness />);
+
+ expect(screen.getByText(en['channel.access.device.ownerMissing'])).toBeInTheDocument();
+ });
+});
diff --git a/src/features/AgentChannel/PlatformDetail/Body.tsx b/src/features/AgentChannel/PlatformDetail/Body.tsx
index 8bb97cf9ca6..58593ecf524 100644
--- a/src/features/AgentChannel/PlatformDetail/Body.tsx
+++ b/src/features/AgentChannel/PlatformDetail/Body.tsx
@@ -29,6 +29,7 @@ import type { SaveModuleId } from './saveModules';
import { ApplicationIdField, SchemaField } from './SchemaField';
import {
getSchemaFields,
+ groupAccessFields,
groupSettingsFields,
groupWakeFields,
WAKE_KEY_PREFIX,
@@ -376,7 +377,35 @@ const Body = memo<BodyProps>(
{t('channel.reply.instant')}
</Text>
)}
- {group.key === 'wake' ? (
+ {group.key === 'access' ? (
+ // Who the owner is, who may talk to the bot and who may use the owner's devices are
+ // three separate decisions, so each gets a block (and a Save) of its own.
+ groupAccessFields(group.fields).map((section) => (
+ <Form.Group
+ className={styles.moduleGroup}
+ collapsible={false}
+ extra={moduleExtra(`access-${section.key}`)}
+ key={section.key}
+ keyValue={`settings-access-${section.key}-${platformDef.id}`}
+ title={t(`channel.access.section.${section.key}`)}
+ variant={'filled'}
+ desc={
+ section.key === 'identity'
+ ? undefined
+ : t(`channel.access.section.${section.key}Desc`)
+ }
+ >
+ <AccessSection
+ disabled={disabled}
+ fields={section.fields}
+ form={form}
+ section={section.key}
+ userIdExtras={renderExtras(section.fields.find((f) => f.key === 'userId'))}
+ onValuesChange={onValuesChange}
+ />
+ </Form.Group>
+ ))
+ ) : group.key === 'wake' ? (
// Keywords, channels, pace and judgement each get a block of their own, so a long
// list of options reads as four decisions.
groupWakeFields(group.fields).map((section) => (
@@ -411,18 +440,7 @@ const Body = memo<BodyProps>(
: undefined
}
>
- {group.key === 'access' &&
- group.fields.some((f) => f.key === 'dmPolicy' || f.key === 'groupPolicy') ? (
- <AccessSection
- disabled={disabled}
- fields={group.fields}
- form={form}
- userIdExtras={renderExtras(group.fields.find((f) => f.key === 'userId'))}
- onValuesChange={onValuesChange}
- />
- ) : (
- renderSettingsFields(group.fields)
- )}
+ {renderSettingsFields(group.fields)}
{group.key === 'advanced' && (
<Flexbox horizontal justify={'flex-end'} style={{ paddingBlock: 8 }}>
<Button
diff --git a/src/features/AgentChannel/PlatformDetail/accessStance.test.ts b/src/features/AgentChannel/PlatformDetail/accessStance.test.ts
index 48afd4f75a1..fdaf39db59f 100644
--- a/src/features/AgentChannel/PlatformDetail/accessStance.test.ts
+++ b/src/features/AgentChannel/PlatformDetail/accessStance.test.ts
@@ -85,6 +85,21 @@ describe('accessIssues', () => {
});
describe('dropHiddenIncompleteRows', () => {
+ it('drops a half-added device row once devices are back to the owner only', () => {
+ expect(
+ dropHiddenIncompleteRows({
+ deviceAllowFrom: [{ id: '7' }, { id: '' }],
+ devicePolicy: 'owner',
+ }),
+ ).toEqual({ deviceAllowFrom: [{ id: '7' }] });
+ });
+
+ it('keeps an incomplete device row while the device list is shown', () => {
+ expect(
+ dropHiddenIncompleteRows({ deviceAllowFrom: [{ id: '' }], devicePolicy: 'allowlist' }),
+ ).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 ee4ef87c743..4e04b7f0130 100644
--- a/src/features/AgentChannel/PlatformDetail/accessStance.ts
+++ b/src/features/AgentChannel/PlatformDetail/accessStance.ts
@@ -79,6 +79,8 @@ export const applyDmStance = (stance: DmStance, settings: StanceSettings): Stanc
export type AccessIssue = 'approverMissing' | 'groupListEmpty' | 'listEmpty';
export interface AccessSettings extends StanceSettings {
+ deviceAllowFrom?: unknown;
+ devicePolicy?: string;
groupAllowFrom?: unknown;
groupPolicy?: string;
userId?: unknown;
@@ -114,7 +116,7 @@ export const dropHiddenIncompleteRows = (
settings: AccessSettings & { groupAllowFrom?: unknown; groupPolicy?: string },
): Record<string, unknown> => {
const patch: Record<string, unknown> = {};
- const prune = (key: 'allowFrom' | 'groupAllowFrom') => {
+ const prune = (key: 'allowFrom' | 'deviceAllowFrom' | 'groupAllowFrom') => {
const list = settings[key];
if (Array.isArray(list) && list.some((entry) => !hasId(entry))) patch[key] = list.filter(hasId);
};
@@ -124,6 +126,7 @@ export const dropHiddenIncompleteRows = (
stance === 'approval' || stance === 'listed' || countListed(settings.allowFrom) > 0;
if (!peopleListShown) prune('allowFrom');
if (settings.groupPolicy !== 'allowlist') prune('groupAllowFrom');
+ if (settings.devicePolicy !== 'allowlist') prune('deviceAllowFrom');
return patch;
};
diff --git a/src/features/AgentChannel/PlatformDetail/saveModules.test.ts b/src/features/AgentChannel/PlatformDetail/saveModules.test.ts
index 525ebfc5d25..d5f562e96e8 100644
--- a/src/features/AgentChannel/PlatformDetail/saveModules.test.ts
+++ b/src/features/AgentChannel/PlatformDetail/saveModules.test.ts
@@ -21,6 +21,8 @@ describe('resolveSaveModules', () => {
'userId',
'dmPolicy',
'groupPolicy',
+ 'devicePolicy',
+ 'deviceAllowFrom',
'watchKeywords',
'botWakeEnabled',
'botWakeScope',
@@ -36,7 +38,9 @@ describe('resolveSaveModules', () => {
expect(resolveSaveModules(discord, true).map((m) => m.id)).toEqual([
'credentials',
'connection',
- 'access',
+ 'access-identity',
+ 'access-conversation',
+ 'access-device',
'wake-judgement',
'wake-keywords',
'wake-channels',
@@ -60,10 +64,12 @@ describe('resolveSaveModules', () => {
});
it('has a credentials module only when the platform asks for credentials', () => {
- expect(resolveSaveModules(groups(['dmPolicy']), false).map((m) => m.id)).toEqual(['access']);
+ expect(resolveSaveModules(groups(['dmPolicy']), false).map((m) => m.id)).toEqual([
+ 'access-conversation',
+ ]);
expect(resolveSaveModules(groups(['dmPolicy']), true).map((m) => m.id)).toEqual([
'credentials',
- 'access',
+ 'access-conversation',
]);
});
@@ -74,10 +80,34 @@ describe('resolveSaveModules', () => {
for (const module of wake) expect(module.alsoWrites).toEqual(['botWakeEnabled']);
});
+ it('splits access into owner identity, conversation and device blocks', () => {
+ const access = resolveSaveModules(discord, false).filter((m) => m.id.startsWith('access-'));
+
+ expect(access.map((m) => [m.id, m.keys])).toEqual([
+ ['access-identity', ['userId']],
+ ['access-conversation', ['dmPolicy', 'groupPolicy']],
+ ['access-device', ['devicePolicy', 'deviceAllowFrom']],
+ ]);
+ });
+
+ it('saves the owner ID with the conversation block, which a pairing policy needs', () => {
+ const conversation = resolveSaveModules(discord, false).find(
+ (m) => m.id === 'access-conversation',
+ )!;
+
+ expect(
+ settingsToSave(
+ conversation,
+ { settings: { dmPolicy: 'pairing', userId: 'owner-1' } },
+ { settings: { dmPolicy: 'open' } },
+ ),
+ ).toEqual({ dmPolicy: 'pairing', userId: 'owner-1' });
+ });
+
it('maps a module to the tab it sits on', () => {
expect(tabOfModule('credentials')).toBe('connect');
expect(tabOfModule('connection')).toBe('connect');
- expect(tabOfModule('access')).toBe('access');
+ expect(tabOfModule('access-device')).toBe('access');
expect(tabOfModule('wake-pace')).toBe('wake');
expect(tabOfModule('advanced')).toBe('advanced');
});
diff --git a/src/features/AgentChannel/PlatformDetail/saveModules.ts b/src/features/AgentChannel/PlatformDetail/saveModules.ts
index 3d75e5181d9..d3a28a3476e 100644
--- a/src/features/AgentChannel/PlatformDetail/saveModules.ts
+++ b/src/features/AgentChannel/PlatformDetail/saveModules.ts
@@ -2,7 +2,7 @@ import isEqual from 'fast-deep-equal';
import type { ChannelTab, ChannelValues } from './channelTabs';
import { pickKeys, replyDiffers } from './replySettings';
-import { groupWakeFields, type SettingsGroup } from './settingsGroups';
+import { groupAccessFields, groupWakeFields, type SettingsGroup } from './settingsGroups';
/**
* The page saves one block at a time. A block is a titled group of options with its own Save
@@ -12,7 +12,7 @@ import { groupWakeFields, type SettingsGroup } from './settingsGroups';
* Replies are not a block: they take effect as soon as they change and save themselves.
*/
export type SaveModuleId =
- | 'access'
+ | `access-${'conversation' | 'device' | 'identity'}`
| 'advanced'
| 'connection'
| 'credentials'
@@ -20,8 +20,9 @@ export type SaveModuleId =
export interface SaveModule {
/**
- * Settings keys written with this block that no field of it shows (the hidden wake switch), so
- * a bot saved before the wake options existed still gets it.
+ * Settings keys written with this block that no field of it shows: the hidden wake switch, so
+ * a bot saved before the wake options existed still gets it, and the owner's ID with the
+ * conversation block, which a pairing policy needs.
*/
alsoWrites?: string[];
id: SaveModuleId;
@@ -63,7 +64,18 @@ export const resolveSaveModules = (
settings('connection', group.fields);
break;
}
- case 'access':
+ case 'access': {
+ for (const section of groupAccessFields(group.fields)) {
+ // Approving strangers needs the approver: saving that choice saves the owner's ID too,
+ // or the server would refuse a pairing policy with no one to approve.
+ settings(
+ `access-${section.key}`,
+ section.fields,
+ section.key === 'conversation' ? ['userId'] : undefined,
+ );
+ }
+ break;
+ }
case 'advanced': {
settings(group.key, group.fields);
break;
@@ -84,7 +96,8 @@ export const resolveSaveModules = (
/** The tab a block sits on, to mark a tab that holds unsaved changes. */
export const tabOfModule = (id: SaveModuleId): ChannelTab => {
if (id === 'credentials' || id === 'connection') return 'connect';
- if (id === 'access' || id === 'advanced') return id;
+ if (id.startsWith('access-')) return 'access';
+ if (id === 'advanced') return id;
return 'wake';
};
diff --git a/src/features/AgentChannel/PlatformDetail/settingsGroups.test.ts b/src/features/AgentChannel/PlatformDetail/settingsGroups.test.ts
index 906f60e25c6..cd63d267f89 100644
--- a/src/features/AgentChannel/PlatformDetail/settingsGroups.test.ts
+++ b/src/features/AgentChannel/PlatformDetail/settingsGroups.test.ts
@@ -4,10 +4,38 @@ import { BOT_WAKE_SETTING_KEYS } from '@/server/services/agentSignal/scenarios/b
import { botWakeFields } from '@/server/services/bot/platforms/botWakeFields';
import type { FieldSchema } from '@/server/services/bot/platforms/types';
-import { getSchemaFields, groupSettingsFields, groupWakeFields } from './settingsGroups';
+import {
+ getSchemaFields,
+ groupAccessFields,
+ groupSettingsFields,
+ groupWakeFields,
+} from './settingsGroups';
const field = (key: string): FieldSchema => ({ key, label: key, type: 'string' });
+describe('groupAccessFields', () => {
+ it('splits access into owner identity, conversation and device blocks, in page order', () => {
+ const sections = groupAccessFields(
+ ['deviceAllowFrom', 'groupPolicy', 'userId', 'devicePolicy', 'dmPolicy', 'serverId'].map(
+ field,
+ ),
+ );
+
+ expect(sections.map((s) => [s.key, s.fields.map((f) => f.key)])).toEqual([
+ ['identity', ['userId', 'serverId']],
+ ['conversation', ['dmPolicy', 'groupPolicy']],
+ ['device', ['devicePolicy', 'deviceAllowFrom']],
+ ]);
+ });
+
+ it('drops a block the platform has no fields for', () => {
+ expect(groupAccessFields(['userId', 'devicePolicy'].map(field)).map((s) => s.key)).toEqual([
+ 'identity',
+ 'device',
+ ]);
+ });
+});
+
describe('groupSettingsFields', () => {
it('sorts fields into connect, access, reply and advanced, ordered by how a person decides them', () => {
const groups = groupSettingsFields(
diff --git a/src/features/AgentChannel/PlatformDetail/settingsGroups.ts b/src/features/AgentChannel/PlatformDetail/settingsGroups.ts
index 5e83582725e..163aa89de25 100644
--- a/src/features/AgentChannel/PlatformDetail/settingsGroups.ts
+++ b/src/features/AgentChannel/PlatformDetail/settingsGroups.ts
@@ -32,21 +32,38 @@ export interface SettingsGroup {
key: SettingsGroupKey;
}
+export type AccessSectionKey = 'conversation' | 'device' | 'identity';
+
+export interface AccessSectionGroup {
+ fields: FieldSchema[];
+ key: AccessSectionKey;
+}
+
/**
- * Who the bot talks to, in the order a person decides it: who you are and which
- * server is yours, then DMs
- * (and the list they lean on), then groups.
+ * The access tab's blocks, in page order, each answering one question:
+ *
+ * - identity: who the owner is (their own ID, and the server that is theirs)
+ * - conversation: who may talk to the bot, in DMs (and the list they lean on) and in groups
+ * - device: who, besides the owner, may use the owner's devices through the bot
*/
-const ACCESS_KEYS = [
- 'userId',
- 'serverId',
- 'dmPolicy',
- 'allowFrom',
- 'guestPolicy',
- 'groupPolicy',
- 'groupAllowFrom',
+const ACCESS_SECTION_KEYS: Array<[AccessSectionKey, string[]]> = [
+ ['identity', ['userId', 'serverId']],
+ ['conversation', ['dmPolicy', 'allowFrom', 'guestPolicy', 'groupPolicy', 'groupAllowFrom']],
+ ['device', ['devicePolicy', 'deviceAllowFrom']],
];
+const ACCESS_KEYS = ACCESS_SECTION_KEYS.flatMap(([, keys]) => keys);
+
+/** Split the access tab's fields into its blocks. Empty blocks are dropped. */
+export const groupAccessFields = (fields: FieldSchema[]): AccessSectionGroup[] => {
+ const byKey = new Map(fields.map((field) => [field.key, field]));
+
+ return ACCESS_SECTION_KEYS.map(([key, keys]) => ({
+ fields: keys.map((k) => byKey.get(k)).filter((field): field is FieldSchema => !!field),
+ key,
+ })).filter((section) => section.fields.length > 0);
+};
+
/** What a reply looks like in the chat. */
export const REPLY_KEYS = ['replyPlacement', 'displayToolCalls', 'showUsageStats', 'reactionMode'];